@hitrading/ctp-node 2.0.0 → 3.0.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.
Files changed (79) hide show
  1. package/CHANGELOG.md +67 -0
  2. package/README.md +47 -32
  3. package/README.zh-CN.md +37 -27
  4. package/RELEASING.md +78 -0
  5. package/dist/client.d.ts +36 -15
  6. package/dist/client.d.ts.map +1 -1
  7. package/dist/client.js +234 -62
  8. package/dist/client.js.map +1 -1
  9. package/dist/codec.d.ts.map +1 -1
  10. package/dist/codec.js +84 -19
  11. package/dist/codec.js.map +1 -1
  12. package/dist/generated/structs.gen.d.ts +5461 -5461
  13. package/dist/generated/structs.gen.d.ts.map +1 -1
  14. package/dist/generated/trader.gen.d.ts.map +1 -1
  15. package/dist/generated/trader.gen.js +788 -94
  16. package/dist/generated/trader.gen.js.map +1 -1
  17. package/dist/index.cjs +1875 -415
  18. package/dist/index.d.cts +1 -1
  19. package/dist/index.d.ts +1 -1
  20. package/dist/index.d.ts.map +1 -1
  21. package/dist/index.js.map +1 -1
  22. package/dist/market-data.d.ts +41 -24
  23. package/dist/market-data.d.ts.map +1 -1
  24. package/dist/market-data.js +148 -29
  25. package/dist/market-data.js.map +1 -1
  26. package/dist/native-binding.d.ts.map +1 -1
  27. package/dist/native-binding.js +4 -0
  28. package/dist/native-binding.js.map +1 -1
  29. package/dist/trader.d.ts +111 -71
  30. package/dist/trader.d.ts.map +1 -1
  31. package/dist/trader.js +774 -180
  32. package/dist/trader.js.map +1 -1
  33. package/dist/validation.d.ts +27 -0
  34. package/dist/validation.d.ts.map +1 -0
  35. package/dist/validation.js +85 -0
  36. package/dist/validation.js.map +1 -0
  37. package/docs/API.md +1437 -0
  38. package/docs/API.zh-CN.md +1278 -0
  39. package/docs/MIGRATION.md +54 -0
  40. package/docs/assets/validation.svg +27 -0
  41. package/docs/integration.md +60 -0
  42. package/docs/native-hooks.md +281 -0
  43. package/docs/native-hooks.zh-CN.md +205 -0
  44. package/docs/troubleshooting.md +257 -0
  45. package/docs/troubleshooting.zh-CN.md +220 -0
  46. package/package.json +12 -4
  47. package/prebuilds/linux-x64/@hitrading+ctp-node.node +0 -0
  48. package/prebuilds/win32-x64/@hitrading+ctp-node.node +0 -0
  49. package/scripts/bench-decode.mjs +37 -0
  50. package/scripts/bench-fullmarket-offline.mjs +207 -0
  51. package/scripts/stress-fullmarket.mjs +255 -0
  52. package/src/addon.cc +2 -2
  53. package/src/client.ts +255 -65
  54. package/src/codec.ts +86 -19
  55. package/src/generated/structs.gen.ts +5461 -5461
  56. package/src/generated/trader.gen.ts +309 -94
  57. package/src/generated/traderreq.gen.cc +194 -18
  58. package/src/generated/traderreq.gen.h +4 -0
  59. package/src/generated/traderspi.gen.cc +129 -15
  60. package/src/generated/traderspi.gen.h +4 -2
  61. package/src/index.ts +8 -1
  62. package/src/market-data.ts +199 -46
  63. package/src/native/arm.cc +114 -30
  64. package/src/native/arm.h +16 -4
  65. package/src/native/channel.cc +209 -81
  66. package/src/native/channel.h +65 -24
  67. package/src/native/ctp_field.h +23 -0
  68. package/src/native/mdapi.cc +582 -69
  69. package/src/native/mdspi.cc +219 -16
  70. package/src/native/mdspi.h +59 -10
  71. package/src/native/order_capability.h +75 -0
  72. package/src/native/risk.cc +2030 -213
  73. package/src/native/risk.h +431 -78
  74. package/src/native/shared_handle.h +37 -0
  75. package/src/native/snapshot.h +75 -16
  76. package/src/native/traderapi.cc +753 -124
  77. package/src/native-binding.ts +4 -0
  78. package/src/trader.ts +971 -204
  79. package/src/validation.ts +96 -0
package/src/client.ts CHANGED
@@ -40,6 +40,10 @@ const S_ERRID = 12;
40
40
  const S_SID = 16;
41
41
  const S_PLEN = 20;
42
42
  const S_ERRMSG = 24;
43
+ // At one send per 1.1 s, an accidental Promise.all over thousands of queries
44
+ // otherwise creates a multi-hour, unbounded Promise backlog. Normal sequential
45
+ // use and bounded concurrency stay fully automatic.
46
+ const MAX_SCHEDULED_QUERIES = 256;
43
47
 
44
48
  export interface RspInfo {
45
49
  errorId: number;
@@ -69,7 +73,6 @@ export interface NativeClient {
69
73
  _dropCount(): number;
70
74
  // Present only on drop-oldest channels (market data); used by drainOldest().
71
75
  _readIndex?(): number;
72
- _validate?(claimed: number): number;
73
76
  close(): void;
74
77
  }
75
78
 
@@ -78,12 +81,13 @@ interface Pending {
78
81
  resolve: (v: unknown) => void;
79
82
  reject: (e: unknown) => void;
80
83
  single: boolean;
84
+ zeroIdEvent?: number;
85
+ sessionTransition?: boolean;
81
86
  timer?: ReturnType<typeof setTimeout>;
82
87
  }
83
88
 
84
- /** One record decoded out of the ring, split from delivery so the drop-oldest
85
- * path can decode a whole batch, then discard any torn (overwritten) records,
86
- * before any handler runs. */
89
+ /** One decoded ring record. The keep-newest path decodes a claimed batch before
90
+ * delivery while native ownership prevents it from being displaced. */
87
91
  interface DecodedRecord {
88
92
  evt: number;
89
93
  value: unknown;
@@ -91,10 +95,8 @@ interface DecodedRecord {
91
95
  }
92
96
 
93
97
  // --- Lifecycle tripwire (dev aid) --------------------------------------------
94
- // The CTP vendor DLLs deadlock inside Release() after a handful of
95
- // Init()->Release() cycles in one process - a long-standing limitation of the
96
- // vendor SDK (its api objects are not safe to create/Init/Release repeatedly),
97
- // NOT a bug in this binding. Correct usage is to create each MarketData/Trader
98
+ // Repeated Init()->Release() cycles have been observed to hang inside the
99
+ // Windows CTP vendor DLL. Correct usage is to create each MarketData/Trader
98
100
  // ONCE and reuse it, handling reconnects in place; a "reconnect by destroy-and-
99
101
  // recreate" bug instead churns through clients and will eventually wedge the
100
102
  // whole process. We count clients that were started (Init) and then closed
@@ -105,10 +107,8 @@ interface DecodedRecord {
105
107
  // for any sane app (a few long-lived clients) and for the test suite. See
106
108
  // docs/native-hooks.md ("Process lifecycle").
107
109
  function recreateWarnThreshold(raw: string | undefined): number {
108
- // Default 3: the vendor DLL deadlocks inside Release() after only ~4
109
- // Init()/Release() cycles, so a higher threshold would never fire before the
110
- // very hang it warns about. 3 lets the warning print on the close() that
111
- // precedes the typical wedge, while a create-once app (one or two long-lived
110
+ // Default 3: this warns before the low cycle counts at which hangs have been
111
+ // observed, while a create-once app (one or two long-lived
112
112
  // clients closed at shutdown) stays under it. 0 disables.
113
113
  const DEFAULT = 3;
114
114
  if (raw === undefined) return DEFAULT;
@@ -128,8 +128,8 @@ function noteClientReleased(): void {
128
128
  recreateWarned = true;
129
129
  console.warn(
130
130
  `[ctp-node] ${startedThenClosed} CTP clients have been created and closed ` +
131
- `in this process. The CTP vendor DLLs deadlock inside Release() after a few ` +
132
- `Init()/Release() cycles, so a MarketData/Trader must be created ONCE and ` +
131
+ `in this process. Repeated CTP Init()/Release() cycles have been observed ` +
132
+ `to hang inside the vendor DLL's Release(), so a MarketData/Trader must be created ONCE and ` +
133
133
  `reused: handle reconnects in place (re-run your front-connected handshake), ` +
134
134
  `never destroy and recreate the client. Set CTP_RECREATE_WARN=0 to silence, ` +
135
135
  `or to another number to retune. See docs/native-hooks.md (Process lifecycle).`
@@ -152,12 +152,11 @@ export abstract class CtpClient extends EventEmitter {
152
152
  private headerSize = 0;
153
153
  private readPos = 0;
154
154
  // Overflow policy of the underlying channel (from _info()). Drop-oldest (market
155
- // data) takes the buffered drainOldest() path; drop-newest (trader) the inline
155
+ // data) takes the buffered drainOldest() path; lossless Trader uses inline
156
156
  // drain(). See src/native/channel.h.
157
157
  private dropOldest = false;
158
158
  // Reused scratch holding a whole decoded batch for the drop-oldest path, so we
159
- // can validate against producer overruns *after* decoding and before delivering
160
- // (a torn record never reaches a handler). Indices 0..count-1 are live per drain.
159
+ // can validate logical displacement after decoding and before delivery.
161
160
  private batch: (DecodedRecord | undefined)[] = [];
162
161
  // Set the instant close() begins. close() frees the native ring synchronously,
163
162
  // so if an event handler invoked from drain() calls close() mid-batch, the
@@ -170,12 +169,18 @@ export abstract class CtpClient extends EventEmitter {
170
169
  private started = false;
171
170
  private readonly pending = new Map<number, Pending>();
172
171
  private reqSeq = 0;
173
- /** Event ids whose requestId-0 response should resolve the oldest pending
174
- * request. Needed only for SimNow market-data login/logout, which don't echo
175
- * the id; scoping to those events means an unrelated id-0 response
176
- * (sub/unsub/error) can't hijack them. The trader echoes ids and leaves this
177
- * empty. */
178
- protected readonly zeroIdFallbackEvents = new Set<number>();
172
+ private queryQueue: Promise<void> = Promise.resolve();
173
+ // The first query must be eligible immediately even during the first 1.1 s
174
+ // of process uptime. Later sends replace this with a monotonic timestamp.
175
+ private lastQuerySentAt = Number.NEGATIVE_INFINITY;
176
+ private requestContextEpoch = 0;
177
+ // Counts only deliberate login/logout transitions. Front callbacks advance
178
+ // the context epoch but not this counter, which lets a compound handshake
179
+ // distinguish the one expected login invalidation from an inline disconnect.
180
+ private explicitRequestTransitionSeq = 0;
181
+ private queryInvalidationReason = "client context changed";
182
+ private scheduledQueries = 0;
183
+ private cancelQueryDelay?: () => void;
179
184
  /** A request that goes idle this long (no response and, for multi-row queries,
180
185
  * no further rows) rejects, so awaiters don't hang forever. The timer resets
181
186
  * on each row, so a large streaming query isn't cut off by total duration. */
@@ -193,8 +198,11 @@ export abstract class CtpClient extends EventEmitter {
193
198
  this.layouts = parseLayouts(layoutBlob);
194
199
  this.decoders = new Array(this.layouts.length);
195
200
  this.events = events;
196
- // A dropped connection won't deliver in-flight responses - fail them fast.
197
- this.on("front-disconnected", () => this.rejectAllPending("front disconnected"));
201
+ // A front transition invalidates both in-flight requests and query calls
202
+ // which are still queued behind them. This also covers providers that emit
203
+ // a new connected event without a preceding disconnected callback.
204
+ this.on("front-connected", () => this.invalidateRequestContext("front connected"));
205
+ this.on("front-disconnected", () => this.invalidateRequestContext("front disconnected"));
198
206
  }
199
207
 
200
208
  /** Reject and clear every in-flight request (on disconnect / close). */
@@ -208,6 +216,63 @@ export abstract class CtpClient extends EventEmitter {
208
216
  }
209
217
  }
210
218
 
219
+ /** Invalidate all work tied to the previous connection/login context.
220
+ * Subclasses call this immediately before a login/logout transition. */
221
+ protected invalidateRequestContext(reason: string): void {
222
+ this.requestContextEpoch++;
223
+ this.queryInvalidationReason = reason;
224
+ // Wake the sole query currently waiting for its spacing deadline so it can
225
+ // observe the new epoch. Tail entries then reject in queue order without
226
+ // ever reaching native code.
227
+ this.cancelQueryDelay?.();
228
+ this.cancelQueryDelay = undefined;
229
+ this.rejectAllPending(reason);
230
+ }
231
+
232
+ /** Begin a deliberate login/logout transition. Generated/manual public
233
+ * transition methods use this rather than calling invalidate directly. */
234
+ protected beginRequestContextTransition(reason: string): void {
235
+ this.explicitRequestTransitionSeq++;
236
+ this.invalidateRequestContext(reason);
237
+ }
238
+
239
+ /** Capture/validate the connection-login epoch across a compound async
240
+ * operation. QueryRequest protects one queued send; session/sync helpers use
241
+ * this token so a later step cannot silently continue on a new front. */
242
+ protected requestContextToken(): number {
243
+ return this.requestContextEpoch;
244
+ }
245
+
246
+ protected requestTransitionToken(): number {
247
+ return this.explicitRequestTransitionSeq;
248
+ }
249
+
250
+ protected assertRequestContext(token: number, operation: string): void {
251
+ if (this.closing) throw new Error("client closed");
252
+ if (token !== this.requestContextEpoch) {
253
+ throw new Error(`${operation} invalidated: ${this.queryInvalidationReason}`);
254
+ }
255
+ }
256
+
257
+ /** Internal state hook for a response that actually matched and successfully
258
+ * settled the current request. Streaming stale callbacks are still emitted to
259
+ * users, but cannot mutate a subclass's confirmed session identity. */
260
+ protected onRequestResolved(
261
+ _eventName: string | undefined,
262
+ _value: unknown,
263
+ _options: CallbackOptions
264
+ ): void {}
265
+
266
+ /** Linearize a session-request idle timeout with native login/logout state.
267
+ * Subclasses return false when the final native callback already won the
268
+ * race and its non-droppable response is merely waiting to be drained. */
269
+ protected shouldTimeoutRequest(
270
+ _requestId: number,
271
+ _sessionTransition: boolean
272
+ ): boolean {
273
+ return true;
274
+ }
275
+
211
276
  /** Wire up the ring view + doorbell. Subclasses call this in their ctor. */
212
277
  protected start(): void {
213
278
  const info = this.native._info();
@@ -232,7 +297,7 @@ export abstract class CtpClient extends EventEmitter {
232
297
  close(): void {
233
298
  if (this.closing) return; // idempotent; also stops any in-progress drain
234
299
  this.closing = true;
235
- this.rejectAllPending("client closed");
300
+ this.invalidateRequestContext("client closed");
236
301
  if (this.started) noteClientReleased(); // dev tripwire (see top of file)
237
302
  this.native.close();
238
303
  }
@@ -295,19 +360,15 @@ export abstract class CtpClient extends EventEmitter {
295
360
  }
296
361
 
297
362
  /**
298
- * Drop-oldest drain (market data). The producer overwrites the oldest unread
299
- * record when full and never blocks, so the consumer can be lapped mid-read.
300
- * We therefore decode the whole claimed batch first, then ask the channel how
301
- * many of the oldest records it overwrote *during* that decode (validate()),
302
- * discard those (they hold torn bytes), and only then deliver the rest — so a
303
- * torn record never reaches a handler. The records we do deliver are always the
304
- * freshest available, and conservation holds (received + dropped == produced).
363
+ * Keep-newest drain (market data). Overflow is copied into native staging,
364
+ * never over a slot JS may be reading. A claimed batch is owned until release,
365
+ * so newer records can displace only the unclaimed logical window.
305
366
  */
306
367
  private drainOldest(): void {
307
368
  let count = this.native._claim();
308
369
  while (count > 0) {
309
370
  if (this.closing) return;
310
- // claim() may have advanced readIdx_ past lapped records; resync our slot
371
+ // claim() may have advanced readIdx_ past displaced records; resync our slot
311
372
  // cursor to the channel's authoritative read index before decoding.
312
373
  this.readPos = (this.native._readIndex as () => number)();
313
374
  const numSlots = this.numSlots;
@@ -317,16 +378,11 @@ export abstract class CtpClient extends EventEmitter {
317
378
  const slot = ((this.readPos + i) % numSlots) * slotSize;
318
379
  batch[i] = this.decodeSlot(slot);
319
380
  }
320
- // How many leading (oldest) records did the producer overwrite while we
321
- // were decoding? Those are torn — discard them (validate() counts them as
322
- // drops). The remainder were provably untouched during decode.
323
- const torn = (this.native._validate as (n: number) => number)(count);
324
- for (let i = 0; i < torn; i++) batch[i] = undefined; // release torn refs
325
381
  if (this.closing) {
326
- for (let i = torn; i < count; i++) batch[i] = undefined;
382
+ for (let i = 0; i < count; i++) batch[i] = undefined;
327
383
  return;
328
384
  }
329
- for (let i = torn; i < count; i++) {
385
+ for (let i = 0; i < count; i++) {
330
386
  const rec = batch[i]!;
331
387
  batch[i] = undefined;
332
388
  // A handler from an earlier record this batch may have called close(),
@@ -363,15 +419,10 @@ export abstract class CtpClient extends EventEmitter {
363
419
  const base = slot + this.headerSize;
364
420
 
365
421
  let value: unknown;
366
- // sid bounds check (sid < layouts.length): under the drop-oldest path a slot
367
- // may be overwritten while we decode it (a torn read). The header int32s are
368
- // normally read old-or-new intact, but DataView.getInt32 atomicity isn't
369
- // guaranteed, so a torn sid could land out of range; decoderFor() would then
370
- // build over an undefined layout and throw. The torn record is discarded by
371
- // validate() afterward, but the throw would escape the decode loop (which is
372
- // not wrapped) and crash the doorbell callback. Bounding sid keeps decodeSlot
373
- // total: an out-of-range sid yields an undefined value, harmlessly dropped.
374
- if (plen > 0 && sid >= 0 && sid < this.layouts.length)
422
+ // Keep the decoder total even if a native/provider record contains a corrupt
423
+ // struct id. Staged overflow no longer mutates ring bytes during this read.
424
+ if (plen > 0 && sid >= 0 && sid < this.layouts.length &&
425
+ plen >= this.layouts[sid].size)
375
426
  value = this.decoderFor(sid)(v, u8, base);
376
427
  else if (sid === -2 && plen >= 4) value = v.getInt32(base, true);
377
428
  else value = undefined;
@@ -399,15 +450,23 @@ export abstract class CtpClient extends EventEmitter {
399
450
 
400
451
  // Responses (Rsp*) carry isLast (0/1 -> boolean); streaming pushes (Rtn*,
401
452
  // front, …) use -1 (-> undefined). Correlate a response to its pending
402
- // request by requestId; only for the configured zeroIdFallbackEvent
403
- // (MarketData's login) do we resolve a server requestId of 0 against the
404
- // oldest pending request — SimNow's MD login doesn't echo the id. Scoping to
405
- // that one event keeps an unrelated id-0 response from hijacking a request.
453
+ // request by requestId. SimNow's MD login/logout don't echo the id (server
454
+ // requestId 0), so those requests tag themselves with the event they await
455
+ // (zeroIdEvent); an id-0 response then matches only the pending request
456
+ // expecting THIS event — see the id-0 branch below.
406
457
  if (options.isLast !== undefined && this.pending.size > 0) {
407
458
  let key: number | undefined =
408
459
  reqId !== 0 && this.pending.has(reqId) ? reqId : undefined;
409
- if (key === undefined && reqId === 0 && this.zeroIdFallbackEvents.has(evt)) {
410
- key = this.pending.keys().next().value;
460
+ if (key === undefined && reqId === 0) {
461
+ // SimNow MD login/logout may return requestId 0. Match only a request
462
+ // that explicitly expects THIS response event; a concurrent logout can
463
+ // no longer consume a login response (or vice versa).
464
+ for (const [candidate, pending] of this.pending) {
465
+ if (pending.zeroIdEvent === evt) {
466
+ key = candidate;
467
+ break;
468
+ }
469
+ }
411
470
  }
412
471
  const p = key !== undefined ? this.pending.get(key) : undefined;
413
472
  if (p && key !== undefined) {
@@ -425,7 +484,13 @@ export abstract class CtpClient extends EventEmitter {
425
484
  if (options.isLast === true) {
426
485
  if (p.timer) clearTimeout(p.timer);
427
486
  this.pending.delete(key);
428
- p.resolve(p.single ? p.rows[0] : p.rows);
487
+ const result = p.single ? p.rows[0] : p.rows;
488
+ try {
489
+ this.onRequestResolved(this.events.get(evt), result, options);
490
+ p.resolve(result);
491
+ } catch (error) {
492
+ p.reject(error);
493
+ }
429
494
  } else {
430
495
  this.armRequestTimer(key, p); // more rows expected: reset idle timeout
431
496
  }
@@ -452,9 +517,12 @@ export abstract class CtpClient extends EventEmitter {
452
517
  // getInt32, so the pending-map key MUST stay within positive int32 or it
453
518
  // would stop matching the echoed wire id past 2^31 requests (responses would
454
519
  // then only ever reject on the idle timeout). Cycle 1..2^31-1; skip 0, which
455
- // is the "no id" / zeroIdFallback sentinel. (Reuse can't collide: nothing
456
- // stays pending across 2^31 requests — the idle timeout is seconds.)
457
- this.reqSeq = this.reqSeq >= 0x7fffffff ? 1 : this.reqSeq + 1;
520
+ // is the "no id" / zeroIdFallback sentinel. Trader armed orders reserve the
521
+ // upper positive-int half (0x40000000..0x7fffffff), so a native arm error can
522
+ // never settle an unrelated JS request with the same id. Reuse cannot
523
+ // collide: nothing stays pending across a billion requests (idle timeout is
524
+ // seconds).
525
+ this.reqSeq = this.reqSeq >= 0x3fffffff ? 1 : this.reqSeq + 1;
458
526
  return this.reqSeq;
459
527
  }
460
528
 
@@ -472,9 +540,19 @@ export abstract class CtpClient extends EventEmitter {
472
540
  case -10002:
473
541
  return "rate limited (order rate exceeded)";
474
542
  case -10003:
475
- return "blocked by max position cost";
543
+ return "blocked by position margin limit";
476
544
  case -10004:
477
545
  return "blocked by max position volume (lots)";
546
+ case -10005:
547
+ return "duplicate orderRef in this front/session";
548
+ case -10006:
549
+ return "request is unavailable in the current risk mode or cannot be fully covered by configured local risk controls";
550
+ case -10007:
551
+ return "required risk state or metadata unavailable (reconcile positions/orders and refresh price, multiplier and margin inputs)";
552
+ case -10008:
553
+ return "invalid order direction/hedge flag or unsupported combOffsetFlag (single-leg only)";
554
+ case -10009:
555
+ return "session transition already in flight or ambiguous; await it, or reconnect after a timeout";
478
556
  default:
479
557
  return undefined;
480
558
  }
@@ -484,7 +562,13 @@ export abstract class CtpClient extends EventEmitter {
484
562
  * Send a request and resolve when its response arrives (matched by id).
485
563
  * `single` resolves with the one row; otherwise with the accumulated rows.
486
564
  */
487
- protected request<T>(send: (id: number) => number, single = false): Promise<T> {
565
+ protected request<T>(
566
+ send: (id: number) => number,
567
+ single = false,
568
+ zeroIdEvent?: number,
569
+ sessionTransition = false
570
+ ): Promise<T> {
571
+ if (this.closing) return Promise.reject(new Error("client closed"));
488
572
  const id = this.nextRequestId();
489
573
  return new Promise<T>((resolve, reject) => {
490
574
  const entry: Pending = {
@@ -492,6 +576,8 @@ export abstract class CtpClient extends EventEmitter {
492
576
  resolve: resolve as (v: unknown) => void,
493
577
  reject,
494
578
  single,
579
+ zeroIdEvent,
580
+ sessionTransition,
495
581
  };
496
582
  this.pending.set(id, entry);
497
583
  let rc: number;
@@ -505,21 +591,124 @@ export abstract class CtpClient extends EventEmitter {
505
591
  if (rc !== 0) {
506
592
  this.pending.delete(id);
507
593
  const msg = this.riskRejectMessage(rc) ?? `request rejected by CTP API (code ${rc})`;
508
- reject(new Error(msg));
594
+ reject(Object.assign(new Error(msg), { ctpReturnCode: rc }));
509
595
  return;
510
596
  }
511
597
  // Backstop: if the request goes idle (no response / no further rows for a
512
598
  // multi-row query), fail rather than hang forever.
513
- this.armRequestTimer(id, entry);
599
+ // A provider is allowed to invoke the response callback inline from
600
+ // send(). In that case deliver() has already settled and removed this
601
+ // entry; do not leave a dead timeout behind for another 30 seconds.
602
+ if (this.pending.get(id) === entry) this.armRequestTimer(id, entry);
514
603
  });
515
604
  }
516
605
 
606
+ /** Serialize every ReqQry* / ReqQuery* call on this CTP client.
607
+ * CTP commonly allows about one query per second; putting the scheduler below
608
+ * the generated surface means raw concurrent reqQry* calls are covered too,
609
+ * not only the higher-level sync helpers. */
610
+ protected queryRequest<T>(
611
+ send: (id: number) => number,
612
+ single = false
613
+ ): Promise<T> {
614
+ if (this.closing) return Promise.reject(new Error("client closed"));
615
+ if (this.scheduledQueries >= MAX_SCHEDULED_QUERIES) {
616
+ return Promise.reject(new Error(
617
+ `query queue is full (${MAX_SCHEDULED_QUERIES}); await earlier queries before submitting more`
618
+ ));
619
+ }
620
+ this.scheduledQueries++;
621
+ const epoch = this.requestContextEpoch;
622
+ let resolveOuter!: (value: T | PromiseLike<T>) => void;
623
+ let rejectOuter!: (reason?: unknown) => void;
624
+ const outer = new Promise<T>((resolve, reject) => {
625
+ resolveOuter = resolve;
626
+ rejectOuter = reject;
627
+ });
628
+ const run = this.queryQueue.then(async () => {
629
+ const invalidReason = () => this.closing
630
+ ? "client closed"
631
+ : epoch !== this.requestContextEpoch
632
+ ? this.queryInvalidationReason
633
+ : undefined;
634
+ let reason = invalidReason();
635
+ if (reason !== undefined) {
636
+ rejectOuter(new Error(reason));
637
+ return;
638
+ }
639
+ // performance.now() is monotonic; a wall-clock adjustment must not turn a
640
+ // one-second query interval into an hours-long delay or a rate-limit burst.
641
+ // Re-check after every timer: Node may round or wake a timer slightly
642
+ // early, and the public contract is AT LEAST 1100 ms between attempts.
643
+ for (;;) {
644
+ reason = invalidReason();
645
+ if (reason !== undefined) {
646
+ rejectOuter(new Error(reason));
647
+ return;
648
+ }
649
+ const wait = 1100 - (performance.now() - this.lastQuerySentAt);
650
+ if (wait <= 0) break;
651
+ await new Promise<void>((resolve) => {
652
+ let settled = false;
653
+ const finish = () => {
654
+ if (settled) return;
655
+ settled = true;
656
+ clearTimeout(timer);
657
+ if (this.cancelQueryDelay === finish) this.cancelQueryDelay = undefined;
658
+ resolve();
659
+ };
660
+ const timer = setTimeout(finish, Math.ceil(wait));
661
+ this.cancelQueryDelay = finish;
662
+ });
663
+ }
664
+ reason = invalidReason();
665
+ if (reason !== undefined) {
666
+ rejectOuter(new Error(reason));
667
+ return;
668
+ }
669
+ this.lastQuerySentAt = performance.now();
670
+ try {
671
+ resolveOuter(await this.request<T>(send, single));
672
+ } catch (error) {
673
+ rejectOuter(error);
674
+ }
675
+ });
676
+ // Keep failures in scheduler plumbing observable by the caller too. The
677
+ // queue itself deliberately recovers below so one failed query cannot
678
+ // poison every later query.
679
+ void run.then(undefined, rejectOuter);
680
+ const releaseScheduledSlot = () => { this.scheduledQueries--; };
681
+ void run.then(releaseScheduledSlot, releaseScheduledSlot);
682
+ this.queryQueue = run.then(
683
+ () => undefined,
684
+ () => undefined
685
+ );
686
+ return outer;
687
+ }
688
+
517
689
  /** (Re)arm a pending request's idle timeout. Called at send and reset on each
518
690
  * row, so a long streaming query isn't cut off by total elapsed time. */
519
691
  private armRequestTimer(id: number, entry: Pending): void {
520
692
  if (this.requestTimeoutMs <= 0) return;
521
693
  if (entry.timer) clearTimeout(entry.timer);
522
694
  entry.timer = setTimeout(() => {
695
+ if (this.pending.get(id) !== entry) return;
696
+ let shouldTimeout: boolean;
697
+ try {
698
+ shouldTimeout = this.shouldTimeoutRequest(
699
+ id, entry.sessionTransition === true
700
+ );
701
+ } catch (error) {
702
+ if (this.pending.delete(id)) entry.reject(error);
703
+ return;
704
+ }
705
+ if (!shouldTimeout) {
706
+ // Native final processing already happened under its state lock. The
707
+ // control response is lossless, so wait for the queued row instead of
708
+ // manufacturing a timeout/native-session split brain.
709
+ this.armRequestTimer(id, entry);
710
+ return;
711
+ }
523
712
  if (this.pending.delete(id)) entry.reject(new Error("request timed out"));
524
713
  }, this.requestTimeoutMs);
525
714
  if (typeof entry.timer.unref === "function") entry.timer.unref();
@@ -533,6 +722,7 @@ export abstract class CtpClient extends EventEmitter {
533
722
  * rtn-trade events, correlating by orderRef.
534
723
  */
535
724
  protected submit(send: (id: number) => number): Promise<void> {
725
+ if (this.closing) return Promise.reject(new Error("client closed"));
536
726
  const id = this.nextRequestId();
537
727
  let rc: number;
538
728
  try {
@@ -542,6 +732,6 @@ export abstract class CtpClient extends EventEmitter {
542
732
  }
543
733
  if (rc === 0) return Promise.resolve();
544
734
  const msg = this.riskRejectMessage(rc) ?? `order rejected by CTP API (code ${rc})`;
545
- return Promise.reject(new Error(msg));
735
+ return Promise.reject(Object.assign(new Error(msg), { ctpReturnCode: rc }));
546
736
  }
547
737
  }
package/src/codec.ts CHANGED
@@ -13,6 +13,7 @@
13
13
  */
14
14
 
15
15
  import { STRUCTS } from "./generated/structs.gen.js";
16
+ import { ownStringKeys } from "./validation.js";
16
17
 
17
18
  export interface FieldLayout {
18
19
  offset: number;
@@ -26,18 +27,50 @@ export interface StructLayout {
26
27
 
27
28
  /** Parse the packed Int32 blob from native `__layoutData()`. */
28
29
  export function parseLayouts(data: Int32Array): StructLayout[] {
30
+ if (!(data instanceof Int32Array))
31
+ throw new TypeError("codec: layout data must be an Int32Array");
32
+ if (data.length === 0)
33
+ throw new Error("codec: empty layout data");
29
34
  const out: StructLayout[] = [];
30
35
  let p = 0;
31
- const n = data[p++];
36
+ const next = (label: string): number => {
37
+ if (p >= data.length) throw new Error(`codec: truncated layout data at ${label}`);
38
+ return data[p++];
39
+ };
40
+ const n = next("struct count");
41
+ let descriptorCount = 0;
42
+ while (STRUCTS[descriptorCount]?.id === descriptorCount) descriptorCount++;
43
+ if (n !== descriptorCount)
44
+ throw new Error(`codec: struct-count mismatch (layout ${n} vs descriptor ${descriptorCount})`);
32
45
  for (let i = 0; i < n; i++) {
33
- const size = data[p++];
34
- const fc = data[p++];
46
+ const size = next(`struct ${i} size`);
47
+ const fc = next(`struct ${i} field count`);
48
+ if (size <= 0 || fc < 0)
49
+ throw new Error(`codec: invalid layout header for struct ${i}`);
50
+ const desc = STRUCTS[i];
51
+ if (!desc || fc !== desc.fields.length)
52
+ throw new Error(`codec: field-count mismatch for struct ${i}`);
35
53
  const fields: FieldLayout[] = new Array(fc);
54
+ const occupied: Array<[number, number]> = [];
36
55
  for (let j = 0; j < fc; j++) {
37
- fields[j] = { offset: data[p++], size: data[p++], kind: data[p++] };
56
+ const offset = next(`struct ${i} field ${j} offset`);
57
+ const fieldSize = next(`struct ${i} field ${j} size`);
58
+ const kind = next(`struct ${i} field ${j} kind`);
59
+ const fixedSize = kind === 1 ? 4 : kind === 2 ? 2 : kind === 3 ? 8 : undefined;
60
+ if (offset < 0 || fieldSize <= 0 || offset + fieldSize > size ||
61
+ kind < 0 || kind > 3 || (fixedSize !== undefined && fieldSize !== fixedSize) ||
62
+ kind !== desc.fields[j].kind) {
63
+ throw new Error(`codec: invalid layout for struct ${i} field ${j}`);
64
+ }
65
+ if (occupied.some(([start, end]) => offset < end && start < offset + fieldSize))
66
+ throw new Error(`codec: overlapping layout for struct ${i} field ${j}`);
67
+ occupied.push([offset, offset + fieldSize]);
68
+ fields[j] = { offset, size: fieldSize, kind };
38
69
  }
39
70
  out.push({ size, fields });
40
71
  }
72
+ if (p !== data.length)
73
+ throw new Error(`codec: trailing layout data (${data.length - p} int32 values)`);
41
74
  return out;
42
75
  }
43
76
 
@@ -127,33 +160,67 @@ export function encodeStruct(
127
160
  obj: Record<string, unknown>,
128
161
  encodeStr: (s: string) => Uint8Array = (s) => utf8Encoder.encode(s)
129
162
  ): Uint8Array {
163
+ const objectKeys = ownStringKeys(obj, "codec: request");
164
+ if (fields.length !== layout.fields.length) {
165
+ throw new Error(
166
+ `codec: encode field-count mismatch (${layout.fields.length} layout vs ${fields.length} descriptor)`
167
+ );
168
+ }
169
+ const knownFields = new Set(fields.map((field) => field.js));
170
+ for (const key of objectKeys) {
171
+ if (!knownFields.has(key))
172
+ throw new TypeError(`codec: unknown request field ${key}`);
173
+ }
130
174
  const out = new Uint8Array(layout.size);
131
175
  const view = new DataView(out.buffer);
132
176
  for (let i = 0; i < layout.fields.length; i++) {
133
177
  const f = layout.fields[i];
134
- const v = obj[fields[i].js];
135
- if (v === undefined || v === null) continue;
178
+ const fieldName = fields[i].js;
179
+ const v = Object.prototype.hasOwnProperty.call(obj, fieldName)
180
+ ? obj[fieldName]
181
+ : undefined;
182
+ if (v === undefined) continue;
136
183
  switch (f.kind) {
137
184
  case 0: {
138
- // CTP char[N] fields hold up to N-1 bytes + a reserved NUL terminator
139
- // (including the comb*Flag arrays, which are at most N-1 legs), so always
140
- // keep the last byte 0. The buffer is zero-initialized, so writing at most
141
- // N-1 bytes leaves a valid NUL-terminated (or shorter) string; over-long
142
- // input is truncated rather than sent to CTP without a terminator.
143
- const bytes = encodeStr(String(v));
185
+ // CTP char[N] fields hold up to N-1 bytes + a reserved NUL terminator.
186
+ // Reject over-long encoded input: byte truncation can split a GB18030
187
+ // character and silently change an account/password/business field.
188
+ if (typeof v !== "string")
189
+ throw new TypeError(`${fields[i].js} must be a string`);
190
+ if (v.includes("\0"))
191
+ throw new RangeError(`${fields[i].js} must not contain NUL`);
192
+ const bytes = encodeStr(v);
144
193
  const cap = f.size === 1 ? 1 : f.size - 1;
145
- out.set(bytes.subarray(0, Math.min(bytes.length, cap)), f.offset);
194
+ if (bytes.length > cap) {
195
+ throw new RangeError(
196
+ `${fields[i].js} exceeds CTP field capacity (${bytes.length} encoded bytes > ${cap})`
197
+ );
198
+ }
199
+ out.set(bytes, f.offset);
146
200
  break;
147
201
  }
148
- case 1:
149
- view.setInt32(f.offset, Number(v) | 0, true);
202
+ case 1: {
203
+ if (typeof v !== "number" || !Number.isInteger(v) ||
204
+ v < -0x80000000 || v > 0x7fffffff)
205
+ throw new RangeError(`${fields[i].js} must be an int32`);
206
+ view.setInt32(f.offset, v, true);
150
207
  break;
151
- case 2:
152
- view.setInt16(f.offset, Number(v) | 0, true);
208
+ }
209
+ case 2: {
210
+ if (typeof v !== "number" || !Number.isInteger(v) ||
211
+ v < -0x8000 || v > 0x7fff)
212
+ throw new RangeError(`${fields[i].js} must be an int16`);
213
+ view.setInt16(f.offset, v, true);
153
214
  break;
154
- case 3:
155
- view.setFloat64(f.offset, Number(v), true);
215
+ }
216
+ case 3: {
217
+ if (typeof v !== "number" || !Number.isFinite(v))
218
+ throw new RangeError(`${fields[i].js} must be finite`);
219
+ view.setFloat64(f.offset, v, true);
156
220
  break;
221
+ }
222
+ default:
223
+ throw new Error(`codec: unknown encode kind ${f.kind} for ${fields[i].js}`);
157
224
  }
158
225
  }
159
226
  return out;