File: screen_ai_service_handler_base.cc

package info (click to toggle)
chromium 139.0.7258.127-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 6,122,068 kB
  • sloc: cpp: 35,100,771; ansic: 7,163,530; javascript: 4,103,002; python: 1,436,920; asm: 946,517; xml: 746,709; pascal: 187,653; perl: 88,691; sh: 88,436; objc: 79,953; sql: 51,488; cs: 44,583; fortran: 24,137; makefile: 22,147; tcl: 15,277; php: 13,980; yacc: 8,984; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (351 lines) | stat: -rw-r--r-- 11,921 bytes parent folder | download | duplicates (5)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
// Copyright 2025 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/screen_ai/screen_ai_service_handler_base.h"

#include <utility>
#include <vector>

#include "base/containers/flat_map.h"
#include "base/files/file.h"
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/functional/bind.h"
#include "base/location.h"
#include "base/metrics/histogram_functions.h"
#include "base/process/process.h"
#include "base/strings/strcat.h"
#include "base/strings/string_split.h"
#include "base/strings/stringprintf.h"
#include "base/system/sys_info.h"
#include "base/task/sequenced_task_runner.h"
#include "base/task/thread_pool.h"
#include "chrome/browser/screen_ai/screen_ai_install_state.h"
#include "chrome/browser/screen_ai/screen_ai_service_router.h"
#include "content/public/browser/network_service_instance.h"
#include "content/public/browser/service_process_host.h"
#include "content/public/browser/service_process_host_passkeys.h"
#include "mojo/public/mojom/base/file_path.mojom.h"
#include "services/network/public/mojom/network_change_manager.mojom.h"
#include "services/screen_ai/public/cpp/utilities.h"

#if BUILDFLAG(IS_WIN)
#include "base/strings/utf_string_conversions.h"
#endif

namespace screen_ai {

bool IsModelFileContentReadable(base::File& file) {
  if (!file.IsValid()) {
    return false;
  }
  int file_size = file.GetLength();
  if (!file_size) {
    return false;
  }
  std::vector<uint8_t> buffer(file_size);
  return file.ReadAndCheck(0, base::span(buffer));
}

ComponentFiles::ComponentFiles(
    const base::FilePath& library_binary_path,
    const base::FilePath::CharType* files_list_file_name)
    : library_binary_path_(library_binary_path) {
  base::FilePath component_folder = library_binary_path.DirName();

  // Get the files list.
  std::string file_content;
  if (!base::ReadFileToString(component_folder.Append(files_list_file_name),
                              &file_content)) {
    VLOG(0) << "Could not read list of files for " << files_list_file_name;
    return;
  }
  std::vector<std::string> files_list = base::SplitString(
      file_content, "\n", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
  if (files_list.empty()) {
    VLOG(0) << "Could not parse files list for " << files_list_file_name;
    return;
  }

  for (auto& relative_file_path : files_list) {
    // Ignore comment lines.
    if (relative_file_path.empty() || relative_file_path[0] == '#') {
      continue;
    }

#if BUILDFLAG(IS_WIN)
    base::FilePath relative_path(base::UTF8ToWide(relative_file_path));
#else
    base::FilePath relative_path(relative_file_path);
#endif
    const base::FilePath full_path = component_folder.Append(relative_path);
    model_files_[relative_path] =
        base::File(full_path, base::File::FLAG_OPEN | base::File::FLAG_READ);
    if (!IsModelFileContentReadable(model_files_[relative_path])) {
      VLOG(0) << "Could not open " << full_path;
      model_files_.clear();
      return;
    }
  }
}

ComponentFiles::~ComponentFiles() {
  if (model_files_.empty()) {
    return;
  }

  // Transfer ownership of the file handles to a thread that may block, and let
  // them get destroyed there.
  base::ThreadPool::PostTask(
      FROM_HERE,
      {base::MayBlock(), base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN},
      base::BindOnce(
          [](base::flat_map<base::FilePath, base::File> model_files) {},
          std::move(model_files_)));
}

std::unique_ptr<ComponentFiles> ComponentFiles::Load(
    const base::FilePath::CharType* files_list_file_name) {
  return std::make_unique<ComponentFiles>(
      screen_ai::ScreenAIInstallState::GetInstance()
          ->get_component_binary_path(),
      files_list_file_name);
}

ScreenAIServiceHandlerBase::ScreenAIServiceHandlerBase()
    : screen_ai_service_shutdown_handler_(this) {}

ScreenAIServiceHandlerBase::~ScreenAIServiceHandlerBase() = default;

std::string ScreenAIServiceHandlerBase::GetMetricFullName(
    std::string_view metric_name) const {
  return base::StringPrintf("Accessibility.%s.Service.%s", GetServiceName(),
                            metric_name);
}

std::optional<bool> ScreenAIServiceHandlerBase::GetServiceState() {
  if (GetAndRecordSuspendedState()) {
    return false;
  }
  if (IsConnectionBound()) {
    return true;
  }
  if (IsServiceEnabled()) {
    return std::nullopt;
  }
  return false;
}

std::optional<bool> ScreenAIServiceHandlerBase::GetServiceStateAsync(
    ServiceStateCallback callback) {
  auto service_state = GetServiceState();

  // If `service_state` has value, the service is already initialized or
  // disabled.
  if (service_state) {
    std::move(callback).Run(*service_state);
  } else {
    // Put the request in queue and wait for ScreenAIServiceRouter to announce
    // that library download state is changed.
    pending_state_requests_.emplace_back(std::move(callback));
  }

  return service_state;
}

void ScreenAIServiceHandlerBase::OnLibraryAvailablityChanged(bool available) {
  if (pending_state_requests_.empty()) {
    return;
  }

  if (available) {
    InitializeServiceIfNeeded();
  } else {
    CallPendingStatusRequests(false);
  }
}

void ScreenAIServiceHandlerBase::ShuttingDownOnIdle() {
  shutdown_handler_data_.shutdown_message_received = true;
}

bool ScreenAIServiceHandlerBase::GetAndRecordSuspendedState() {
  base::UmaHistogramBoolean(GetMetricFullName("IsSuspended"),
                            shutdown_handler_data_.suspended);
  return shutdown_handler_data_.suspended;
}

void ScreenAIServiceHandlerBase::OnScreenAIServiceDisconnected() {
  screen_ai_service_factory_.reset();
  CallPendingStatusRequests(false);

  if (resource_monitor_) {
    if (resource_monitor_->get_max_resident_memory_kb()) {
      base::UmaHistogramMemoryMB(
          GetMetricFullName("MaxMemoryLoad"),
          resource_monitor_->get_max_resident_memory_kb() / 1000);
    }
    resource_monitor_.reset();

    base::UmaHistogramMediumTimes(GetMetricFullName("LifeTime"),
                                  base::TimeTicks::Now() - service_start_time_);
  }

  screen_ai_service_shutdown_handler_.reset();
  if (shutdown_handler_data_.shutdown_message_received) {
    if (shutdown_handler_data_.crash_count) {
      base::UmaHistogramCounts100(GetMetricFullName("CrashCountBeforeResume"),
                                  shutdown_handler_data_.crash_count);
    }
    shutdown_handler_data_.crash_count = 0;
    return;
  }

  // Crashed!
  shutdown_handler_data_.crash_count++;
  shutdown_handler_data_.suspended = true;
  base::TimeDelta suspense_time =
      ScreenAIServiceRouter::SuggestedWaitTimeBeforeReAttempt(
          shutdown_handler_data_.crash_count);
  base::SequencedTaskRunner::GetCurrentDefault()->PostDelayedTask(
      FROM_HERE,
      base::BindOnce(&ScreenAIServiceHandlerBase::ResetSuspend,
                     weak_ptr_factory_.GetWeakPtr()),
      suspense_time);
  VLOG(0) << "Service suspended due to crash for: " << suspense_time;
}

void ScreenAIServiceHandlerBase::CallPendingStatusRequests(bool successful) {
  std::vector<ServiceStateCallback> requests;
  pending_state_requests_.swap(requests);
  for (auto& callback : requests) {
    std::move(callback).Run(successful);
  }
}

void ScreenAIServiceHandlerBase::LaunchIfNotRunning() {
  ScreenAIInstallState::GetInstance()->SetLastUsageTime();
  if (screen_ai_service_factory_.is_bound()) {
    return;
  }

  auto* state_instance = ScreenAIInstallState::GetInstance();

  // To have a smooth user experience, the callers of the service should ensure
  // that the component is downloaded before promising it to the users and
  // triggering its launch.
  // If it is not done, the calling feature will receive no reply when it tries
  // to use this service. However, they can detect it by using an on-disconnect
  // handler.
  if (!state_instance->IsComponentAvailable()) {
    VLOG(0) << "ScreenAI service launch triggered when component is not "
               "available.";
    state_instance->DownloadComponent();
    return;
  }

  if (GetAndRecordSuspendedState()) {
    VLOG(0) << "ScreenAI service triggered while suspended.";
    return;
  }

  base::FilePath binary_path = state_instance->get_component_binary_path();
#if BUILDFLAG(IS_WIN)
  std::vector<base::FilePath> preload_libraries = {binary_path};
#elif BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
  std::vector<std::string> extra_switches = {
      base::StringPrintf("--%s=%s", screen_ai::GetBinaryPathSwitch(),
                         binary_path.MaybeAsASCII().c_str())};
#endif  // BUILDFLAG(IS_WIN)

  std::string process_name = base::StrCat({GetServiceName(), " Service"});
  content::ServiceProcessHost::Launch(
      screen_ai_service_factory_.BindNewPipeAndPassReceiver(),
      content::ServiceProcessHost::Options()
          .WithDisplayName(process_name)
#if BUILDFLAG(IS_WIN)
          .WithPreloadedLibraries(
              preload_libraries,
              content::ServiceProcessHostPreloadLibraries::GetPassKey())
#elif BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
          .WithExtraCommandLineSwitches(extra_switches)
#endif  // BUILDFLAG(IS_WIN)
          .WithProcessCallback(
              base::BindOnce(&ScreenAIServiceHandlerBase::OnServiceLaunched,
                             weak_ptr_factory_.GetWeakPtr(), process_name))
          .Pass());

  shutdown_handler_data_.shutdown_message_received = false;
  screen_ai_service_factory_->BindShutdownHandler(
      screen_ai_service_shutdown_handler_.BindNewPipeAndPassRemote());

  screen_ai_service_factory_.set_disconnect_handler(
      base::BindOnce(&ScreenAIServiceHandlerBase::OnScreenAIServiceDisconnected,
                     weak_ptr_factory_.GetWeakPtr()));
}

void ScreenAIServiceHandlerBase::OnServiceLaunched(
    const std::string& process_name,
    const base::Process& process) {
  // Post task to ensure that `resource_monitor_` is created after the service
  // process host is registered.
  base::SequencedTaskRunner::GetCurrentDefault()->PostTask(
      FROM_HERE,
      base::BindOnce(&ScreenAIServiceHandlerBase::CreateResourceMonitor,
                     weak_ptr_factory_.GetWeakPtr(), process_name));
  service_start_time_ = base::TimeTicks::Now();
}

void ScreenAIServiceHandlerBase::CreateResourceMonitor(
    const std::string& process_name) {
  CHECK(!resource_monitor_);
  resource_monitor_ = ResourceMonitor::CreateForProcess(process_name);
  CHECK(resource_monitor_);
}

void ScreenAIServiceHandlerBase::InitializeServiceIfNeeded() {
  std::optional<bool> service_state = GetServiceState();
  if (service_state) {
    // Either service is already initialized or disabled.
    CallPendingStatusRequests(*service_state);
    return;
  }

  base::TimeTicks request_start_time = base::TimeTicks::Now();
  LaunchIfNotRunning();

  if (!screen_ai_service_factory_.is_bound()) {
    SetLibraryLoadState(request_start_time, false);
    return;
  }

  LoadModelFilesAndInitialize(request_start_time);
}

void ScreenAIServiceHandlerBase::SetLibraryLoadState(
    base::TimeTicks request_start_time,
    bool successful) {
  base::TimeDelta elapsed_time = base::TimeTicks::Now() - request_start_time;
  base::UmaHistogramBoolean(GetMetricFullName("Initialization"), successful);
  base::UmaHistogramTimes(successful
                              ? GetMetricFullName("InitializationTime.Success")
                              : GetMetricFullName("InitializationTime.Failure"),
                          elapsed_time);

  CallPendingStatusRequests(successful);

  if (!successful) {
    ResetConnection();
  }
}

bool ScreenAIServiceHandlerBase::IsConnectionBoundForTesting() {
  return IsConnectionBound();
}

bool ScreenAIServiceHandlerBase::IsProcessRunningForTesting() {
  return screen_ai_service_factory_.is_bound();
}

}  // namespace screen_ai