@pineliner/odb-client 1.1.5 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -2138,6 +2138,514 @@ var __webpack_exports__ = {};
2138
2138
  return this.client.httpClient.getNamespaces();
2139
2139
  }
2140
2140
  }
2141
+ function toHrana(v) {
2142
+ if (null == v) return {
2143
+ type: 'null'
2144
+ };
2145
+ if ('bigint' == typeof v) return {
2146
+ type: 'integer',
2147
+ value: v.toString()
2148
+ };
2149
+ if ('number' == typeof v) return Number.isInteger(v) ? {
2150
+ type: 'integer',
2151
+ value: String(v)
2152
+ } : {
2153
+ type: 'float',
2154
+ value: v
2155
+ };
2156
+ if ('string' == typeof v) return {
2157
+ type: 'text',
2158
+ value: v
2159
+ };
2160
+ if (v instanceof Uint8Array) return {
2161
+ type: 'blob',
2162
+ base64: Buffer.from(v).toString('base64')
2163
+ };
2164
+ if ('boolean' == typeof v) return {
2165
+ type: 'integer',
2166
+ value: v ? '1' : '0'
2167
+ };
2168
+ return {
2169
+ type: 'text',
2170
+ value: String(v)
2171
+ };
2172
+ }
2173
+ function fromHrana(v) {
2174
+ switch(v.type){
2175
+ case 'null':
2176
+ return null;
2177
+ case 'integer':
2178
+ {
2179
+ const n = Number(v.value);
2180
+ return Number.isSafeInteger(n) ? n : BigInt(v.value);
2181
+ }
2182
+ case 'float':
2183
+ return v.value;
2184
+ case 'text':
2185
+ return v.value;
2186
+ case 'blob':
2187
+ return new Uint8Array(Buffer.from(v.base64, 'base64'));
2188
+ }
2189
+ }
2190
+ function toBatch(steps) {
2191
+ return {
2192
+ steps: steps.map((s, i)=>({
2193
+ condition: 0 === i ? void 0 : {
2194
+ type: 'ok',
2195
+ step: i - 1
2196
+ },
2197
+ stmt: {
2198
+ sql: s.sql,
2199
+ args: (s.params ?? []).map(toHrana)
2200
+ },
2201
+ expect: s.expect ? {
2202
+ affected: s.expect
2203
+ } : void 0
2204
+ }))
2205
+ };
2206
+ }
2207
+ const READ_ONLY_RE = /^\s*(?:SELECT|EXPLAIN|VALUES)\b/i;
2208
+ function mightReturnRows(sql) {
2209
+ return READ_ONLY_RE.test(sql) || /\bRETURNING\b/i.test(sql);
2210
+ }
2211
+ class FrameWriter {
2212
+ socket;
2213
+ pending = Buffer.alloc(0);
2214
+ constructor(socket){
2215
+ this.socket = socket;
2216
+ }
2217
+ send(payload) {
2218
+ const header = Buffer.allocUnsafe(4);
2219
+ header.writeUInt32LE(payload.length, 0);
2220
+ const frame = Buffer.concat([
2221
+ header,
2222
+ payload
2223
+ ]);
2224
+ this.pending = this.pending.length ? Buffer.concat([
2225
+ this.pending,
2226
+ frame
2227
+ ]) : frame;
2228
+ this.flush();
2229
+ }
2230
+ flush() {
2231
+ while(this.pending.length > 0){
2232
+ const n = this.socket.write(this.pending);
2233
+ if (n <= 0) return;
2234
+ this.pending = n < this.pending.length ? this.pending.subarray(n) : Buffer.alloc(0);
2235
+ }
2236
+ }
2237
+ }
2238
+ class FrameReader {
2239
+ buf = Buffer.alloc(0);
2240
+ push(chunk) {
2241
+ this.buf = this.buf.length ? Buffer.concat([
2242
+ this.buf,
2243
+ chunk
2244
+ ]) : chunk;
2245
+ const out = [];
2246
+ while(this.buf.length >= 4){
2247
+ const len = this.buf.readUInt32LE(0);
2248
+ if (this.buf.length < 4 + len) break;
2249
+ out.push(this.buf.subarray(4, 4 + len));
2250
+ this.buf = this.buf.subarray(4 + len);
2251
+ }
2252
+ return out;
2253
+ }
2254
+ }
2255
+ const REQUEST_TIMEOUT_MS = Number(globalThis.process?.env?.ODB_SOCKET_REQUEST_TIMEOUT_MS) || 30000;
2256
+ class SocketClient {
2257
+ target;
2258
+ socket;
2259
+ reader = new FrameReader();
2260
+ writer;
2261
+ pending = new Map();
2262
+ nextId = 1;
2263
+ nextStreamId = 1;
2264
+ ready;
2265
+ constructor(target){
2266
+ this.target = target;
2267
+ this.ready = this.connect();
2268
+ this.ready.catch(()=>{});
2269
+ }
2270
+ failPending(err) {
2271
+ for (const p of this.pending.values()){
2272
+ clearTimeout(p.timer);
2273
+ p.reject(err);
2274
+ }
2275
+ this.pending.clear();
2276
+ }
2277
+ async connect() {
2278
+ const Bun = globalThis.Bun;
2279
+ if (!Bun?.connect) throw new Error('odblite-socket backend requires Bun (Bun.connect)');
2280
+ const opts = this.target.unix ? {
2281
+ unix: this.target.unix
2282
+ } : {
2283
+ hostname: this.target.hostname ?? '127.0.0.1',
2284
+ port: this.target.port ?? 8787
2285
+ };
2286
+ this.socket = await Bun.connect({
2287
+ ...opts,
2288
+ socket: {
2289
+ data: (_s, chunk)=>{
2290
+ for (const frame of this.reader.push(chunk)){
2291
+ const msg = JSON.parse(frame.toString('utf8'));
2292
+ const p = this.pending.get(msg.id);
2293
+ if (p) {
2294
+ this.pending.delete(msg.id);
2295
+ clearTimeout(p.timer);
2296
+ p.resolve(msg.results);
2297
+ }
2298
+ }
2299
+ },
2300
+ drain: (_s)=>this.writer.flush(),
2301
+ close: ()=>{
2302
+ this.socket = void 0;
2303
+ this.reader = new FrameReader();
2304
+ this.failPending(new Error('odblite socket disconnected — request not completed'));
2305
+ },
2306
+ error: (_s, err)=>{
2307
+ this.socket = void 0;
2308
+ this.reader = new FrameReader();
2309
+ this.failPending(err instanceof Error ? err : new Error(`odblite socket error: ${err}`));
2310
+ }
2311
+ }
2312
+ });
2313
+ this.writer = new FrameWriter(this.socket);
2314
+ }
2315
+ allocStream() {
2316
+ return this.nextStreamId++;
2317
+ }
2318
+ async pipeline(tenant, requests, stream) {
2319
+ await this.ready;
2320
+ if (!this.socket) {
2321
+ this.ready = this.connect();
2322
+ this.ready.catch(()=>{});
2323
+ await this.ready;
2324
+ }
2325
+ const id = this.nextId++;
2326
+ return new Promise((resolve, reject)=>{
2327
+ const timer = setTimeout(()=>{
2328
+ if (this.pending.delete(id)) reject(new Error(`odblite socket request ${id} timed out after ${REQUEST_TIMEOUT_MS}ms`));
2329
+ }, REQUEST_TIMEOUT_MS);
2330
+ timer.unref?.();
2331
+ this.pending.set(id, {
2332
+ resolve,
2333
+ reject,
2334
+ timer
2335
+ });
2336
+ const payload = null != stream ? {
2337
+ id,
2338
+ tenant,
2339
+ stream,
2340
+ requests
2341
+ } : {
2342
+ id,
2343
+ tenant,
2344
+ requests
2345
+ };
2346
+ this.writer.send(Buffer.from(JSON.stringify(payload), 'utf8'));
2347
+ });
2348
+ }
2349
+ close() {
2350
+ this.socket?.end?.();
2351
+ this.socket = void 0;
2352
+ this.failPending(new Error('odblite socket closed'));
2353
+ }
2354
+ }
2355
+ function toQueryResult(res) {
2356
+ if ('error' === res.type) throw new Error(res.error.message);
2357
+ const r = res.response.result;
2358
+ const rows = r.rows.map((row)=>{
2359
+ const obj = {};
2360
+ r.cols.forEach((c, i)=>{
2361
+ obj[c.name ?? `c${i}`] = fromHrana(row[i] ?? {
2362
+ type: 'null'
2363
+ });
2364
+ });
2365
+ return obj;
2366
+ });
2367
+ return {
2368
+ rows,
2369
+ rowsAffected: r.affected_row_count,
2370
+ lastInsertRowid: r.last_insert_rowid ? Number(r.last_insert_rowid) : void 0
2371
+ };
2372
+ }
2373
+ class OdbliteSocketConnection {
2374
+ client;
2375
+ tenant;
2376
+ streamId;
2377
+ databaseName;
2378
+ databaseHash;
2379
+ sql;
2380
+ beginPending = false;
2381
+ constructor(client, tenant, streamId){
2382
+ this.client = client;
2383
+ this.tenant = tenant;
2384
+ this.streamId = streamId;
2385
+ this.databaseName = tenant;
2386
+ this.databaseHash = tenant;
2387
+ const self = this;
2388
+ this.sql = function(strings, ...values) {
2389
+ if (strings && 'object' == typeof strings && 'raw' in strings) {
2390
+ const text = strings.reduce((a, s, i)=>a + s + (i < values.length ? '?' : ''), '');
2391
+ const returns = mightReturnRows(text);
2392
+ return (returns ? self.query(text, values) : self.execute(text, values)).then((r)=>r.rows);
2393
+ }
2394
+ throw new Error('sql() fragment helper not implemented in odblite-socket');
2395
+ };
2396
+ }
2397
+ async one(requests) {
2398
+ const [res] = await this.client.pipeline(this.tenant, requests);
2399
+ if (!res) throw new Error('odblite-socket: empty pipeline response');
2400
+ return res;
2401
+ }
2402
+ async streamExec(sql, params = []) {
2403
+ const reqs = [];
2404
+ if (this.beginPending) {
2405
+ reqs.push({
2406
+ type: 'execute',
2407
+ stmt: {
2408
+ sql: 'BEGIN'
2409
+ }
2410
+ });
2411
+ this.beginPending = false;
2412
+ }
2413
+ reqs.push({
2414
+ type: 'execute',
2415
+ stmt: {
2416
+ sql,
2417
+ args: params.map(toHrana)
2418
+ }
2419
+ });
2420
+ const results = await this.client.pipeline(this.tenant, reqs, this.streamId);
2421
+ if (reqs.length > 1 && results[0]?.type === 'error') throw new Error(results[0].error.message);
2422
+ const res = results[results.length - 1];
2423
+ if (!res) throw new Error('odblite-socket: empty stream response');
2424
+ return toQueryResult(res);
2425
+ }
2426
+ async query(sql, params = []) {
2427
+ if (null != this.streamId) return await this.streamExec(sql, params);
2428
+ return toQueryResult(await this.one([
2429
+ {
2430
+ type: 'execute',
2431
+ stmt: {
2432
+ sql,
2433
+ args: params.map(toHrana)
2434
+ }
2435
+ }
2436
+ ]));
2437
+ }
2438
+ async execute(sql, params = []) {
2439
+ const s = 'string' == typeof sql ? sql : sql.sql;
2440
+ const p = 'string' == typeof sql ? params : sql.args ?? [];
2441
+ if (null != this.streamId) return this.streamExec(s, p);
2442
+ return toQueryResult(await this.one([
2443
+ {
2444
+ type: 'execute',
2445
+ stmt: {
2446
+ sql: s,
2447
+ args: p.map(toHrana)
2448
+ }
2449
+ }
2450
+ ]));
2451
+ }
2452
+ async atomic(steps) {
2453
+ const res = await this.one([
2454
+ {
2455
+ type: 'batch',
2456
+ batch: toBatch(steps)
2457
+ }
2458
+ ]);
2459
+ if ('error' === res.type) throw new Error(res.error.message);
2460
+ return res.response.result;
2461
+ }
2462
+ prepare(sql) {
2463
+ return {
2464
+ execute: async (params = [])=>this.execute(sql, params),
2465
+ all: async (params = [])=>(await this.query(sql, params)).rows,
2466
+ get: async (params = [])=>(await this.query(sql, params)).rows[0] ?? null
2467
+ };
2468
+ }
2469
+ async transaction(fn) {
2470
+ if (null != this.streamId) return fn(this);
2471
+ const tx = new OdbliteSocketConnection(this.client, this.tenant, this.client.allocStream());
2472
+ tx.beginPending = true;
2473
+ try {
2474
+ const out = await fn(tx);
2475
+ if (!tx.beginPending) await tx.streamExec('COMMIT');
2476
+ return out;
2477
+ } catch (e) {
2478
+ if (!tx.beginPending) await tx.streamExec('ROLLBACK').catch(()=>{});
2479
+ throw e;
2480
+ }
2481
+ }
2482
+ begin(fn) {
2483
+ return this.transaction(fn);
2484
+ }
2485
+ async savepoint(fn) {
2486
+ if (null == this.streamId) return this.transaction(fn);
2487
+ const name = `sp_${this.client.allocStream()}`;
2488
+ await this.streamExec(`SAVEPOINT ${name}`);
2489
+ try {
2490
+ const out = await fn(this);
2491
+ await this.streamExec(`RELEASE SAVEPOINT ${name}`);
2492
+ return out;
2493
+ } catch (e) {
2494
+ await this.streamExec(`ROLLBACK TO SAVEPOINT ${name}`).catch(()=>{});
2495
+ throw e;
2496
+ }
2497
+ }
2498
+ async ensureNamespaces(namespaces) {
2499
+ return {
2500
+ success: true,
2501
+ databaseName: this.tenant,
2502
+ namespaces
2503
+ };
2504
+ }
2505
+ async getNamespaces() {
2506
+ const ns = (await this.query("SELECT name FROM pragma_database_list WHERE name != 'main'")).rows.map((r)=>r.name);
2507
+ return {
2508
+ success: true,
2509
+ databaseName: this.tenant,
2510
+ exists: true,
2511
+ namespaces: ns,
2512
+ registered: true,
2513
+ registeredNamespaces: ns
2514
+ };
2515
+ }
2516
+ async close() {}
2517
+ }
2518
+ class OdbliteSocketAdapter {
2519
+ type = 'odblite-socket';
2520
+ client;
2521
+ constructor(config){
2522
+ this.client = new SocketClient(config);
2523
+ }
2524
+ async connect(config) {
2525
+ const tenant = config?.databaseHash ?? config?.databaseName;
2526
+ if (!tenant) throw new Error('odblite-socket: databaseHash (or databaseName) required');
2527
+ return new OdbliteSocketConnection(this.client, String(tenant));
2528
+ }
2529
+ async disconnect() {
2530
+ this.client.close();
2531
+ }
2532
+ async isHealthy() {
2533
+ try {
2534
+ const res = await Promise.race([
2535
+ this.client.pipeline('_health', [
2536
+ {
2537
+ type: 'get_version'
2538
+ }
2539
+ ]),
2540
+ new Promise((_, rej)=>setTimeout(()=>rej(new Error('probe timeout')), 1500))
2541
+ ]);
2542
+ const proto = res?.[0]?.response?.protocol;
2543
+ if (proto !== CLIENT_SOCKET_PROTOCOL) {
2544
+ console.warn(`[odb-client] socket protocol mismatch (server=${proto ?? 'none'}, client=${CLIENT_SOCKET_PROTOCOL}) → using HTTP`);
2545
+ return false;
2546
+ }
2547
+ return true;
2548
+ } catch {
2549
+ return false;
2550
+ }
2551
+ }
2552
+ }
2553
+ const CLIENT_SOCKET_PROTOCOL = 2;
2554
+ const DEFAULT_UNIX_SOCKET = '/tmp/odblite.sock';
2555
+ function parseSocketTarget(s) {
2556
+ const v = (s ?? '').trim();
2557
+ if (!v) return {
2558
+ unix: DEFAULT_UNIX_SOCKET
2559
+ };
2560
+ if (v.includes('/')) return {
2561
+ unix: v
2562
+ };
2563
+ const m = v.match(/^(?:([^:]+):)?(\d+)$/);
2564
+ if (m) return {
2565
+ hostname: m[1] || '127.0.0.1',
2566
+ port: Number(m[2])
2567
+ };
2568
+ return {
2569
+ unix: v
2570
+ };
2571
+ }
2572
+ class OdbliteAutoAdapter {
2573
+ type = 'odblite';
2574
+ opts;
2575
+ chosen;
2576
+ onHttp = false;
2577
+ nextRetryAt = 0;
2578
+ constructor(opts){
2579
+ this.opts = opts;
2580
+ this.chosen = this.pick();
2581
+ }
2582
+ async pick() {
2583
+ const hasBun = void 0 !== globalThis.Bun && !!globalThis.Bun.connect;
2584
+ if (hasBun) {
2585
+ const socket = await this.trySocket();
2586
+ if (socket) return socket;
2587
+ }
2588
+ this.onHttp = true;
2589
+ console.log('[odb-client] transport → HTTP (no router_v2 socket reachable)');
2590
+ return new ODBLiteAdapter(this.opts.http);
2591
+ }
2592
+ async trySocket() {
2593
+ for (const target of this.candidates())try {
2594
+ const socket = new OdbliteSocketAdapter(target);
2595
+ if (await socket.isHealthy()) {
2596
+ console.log(`[odb-client] transport → SOCKET (router_v2 @ ${target.unix ?? `${target.hostname}:${target.port}`})`);
2597
+ return socket;
2598
+ }
2599
+ await socket.disconnect();
2600
+ } catch {}
2601
+ return null;
2602
+ }
2603
+ async maybeUpgrade() {
2604
+ if (!this.onHttp) return;
2605
+ const now = Date.now();
2606
+ if (now < this.nextRetryAt) return;
2607
+ this.nextRetryAt = now + 15000;
2608
+ const socket = await this.trySocket();
2609
+ if (socket) {
2610
+ this.chosen = Promise.resolve(socket);
2611
+ this.onHttp = false;
2612
+ }
2613
+ }
2614
+ candidates() {
2615
+ const { socket, http } = this.opts;
2616
+ if (socket?.unix || socket?.port) return [
2617
+ socket
2618
+ ];
2619
+ const env = globalThis.process?.env?.ODB_SOCKET;
2620
+ if (env) return [
2621
+ parseSocketTarget(env)
2622
+ ];
2623
+ const out = [
2624
+ {
2625
+ unix: DEFAULT_UNIX_SOCKET
2626
+ }
2627
+ ];
2628
+ try {
2629
+ const host = new URL(http?.serviceUrl).hostname;
2630
+ const port = Number(globalThis.process?.env?.ODB_SOCKET_PORT ?? 8787);
2631
+ if (host) out.push({
2632
+ hostname: host,
2633
+ port
2634
+ });
2635
+ } catch {}
2636
+ return out;
2637
+ }
2638
+ async connect(config) {
2639
+ await this.maybeUpgrade();
2640
+ return (await this.chosen).connect(config);
2641
+ }
2642
+ async disconnect(tenantId) {
2643
+ return (await this.chosen).disconnect(tenantId);
2644
+ }
2645
+ async isHealthy() {
2646
+ return (await this.chosen).isHealthy();
2647
+ }
2648
+ }
2141
2649
  function parseSQL(sqlContent, options = {}) {
2142
2650
  const separatePragma = options.separatePragma ?? true;
2143
2651
  const statements = splitStatements(sqlContent);
@@ -2249,7 +2757,14 @@ var __webpack_exports__ = {};
2249
2757
  break;
2250
2758
  case 'odblite':
2251
2759
  if (!config.odblite) throw new Error('odblite config required for odblite backend');
2252
- this.adapter = new ODBLiteAdapter(config.odblite);
2760
+ this.adapter = new OdbliteAutoAdapter({
2761
+ socket: config.odbliteSocket,
2762
+ http: config.odblite
2763
+ });
2764
+ break;
2765
+ case 'odblite-socket':
2766
+ if (!config.odbliteSocket) throw new Error('odbliteSocket config required for odblite-socket backend');
2767
+ this.adapter = new OdbliteSocketAdapter(config.odbliteSocket);
2253
2768
  break;
2254
2769
  default:
2255
2770
  throw new Error(`Unknown backend type: ${config.backend}`);
@@ -2367,6 +2882,12 @@ var __webpack_exports__ = {};
2367
2882
  databaseName: `${this.config.databasePath}_${name}`,
2368
2883
  ...this.config.odblite
2369
2884
  };
2885
+ case 'odblite-socket':
2886
+ return {
2887
+ databaseName: name,
2888
+ databaseHash: name,
2889
+ ...this.config.odbliteSocket
2890
+ };
2370
2891
  default:
2371
2892
  throw new Error(`Unknown backend: ${this.config.backend}`);
2372
2893
  }