Исходный код СУБД 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
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
 
#include "onnxruntime_cxx_api.h"
#include <napi.h>
 
#include <cmath>
#include <condition_variable>
#include <cstdint>
#include <cstring>
#include <limits>
#include <string>
#include <utility>
#include <vector>
 
#include "common.h"
#include "ep_context_data_read_helper.h"
 
namespace {
 
// Number.MAX_SAFE_INTEGER. A larger value cannot round-trip through a JavaScript number.
constexpr double kMaxSafeInteger = 9007199254740991.0;
 
// RAII owner for a buffer allocated through the OrtAllocator that ONNX Runtime supplies to the read
// callback. The bytes are only detached (handed over to ONNX Runtime) once the whole callback succeeded.
struct AllocatorBuffer {
  OrtAllocator* allocator = nullptr;
  void* data = nullptr;
  size_t size = 0;
 
  AllocatorBuffer() = default;
  AllocatorBuffer(const AllocatorBuffer&) = delete;
  AllocatorBuffer& operator=(const AllocatorBuffer&) = delete;
  ~AllocatorBuffer() { Reset(); }
 
  void Reset() noexcept {
    if (data != nullptr && allocator != nullptr) {
      allocator->Free(allocator, data);
    }
    data = nullptr;
    size = 0;
  }
 
  void* Detach() noexcept {
    void* detached = data;
    data = nullptr;
    return detached;
  }
};
 
OrtStatus* MakeOrtStatus(OrtErrorCode code, const std::string& message) noexcept {
  return Ort::GetApi().CreateStatus(code, message.c_str());
}
 
}  // namespace
 
// One read request. The requesting ONNX Runtime thread blocks on `Wait()` until the JavaScript thread
// has produced a result or reported a failure.
struct EpContextDataReadState::CallItem {
  // inputs
  const char* name = nullptr;
  OrtAllocator* allocator = nullptr;
  size_t max_data_size = 0;
 
  // outputs
  AllocatorBuffer buffer;
  bool succeeded = false;
  OrtErrorCode error_code = ORT_FAIL;
  std::string error_message;
 
  std::mutex mutex;
  std::condition_variable cv;
  bool completed = false;
 
  void Succeed() noexcept { succeeded = true; }
 
  void Fail(OrtErrorCode code, std::string message) noexcept {
    buffer.Reset();
    succeeded = false;
    error_code = code;
    error_message = std::move(message);
  }
 
  void Complete() noexcept {
    {
      std::lock_guard<std::mutex> lock{mutex};
      completed = true;
    }
    cv.notify_all();
  }
 
  void Wait() noexcept {
    std::unique_lock<std::mutex> lock{mutex};
    cv.wait(lock, [this] { return completed; });
  }
};
 
EpContextDataReadState::EpContextDataReadState(size_t maxDataSize)
    : max_data_size_{maxDataSize}, owner_thread_id_{std::this_thread::get_id()} {}
 
EpContextDataReadState::~EpContextDataReadState() {
  // The thread-safe function finalizer already dropped `callback_ref_` on the JavaScript thread, so no
  // N-API reference is touched here. This destructor may run long after environment teardown.
  Release();
}
 
std::shared_ptr<EpContextDataReadState> EpContextDataReadState::Create(Napi::Env env, Napi::Function callback,
                                                                       size_t maxDataSize) {
  std::shared_ptr<EpContextDataReadState> state{new EpContextDataReadState{maxDataSize}};
 
  state->callback_ref_ = Napi::Persistent(callback);
  // The reference is always dropped explicitly (finalizer or the failure path below). Suppressing the
  // destructor guarantees that the last shared_ptr release never calls into N-API.
  state->callback_ref_.SuppressDestruct();
 
  Napi::String resourceName = Napi::String::New(env, "onnxruntime.epContextDataRead");
 
  // The finalizer data keeps the state alive until N-API is done with the thread-safe function, so the
  // finalizer can never observe a destroyed object, including during environment teardown.
  auto* finalizeData = new std::shared_ptr<EpContextDataReadState>{state};
 
  napi_threadsafe_function tsfn = nullptr;
  napi_status status = napi_create_threadsafe_function(
      env, callback, /* async_resource */ nullptr, resourceName,
      /* max_queue_size */ 0, /* initial_thread_count */ 1, finalizeData,
      &EpContextDataReadState::FinalizeThreadSafeFunction, state.get(), &EpContextDataReadState::CallJs, &tsfn);
  if (status != napi_ok) {
    delete finalizeData;
    state->callback_ref_.Reset();
    ORT_NAPI_THROW_ERROR(env, "Failed to register 'sessionOptions.epContextDataRead.callback'.");
  }
 
  state->tsfn_.store(tsfn, std::memory_order_release);
  state->js_available_.store(true, std::memory_order_release);
 
  // The callback must not keep the Node.js event loop alive on its own: the pending asynchronous session
  // construction already holds the event loop open for as long as callbacks can be delivered.
  napi_unref_threadsafe_function(env, tsfn);
 
  return state;
}
 
void EpContextDataReadState::Release() noexcept {
  if (tsfn_released_.exchange(true, std::memory_order_acq_rel)) {
    return;
  }
  js_available_.store(false, std::memory_order_release);
 
  napi_threadsafe_function tsfn = tsfn_.exchange(nullptr, std::memory_order_acq_rel);
  if (tsfn != nullptr) {
    napi_release_threadsafe_function(tsfn, napi_tsfn_release);
  }
}
 
void EpContextDataReadState::OnThreadSafeFunctionFinalize() noexcept {
  // Runs on the JavaScript thread while the environment is still usable, including during teardown.
  js_available_.store(false, std::memory_order_release);
  tsfn_released_.store(true, std::memory_order_release);
  tsfn_.store(nullptr, std::memory_order_release);
  callback_ref_.Reset();
}
 
void EpContextDataReadState::FinalizeThreadSafeFunction(napi_env /* env */, void* finalizeData, void* /* hint */) {
  auto* holder = static_cast<std::shared_ptr<EpContextDataReadState>*>(finalizeData);
  if (holder == nullptr) {
    return;
  }
  (*holder)->OnThreadSafeFunctionFinalize();
  delete holder;
}
 
void EpContextDataReadState::RunCallback(napi_env rawEnv, napi_value jsCallback, CallItem& item) noexcept {
  try {
    Napi::Env env{rawEnv};
    Napi::HandleScope scope{env};
 
    Napi::Function callback{env, jsCallback};
    Napi::Value result = callback.Call({Napi::String::New(env, item.name)});
 
    // A Node.js Buffer is a Uint8Array, so it is accepted by this check. Any other type is not.
    if (!result.IsTypedArray() || result.As<Napi::TypedArray>().TypedArrayType() != napi_uint8_array) {
      item.Fail(ORT_INVALID_ARGUMENT,
                MakeString("'sessionOptions.epContextDataRead.callback' must return a Uint8Array, but it returned "
                           "another type for '",
                           item.name, "'."));
      return;
    }
 
    auto typedArray = result.As<Napi::TypedArray>();
    const size_t byteLength = typedArray.ByteLength();
    if (byteLength > item.max_data_size) {
      item.Fail(ORT_INVALID_ARGUMENT,
                MakeString("'sessionOptions.epContextDataRead.callback' returned ", byteLength, " bytes for '",
                           item.name, "', which exceeds 'sessionOptions.epContextDataRead.maxDataSize' (",
                           item.max_data_size, ")."));
      return;
    }
 
    // An empty payload is reported as {nullptr, 0}; nothing is allocated for it.
    if (byteLength == 0) {
      item.Succeed();
      return;
    }
 
    void* allocated = item.allocator->Alloc(item.allocator, byteLength);
    if (allocated == nullptr) {
      item.Fail(ORT_FAIL, MakeString("Failed to allocate ", byteLength, " bytes for the EPContext data of '",
                                     item.name, "'."));
      return;
    }
    item.buffer.allocator = item.allocator;
    item.buffer.data = allocated;
    item.buffer.size = byteLength;
 
    const auto* source =
        reinterpret_cast<const uint8_t*>(typedArray.ArrayBuffer().Data()) + typedArray.ByteOffset();
    std::memcpy(allocated, source, byteLength);
    item.Succeed();
  } catch (Napi::Error const& e) {
    item.Fail(ORT_FAIL, MakeString("'sessionOptions.epContextDataRead.callback' failed for '", item.name,
                                   "': ", e.Message()));
  } catch (std::exception const& e) {
    item.Fail(ORT_FAIL, MakeString("'sessionOptions.epContextDataRead.callback' failed for '", item.name,
                                   "': ", e.what()));
  } catch (...) {
    item.Fail(ORT_FAIL, MakeString("'sessionOptions.epContextDataRead.callback' failed for '", item.name,
                                   "' with an unknown error."));
  }
}
 
void EpContextDataReadState::CallJs(napi_env env, napi_value jsCallback, void* /* context */, void* data) {
  auto* payload = static_cast<std::shared_ptr<CallItem>*>(data);
  if (payload == nullptr) {
    return;
  }
  std::shared_ptr<CallItem> item = *payload;
  delete payload;
 
  if (env == nullptr || jsCallback == nullptr) {
    // N-API drains the queue with null arguments when the environment can no longer run JavaScript.
    item->Fail(ORT_FAIL,
               "The JavaScript environment was torn down before 'sessionOptions.epContextDataRead.callback' ran.");
  } else {
    RunCallback(env, jsCallback, *item);
  }
  item->Complete();
}
 
void EpContextDataReadState::InvokeOnOwnerThread(CallItem& item) noexcept {
  try {
    Napi::Env env = callback_ref_.Env();
    Napi::HandleScope scope{env};
    RunCallback(env, callback_ref_.Value(), item);
  } catch (...) {
    item.Fail(ORT_FAIL, "Failed to enter the JavaScript scope for 'sessionOptions.epContextDataRead.callback'.");
  }
}
 
OrtStatus* EpContextDataReadState::Invoke(const char* name, OrtAllocator* allocator, void** buffer,
                                          size_t* data_size) noexcept {
  // The outputs are initialized before anything else runs, so ONNX Runtime never observes stale values.
  if (buffer != nullptr) {
    *buffer = nullptr;
  }
  if (data_size != nullptr) {
    *data_size = 0;
  }
  if (buffer == nullptr || data_size == nullptr || name == nullptr || allocator == nullptr) {
    return MakeOrtStatus(ORT_INVALID_ARGUMENT,
                         "Invalid argument passed to the 'sessionOptions.epContextDataRead' callback.");
  }
 
  // ONNX Runtime does not serialize calls from different EP instances or worker threads, but the
  // JavaScript callback is user code that expects one call at a time.
  std::lock_guard<std::mutex> callLock{call_mutex_};
 
  if (!js_available_.load(std::memory_order_acquire)) {
    return MakeOrtStatus(ORT_FAIL, "'sessionOptions.epContextDataRead.callback' is no longer available.");
  }
 
  auto item = std::make_shared<CallItem>();
  item->name = name;
  item->allocator = allocator;
  item->max_data_size = max_data_size_;
 
  if (std::this_thread::get_id() == owner_thread_id_) {
    // ONNX Runtime can only reach this point on the JavaScript thread while that thread is inside a
    // native call made on its behalf, which is a context where N-API permits calling into JavaScript.
    // A thread-safe function call would deadlock here because the queued item could never be drained.
    InvokeOnOwnerThread(*item);
  } else {
    napi_threadsafe_function tsfn = tsfn_.load(std::memory_order_acquire);
    if (tsfn == nullptr || napi_acquire_threadsafe_function(tsfn) != napi_ok) {
      return MakeOrtStatus(ORT_FAIL, "'sessionOptions.epContextDataRead.callback' is no longer available.");
    }
 
    auto* payload = new std::shared_ptr<CallItem>{item};
    napi_status status = napi_call_threadsafe_function(tsfn, payload, napi_tsfn_blocking);
    if (status != napi_ok) {
      delete payload;
      napi_release_threadsafe_function(tsfn, napi_tsfn_release);
      return MakeOrtStatus(ORT_FAIL,
                           "Failed to dispatch 'sessionOptions.epContextDataRead.callback' to the JavaScript thread.");
    }
 
    item->Wait();
    napi_release_threadsafe_function(tsfn, napi_tsfn_release);
  }
 
  if (!item->succeeded) {
    return MakeOrtStatus(item->error_code, item->error_message);
  }
 
  *data_size = item->buffer.size;
  *buffer = item->buffer.Detach();
  return nullptr;
}
 
OrtStatus* ORT_API_CALL EpContextDataReadState::ReadNamedBuffer(void* state, const char* name,
                                                                OrtAllocator* allocator, void** buffer,
                                                                size_t* data_size) noexcept {
  if (buffer != nullptr) {
    *buffer = nullptr;
  }
  if (data_size != nullptr) {
    *data_size = 0;
  }
  if (state == nullptr) {
    return MakeOrtStatus(ORT_INVALID_ARGUMENT, "'sessionOptions.epContextDataRead' state is missing.");
  }
  return static_cast<EpContextDataReadState*>(state)->Invoke(name, allocator, buffer, data_size);
}
 
void ParseEpContextDataReadOptions(const Napi::Object options, Ort::SessionOptions& sessionOptions,
                                   std::shared_ptr<EpContextDataReadState>& state) {
  Napi::Env env = options.Env();
 
  if (!options.Has("epContextDataRead")) {
    return;
  }
  auto value = options.Get("epContextDataRead");
  if (value.IsNull() || value.IsUndefined()) {
    return;
  }
 
  ORT_NAPI_THROW_TYPEERROR_IF(!value.IsObject(), env,
                              "Invalid argument: sessionOptions.epContextDataRead must be an object.");
  auto config = value.As<Napi::Object>();
 
  auto callbackValue = config.Get("callback");
  ORT_NAPI_THROW_TYPEERROR_IF(!callbackValue.IsFunction(), env,
                              "Invalid argument: sessionOptions.epContextDataRead.callback must be a function.");
 
  auto maxDataSizeValue = config.Get("maxDataSize");
  ORT_NAPI_THROW_TYPEERROR_IF(!maxDataSizeValue.IsNumber(), env,
                              "Invalid argument: sessionOptions.epContextDataRead.maxDataSize must be a number.");
  const double maxDataSize = maxDataSizeValue.As<Napi::Number>().DoubleValue();
  ORT_NAPI_THROW_RANGEERROR_IF(!std::isfinite(maxDataSize) || std::floor(maxDataSize) != maxDataSize ||
                                   maxDataSize < 1 || maxDataSize > kMaxSafeInteger ||
                                   maxDataSize >= static_cast<double>(std::numeric_limits<size_t>::max()),
                               env, "'epContextDataRead.maxDataSize' is invalid: ", maxDataSize);
  const size_t maxDataSizeBytes = static_cast<size_t>(maxDataSize);
 
  // Transactional setup: retain the new state first, register it next, and publish it only after the
  // native setter succeeded.
  auto newState = EpContextDataReadState::Create(env, callbackValue.As<Napi::Function>(), maxDataSizeBytes);
  try {
    sessionOptions.SetEpContextDataReadFunc(&EpContextDataReadState::ReadNamedBuffer, newState.get());
  } catch (...) {
    newState->Release();
    throw;
  }
 
  if (state) {
    state->Release();
  }
  state = std::move(newState);
}
 
namespace {
 
class EpContextDataReadTestWorker final : public Napi::AsyncWorker {
 public:
  EpContextDataReadTestWorker(Napi::Env env, std::shared_ptr<EpContextDataReadState> state, std::string name)
      : Napi::AsyncWorker{env, "onnxruntime.epContextDataRead.test"},
        state_{std::move(state)},
        name_{std::move(name)},
        deferred_{Napi::Promise::Deferred::New(env)} {}
 
  Napi::Promise Promise() const { return deferred_.Promise(); }
 
  void Execute() override {
    try {
      Ort::AllocatorWithDefaultOptions allocator;
      void* buffer = nullptr;
      size_t dataSize = 0;
      OrtStatus* status = EpContextDataReadState::ReadNamedBuffer(
          state_.get(), name_.c_str(), allocator, &buffer, &dataSize);
      if (status != nullptr) {
        const char* message = Ort::GetApi().GetErrorMessage(status);
        SetError(message == nullptr ? "EPContext callback failed." : message);
        Ort::GetApi().ReleaseStatus(status);
        return;
      }
 
      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);
      }
    } catch (const std::exception& error) {
      SetError(error.what());
    } catch (...) {
      SetError("Unknown error while reading EPContext callback data.");
    }
  }
 
  void OnOK() override {
    Napi::Env env = Env();
    Napi::HandleScope scope{env};
    state_->Release();
    if (data_.empty()) {
      deferred_.Resolve(Napi::Buffer<uint8_t>::New(env, 0));
    } else {
      deferred_.Resolve(Napi::Buffer<uint8_t>::Copy(env, data_.data(), data_.size()));
    }
  }
 
  void OnError(const Napi::Error& error) override {
    Napi::Env env = Env();
    Napi::HandleScope scope{env};
    state_->Release();
    deferred_.Reject(error.Value());
  }
 
 private:
  std::shared_ptr<EpContextDataReadState> state_;
  std::string name_;
  std::vector<uint8_t> data_;
  Napi::Promise::Deferred deferred_;
};
 
}  // namespace
 
Napi::Value TestEpContextDataReadCallback(const Napi::CallbackInfo& info) {
  Napi::Env env = info.Env();
  ORT_NAPI_THROW_TYPEERROR_IF(info.Length() != 3 || !info[0].IsFunction() || !info[1].IsNumber() ||
                                  !info[2].IsString(),
                              env, "Expected callback, maxDataSize, and name.");
 
  const double maxDataSize = info[1].As<Napi::Number>().DoubleValue();
  ORT_NAPI_THROW_RANGEERROR_IF(!std::isfinite(maxDataSize) || std::floor(maxDataSize) != maxDataSize ||
                                   maxDataSize < 1 || maxDataSize > kMaxSafeInteger ||
                                   maxDataSize >= static_cast<double>(std::numeric_limits<size_t>::max()),
                               env, "maxDataSize must be a positive safe integer.");
 
  auto state = EpContextDataReadState::Create(env, info[0].As<Napi::Function>(), static_cast<size_t>(maxDataSize));
  auto worker = new EpContextDataReadTestWorker(env, std::move(state), info[2].As<Napi::String>().Utf8Value());
  Napi::Promise promise = worker->Promise();
  worker->Queue();
  return promise;
}