dolphindb 2.0.505 → 2.0.508

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
@@ -239,34 +239,60 @@ class DdbObj {
239
239
  });
240
240
  }
241
241
  case DdbForm.matrix: {
242
- // matrix([
242
+ // rename!(
243
+ // 1..9$3:3,
243
244
  // [1, 2, 3],
244
- // [3, 2, 1]
245
- // ])
246
- // <Buffer 00 has_row_label = , has_col_label =
247
- // 04 03 type = int, form = matrix
248
- // 03 00 00 00 02 00 00 00 rows = 3, cols = 2
249
- // 01 00 00 00 02 00 00 00 03 00 00 00 03 00 00 00 02 00 00 00 01 00 00 00>
245
+ // ['c1', 'c2', 'c3']
246
+ // )
247
+ // <Buffer 04 03 type = int, form = matrix
248
+ // 03 has_row_label (& 0x01) = 1, has_col_label (& 0x02) = 1
249
+ // row labels
250
+ // 04 01 type = int, form = vector
251
+ // 03 00 00 00 01 00 00 00 rows = 3, cols = 1
252
+ // 01 00 00 00 02 00 00 00 03 00 00 00 vector values
253
+ // col labels
254
+ // 12 01 type = string, form = vector
255
+ // 03 00 00 00 01 00 00 00 rows = 3, cols = 1
256
+ // 63 31 00 63 32 00 63 33 00
257
+ // matrix data
258
+ // 04 03 type = matrix.type, form = matrix
259
+ // 03 00 00 00 03 00 00 00 rows = 3, cols = 3
250
260
  const dv = new DataView(buf.buffer, buf.byteOffset + i_data);
251
261
  const label_flags = buf_data[0];
252
262
  const has_row_labels = Boolean(label_flags & 0x01);
253
263
  const has_col_labels = Boolean(label_flags & 0x02);
254
- if (has_row_labels || has_col_labels)
255
- throw new Error('matrix 暂不支持 row labels 和 col labels');
256
- const datatype = buf_data[1];
257
- const rows = dv.getUint32(3, le);
258
- const cols = dv.getUint32(7, le);
259
- const [len_items, value] = this.parse_vector_items(buf_data.subarray(11), le, datatype, rows * cols // 假设小于 2**32
264
+ let row_labels = null;
265
+ let col_labels = null;
266
+ let offset = 1;
267
+ if (has_row_labels) {
268
+ row_labels = this.parse_vector(buf_data.subarray(offset + 2), le, buf_data[offset]);
269
+ row_labels.length += 2;
270
+ offset += row_labels.length;
271
+ }
272
+ if (has_col_labels) {
273
+ col_labels = this.parse_vector(buf_data.subarray(offset + 2), le, buf_data[offset]);
274
+ col_labels.length += 2;
275
+ offset += col_labels.length;
276
+ }
277
+ if (buf_data[offset] !== type)
278
+ throw new Error('matrix.datatype !== matrix.type');
279
+ const rows = dv.getUint32(offset + 2, le);
280
+ const cols = dv.getUint32(offset + 6, le);
281
+ const [len_items, data] = this.parse_vector_items(buf_data.subarray(offset + 10), le, type, rows * cols // 假设小于 2**32
260
282
  );
283
+ offset += 10 + len_items;
261
284
  return new this({
262
285
  le,
263
286
  form,
264
287
  type,
265
- length: i_data + 11 + len_items,
288
+ length: i_data + offset,
266
289
  rows,
267
290
  cols,
268
- datatype,
269
- value,
291
+ value: {
292
+ rows: row_labels,
293
+ cols: col_labels,
294
+ data,
295
+ },
270
296
  });
271
297
  }
272
298
  default:
@@ -618,7 +644,7 @@ class DdbObj {
618
644
  }
619
645
  pack() {
620
646
  const { form, type, value } = this;
621
- let header = new Uint8Array(new ArrayBuffer(2));
647
+ let header = new Uint8Array(2);
622
648
  header[0] = type;
623
649
  header[1] = form;
624
650
  const body = (() => {
@@ -759,12 +785,17 @@ class DdbObj {
759
785
  value[0].pack(),
760
786
  value[1].pack(),
761
787
  ];
762
- case DdbForm.matrix:
788
+ case DdbForm.matrix: {
789
+ const { rows, cols, data } = value;
763
790
  return [
764
- Uint8Array.of(0, this.datatype, this.form),
791
+ Uint8Array.of((rows && 0x01) | (cols && 0x02)),
792
+ ...rows ? [rows.pack()] : [],
793
+ ...cols ? [cols.pack()] : [],
794
+ Uint8Array.of(this.type, this.form),
765
795
  Uint32Array.of(this.rows, this.cols),
766
- ...DdbObj.pack_vector_body(value, this.datatype, this.rows * this.cols)
796
+ ...DdbObj.pack_vector_body(data, this.type, this.rows * this.cols)
767
797
  ];
798
+ }
768
799
  default:
769
800
  throw new Error(`${DdbForm[form]} 暂不支持序列化`);
770
801
  }
@@ -878,16 +909,22 @@ class DdbObj {
878
909
  case DdbForm.dict:
879
910
  return `dict<${DdbType[this.value[0].type]}, ${DdbType[this.value[1].type]}>`;
880
911
  case DdbForm.matrix:
881
- return `matrix<${DdbType[this.datatype]}>[${this.rows} rows][${this.cols} cols]`;
912
+ return `matrix<${DdbType[this.type]}>[${this.rows} rows][${this.cols} cols]`;
882
913
  default:
883
914
  return `${DdbForm[this.form]} ${tname}`;
884
915
  }
885
916
  })();
886
917
  const data = (() => {
887
- if (this.form === DdbForm.pair)
888
- return `${(0, utils_js_1.inspect)(this.value[0], options)}, ${(0, utils_js_1.inspect)(this.value[1], options)}`;
889
- if (this.form === DdbForm.scalar && this.type === DdbType.functiondef)
890
- return (0, utils_js_1.inspect)(this.value.name, options);
918
+ switch (this.form) {
919
+ case DdbForm.pair:
920
+ return `${(0, utils_js_1.inspect)(this.value[0], options)}, ${(0, utils_js_1.inspect)(this.value[1], options)}`;
921
+ case DdbForm.scalar:
922
+ switch (this.type) {
923
+ case DdbType.functiondef:
924
+ return (0, utils_js_1.inspect)(this.value.name, options);
925
+ }
926
+ break;
927
+ }
891
928
  if (this.value instanceof Uint8Array)
892
929
  return (0, utils_js_1.inspect)((0, utils_js_1.typed_array_to_buffer)(this.value), options);
893
930
  return (0, utils_js_1.inspect)(this.value, options);
@@ -901,21 +938,26 @@ class DdbObj {
901
938
  for (let i = 0; i < this.rows; i++) {
902
939
  let row = {};
903
940
  for (let j = 0; j < this.cols; j++) {
904
- const { type, name, value } = this.value[j]; // column
941
+ const { type, name, value: values } = this.value[j]; // column
905
942
  switch (type) {
906
- case DdbType.bool:
907
- row[name] = Boolean(value[i]);
943
+ case DdbType.bool: {
944
+ const value = values[i];
945
+ row[name] = value === exports.nulls.int8 ?
946
+ null
947
+ :
948
+ Boolean(value);
908
949
  break;
950
+ }
909
951
  case DdbType.ipaddr:
910
- row[name] = value.subarray(16 * i, 16 * (i + 1));
952
+ row[name] = values.subarray(16 * i, 16 * (i + 1));
911
953
  break;
912
954
  case DdbType.symbol_extended: {
913
- const { base, data } = value;
955
+ const { base, data } = values;
914
956
  row[name] = base[data[i]];
915
957
  break;
916
958
  }
917
959
  default:
918
- row[name] = value[i];
960
+ row[name] = values[i];
919
961
  }
920
962
  }
921
963
  rows[i] = row;
@@ -1367,7 +1409,6 @@ class DDB {
1367
1409
  /** utf-8 text decoder */
1368
1410
  this.dec = new TextDecoder('utf-8');
1369
1411
  this.enc = new TextEncoder();
1370
- this.print_buffer = false;
1371
1412
  this.websocket = null;
1372
1413
  /** little endian (server) */
1373
1414
  this.le = true;
@@ -1379,8 +1420,13 @@ class DDB {
1379
1420
  this.password = '123456';
1380
1421
  /** python session flag (2048) */
1381
1422
  this.python = false;
1423
+ this.print_message_buffer = false;
1424
+ this.print_object_buffer = false;
1425
+ this.print_message = true;
1382
1426
  this.parse_object = true;
1383
- this.presult = Promise.resolve(null);
1427
+ /** DdbMessage listeners */
1428
+ this.listeners = [];
1429
+ this.promise = Promise.resolve(null);
1384
1430
  this.url = url;
1385
1431
  if (options.autologin !== undefined)
1386
1432
  this.autologin = options.autologin;
@@ -1391,24 +1437,10 @@ class DDB {
1391
1437
  if (options.python !== undefined)
1392
1438
  this.python = options.python;
1393
1439
  }
1394
- /** message handler */
1395
- on_message({ type, data }, _this) {
1396
- switch (type) {
1397
- case 'print':
1398
- console.log(data);
1399
- return;
1400
- case 'object':
1401
- if (this.print_buffer)
1402
- console.log((0, utils_js_1.typed_array_to_buffer)(data.buffer));
1403
- return;
1404
- }
1405
- }
1406
- /** resolver, rejector, promise of last rpc */
1407
- presolver(message) { }
1408
- prejector(error) { }
1409
1440
  get connected() {
1410
1441
  return this.websocket?.readyState === ws_1.WebSocket.OPEN;
1411
1442
  }
1443
+ on_message(event) { }
1412
1444
  /** Establish the actual WebSocket connection to the DolphinDB corresponding to the URL
1413
1445
  - options?:
1414
1446
  - url?: DolphinDB WebSocket URL. By default, the WebSocket URL passed in when the instance is initialized is used
@@ -1436,36 +1468,44 @@ class DDB {
1436
1468
  await this.rpc('connect', {});
1437
1469
  },
1438
1470
  on_message: event => {
1439
- const buf = new Uint8Array(event.data);
1440
- try {
1441
- const message = this.parse_message(buf);
1442
- this.on_message(message, this);
1443
- if (message.type === 'print')
1444
- return;
1445
- this.presolver(message);
1446
- }
1447
- catch (error) {
1448
- this.prejector(error);
1449
- }
1471
+ this.on_message(event);
1450
1472
  }
1451
1473
  });
1452
- if (!this.python)
1453
- await this.eval('def pnode_run (nodes, func_name, args, add_node_alias = true) {\n' +
1474
+ await this.eval(this.python ?
1475
+ 'def pnode_run (nodes, func_name, args, add_node_alias):\n' +
1454
1476
  ' nargs = size(args)\n' +
1455
1477
  ' func = funcByName(func_name)\n' +
1456
1478
  ' \n' +
1457
- ' if (!nargs)\n' +
1479
+ ' if not nargs:\n' +
1458
1480
  ' return pnodeRun(func, nodes, add_node_alias)\n' +
1459
1481
  ' \n' +
1460
- ' args_partial = array(any, 1 + nargs, 1 + nargs)\n' +
1461
- ' args_partial[0] = func\n' +
1462
- ' args_partial[1:] = args\n' +
1482
+ ' args_partial = [ ]\n' +
1483
+ ' args_partial.append(func)\n' +
1484
+ ' for a in args:\n' +
1485
+ ' args_partial.append(a)\n' +
1486
+ ' \n' +
1463
1487
  ' return pnodeRun(\n' +
1464
1488
  ' unifiedCall(partial, args_partial),\n' +
1465
1489
  ' nodes,\n' +
1466
1490
  ' add_node_alias\n' +
1467
- ' )\n' +
1468
- '}\n', { urgent: true });
1491
+ ' )\n'
1492
+ :
1493
+ 'def pnode_run (nodes, func_name, args, add_node_alias = true) {\n' +
1494
+ ' nargs = size(args)\n' +
1495
+ ' func = funcByName(func_name)\n' +
1496
+ ' \n' +
1497
+ ' if (!nargs)\n' +
1498
+ ' return pnodeRun(func, nodes, add_node_alias)\n' +
1499
+ ' \n' +
1500
+ ' args_partial = array(any, 1 + nargs, 1 + nargs)\n' +
1501
+ ' args_partial[0] = func\n' +
1502
+ ' args_partial[1:] = args\n' +
1503
+ ' return pnodeRun(\n' +
1504
+ ' unifiedCall(partial, args_partial),\n' +
1505
+ ' nodes,\n' +
1506
+ ' add_node_alias\n' +
1507
+ ' )\n' +
1508
+ '}\n', { urgent: true });
1469
1509
  if (this.autologin)
1470
1510
  if (this.python)
1471
1511
  await this.eval(`login(${this.username.quote('double')}, ${this.password.quote('double')})`, { urgent: true });
@@ -1506,45 +1546,64 @@ class DDB {
1506
1546
  disconnect() {
1507
1547
  if (this.connected)
1508
1548
  this.websocket.close(1000);
1509
- this.presolver = buf => { };
1510
- this.prejector = error => { };
1511
- this.presult = Promise.resolve(null);
1549
+ this.on_message = () => { };
1550
+ this.promise = Promise.resolve(null);
1512
1551
  }
1513
1552
  /** rpc through websocket (function/script/variable command)
1514
1553
  - type: API 类型: 'script' | 'function' | 'variable'
1515
1554
  - options:
1516
1555
  - urgent?: 决定 `行为标识` 那一行字符串的取值(只适用于 script 和 function)
1517
1556
  - vars?: type === 'variable' 时必传,variable 指令中待上传的变量名
1518
- - on_message?: 在该次 rpc 期间设置 message handler, 结束后恢复原有
1557
+ - handler?: Process messages during this rpc (DdbMessage)
1519
1558
  - parse_object?: 在该次 rpc 期间设置 parse_object, 结束后恢复原有,为 false 时返回的 DdbObj 仅含有 buffer 和 le,
1520
1559
  不做解析,以便后续转发、序列化
1521
1560
  */
1522
- async rpc(type, { script, func, args = [], vars = [], urgent, on_message, parse_object, }) {
1561
+ async rpc(type, { script, func, args = [], vars = [], urgent, listener, parse_object, }) {
1523
1562
  if (!this.websocket)
1524
1563
  await this.connect();
1525
1564
  if (!this.connected)
1526
1565
  throw new Error(`${this.url} is already disconnected`);
1566
+ // this 上的当前配置需要在 message 到达后使用,先保存起来
1567
+ const _handlers = [...this.listeners].reverse();
1527
1568
  // 临界区:保证多个 rpc 并发时形成 promise 链
1528
1569
  // ddb 世界观:需要等待上一个 rpc 结果从 server 返回之后才能发起下一个调用
1529
1570
  // 违反世界观可能造成:
1530
1571
  // 1. 并发多个请求只返回第一个结果(阻塞,需后续请求疏通)
1531
1572
  // 2. windows 下 ddb server 返回多个相同的结果
1532
- const ptail = this.presult;
1533
- let presolver;
1534
- let prejector;
1535
- const presult = this.presult = new Promise((resolve, reject) => {
1536
- presolver = resolve;
1537
- prejector = reject;
1573
+ const ptail = this.promise;
1574
+ let resolve;
1575
+ let reject;
1576
+ const promise = this.promise = new Promise((_resolve, _reject) => {
1577
+ resolve = _resolve;
1578
+ reject = _reject;
1538
1579
  });
1539
1580
  try {
1540
1581
  await ptail;
1541
1582
  }
1542
1583
  catch { }
1543
- this.presolver = presolver;
1544
- this.prejector = prejector;
1545
- // 临界区结束,只有一个 rpc 请求可以写 WebSocket
1546
- if (urgent && type !== 'script' && type !== 'function')
1547
- throw new Error('urgent 只适用于 script 和 funciton');
1584
+ // 临界区结束,只有一个 rpc 函数调用运行到这里,可以独占 this.on_message 然后写 WebSocket
1585
+ this.on_message = ({ data: buffer }) => {
1586
+ const buf = new Uint8Array(buffer);
1587
+ if (this.print_message_buffer)
1588
+ console.log((0, utils_js_1.typed_array_to_buffer)(buf));
1589
+ const message = this.parse_message(buf, parse_object);
1590
+ listener?.(message, this);
1591
+ for (const listener of _handlers)
1592
+ listener(message, this);
1593
+ const { type, data } = message;
1594
+ switch (type) {
1595
+ case 'print':
1596
+ if (this.print_message)
1597
+ console.log(data);
1598
+ return;
1599
+ case 'object':
1600
+ resolve(data);
1601
+ return;
1602
+ case 'error':
1603
+ reject(data);
1604
+ return;
1605
+ }
1606
+ };
1548
1607
  args = this.to_ddbobjs(args);
1549
1608
  const command = this.enc.encode((() => {
1550
1609
  switch (type) {
@@ -1565,54 +1624,40 @@ class DDB {
1565
1624
  return 'connect\n';
1566
1625
  }
1567
1626
  })());
1568
- const message = (0, utils_js_1.concat)([
1627
+ this.websocket.send((0, utils_js_1.concat)([
1569
1628
  this.enc.encode(`API2 ${this.sid} ${command.length} / ${this.get_rpc_options({ urgent })}\n`),
1570
1629
  command,
1571
1630
  ...args.map((arg) => arg.pack())
1572
- ]);
1573
- const _on_message = this.on_message;
1574
- const _parse_object = this.parse_object;
1575
- if (on_message)
1576
- this.on_message = on_message;
1577
- if (parse_object !== undefined)
1578
- this.parse_object = parse_object;
1579
- try {
1580
- this.websocket.send(message);
1581
- const { data } = (await presult);
1582
- return data;
1583
- }
1584
- finally {
1585
- this.on_message = _on_message;
1586
- this.parse_object = _parse_object;
1587
- }
1631
+ ]));
1632
+ return promise;
1588
1633
  }
1589
1634
  /** eval script through websocket (script command)
1590
- - script?: 执行的脚本
1591
- - options?: 执行选项
1592
- - urgent?: 紧急 flag,确保提交的脚本使用 urgent worker 处理,防止被其它作业阻塞
1593
- - on_message?: 在该次 rpc 期间设置 message handler, 结束后恢复原有
1594
- - parse_object?: 在该次 rpc 期间设置 parse_object, 结束后恢复原有,为 false 时返回的 DdbObj 仅含有 buffer 和 le,
1595
- 不做解析,以便后续转发、序列化
1635
+ - script?: Script to execute
1636
+ - options?: execution options
1637
+ - urgent?: Urgent flag to ensure that submitted scripts are processed by urgent workers to prevent being blocked by other jobs
1638
+ - listener?: Process messages during this rpc (DdbMessage)
1639
+ - parse_object?: Set parse_object during this rpc, and restore the original after the end.
1640
+ When it is false, the returned DdbObj only contains buffer and le without parsing,
1641
+ so as to facilitate subsequent forwarding and serialization
1596
1642
  */
1597
- async eval(script, { urgent, on_message, parse_object, } = {}) {
1598
- return this.rpc('script', { script, urgent, on_message, parse_object });
1643
+ async eval(script, { urgent, listener, parse_object, } = {}) {
1644
+ return this.rpc('script', { script, urgent, listener, parse_object });
1599
1645
  }
1600
1646
  /** call function through websocket (function command)
1601
- - func: 函数名
1602
- - args?: `[ ]` 调用参数 (传入的原生 string 和 boolean 会被自动转换为 DdbObj<string> 和 DdbObj<boolean>)
1603
- - options?: 调用选项
1604
- - urgent?: 紧急 flag。使用 urgent worker 执行,防止被其它作业阻塞
1605
- - node?: 设置结点 alias 时发送到集群中对应的结点执行 (使用 DolphinDB 中的 rpc 方法)
1606
- - nodes?: 设置多个结点 alias 时发送到集群中对应的多个结点执行 (使用 DolphinDB 中的 pnodeRun 方法)
1607
- - func_type?: 设置 node 参数时必传,需指定函数类型,其它情况下不传
1608
- - add_node_alias?: 设置 nodes 参数时选传,其它情况不传
1609
- - on_message?: 在该次 rpc 期间设置 message handler, 结束后恢复原有
1610
- - parse_object?: 在该次 rpc 期间设置 parse_object, 结束后恢复原有,为 false 时返回的 DdbObj 仅含有 buffer 和 le,
1611
- 不做解析,以便后续转发、序列化
1647
+ - func: function name
1648
+ - args?: `[ ]` Call parameters (the incoming native string and boolean will be automatically converted to DdbObj<string> and DdbObj<boolean>)
1649
+ - options?: call options
1650
+ - urgent?: Emergency flag. Use urgent worker execution to prevent being blocked by other jobs
1651
+ - node?: When the node alias is set, it is sent to the corresponding node in the cluster for execution (using the rpc method in DolphinDB)
1652
+ - nodes?: When setting multiple node aliases, send them to the corresponding multiple nodes in the cluster for execution (using the pnodeRun method in DolphinDB)
1653
+ - func_type?: It must be passed when setting the node parameter, the function type needs to be specified, and it is not passed in other cases
1654
+ - add_node_alias?: Select to pass when setting the nodes parameter, otherwise not pass
1655
+ - listener?: Process messages during this rpc (DdbMessage)
1656
+ - parse_object?: Set parse_object during this rpc, and restore the original after the end.
1657
+ When it is false, the returned DdbObj only contains buffer and le without parsing,
1658
+ so as to facilitate subsequent forwarding and serialization
1612
1659
  */
1613
- async call(func, args = [], { urgent, node, nodes, func_type, add_node_alias, on_message, parse_object, } = {}) {
1614
- if (this.python)
1615
- throw new Error('call doesn\'t support python session yet');
1660
+ async call(func, args = [], { urgent, node, nodes, func_type, add_node_alias, listener, parse_object, } = {}) {
1616
1661
  if (node) {
1617
1662
  if (typeof func_type === 'undefined')
1618
1663
  throw new Error('指定 node 时必须设置 func_type');
@@ -1642,7 +1687,7 @@ class DDB {
1642
1687
  func,
1643
1688
  args,
1644
1689
  urgent,
1645
- on_message,
1690
+ listener,
1646
1691
  parse_object
1647
1692
  });
1648
1693
  }
@@ -1651,10 +1696,10 @@ class DDB {
1651
1696
  /** Uploaded variables' name */
1652
1697
  vars,
1653
1698
  /** Uploaded variables' value */
1654
- args, { on_message, parse_object, } = {}) {
1699
+ args, { listener, parse_object, } = {}) {
1655
1700
  if (!args.length || args.length !== vars.length)
1656
- throw new Error('variable 指令参数为空或参数名为空,或数量不匹配');
1657
- return this.rpc('variable', { vars, args, on_message, parse_object });
1701
+ throw new Error('variable command parameter is empty or parameter name is empty, or the number does not match');
1702
+ return this.rpc('variable', { vars, args, listener, parse_object });
1658
1703
  }
1659
1704
  /** 解析服务端响应报文,返回去掉 header 的 data buf */
1660
1705
  parse_message(buf, parse_object = this.parse_object) {
@@ -1687,12 +1732,17 @@ class DDB {
1687
1732
  /** 'OK' 表示成功,其它文本表示失败 */
1688
1733
  const message = this.dec.decode(buf.subarray(i_ls_1, i_lf_1));
1689
1734
  if (message !== 'OK')
1690
- throw new Error(message);
1735
+ return {
1736
+ type: 'error',
1737
+ data: new Error(message)
1738
+ };
1691
1739
  const buf_obj = buf.subarray(i_lf_1 + 1);
1740
+ if (this.print_object_buffer)
1741
+ console.log((0, utils_js_1.typed_array_to_buffer)(buf_obj));
1692
1742
  return {
1693
1743
  type: 'object',
1694
1744
  data: parse_object ?
1695
- Object.assign(DdbObj.parse(buf_obj, this.le), { buffer: buf_obj })
1745
+ DdbObj.parse(buf_obj, this.le)
1696
1746
  :
1697
1747
  new DdbObj({
1698
1748
  form: DdbForm.scalar,