Исходный код СУБД RuDB — свободной СУБД с открытым исходным кодом на базе PostgreSQL
rudb
2 days ago bd039d1e92813358c5c5a1e346b49074baf513f2
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
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
 
#include "EpContextDataReadCallback.h"
#include "EpContextDataReadPolicy.h"
#include "AsyncWorker.h"
#include <algorithm>
#include <atomic>
#include <chrono>
#include <cmath>
#include <cstring>
#include <limits>
#include <stdexcept>
#include <utility>
 
using namespace facebook::jsi;
 
namespace onnxruntimejsi {
 
namespace {
 
OrtStatus* makeStatus(OrtErrorCode code, const std::string& message) noexcept {
  return Ort::GetApi().CreateStatus(code, message.c_str());
}
 
Value getTypedArrayProperty(Runtime& runtime,
                            const Object& typedArrayPrototype,
                            const Object& typedArray,
                            const char* propertyName) {
  auto objectConstructor =
      runtime.global().getPropertyAsObject(runtime, "Object");
  auto getOwnPropertyDescriptor = objectConstructor.getPropertyAsFunction(
      runtime, "getOwnPropertyDescriptor");
  auto descriptor =
      getOwnPropertyDescriptor
          .call(runtime, typedArrayPrototype,
                String::createFromAscii(runtime, propertyName))
          .asObject(runtime);
  auto getter = descriptor.getPropertyAsFunction(runtime, "get");
  return getter.callWithThis(runtime, typedArray);
}
 
bool toViewIndex(double value, size_t& result) noexcept {
  if (!std::isfinite(value) || value < 0 || std::trunc(value) != value ||
      value >= static_cast<double>(std::numeric_limits<size_t>::max())) {
    return false;
  }
  result = static_cast<size_t>(value);
  return true;
}
 
class VectorMutableBuffer final : public MutableBuffer {
 public:
  explicit VectorMutableBuffer(std::vector<uint8_t> data)
      : data_(std::move(data)) {}
 
  size_t size() const override { return data_.size(); }
  uint8_t* data() override { return data_.data(); }
 
 private:
  std::vector<uint8_t> data_;
};
 
class EpContextDataReadTestCallInvoker final
    : public facebook::react::CallInvoker,
      public std::enable_shared_from_this<EpContextDataReadTestCallInvoker> {
 public:
  explicit EpContextDataReadTestCallInvoker(const std::shared_ptr<Env>& env)
      : env_(env) {}
 
  void invokeAsync(facebook::react::CallFunc&& func) override {
    auto env = env_.lock();
    auto self = shared_from_this();
    if (!env || !env->runOnJsThread([self, func = std::move(func)]() {
          if (!self->discardDispatch_.load()) {
            func();
          }
        })) {
      throw std::runtime_error("ONNX Runtime JSI bindings were torn down");
    }
    {
      std::lock_guard<std::mutex> lock(dispatchMutex_);
      dispatchQueued_ = true;
    }
    dispatchCv_.notify_all();
  }
 
  void invokeSync(facebook::react::CallFunc&&) override {
    throw std::logic_error("The callback test bridge only supports asynchronous dispatch");
  }
 
  bool waitForDispatch() {
    std::unique_lock<std::mutex> lock(dispatchMutex_);
    return dispatchCv_.wait_for(lock, std::chrono::seconds(5),
                                [this] { return dispatchQueued_; });
  }
 
  void discardDispatch() noexcept { discardDispatch_.store(true); }
 
 private:
  std::weak_ptr<Env> env_;
  std::mutex dispatchMutex_;
  std::condition_variable dispatchCv_;
  bool dispatchQueued_ = false;
  std::atomic<bool> discardDispatch_{false};
};
 
class EpContextDataReadTestWorker final : public AsyncWorker {
 public:
  EpContextDataReadTestWorker(
      Runtime& runtime, std::shared_ptr<Env> env,
      std::shared_ptr<EpContextDataReadCallback> callback,
      std::shared_ptr<Env> callbackEnv,
      std::shared_ptr<EpContextDataReadTestCallInvoker> callbackInvoker,
      std::string name)
      : AsyncWorker(runtime, std::move(env)),
        callback_(std::move(callback)),
        callbackEnv_(std::move(callbackEnv)),
        callbackInvoker_(std::move(callbackInvoker)),
        name_(std::move(name)) {}
 
  ~EpContextDataReadTestWorker() override { abortAndJoin(); }
 
  Value get(Runtime& runtime, const PropNameID& name) override {
    const std::string property = name.utf8(runtime);
    if (property == "abort") {
      auto self = std::static_pointer_cast<EpContextDataReadTestWorker>(
          shared_from_this());
      return Function::createFromHostFunction(
          runtime, name, 0,
          [self](Runtime&, const Value&, const Value*, size_t) {
            self->requestAbort();
            return Value::undefined();
          });
    }
    if (property == "forceInvalidate") {
      auto self = std::static_pointer_cast<EpContextDataReadTestWorker>(
          shared_from_this());
      return Function::createFromHostFunction(
          runtime, name, 0,
          [self](Runtime&, const Value&, const Value*, size_t) {
            self->callback_->invalidate();
            return Value::undefined();
          });
    }
    if (property == "invalidateEnv") {
      auto self = std::static_pointer_cast<EpContextDataReadTestWorker>(
          shared_from_this());
      return Function::createFromHostFunction(
          runtime, name, 0,
          [self](Runtime&, const Value&, const Value*, size_t) {
            self->callbackInvoker_->discardDispatch();
            self->callbackEnv_->invalidate();
            return Value::undefined();
          });
    }
    if (property == "waitForDispatch") {
      auto self = std::static_pointer_cast<EpContextDataReadTestWorker>(
          shared_from_this());
      return Function::createFromHostFunction(
          runtime, name, 0,
          [self](Runtime& runtime, const Value&, const Value*, size_t) {
            if (!self->callbackInvoker_->waitForDispatch()) {
              throw JSError(runtime, "The callback bridge worker did not queue its read");
            }
            return Value::undefined();
          });
    }
    if (property == "isFinished") {
      return Value(finished_.load());
    }
    if (property == "wasAborted") {
      return Value(aborted_.load());
    }
    return Value::undefined();
  }
 
 protected:
  void execute() override {
    Ort::AllocatorWithDefaultOptions allocator;
    void* buffer = nullptr;
    size_t dataSize = 0;
    OrtStatus* status = EpContextDataReadCallback::read(
        callback_.get(), name_.c_str(), allocator, &buffer, &dataSize);
    if (status != nullptr) {
      const char* message = Ort::GetApi().GetErrorMessage(status);
      std::string error = message == nullptr ? "EPContext callback failed." : message;
      Ort::GetApi().ReleaseStatus(status);
      throw std::runtime_error(error);
    }
 
    try {
      if (dataSize > 0) {
        const auto* bytes = static_cast<const uint8_t*>(buffer);
        data_.assign(bytes, bytes + dataSize);
      }
    } catch (...) {
      if (buffer != nullptr) {
        allocator.Free(buffer);
      }
      throw;
    }
    if (buffer != nullptr) {
      allocator.Free(buffer);
    }
  }
 
  Value onResolve(Runtime& runtime) override {
    callback_->invalidate();
    ArrayBuffer buffer(runtime,
                       std::make_shared<VectorMutableBuffer>(std::move(data_)));
    auto uint8Array = runtime.global().getPropertyAsFunction(runtime, "Uint8Array");
    return uint8Array.callAsConstructor(runtime, Value(runtime, std::move(buffer)));
  }
 
  Value onReject(Runtime& runtime, const std::string& error) override {
    callback_->invalidate();
    return String::createFromUtf8(runtime, error);
  }
 
  void onAbort() override {
    aborted_.store(true);
    callback_->invalidate();
  }
 
  void onFinished() noexcept override { finished_.store(true); }
 
 private:
  std::shared_ptr<EpContextDataReadCallback> callback_;
  std::shared_ptr<Env> callbackEnv_;
  std::shared_ptr<EpContextDataReadTestCallInvoker> callbackInvoker_;
  std::string name_;
  std::vector<uint8_t> data_;
  std::atomic<bool> finished_{false};
  std::atomic<bool> aborted_{false};
};
 
}  // namespace
 
Value EpContextDataReadCallback::testCallbackBridge(
    Runtime& runtime, const Value* arguments, size_t count,
    const std::shared_ptr<Env>& env) {
  if (count != 3 || !arguments[0].isObject() ||
      !arguments[0].asObject(runtime).isFunction(runtime) ||
      !arguments[1].isNumber() || !arguments[2].isString()) {
    throw JSError(runtime,
                  "Expected callback, maxDataSize, and name for the test bridge");
  }
  const double rawMaxDataSize = arguments[1].asNumber();
  if (!std::isfinite(rawMaxDataSize) || rawMaxDataSize < 1 ||
      std::trunc(rawMaxDataSize) != rawMaxDataSize ||
      rawMaxDataSize >=
          static_cast<double>(std::numeric_limits<size_t>::max())) {
    throw JSError(runtime, "maxDataSize must be a positive integer");
  }
 
  auto callback = std::make_shared<Function>(
      arguments[0].asObject(runtime).asFunction(runtime));
  // Isolate listener teardown from the app's Env so the test can keep polling and reporting results.
  auto callbackInvoker = std::make_shared<EpContextDataReadTestCallInvoker>(env);
  auto callbackEnv = std::make_shared<Env>(callbackInvoker);
  auto state = std::make_shared<EpContextDataReadCallback>(
      callbackEnv, runtime, std::move(callback),
      static_cast<size_t>(rawMaxDataSize));
  callbackEnv->addTeardownListener(state);
  env->addTeardownListener(state);
  auto worker = std::make_shared<EpContextDataReadTestWorker>(
      runtime, env, std::move(state), std::move(callbackEnv),
      std::move(callbackInvoker),
      arguments[2].asString(runtime).utf8(runtime));
  auto promise = worker->toPromise(runtime);
  promise.asObject(runtime).setProperty(
      runtime, "__testWorker", Object::createFromHostObject(runtime, worker));
  return promise;
}
 
bool EpContextDataReadCallback::PendingCall::isFinished() noexcept {
  std::lock_guard<std::mutex> lock(mutex);
  return finished;
}
 
void EpContextDataReadCallback::PendingCall::finish(
    CallStatus newStatus, std::string newError,
    std::vector<uint8_t> newData) noexcept {
  {
    std::lock_guard<std::mutex> lock(mutex);
    if (finished) return;
    finished = true;
    status = newStatus;
    error = std::move(newError);
    data = std::move(newData);
  }
  cv.notify_all();
}
 
void EpContextDataReadCallback::PendingCall::wait() {
  std::unique_lock<std::mutex> lock(mutex);
  cv.wait(lock, [this] { return finished; });
}
 
EpContextDataReadCallback::EpContextDataReadCallback(
    std::shared_ptr<Env> env, Runtime& runtime,
    std::shared_ptr<Function> callback, size_t maxDataSize)
    : env_(std::move(env)),
      maxDataSize_(maxDataSize),
      runtime_(&runtime),
      callback_(std::move(callback)) {}
 
EpContextDataReadCallback::~EpContextDataReadCallback() {
  invalidate();
 
  std::shared_ptr<Function> callback;
  {
    std::lock_guard<std::mutex> lock(stateMutex_);
    callback.swap(callback_);
  }
  if (callback && !env_->isJsThread()) {
    // Releasing a jsi::Function writes through the runtime that created it. Off the JS thread that
    // runtime may already be gone, so hand the last reference to a deliberate leak rather than
    // invalidate a pointer into freed memory. invalidate() drops the reference on the JS thread in
    // every expected teardown path, so this is a safety net rather than a routine leak.
    new std::shared_ptr<Function>(std::move(callback));
  }
}
 
std::shared_ptr<EpContextDataReadCallback>
EpContextDataReadCallback::createAndRegister(Runtime& runtime,
                                             const Object& options,
                                             const std::shared_ptr<Env>& env,
                                             Ort::SessionOptions& sessionOptions) {
  if (!options.hasProperty(runtime, "epContextDataRead")) {
    return nullptr;
  }
  auto value = options.getProperty(runtime, "epContextDataRead");
  if (value.isUndefined() || value.isNull()) {
    return nullptr;
  }
  if (!value.isObject()) {
    throw JSError(runtime,
                  "session option \"epContextDataRead\" must be an object");
  }
  auto config = value.asObject(runtime);
 
  auto callbackValue = config.getProperty(runtime, "callback");
  if (!callbackValue.isObject() ||
      !callbackValue.asObject(runtime).isFunction(runtime)) {
    throw JSError(
        runtime,
        "session option \"epContextDataRead.callback\" must be a function");
  }
 
  auto maxDataSizeValue = config.getProperty(runtime, "maxDataSize");
  if (!maxDataSizeValue.isNumber()) {
    throw JSError(runtime,
                  "session option \"epContextDataRead.maxDataSize\" is "
                  "required and must be a number");
  }
  auto maxDataSize = parseMaxDataSize(maxDataSizeValue.asNumber());
  if (!maxDataSize.ok) {
    throw JSError(runtime, maxDataSize.error);
  }
 
  auto state = std::make_shared<EpContextDataReadCallback>(
      env, runtime,
      std::make_shared<Function>(
          callbackValue.asObject(runtime).asFunction(runtime)),
      maxDataSize.value);
 
  // Publish the state only once ONNX Runtime accepted it. If the setter throws, `state` is
  // destroyed here on the JS thread and nothing observed a half-registered callback.
  sessionOptions.SetEpContextDataReadFunc(&EpContextDataReadCallback::read,
                                          state.get());
 
  env->addTeardownListener(state);
  return state;
}
 
OrtStatus* ORT_API_CALL EpContextDataReadCallback::read(
    void* state, const char* name, OrtAllocator* allocator, void** buffer,
    size_t* dataSize) noexcept {
  // Initialize the outputs before anything that can fail so ORT never observes stale values.
  if (buffer != nullptr) {
    *buffer = nullptr;
  }
  if (dataSize != nullptr) {
    *dataSize = 0;
  }
 
  if (state == nullptr || name == nullptr || allocator == nullptr ||
      buffer == nullptr || dataSize == nullptr) {
    return makeStatus(
        ORT_INVALID_ARGUMENT,
        "EPContext data read callback received an invalid argument");
  }
 
  try {
    return static_cast<EpContextDataReadCallback*>(state)->readImpl(
        std::string(name), allocator, buffer, dataSize);
  } catch (const std::exception& e) {
    return makeStatus(ORT_FAIL, "EPContext data read callback failed: " +
                                    std::string(e.what()));
  } catch (...) {
    return makeStatus(
        ORT_FAIL, "EPContext data read callback failed with an unknown error");
  }
}
 
OrtStatus* EpContextDataReadCallback::readImpl(const std::string& name,
                                               OrtAllocator* allocator,
                                               void** buffer,
                                               size_t* dataSize) {
  // ORT does not serialize calls made by different EP instances or worker threads.
  std::lock_guard<std::mutex> callLock(callMutex_);
 
  auto pending = std::make_shared<PendingCall>();
 
  if (env_->isJsThread()) {
    // Dispatching from the JS thread would deadlock, so run inline. A single state object belongs
    // to a single session load, which either runs entirely on the JS thread or entirely off it, so
    // this branch cannot overlap with a thread waiting for the JS thread to drain.
    {
      std::lock_guard<std::mutex> lock(stateMutex_);
      if (!valid_) {
        return makeStatus(ORT_FAIL,
                          "EPContext data read callback was released before "
                          "\"" +
                              name + "\" could be read");
      }
    }
    invokeOnJsThread(name, *pending);
  } else {
    {
      std::lock_guard<std::mutex> lock(stateMutex_);
      if (!valid_) {
        return makeStatus(ORT_FAIL,
                          "EPContext data read callback was released before "
                          "\"" +
                              name + "\" could be read");
      }
      pending_.push_back(pending);
    }
 
    std::weak_ptr<EpContextDataReadCallback> weakSelf = weak_from_this();
    const bool queued = env_->runOnJsThread([weakSelf, pending, name]() {
      if (pending->isFinished()) return;
      auto self = weakSelf.lock();
      if (!self) {
        pending->finish(CallStatus::Failed,
                        "EPContext data read callback was released before \"" +
                            name + "\" could be read");
        return;
      }
      self->invokeOnJsThread(name, *pending);
    });
 
    if (!queued) {
      unregisterPending(pending);
      return makeStatus(ORT_FAIL,
                        "ONNX Runtime JSI bindings were torn down before \"" +
                            name + "\" could be read");
    }
 
    // invalidate() finishes every registered call, so teardown cannot leave this thread blocked.
    pending->wait();
    unregisterPending(pending);
  }
 
  CallStatus status;
  std::string error;
  std::vector<uint8_t> data;
  {
    std::lock_guard<std::mutex> lock(pending->mutex);
    status = pending->status;
    error = std::move(pending->error);
    data = std::move(pending->data);
  }
 
  switch (status) {
    case CallStatus::Ok:
      break;
    case CallStatus::InvalidArgument:
      return makeStatus(ORT_INVALID_ARGUMENT, error);
    case CallStatus::Failed:
      return makeStatus(ORT_FAIL, error);
  }
 
  // An empty payload is reported as a null buffer, not as a zero-sized allocation.
  if (data.empty()) {
    return nullptr;
  }
 
  // The limit is already enforced on the JS thread; re-check before touching the allocator so the
  // guarantee holds even if the two paths ever diverge.
  auto sizeCheck = checkDataSize(data.size(), maxDataSize_, name);
  if (!sizeCheck.ok) {
    return makeStatus(ORT_INVALID_ARGUMENT, sizeCheck.error);
  }
 
  void* allocated = allocator->Alloc(allocator, data.size());
  if (allocated == nullptr) {
    return makeStatus(ORT_FAIL, "failed to allocate " +
                                    std::to_string(data.size()) +
                                    " bytes for EPContext data \"" + name +
                                    "\"");
  }
  std::memcpy(allocated, data.data(), data.size());
  *buffer = allocated;
  *dataSize = data.size();
  return nullptr;
}
 
void EpContextDataReadCallback::invokeOnJsThread(const std::string& name,
                                                 PendingCall& pending) noexcept {
  Runtime* runtime = nullptr;
  std::shared_ptr<Function> callback;
  {
    std::lock_guard<std::mutex> lock(stateMutex_);
    if (!valid_ || runtime_ == nullptr || !callback_) {
      pending.finish(CallStatus::Failed,
                     "EPContext data read callback was released before \"" +
                         name + "\" could be read");
      return;
    }
    runtime = runtime_;
    callback = callback_;
  }
 
  try {
    auto result =
        callback->call(*runtime, String::createFromUtf8(*runtime, name));
    if (!result.isObject()) {
      pending.finish(CallStatus::InvalidArgument,
                     "session option \"epContextDataRead.callback\" must "
                     "return a Uint8Array for \"" +
                         name + "\"");
      return;
    }
 
    auto resultObject = result.asObject(*runtime);
    auto uint8ArrayConstructor =
        runtime->global().getPropertyAsFunction(*runtime, "Uint8Array");
    if (!resultObject.instanceOf(*runtime, uint8ArrayConstructor)) {
      pending.finish(CallStatus::InvalidArgument,
                     "session option \"epContextDataRead.callback\" must "
                     "return a Uint8Array for \"" +
                         name + "\"");
      return;
    }
 
    auto uint8ArrayPrototype =
        uint8ArrayConstructor.getPropertyAsObject(*runtime, "prototype");
    auto objectConstructor =
        runtime->global().getPropertyAsObject(*runtime, "Object");
    auto getPrototypeOf =
        objectConstructor.getPropertyAsFunction(*runtime, "getPrototypeOf");
    auto typedArrayPrototype =
        getPrototypeOf.call(*runtime, uint8ArrayPrototype).asObject(*runtime);
 
    auto arrayBufferValue = getTypedArrayProperty(
        *runtime, typedArrayPrototype, resultObject, "buffer");
    if (!arrayBufferValue.isObject() ||
        !arrayBufferValue.asObject(*runtime).isArrayBuffer(*runtime)) {
      pending.finish(
          CallStatus::InvalidArgument,
          "session option \"epContextDataRead.callback\" returned a "
          "Uint8Array with an invalid backing buffer for \"" +
              name + "\"");
      return;
    }
    auto arrayBuffer =
        arrayBufferValue.asObject(*runtime).getArrayBuffer(*runtime);
 
    size_t byteOffset = 0;
    size_t byteLength = 0;
    if (!toViewIndex(getTypedArrayProperty(*runtime, typedArrayPrototype,
                                           resultObject, "byteOffset")
                         .asNumber(),
                     byteOffset) ||
        !toViewIndex(getTypedArrayProperty(*runtime, typedArrayPrototype,
                                           resultObject, "byteLength")
                         .asNumber(),
                     byteLength)) {
      pending.finish(CallStatus::InvalidArgument,
                     "session option \"epContextDataRead.callback\" returned a "
                     "Uint8Array with invalid view bounds for \"" +
                         name + "\"");
      return;
    }
    if (byteOffset > arrayBuffer.size(*runtime) ||
        byteLength > arrayBuffer.size(*runtime) - byteOffset) {
      pending.finish(CallStatus::InvalidArgument,
                     "session option \"epContextDataRead.callback\" returned a "
                     "Uint8Array with an unreadable range for \"" +
                         name + "\"");
      return;
    }
 
    // Reject an oversized payload before copying and before any allocator call.
    auto sizeCheck = checkDataSize(byteLength, maxDataSize_, name);
    if (!sizeCheck.ok) {
      pending.finish(CallStatus::InvalidArgument, sizeCheck.error);
      return;
    }
 
    // Copy while still on the JS thread: the backing store belongs to JavaScript and may be
    // collected or moved once this function returns.
    std::vector<uint8_t> data;
    if (byteLength > 0) {
      const uint8_t* begin = arrayBuffer.data(*runtime) + byteOffset;
      data.assign(begin, begin + byteLength);
    }
    pending.finish(CallStatus::Ok, {}, std::move(data));
  } catch (const JSError& e) {
    pending.finish(CallStatus::Failed,
                   "session option \"epContextDataRead.callback\" threw while "
                   "reading \"" +
                       name + "\": " + e.getMessage());
  } catch (const std::exception& e) {
    pending.finish(CallStatus::Failed,
                   "session option \"epContextDataRead.callback\" failed while "
                   "reading \"" +
                       name + "\": " + std::string(e.what()));
  } catch (...) {
    pending.finish(CallStatus::Failed,
                   "session option \"epContextDataRead.callback\" failed with "
                   "an unknown error while reading \"" +
                       name + "\"");
  }
}
 
void EpContextDataReadCallback::unregisterPending(
    const std::shared_ptr<PendingCall>& pending) noexcept {
  std::lock_guard<std::mutex> lock(stateMutex_);
  pending_.erase(std::remove(pending_.begin(), pending_.end(), pending),
                 pending_.end());
}
 
void EpContextDataReadCallback::invalidate() noexcept {
  std::vector<std::shared_ptr<PendingCall>> pending;
  std::shared_ptr<Function> callback;
  const bool onJsThread = env_->isJsThread();
  {
    std::lock_guard<std::mutex> lock(stateMutex_);
    if (!valid_) return;
    valid_ = false;
    runtime_ = nullptr;
    pending.swap(pending_);
    if (onJsThread) {
      // Safe to drop the JS function here: the runtime is alive on its own thread.
      callback.swap(callback_);
    }
  }
 
  for (auto& call : pending) {
    call->finish(CallStatus::Failed,
                 "EPContext data read callback was released while a read was "
                 "in flight");
  }
}
 
}  // namespace onnxruntimejsi