File: one_time_message_handler.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 (722 lines) | stat: -rw-r--r-- 28,372 bytes parent folder | download | duplicates (3)
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
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
// Copyright 2017 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "extensions/renderer/api/messaging/one_time_message_handler.h"

#include <algorithm>
#include <map>
#include <vector>

#include "base/containers/contains.h"
#include "base/functional/bind.h"
#include "base/functional/callback.h"
#include "base/supports_user_data.h"
#include "content/public/renderer/render_frame.h"
#include "extensions/common/api/messaging/message.h"
#include "extensions/common/api/messaging/port_id.h"
#include "extensions/common/extension_features.h"
#include "extensions/common/mojom/event_dispatcher.mojom.h"
#include "extensions/common/mojom/message_port.mojom-shared.h"
#include "extensions/renderer/api/messaging/message_target.h"
#include "extensions/renderer/api/messaging/messaging_util.h"
#include "extensions/renderer/bindings/api_binding_types.h"
#include "extensions/renderer/bindings/api_binding_util.h"
#include "extensions/renderer/bindings/api_bindings_system.h"
#include "extensions/renderer/bindings/api_event_handler.h"
#include "extensions/renderer/bindings/api_request_handler.h"
#include "extensions/renderer/bindings/get_per_context_data.h"
#include "extensions/renderer/console.h"
#include "extensions/renderer/gc_callback.h"
#include "extensions/renderer/get_script_context.h"
#include "extensions/renderer/ipc_message_sender.h"
#include "extensions/renderer/native_extension_bindings_system.h"
#include "extensions/renderer/script_context.h"
#include "gin/arguments.h"
#include "gin/dictionary.h"
#include "gin/handle.h"
#include "gin/per_context_data.h"
#include "ipc/ipc_message.h"
#include "v8/include/v8-container.h"
#include "v8/include/v8-exception.h"
#include "v8/include/v8-external.h"
#include "v8/include/v8-function-callback.h"
#include "v8/include/v8-function.h"
#include "v8/include/v8-isolate.h"
#include "v8/include/v8-object.h"
#include "v8/include/v8-persistent-handle.h"
#include "v8/include/v8-primitive.h"

namespace extensions {

namespace {

// An opener port in the context; i.e., the caller of runtime.sendMessage.
struct OneTimeOpener {
  int request_id = -1;
  binding::AsyncResponseType async_type = binding::AsyncResponseType::kNone;
  mojom::ChannelType channel_type;
};

// A receiver port in the context; i.e., a listener to runtime.onMessage.
struct OneTimeReceiver {
  std::string event_name;
  v8::Global<v8::Object> sender;
  v8::Global<v8::Function> response_function;
};

using OneTimeMessageCallback =
    base::OnceCallback<void(gin::Arguments* arguments)>;
struct OneTimeMessageContextData : public base::SupportsUserData::Data {
  static constexpr char kPerContextDataKey[] =
      "extension_one_time_message_context_data";

  std::map<PortId, OneTimeOpener> openers;
  std::map<PortId, OneTimeReceiver> receivers;
  std::vector<std::unique_ptr<OneTimeMessageCallback>> pending_callbacks;
};

constexpr char OneTimeMessageContextData::kPerContextDataKey[];

void OneTimeMessageResponseHelper(
    const v8::FunctionCallbackInfo<v8::Value>& info) {
  CHECK(info.Data()->IsExternal());

  gin::Arguments arguments(info);
  v8::Isolate* isolate = arguments.isolate();
  v8::HandleScope handle_scope(isolate);
  v8::Local<v8::Context> context = isolate->GetCurrentContext();

  OneTimeMessageContextData* data =
      GetPerContextData<OneTimeMessageContextData>(context,
                                                   kDontCreateIfMissing);
  if (!data)
    return;

  v8::Local<v8::External> external = info.Data().As<v8::External>();
  auto* raw_callback = static_cast<OneTimeMessageCallback*>(external->Value());
  auto iter = std::ranges::find(data->pending_callbacks, raw_callback,
                                &std::unique_ptr<OneTimeMessageCallback>::get);
  if (iter == data->pending_callbacks.end())
    return;

  std::unique_ptr<OneTimeMessageCallback> callback = std::move(*iter);
  data->pending_callbacks.erase(iter);
  std::move(*callback).Run(&arguments);
}

// Returns true if any of the listeners responded with `true` or a Promise,
// indicating they will respond to the call asynchronously. If a Promise is
// returned, `promise_settled_function` is attached to its resolution.
bool CheckAndHandleAsyncListenerReply(
    v8::Isolate* isolate,
    v8::Local<v8::Context> context,
    v8::Local<v8::Value> result,
    v8::Local<v8::Function> promise_settled_function) {
  // `result` can be undefined if the context was destroyed before the
  // listeners were run (or while they were running).
  if (result->IsUndefined()) {
    return false;
  }

  // We expect results as a value with an array of results as a `results`
  // property, however, since this comes from untrusted JS let's confirm this
  // first.
  if (!result->IsObject()) {
    return false;
  }
  v8::Local<v8::Object> result_object = result.As<v8::Object>();
  v8::Local<v8::Value> results_value;
  if (!result_object->Get(context, gin::StringToSymbol(isolate, "results"))
           .ToLocal(&results_value)) {
    return false;
  }
  if (!results_value->IsArray()) {
    return false;
  }

  v8::Local<v8::Array> results_array = results_value.As<v8::Array>();
  uint32_t results_count = results_array->Length();

  bool promise_return_support_enabled = base::FeatureList::IsEnabled(
      extensions_features::kRuntimeOnMessagePromiseReturnSupport);
  for (uint32_t i = 0; i < results_count; ++i) {
    v8::MaybeLocal<v8::Value> maybe_result = results_array->Get(context, i);
    v8::Local<v8::Value> listener_return;
    // Assume the result could throw due to changes at runtime by the
    // extension's JS code.
    if (!maybe_result.ToLocal(&listener_return)) {
      continue;
    }

    // Check if any of the results is indicating it will reply async by
    // returning `true`.
    if (listener_return->IsBoolean() &&
        listener_return.As<v8::Boolean>()->Value()) {
      return true;
    }

    // Check if any of the returns are a promise -- indicating the listener
    // will reply async. If they do, we call the equivalent of
    // sendResponse() with the promise's settled value.
    if (listener_return->IsPromise() && promise_return_support_enabled) {
      // TODO(crbug.com/40753031): Support promise rejects as per the polyfill:
      // https://github.com/mozilla/webextension-polyfill/tree/master. If
      // rejected value is object with a ".message" property then return an
      // error with that message, otherwise a generic message ("An unexpected
      // error occurred").
      std::ignore = listener_return.As<v8::Promise>()->Then(
          context, promise_settled_function);
      // TODO(crbug.com/40753031): Consider setting lastError in JS
      // when promise is rejected.
      return true;
    }
  }

  return false;
}

}  // namespace

OneTimeMessageHandler::OneTimeMessageHandler(
    NativeExtensionBindingsSystem* bindings_system)
    : bindings_system_(bindings_system) {}
OneTimeMessageHandler::~OneTimeMessageHandler() = default;

bool OneTimeMessageHandler::HasPort(ScriptContext* script_context,
                                    const PortId& port_id) {
  v8::Isolate* isolate = script_context->isolate();
  v8::HandleScope handle_scope(isolate);

  OneTimeMessageContextData* data =
      GetPerContextData<OneTimeMessageContextData>(script_context->v8_context(),
                                                   kDontCreateIfMissing);
  if (!data)
    return false;
  return port_id.is_opener ? base::Contains(data->openers, port_id)
                           : base::Contains(data->receivers, port_id);
}

v8::Local<v8::Promise> OneTimeMessageHandler::SendMessage(
    ScriptContext* script_context,
    const PortId& new_port_id,
    const MessageTarget& target,
    mojom::ChannelType channel_type,
    const Message& message,
    binding::AsyncResponseType async_type,
    v8::Local<v8::Function> response_callback,
    mojom::MessagePortHost* message_port_host,
    mojo::PendingAssociatedRemote<mojom::MessagePort> message_port,
    mojo::PendingAssociatedReceiver<mojom::MessagePortHost>
        message_port_host_receiver) {
  v8::Isolate* isolate = script_context->isolate();
  v8::EscapableHandleScope handle_scope(isolate);

  DCHECK(new_port_id.is_opener);
  DCHECK_EQ(script_context->context_id(), new_port_id.context_id);

  OneTimeMessageContextData* data =
      GetPerContextData<OneTimeMessageContextData>(script_context->v8_context(),
                                                   kCreateIfMissing);
  DCHECK(data);

  v8::Local<v8::Promise> promise;
  bool wants_response = async_type != binding::AsyncResponseType::kNone;
  if (wants_response) {
    // If this is a promise based request no callback should have been passed
    // in.
    if (async_type == binding::AsyncResponseType::kPromise)
      DCHECK(response_callback.IsEmpty());

    APIRequestHandler::RequestDetails details =
        bindings_system_->api_system()->request_handler()->AddPendingRequest(
            script_context->v8_context(), async_type, response_callback,
            binding::ResultModifierFunction());
    OneTimeOpener& port = data->openers[new_port_id];
    port.request_id = details.request_id;
    port.async_type = async_type;
    port.channel_type = channel_type;
    promise = details.promise;
    DCHECK_EQ(async_type == binding::AsyncResponseType::kPromise,
              !promise.IsEmpty());
  }

  IPCMessageSender* ipc_sender = bindings_system_->GetIPCMessageSender();
  std::string channel_name;
  switch (channel_type) {
    case mojom::ChannelType::kSendRequest:
      channel_name = messaging_util::kSendRequestChannel;
      break;
    case mojom::ChannelType::kSendMessage:
      channel_name = messaging_util::kSendMessageChannel;
      break;
    case mojom::ChannelType::kNative:
      // Native messaging doesn't use channel names.
      break;
    case mojom::ChannelType::kConnect:
      // connect() calls aren't handled by the OneTimeMessageHandler.
      NOTREACHED();
  }

  ipc_sender->SendOpenMessageChannel(
      script_context, new_port_id, target, channel_type, channel_name,
      std::move(message_port), std::move(message_port_host_receiver));
  message_port_host->PostMessage(message);

  // If the sender doesn't provide a response callback, we can immediately
  // close the channel. Note: we only do this for extension messages, not
  // native apps.
  // TODO(devlin): This is because of some subtle ordering in the browser side,
  // where closing the channel after sending the message causes things to be
  // destroyed in the wrong order. That would be nice to fix.
  if (!wants_response && target.type != MessageTarget::NATIVE_APP) {
    message_port_host->ClosePort(/*close_channel=*/true);
  }

  return handle_scope.Escape(promise);
}

void OneTimeMessageHandler::AddReceiver(ScriptContext* script_context,
                                        const PortId& target_port_id,
                                        v8::Local<v8::Object> sender,
                                        const std::string& event_name) {
  DCHECK(!target_port_id.is_opener);
  DCHECK_NE(script_context->context_id(), target_port_id.context_id);

  v8::Isolate* isolate = script_context->isolate();
  v8::HandleScope handle_scope(isolate);
  v8::Local<v8::Context> context = script_context->v8_context();

  OneTimeMessageContextData* data =
      GetPerContextData<OneTimeMessageContextData>(context, kCreateIfMissing);
  DCHECK(data);
  DCHECK(!base::Contains(data->receivers, target_port_id));
  OneTimeReceiver& receiver = data->receivers[target_port_id];
  receiver.sender.Reset(isolate, sender);
  receiver.event_name = event_name;
}

void OneTimeMessageHandler::AddReceiverForTesting(
    ScriptContext* script_context,
    const PortId& target_port_id,
    v8::Local<v8::Object> sender,
    const std::string& event_name,
    mojo::PendingAssociatedRemote<mojom::MessagePort>& message_port_remote,
    mojo::PendingAssociatedReceiver<mojom::MessagePortHost>&
        message_port_host_receiver) {
  AddReceiver(script_context, target_port_id, sender, event_name);
  bindings_system_->messaging_service()->BindPortForTesting(  // IN-TEST
      script_context, target_port_id, message_port_remote,
      message_port_host_receiver);
}

bool OneTimeMessageHandler::DeliverMessage(ScriptContext* script_context,
                                           const Message& message,
                                           const PortId& target_port_id) {
  v8::Isolate* isolate = script_context->isolate();
  v8::HandleScope handle_scope(isolate);

  return target_port_id.is_opener
             ? DeliverReplyToOpener(script_context, message, target_port_id)
             : DeliverMessageToReceiver(script_context, message,
                                        target_port_id);
}

bool OneTimeMessageHandler::Disconnect(ScriptContext* script_context,
                                       const PortId& port_id,
                                       const std::string& error_message) {
  v8::Isolate* isolate = script_context->isolate();
  v8::HandleScope handle_scope(isolate);

  return port_id.is_opener
             ? DisconnectOpener(script_context, port_id, error_message)
             : DisconnectReceiver(script_context, port_id);
}

int OneTimeMessageHandler::GetPendingCallbackCountForTest(
    ScriptContext* script_context) {
  v8::Isolate* isolate = script_context->isolate();
  v8::HandleScope handle_scope(isolate);

  OneTimeMessageContextData* data =
      GetPerContextData<OneTimeMessageContextData>(script_context->v8_context(),
                                                   kDontCreateIfMissing);
  return data ? data->pending_callbacks.size() : 0;
}

bool OneTimeMessageHandler::DeliverMessageToReceiver(
    ScriptContext* script_context,
    const Message& message,
    const PortId& target_port_id) {
  DCHECK(!target_port_id.is_opener);

  v8::Isolate* isolate = script_context->isolate();
  v8::Local<v8::Context> context = script_context->v8_context();

  bool handled = false;

  OneTimeMessageContextData* data =
      GetPerContextData<OneTimeMessageContextData>(context,
                                                   kDontCreateIfMissing);
  if (!data)
    return handled;

  auto iter = data->receivers.find(target_port_id);
  if (iter == data->receivers.end())
    return handled;

  handled = true;
  OneTimeReceiver& port = iter->second;

  // This port is a receiver, so we invoke the onMessage event and provide a
  // callback through which the port can respond. The port stays open until we
  // receive a response.
  // TODO(devlin): With chrome.runtime.sendMessage, we actually require that a
  // listener indicate if they intend to respond asynchronously; otherwise we
  // close the port.

  auto callback = std::make_unique<OneTimeMessageCallback>(
      base::BindOnce(&OneTimeMessageHandler::OnOneTimeMessageResponse,
                     weak_factory_.GetWeakPtr(), target_port_id));
  v8::Local<v8::External> external = v8::External::New(isolate, callback.get());
  v8::Local<v8::Function> response_function;

  if (!v8::Function::New(context, &OneTimeMessageResponseHelper, external)
           .ToLocal(&response_function)) {
    NOTREACHED();
  }

  new GCCallback(
      script_context, response_function,
      base::BindOnce(&OneTimeMessageHandler::OnResponseCallbackCollected,
                     weak_factory_.GetWeakPtr(), script_context, target_port_id,
                     reinterpret_cast<CallbackID>(callback.get())),
      base::OnceClosure());

  port.response_function = v8::Global<v8::Function>(isolate, response_function);

  v8::HandleScope handle_scope(isolate);

  // The current port is a receiver. The parsing should be fail-safe if this is
  // a receiver for a native messaging host (i.e. the event name is
  // kOnConnectNativeEvent). This is because a native messaging host can send
  // malformed messages.
  std::string error;
  v8::Local<v8::Value> v8_message = messaging_util::MessageToV8(
      context, message,
      port.event_name == messaging_util::kOnConnectNativeEvent, &error);

  if (error.empty()) {
    v8::Local<v8::Object> v8_sender = port.sender.Get(isolate);
    v8::LocalVector<v8::Value> args(isolate,
                                    {v8_message, v8_sender, response_function});

    v8::Local<v8::Function> dispatch_callback_function;
    // For runtime.onMessage, we require that the listener indicate if they
    // intend to respond asynchronously. Check the results of the listeners.
    if (port.event_name == messaging_util::kOnMessageEvent) {
      auto dispatch_callback = std::make_unique<OneTimeMessageCallback>(
          base::BindOnce(&OneTimeMessageHandler::OnEventFired,
                         weak_factory_.GetWeakPtr(), target_port_id));
      v8::Local<v8::External> dispatch_external =
          v8::External::New(isolate, dispatch_callback.get());

      // TODO(crbug.com/40753031): Pull out the functionality of
      // OneTimeMessageResponseHelper wrapping the callback into a helper class
      // so it's clearer to understand this mechanism.
      if (!v8::Function::New(context, &OneTimeMessageResponseHelper,
                             dispatch_external)
               .ToLocal(&dispatch_callback_function)) {
        NOTREACHED();
      }
      data->pending_callbacks.push_back(std::move(dispatch_callback));
    }

    data->pending_callbacks.push_back(std::move(callback));
    bindings_system_->api_system()->event_handler()->FireEventInContext(
        port.event_name, context, &args, nullptr, dispatch_callback_function);
  } else {
    console::AddMessage(script_context,
                        blink::mojom::ConsoleMessageLevel::kError, error);
  }

  // Note: The context could be invalidated at this point!

  return handled;
}

bool OneTimeMessageHandler::DeliverReplyToOpener(ScriptContext* script_context,
                                                 const Message& message,
                                                 const PortId& target_port_id) {
  DCHECK(target_port_id.is_opener);

  v8::Local<v8::Context> v8_context = script_context->v8_context();
  bool handled = false;

  OneTimeMessageContextData* data =
      GetPerContextData<OneTimeMessageContextData>(v8_context,
                                                   kDontCreateIfMissing);
  if (!data)
    return handled;

  auto iter = data->openers.find(target_port_id);
  if (iter == data->openers.end())
    return handled;

  handled = true;

  // Note: make a copy of port, since we're about to free it.
  const OneTimeOpener port = iter->second;
  DCHECK_NE(-1, port.request_id);

  // We erase the opener now, since delivering the reply can cause JS to run,
  // which could either invalidate the context or modify the |openers|
  // collection (e.g., by sending another message).
  data->openers.erase(iter);

  // This port was the opener, so the message is the response from the
  // receiver. Invoke the callback and close the message port.
  v8::Isolate* isolate = script_context->isolate();

  // Parsing should be fail-safe for kNative channel type as native messaging
  // hosts can send malformed messages.
  std::string error;
  v8::Local<v8::Value> v8_message = messaging_util::MessageToV8(
      v8_context, message, port.channel_type == mojom::ChannelType::kNative,
      &error);

  if (v8_message.IsEmpty()) {
    // If the parsing fails, send back a v8::Undefined() message.
    v8_message = v8::Undefined(isolate);
  }

  v8::LocalVector<v8::Value> args(isolate, {v8_message});
  bindings_system_->api_system()->request_handler()->CompleteRequest(
      port.request_id, args, error);

  bindings_system_->messaging_service()->CloseMessagePort(
      script_context, target_port_id, /*close_channel=*/true);

  // Note: The context could be invalidated at this point!

  return handled;
}

bool OneTimeMessageHandler::DisconnectReceiver(ScriptContext* script_context,
                                               const PortId& port_id) {
  v8::Local<v8::Context> context = script_context->v8_context();
  bool handled = false;

  OneTimeMessageContextData* data =
      GetPerContextData<OneTimeMessageContextData>(context,
                                                   kDontCreateIfMissing);
  if (!data)
    return handled;

  auto iter = data->receivers.find(port_id);
  if (iter == data->receivers.end())
    return handled;

  handled = true;
  data->receivers.erase(iter);
  return handled;
}

bool OneTimeMessageHandler::DisconnectOpener(ScriptContext* script_context,
                                             const PortId& port_id,
                                             const std::string& error_message) {
  bool handled = false;

  v8::Local<v8::Context> v8_context = script_context->v8_context();
  OneTimeMessageContextData* data =
      GetPerContextData<OneTimeMessageContextData>(v8_context,
                                                   kDontCreateIfMissing);
  if (!data)
    return handled;

  auto iter = data->openers.find(port_id);
  if (iter == data->openers.end())
    return handled;

  handled = true;

  // Note: make a copy of port, since we're about to free it.
  const OneTimeOpener opener = iter->second;
  DCHECK_NE(-1, opener.request_id);

  // We erase the opener now, since delivering the reply can cause JS to run,
  // which could either invalidate the context or modify the |openers|
  // collection (e.g., by sending another message).
  data->openers.erase(iter);

  std::string error;
  // Set the error for the message port. If the browser supplies an error, we
  // always use that. Otherwise, the behavior is different for promise-based vs
  // callback-based channels.
  // For a promise-based channel, not receiving a response is fine (assuming the
  // listener didn't indicate it would send one) - the extension may simply be
  // waiting for confirmation that the message sent.
  // In the callback-based scenario, we use the presence of the callback as an
  // indication that the extension expected a specific response. This is an
  // unfortunate behavior difference that we keep for backwards-compatibility in
  // callback-based API calls.
  if (!error_message.empty()) {
    // If the browser supplied us with an error message, use that.
    error = error_message;
  } else if (opener.async_type == binding::AsyncResponseType::kCallback) {
    error = "The message port closed before a response was received.";
  }

  bindings_system_->api_system()->request_handler()->CompleteRequest(
      opener.request_id, v8::LocalVector<v8::Value>(v8_context->GetIsolate()),
      error);

  // Note: The context could be invalidated at this point!

  return handled;
}

void OneTimeMessageHandler::OnOneTimeMessageResponse(
    const PortId& port_id,
    gin::Arguments* arguments) {
  v8::Isolate* isolate = arguments->isolate();
  v8::Local<v8::Context> context = isolate->GetCurrentContext();

  // The listener may try replying after the context or the channel has been
  // closed. Fail gracefully.
  // TODO(devlin): At least in the case of the channel being closed (e.g.
  // because the listener did not indicate it would reply asynchronously), it
  // might be good to surface an error.
  OneTimeMessageContextData* data =
      GetPerContextData<OneTimeMessageContextData>(context,
                                                   kDontCreateIfMissing);
  if (!data)
    return;

  auto iter = data->receivers.find(port_id);
  if (iter == data->receivers.end())
    return;

  data->receivers.erase(iter);

  v8::Local<v8::Value> value;
  // We allow omitting the message argument (e.g., sendMessage()). Default the
  // value to undefined.
  if (arguments->Length() > 0)
    CHECK(arguments->GetNext(&value));
  else
    value = v8::Undefined(isolate);

  std::string error;
  std::unique_ptr<Message> message = messaging_util::MessageFromV8(
      context, value, port_id.serialization_format, &error);
  if (!message) {
    arguments->ThrowTypeError(error);
    return;
  }
  // If the MessagePortHost is still alive return the response. But the listener
  // might be replying after the channel has been closed.
  ScriptContext* script_context = GetScriptContextFromV8Context(context);
  if (auto* message_port_host =
          bindings_system_->messaging_service()->GetMessagePortHostIfExists(
              script_context, port_id)) {
    message_port_host->PostMessage(*message);
    bindings_system_->messaging_service()->CloseMessagePort(
        script_context, port_id, /*close_channel=*/true);
  }
}

void OneTimeMessageHandler::OnResponseCallbackCollected(
    ScriptContext* script_context,
    const PortId& port_id,
    CallbackID raw_callback) {
  // Note: we know |script_context| is still valid because the GC callback won't
  // be called after context invalidation.
  v8::HandleScope handle_scope(script_context->isolate());
  OneTimeMessageContextData* data =
      GetPerContextData<OneTimeMessageContextData>(script_context->v8_context(),
                                                   kDontCreateIfMissing);
  // ScriptContext invalidation and PerContextData cleanup happen "around" the
  // same time, but there aren't strict guarantees about ordering. It's possible
  // the data was collected.
  if (!data)
    return;

  auto iter = data->receivers.find(port_id);
  // The channel may already be closed (if the receiver replied before the reply
  // callback was collected).
  if (iter == data->receivers.end())
    return;

  data->receivers.erase(iter);

  // Since there is no way to call the callback anymore, we can remove it from
  // the pending callbacks.
  std::erase_if(
      data->pending_callbacks,
      [raw_callback](const std::unique_ptr<OneTimeMessageCallback>& callback) {
        return reinterpret_cast<CallbackID>(callback.get()) == raw_callback;
      });

  // Close the message port. There's no way to send a reply anymore. Don't
  // close the channel because another listener may reply.
  NativeRendererMessagingService* messaging_service =
      bindings_system_->messaging_service();
  messaging_service->CloseMessagePort(script_context, port_id,
                                      /*close_channel=*/false);
}

void OneTimeMessageHandler::OnEventFired(const PortId& port_id,
                                         gin::Arguments* arguments) {
  v8::Isolate* isolate = arguments->isolate();
  v8::Local<v8::Context> context = isolate->GetCurrentContext();

  v8::Local<v8::Value> result;
  if (arguments->Length() > 0) {
    CHECK(arguments->GetNext(&result));
  } else {
    result = v8::Undefined(isolate);
  }

  // The context could be tearing down by the time the event is fully
  // dispatched.
  OneTimeMessageContextData* data =
      GetPerContextData<OneTimeMessageContextData>(context,
                                                   kDontCreateIfMissing);
  if (!data)
    return;
  auto iter = data->receivers.find(port_id);
  // The channel may already be closed (if the listener replied).
  if (iter == data->receivers.end())
    return;

  OneTimeReceiver& port = iter->second;

  NativeRendererMessagingService* messaging_service =
      bindings_system_->messaging_service();

  if (CheckAndHandleAsyncListenerReply(isolate, context, result,
                                       port.response_function.Get(isolate))) {
    // Ensure the global function doesn't outlive port closing.
    port.response_function.SetWeak();
    // Inform the browser that one of the listeners said they would be replying
    // later and leave the channel open.
    ScriptContext* script_context = GetScriptContextFromV8Context(context);
    if (auto* message_port_host = messaging_service->GetMessagePortHostIfExists(
            script_context, port_id)) {
      message_port_host->ResponsePending();
    }
    return;
  }

  data->receivers.erase(iter);

  // The listener did not reply and did not indicate it would reply later from
  // any of its listeners. Close the message port. Don't close the channel
  // because another listener (in a separate context) may reply.
  ScriptContext* script_context = GetScriptContextFromV8Context(context);
  messaging_service->CloseMessagePort(script_context, port_id,
                                      /*close_channel=*/false);
}

}  // namespace extensions