dolphindb 2.0.946 → 2.0.948

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/index.js CHANGED
@@ -4,7 +4,7 @@ import DayjsCustomParseFormat from 'dayjs/plugin/customParseFormat.js';
4
4
  dayjs.extend(DayjsCustomParseFormat);
5
5
  import ipaddrjs from 'ipaddr.js';
6
6
  const { fromByteArray: buf2ipaddr } = ipaddrjs;
7
- import { concat, assert, inspect, typed_array_to_buffer, connect_websocket, WebSocket, defer } from 'xshell';
7
+ import { concat, assert, inspect, typed_array_to_buffer, connect_websocket, WebSocket, Lock } from 'xshell';
8
8
  import { t } from './i18n/index.js';
9
9
  export var DdbForm;
10
10
  (function (DdbForm) {
@@ -2173,7 +2173,8 @@ export class DDB {
2173
2173
  e.g. `ws://127.0.0.1:8848/`, `wss://dolphindb.com`
2174
2174
  */
2175
2175
  url;
2176
- websocket = null;
2176
+ /** 为所有 websocket 操作加锁,包括设置 this.on_message, this.on_error, websocket.send */
2177
+ lwebsocket = new Lock();
2177
2178
  /** little endian (server) */
2178
2179
  le = true;
2179
2180
  /** little endian (client) */
@@ -2203,15 +2204,15 @@ export class DDB {
2203
2204
  error;
2204
2205
  /** DdbMessage listeners */
2205
2206
  listeners = [];
2206
- /** 为所有 websocket 操作加锁,包括设置 this.on_message, this.on_error, websocket.send */
2207
- pwebsocket = defer(null);
2208
- /** 为定义 pnode_run 函数加锁,避免重复定义 */
2209
- ppnode_run = defer(null);
2207
+ /** 首次 connect 连接的 promise, 后面的 connect 调用都返回这个 */
2208
+ pconnect;
2209
+ /** 首次定义 pnode_run 的 promise,保证并发调用 rpc 时只定义一次 pnode_run */
2210
+ ppnode_run;
2210
2211
  get connected() {
2211
- return !this.error && this.websocket?.readyState === WebSocket.OPEN;
2212
+ return !this.error && this.lwebsocket.resource?.readyState === WebSocket.OPEN;
2212
2213
  }
2213
2214
  get errored() {
2214
- return this.error || (this.websocket && this.websocket.readyState !== WebSocket.OPEN);
2215
+ return Boolean(this.error || (this.lwebsocket.resource && this.lwebsocket.resource.readyState !== WebSocket.OPEN));
2215
2216
  }
2216
2217
  /**
2217
2218
  使用 WebSocket URL 初始化连接到 DolphinDB 的实例(不建立实际的网络连接)
@@ -2277,62 +2278,46 @@ export class DDB {
2277
2278
  throw this.error || new DdbConnectionError(this);
2278
2279
  if (this.connected)
2279
2280
  return;
2280
- // 准备进入 websocket 临界区
2281
- const ptail = this.pwebsocket;
2282
- let pwebsocket = this.pwebsocket = defer();
2283
- // 避免 pwebsocket.reject 后出现 triggerUncaughtException
2284
- pwebsocket.catch(() => { });
2285
- // 上一个请求出现了 websocket 错误,那么直接抛出异常,且通过 reject 当前锁 (pwebsocket),安全退出临界区
2286
- try {
2287
- await ptail;
2288
- // 已进入 websocket 临界区
2289
- }
2290
- catch (error) {
2291
- pwebsocket.reject(error);
2292
- throw error;
2293
- }
2294
- if (this.errored) {
2295
- const error = this.error || new DdbConnectionError(this);
2296
- pwebsocket.reject(error);
2297
- throw error;
2298
- }
2299
- if (this.connected) {
2300
- pwebsocket.resolve();
2301
- return;
2302
- }
2303
- this.on_error = () => {
2304
- pwebsocket.reject(this.error /* 一定有,不需要再 || new DdbConnectionError(this) */);
2305
- };
2306
- try {
2307
- this.websocket = await connect_websocket(this.url, {
2308
- protocols: (() => {
2309
- if (this.streaming)
2310
- return 'streaming';
2311
- if (this.python)
2312
- return 'python';
2313
- })(),
2314
- on_message: (buffer, websocket) => {
2315
- this.on_message(buffer, websocket);
2316
- },
2317
- on_error: error => {
2318
- this.error ??= new DdbConnectionError(this, error);
2319
- this.on_error();
2320
- }
2321
- });
2322
- }
2323
- catch (error) {
2324
- this.error ??= new DdbConnectionError(this, error);
2325
- pwebsocket.reject(error);
2326
- throw this.error;
2327
- }
2328
- assert(this.connected);
2329
- pwebsocket.resolve();
2330
- // websocket 临界区结束
2331
- await this.rpc('connect', {});
2332
- if (this.autologin)
2333
- await this.call('login', [this.username, this.password], { urgent: true });
2334
- if (this.streaming)
2335
- await this.subscribe();
2281
+ return this.pconnect ??= new Promise(async (resolve, reject) => {
2282
+ this.on_error = () => {
2283
+ reject(this.error /* 一定有,不需要再 || new DdbConnectionError(this) */);
2284
+ };
2285
+ try {
2286
+ // 连接建立之前应该不会有别的调用占用 this.lwebsocket
2287
+ this.lwebsocket.resource = await connect_websocket(this.url, {
2288
+ protocols: (() => {
2289
+ if (this.streaming)
2290
+ return 'streaming';
2291
+ if (this.python)
2292
+ return 'python';
2293
+ })(),
2294
+ on_message: (buffer, websocket) => {
2295
+ this.on_message(buffer, websocket);
2296
+ },
2297
+ on_error: error => {
2298
+ this.error ??= new DdbConnectionError(this, error);
2299
+ this.on_error();
2300
+ }
2301
+ });
2302
+ }
2303
+ catch (error) {
2304
+ this.error ??= new DdbConnectionError(this, error);
2305
+ reject(this.error);
2306
+ return;
2307
+ }
2308
+ try {
2309
+ assert(this.connected);
2310
+ await this.rpc('connect', { skip_connection_check: true });
2311
+ if (this.autologin)
2312
+ await this.call('login', [this.username, this.password], { urgent: true, skip_connection_check: true });
2313
+ if (this.streaming)
2314
+ await this.subscribe();
2315
+ resolve();
2316
+ }
2317
+ catch (error) {
2318
+ reject(error);
2319
+ }
2320
+ });
2336
2321
  }
2337
2322
  get_rpc_options({ urgent = false, secondary = false, async: _async = false, pickle = false, clear = false, api = false, compress = false, cancellable = true, priority = urgent ? 8 : 4, parallelism = 8, root_id = '', limit, } = {}) {
2338
2323
  let flag = 0;
@@ -2367,7 +2352,8 @@ export class DDB {
2367
2352
  }
2368
2353
  disconnect() {
2369
2354
  if (this.connected)
2370
- this.websocket.close(1000);
2355
+ // 这里不获取 lock,直接关闭连接
2356
+ this.lwebsocket.resource.close(1000);
2371
2357
  }
2372
2358
  /** (内部使用的方法) rpc through websocket (function/script/variable command)
2373
2359
  未连接到 DDB 时调用会自动连接,连接断开时调用会抛出 DdbConnectionError
@@ -2378,165 +2364,138 @@ export class DDB {
2378
2364
  - vars?: type === 'variable' 时必传,variable 指令中待上传的变量名
2379
2365
  - listener?: 处理本次 rpc 期间的消息 (DdbMessage)
2380
2366
  - parse_object?: 在本次 rpc 期间设置 parse_object, 结束后恢复原有
2381
- 为 false 时返回的 DdbObj 仅含有 buffer 和 le,不做解析,以便后续转发、序列化 */
2367
+ 为 false 时返回的 DdbObj 仅含有 buffer 和 le,不做解析,以便后续转发、序列化
2368
+ - skip_connection_check?: 在首次 await ddb.connect() 建立连接时不能再次调用 await this.connect() 确保连接状态,会导致循环依赖,
2369
+ 将这个 flag 设为 true 跳过连接状态检查 */
2382
2370
  async rpc(type, options) {
2383
2371
  // 保留调用栈信息
2384
2372
  let error = new DdbDatabaseError('', this, type, options);
2385
- await this.connect();
2373
+ if (!options.skip_connection_check)
2374
+ await this.connect();
2386
2375
  const { script, func, args: _args = [], vars = [], urgent, listener, } = options;
2387
- if (func === 'pnode_run' && !this.pnode_run_defined) {
2388
- // 准备进入 pnode_run 临界区,保证并发调用 rpc 时只定义一次 pnode_run
2389
- const ptail = this.ppnode_run;
2390
- let ppnode_run = this.ppnode_run = defer();
2391
- // 避免 ppnode_run.reject 后出现 triggerUncaughtException
2392
- ppnode_run.catch(() => { });
2393
- // 如果之前的定义失败了,再定义一次也会失败,直接抛出之前的错误,且安全地退出临界区
2394
- try {
2395
- await ptail;
2396
- // 已进入 pnode_run 临界区
2397
- }
2398
- catch (error) {
2399
- ppnode_run.reject(error);
2400
- throw error;
2401
- }
2402
- if (!this.pnode_run_defined)
2403
- try {
2404
- await this.eval(this.python ?
2405
- 'def pnode_run (nodes, func_name, args, add_node_alias):\n' +
2406
- ' nargs = size(args)\n' +
2407
- ' func = funcByName(func_name)\n' +
2408
- ' \n' +
2409
- ' if not nargs:\n' +
2410
- ' return pnodeRun(func, nodes, add_node_alias)\n' +
2411
- ' \n' +
2412
- ' args_partial = [ ]\n' +
2413
- ' args_partial.append(func)\n' +
2414
- ' for a in args:\n' +
2415
- ' args_partial.append(a)\n' +
2416
- ' \n' +
2417
- ' return pnodeRun(\n' +
2418
- ' unifiedCall(partial, args_partial),\n' +
2419
- ' nodes,\n' +
2420
- ' add_node_alias\n' +
2421
- ' )\n'
2422
- :
2423
- 'def pnode_run (nodes, func_name, args, add_node_alias = true) {\n' +
2424
- ' nargs = size(args)\n' +
2425
- ' func = funcByName(func_name)\n' +
2426
- ' \n' +
2427
- ' if (!nargs)\n' +
2428
- ' return pnodeRun(func, nodes, add_node_alias)\n' +
2429
- ' \n' +
2430
- ' args_partial = array(any, 1 + nargs, 1 + nargs)\n' +
2431
- ' args_partial[0] = func\n' +
2432
- ' args_partial[1:] = args\n' +
2433
- ' return pnodeRun(\n' +
2434
- ' unifiedCall(partial, args_partial),\n' +
2435
- ' nodes,\n' +
2436
- ' add_node_alias\n' +
2437
- ' )\n' +
2438
- '}\n', { urgent: true });
2439
- this.pnode_run_defined = true;
2440
- ppnode_run.resolve();
2441
- }
2442
- catch (error) {
2443
- // 这次失败了,之后的执行肯定也会失败
2444
- ppnode_run.reject(error);
2445
- throw error;
2446
- }
2447
- }
2376
+ if (func === 'pnode_run')
2377
+ await (this.ppnode_run ??= this.eval(this.python ?
2378
+ '\n' +
2379
+ 'def pnode_run (nodes, func_name, args, add_node_alias):\n' +
2380
+ ' nargs = size(args)\n' +
2381
+ ' func = funcByName(func_name)\n' +
2382
+ ' \n' +
2383
+ ' if not nargs:\n' +
2384
+ ' return pnodeRun(func, nodes, add_node_alias)\n' +
2385
+ ' \n' +
2386
+ ' args_partial = [ ]\n' +
2387
+ ' args_partial.append(func)\n' +
2388
+ ' for a in args:\n' +
2389
+ ' args_partial.append(a)\n' +
2390
+ ' \n' +
2391
+ ' return pnodeRun(\n' +
2392
+ ' unifiedCall(partial, args_partial),\n' +
2393
+ ' nodes,\n' +
2394
+ ' add_node_alias\n' +
2395
+ ' )\n'
2396
+ :
2397
+ // 这个开头的空行很重要,应该可以绕过 webLoginRequired = true 时禁止执行代码
2398
+ // 搜一下 APISocketConsole::execute
2399
+ // https://dolphindb1.atlassian.net/browse/D20-4991
2400
+ '\n' +
2401
+ 'def pnode_run (nodes, func_name, args, add_node_alias = true) {\n' +
2402
+ ' nargs = size(args)\n' +
2403
+ ' func = funcByName(func_name)\n' +
2404
+ ' \n' +
2405
+ ' if (!nargs)\n' +
2406
+ ' return pnodeRun(func, nodes, add_node_alias)\n' +
2407
+ ' \n' +
2408
+ ' args_partial = array(any, 1 + nargs, 1 + nargs)\n' +
2409
+ ' args_partial[0] = func\n' +
2410
+ ' args_partial[1:] = args\n' +
2411
+ ' return pnodeRun(\n' +
2412
+ ' unifiedCall(partial, args_partial),\n' +
2413
+ ' nodes,\n' +
2414
+ ' add_node_alias\n' +
2415
+ ' )\n' +
2416
+ '}\n', { urgent: true }));
2448
2417
  // this 上的当前配置需要在 message 到达后使用,先保存起来
2449
2418
  const _listeners = [...this.listeners].reverse();
2450
- // websocket 临界区:保证多个 rpc 并发时形成 promise 链
2419
+ // rpc 请求期间需要独占 websocket,所以设计了一个锁,申请之后才能使用
2451
2420
  // ddb 世界观:需要等待上一个 rpc 结果从 server 返回之后才能发起下一个调用
2452
2421
  // 违反世界观可能造成:
2453
2422
  // 1. 并发多个请求只返回第一个结果(阻塞,需后续请求疏通)
2454
2423
  // 2. windows 下 ddb server 返回多个相同的结果
2455
- const ptail = this.pwebsocket;
2456
- let pwebsocket = this.pwebsocket = defer();
2457
- // 避免 pwebsocket.reject 后出现 triggerUncaughtException
2458
- pwebsocket.catch(() => { });
2459
- // 上一个请求出现了 websocket 错误,那么直接抛出异常,且通过 reject 当前锁 (pwebsocket),安全退出临界区
2460
- try {
2461
- await ptail;
2462
- // 已进入临界区,只有一个 rpc 函数调用运行到这里,可以独占 this.on_message 然后写 WebSocket
2463
- }
2464
- catch (error) {
2465
- pwebsocket.reject(error);
2466
- throw error;
2467
- }
2468
2424
  // 既然上一个请求没有出现 websocket error,且函数开头已经调用了 await this.connect() 检查过,
2469
2425
  // 这里也乐观的认为 this.connected && !this.errored 为 true
2470
- return new Promise((resolve, reject) => {
2471
- this.on_error = () => {
2472
- pwebsocket.reject(this.error /* 这里一定有了 this.error, 不需要再 || new DdbConnectionError(this) */);
2473
- reject(this.error);
2474
- };
2475
- this.on_message = buffer => {
2476
- try {
2477
- const buf = new Uint8Array(buffer);
2478
- if (this.print_message_buffer)
2479
- console.log(typed_array_to_buffer(buf));
2480
- const message = this.parse_message(buf, error);
2481
- listener?.(message, this);
2482
- for (const listener of _listeners)
2483
- listener(message, this);
2484
- const { type, data } = message;
2426
+ return this.lwebsocket.request(async (websocket) => {
2427
+ // 独占资源后先检查状态
2428
+ if (this.errored || !this.connected)
2429
+ throw this.error || new DdbConnectionError(this);
2430
+ // 使用资源发送请求并等待请求完成
2431
+ return new Promise((resolve, reject) => {
2432
+ this.on_error = () => {
2433
+ // 这里一定有了 this.error, 不需要再 || new DdbConnectionError(this)
2434
+ reject(this.error);
2435
+ };
2436
+ this.on_message = buffer => {
2437
+ try {
2438
+ const buf = new Uint8Array(buffer);
2439
+ if (this.print_message_buffer)
2440
+ console.log(typed_array_to_buffer(buf));
2441
+ const message = this.parse_message(buf, error);
2442
+ listener?.(message, this);
2443
+ for (const listener of _listeners)
2444
+ listener(message, this);
2445
+ const { type, data } = message;
2446
+ switch (type) {
2447
+ case 'print':
2448
+ if (this.print_message)
2449
+ console.log(data);
2450
+ break;
2451
+ case 'object':
2452
+ resolve(data);
2453
+ break;
2454
+ case 'error':
2455
+ reject(data);
2456
+ break;
2457
+ }
2458
+ }
2459
+ catch (error) {
2460
+ // 这里的错误并非 websocket 错误,而是 rpc 错误
2461
+ reject(error);
2462
+ }
2463
+ };
2464
+ const args = DdbObj.to_ddbobjs(_args);
2465
+ const command = this.enc.encode((() => {
2485
2466
  switch (type) {
2486
- case 'print':
2487
- if (this.print_message)
2488
- console.log(data);
2489
- break;
2490
- case 'object':
2491
- pwebsocket.resolve();
2492
- resolve(data);
2493
- break;
2494
- case 'error':
2495
- pwebsocket.resolve();
2496
- reject(data);
2497
- break;
2467
+ case 'function':
2468
+ if (this.verbose)
2469
+ console.log(func + inspect(args, { colors: false }));
2470
+ return 'function\n' +
2471
+ `${func}\n` +
2472
+ `${args.length}\n` +
2473
+ `${Number(DDB.le_client)}\n`;
2474
+ case 'script':
2475
+ if (this.verbose)
2476
+ console.log(script);
2477
+ return 'script\n' +
2478
+ script;
2479
+ case 'variable':
2480
+ if (this.verbose)
2481
+ for (let i = 0; i < vars.length; i++)
2482
+ console.log(`${vars[i]} = ${inspect(args[i], { colors: false })}`);
2483
+ return 'variable\n' +
2484
+ `${vars.join(',')}\n` +
2485
+ `${vars.length}\n` +
2486
+ `${Number(DDB.le_client)}\n`;
2487
+ case 'connect':
2488
+ if (this.verbose)
2489
+ console.log('connect()');
2490
+ return 'connect\n';
2498
2491
  }
2499
- }
2500
- catch (error) {
2501
- pwebsocket.resolve();
2502
- // 这里的错误并非 websocket 错误,而是 rpc 错误
2503
- reject(error);
2504
- }
2505
- };
2506
- const args = DdbObj.to_ddbobjs(_args);
2507
- const command = this.enc.encode((() => {
2508
- switch (type) {
2509
- case 'function':
2510
- if (this.verbose)
2511
- console.log(func + inspect(args, { colors: false }));
2512
- return 'function\n' +
2513
- `${func}\n` +
2514
- `${args.length}\n` +
2515
- `${Number(DDB.le_client)}\n`;
2516
- case 'script':
2517
- if (this.verbose)
2518
- console.log(script);
2519
- return 'script\n' +
2520
- script;
2521
- case 'variable':
2522
- if (this.verbose)
2523
- for (let i = 0; i < vars.length; i++)
2524
- console.log(`${vars[i]} = ${inspect(args[i], { colors: false })}`);
2525
- return 'variable\n' +
2526
- `${vars.join(',')}\n` +
2527
- `${vars.length}\n` +
2528
- `${Number(DDB.le_client)}\n`;
2529
- case 'connect':
2530
- if (this.verbose)
2531
- console.log('connect()');
2532
- return 'connect\n';
2533
- }
2534
- })());
2535
- this.websocket.send(concat([
2536
- this.enc.encode(`API2 ${this.sid} ${command.length} / ${this.get_rpc_options({ urgent })}\n`),
2537
- command,
2538
- ...args.map(arg => arg.pack())
2539
- ]));
2492
+ })());
2493
+ websocket.send(concat([
2494
+ this.enc.encode(`API2 ${this.sid} ${command.length} / ${this.get_rpc_options({ urgent })}\n`),
2495
+ command,
2496
+ ...args.map(arg => arg.pack())
2497
+ ]));
2498
+ });
2540
2499
  });
2541
2500
  }
2542
2501
  /** eval script through websocket (script command)
@@ -2576,8 +2535,11 @@ export class DDB {
2576
2535
  Set parse_object during this rpc, and restore the original after the end.
2577
2536
  When it is false, the returned DdbObj only contains buffer and le without parsing,
2578
2537
  so as to facilitate subsequent forwarding and serialization
2579
- */
2580
- async call(func, args = [], { urgent, node, nodes, func_type, add_node_alias, listener, parse_object, } = {}) {
2538
+ - skip_connection_check?: (内部使用) 在首次 await ddb.connect() 建立连接时不能再次调用 await this.connect() 确保连接状态,会导致循环依赖,
2539
+ 将这个 flag 设为 true 跳过连接状态检查
2540
+ (internal use) When await ddb.connect() establishes a connection for the first time, you cannot call await this.connect() again to ensure the connection status, which will lead to circular dependencies.
2541
+ Set this flag to true to skip connection status checks */
2542
+ async call(func, args = [], { urgent, node, nodes, func_type, add_node_alias, listener, parse_object, skip_connection_check } = {}) {
2581
2543
  if (node) {
2582
2544
  assert(func_type in DdbFunctionType, t('指定 node 时必须设置 func_type'));
2583
2545
  args = [
@@ -2607,7 +2569,8 @@ export class DDB {
2607
2569
  args,
2608
2570
  urgent,
2609
2571
  listener,
2610
- parse_object
2572
+ parse_object,
2573
+ skip_connection_check
2611
2574
  });
2612
2575
  }
2613
2576
  /** upload variable through websocket (variable command) */
@@ -2699,7 +2662,7 @@ export class DDB {
2699
2662
  // new DdbInt(-1), // offset
2700
2663
  // filter
2701
2664
  // allow exists
2702
- ])).value);
2665
+ ], { skip_connection_check: true })).value);
2703
2666
  this.streaming.window = {
2704
2667
  offset: 0,
2705
2668
  rows: 0,