@hitrading/ctp-node 1.2.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 (104) hide show
  1. package/CHANGELOG.md +67 -0
  2. package/README.md +52 -31
  3. package/README.zh-CN.md +42 -26
  4. package/RELEASING.md +78 -0
  5. package/binding.gyp +13 -13
  6. package/dist/client.d.ts +40 -15
  7. package/dist/client.d.ts.map +1 -1
  8. package/dist/client.js +241 -62
  9. package/dist/client.js.map +1 -1
  10. package/dist/codec.d.ts.map +1 -1
  11. package/dist/codec.js +84 -19
  12. package/dist/codec.js.map +1 -1
  13. package/dist/generated/structs.gen.d.ts +5461 -5461
  14. package/dist/generated/structs.gen.d.ts.map +1 -1
  15. package/dist/generated/trader.gen.d.ts.map +1 -1
  16. package/dist/generated/trader.gen.js +788 -94
  17. package/dist/generated/trader.gen.js.map +1 -1
  18. package/dist/index.cjs +1896 -420
  19. package/dist/index.d.cts +1 -1
  20. package/dist/index.d.ts +1 -1
  21. package/dist/index.d.ts.map +1 -1
  22. package/dist/index.js.map +1 -1
  23. package/dist/market-data.d.ts +48 -21
  24. package/dist/market-data.d.ts.map +1 -1
  25. package/dist/market-data.js +165 -26
  26. package/dist/market-data.js.map +1 -1
  27. package/dist/native-binding.d.ts.map +1 -1
  28. package/dist/native-binding.js +5 -1
  29. package/dist/native-binding.js.map +1 -1
  30. package/dist/trader.d.ts +127 -79
  31. package/dist/trader.d.ts.map +1 -1
  32. package/dist/trader.js +788 -200
  33. package/dist/trader.js.map +1 -1
  34. package/dist/validation.d.ts +27 -0
  35. package/dist/validation.d.ts.map +1 -0
  36. package/dist/validation.js +85 -0
  37. package/dist/validation.js.map +1 -0
  38. package/docs/API.md +1437 -0
  39. package/docs/API.zh-CN.md +1278 -0
  40. package/docs/MIGRATION.md +54 -0
  41. package/docs/assets/validation.svg +27 -0
  42. package/docs/integration.md +60 -0
  43. package/docs/native-hooks.md +281 -0
  44. package/docs/native-hooks.zh-CN.md +205 -0
  45. package/docs/troubleshooting.md +257 -0
  46. package/docs/troubleshooting.zh-CN.md +220 -0
  47. package/package.json +14 -6
  48. package/prebuilds/linux-x64/@hitrading+ctp-node.node +0 -0
  49. package/prebuilds/win32-x64/@hitrading+ctp-node.node +0 -0
  50. package/scripts/bench-decode.mjs +37 -0
  51. package/scripts/bench-fullmarket-offline.mjs +207 -0
  52. package/scripts/stress-fullmarket.mjs +255 -0
  53. package/src/addon.cc +2 -2
  54. package/src/client.ts +263 -65
  55. package/src/codec.ts +86 -19
  56. package/src/generated/structs.gen.ts +5461 -5461
  57. package/src/generated/trader.gen.ts +309 -94
  58. package/src/generated/traderreq.gen.cc +194 -18
  59. package/src/generated/traderreq.gen.h +4 -0
  60. package/src/generated/traderspi.gen.cc +130 -10
  61. package/src/generated/traderspi.gen.h +4 -2
  62. package/src/index.ts +8 -1
  63. package/src/market-data.ts +219 -43
  64. package/src/native/arm.cc +114 -30
  65. package/src/native/arm.h +16 -4
  66. package/src/native/channel.cc +209 -81
  67. package/src/native/channel.h +65 -24
  68. package/src/native/ctp_field.h +23 -0
  69. package/src/native/mdapi.cc +621 -61
  70. package/src/native/mdspi.cc +221 -14
  71. package/src/native/mdspi.h +62 -9
  72. package/src/native/order_capability.h +75 -0
  73. package/src/native/risk.cc +2051 -205
  74. package/src/native/risk.h +450 -57
  75. package/src/native/shared_handle.h +37 -0
  76. package/src/native/snapshot.h +120 -0
  77. package/src/native/traderapi.cc +749 -170
  78. package/src/native-binding.ts +5 -1
  79. package/src/trader.ts +993 -229
  80. package/src/validation.ts +96 -0
  81. /package/{tradeapi → ctpsdk}/ThostFtdcMdApi.h +0 -0
  82. /package/{tradeapi → ctpsdk}/ThostFtdcTraderApi.h +0 -0
  83. /package/{tradeapi → ctpsdk}/ThostFtdcUserApiDataType.h +0 -0
  84. /package/{tradeapi → ctpsdk}/ThostFtdcUserApiStruct.h +0 -0
  85. /package/{tradeapi → ctpsdk}/error.dtd +0 -0
  86. /package/{tradeapi → ctpsdk}/error.xml +0 -0
  87. /package/{tradeapi → ctpsdk}/linux/thostmduserapi_se.so +0 -0
  88. /package/{tradeapi → ctpsdk}/linux/thosttraderapi_se.so +0 -0
  89. /package/{tradeapi → ctpsdk}/macos/thostmduserapi_se.framework/Versions/A/Headers/ThostFtdcMdApi.h +0 -0
  90. /package/{tradeapi → ctpsdk}/macos/thostmduserapi_se.framework/Versions/A/Headers/ThostFtdcUserApiDataType.h +0 -0
  91. /package/{tradeapi → ctpsdk}/macos/thostmduserapi_se.framework/Versions/A/Headers/ThostFtdcUserApiStruct.h +0 -0
  92. /package/{tradeapi → ctpsdk}/macos/thostmduserapi_se.framework/Versions/A/Resources/Info.plist +0 -0
  93. /package/{tradeapi → ctpsdk}/macos/thostmduserapi_se.framework/Versions/A/_CodeSignature/CodeResources +0 -0
  94. /package/{tradeapi → ctpsdk}/macos/thostmduserapi_se.framework/Versions/A/thostmduserapi_se +0 -0
  95. /package/{tradeapi → ctpsdk}/macos/thosttraderapi_se.framework/Versions/A/Headers/ThostFtdcTraderApi.h +0 -0
  96. /package/{tradeapi → ctpsdk}/macos/thosttraderapi_se.framework/Versions/A/Headers/ThostFtdcUserApiDataType.h +0 -0
  97. /package/{tradeapi → ctpsdk}/macos/thosttraderapi_se.framework/Versions/A/Headers/ThostFtdcUserApiStruct.h +0 -0
  98. /package/{tradeapi → ctpsdk}/macos/thosttraderapi_se.framework/Versions/A/Resources/Info.plist +0 -0
  99. /package/{tradeapi → ctpsdk}/macos/thosttraderapi_se.framework/Versions/A/_CodeSignature/CodeResources +0 -0
  100. /package/{tradeapi → ctpsdk}/macos/thosttraderapi_se.framework/Versions/A/thosttraderapi_se +0 -0
  101. /package/{tradeapi → ctpsdk}/windows/thostmduserapi_se.dll +0 -0
  102. /package/{tradeapi → ctpsdk}/windows/thostmduserapi_se.lib +0 -0
  103. /package/{tradeapi → ctpsdk}/windows/thosttraderapi_se.dll +0 -0
  104. /package/{tradeapi → ctpsdk}/windows/thosttraderapi_se.lib +0 -0
package/dist/client.d.ts CHANGED
@@ -24,7 +24,6 @@ export interface NativeClient {
24
24
  };
25
25
  _dropCount(): number;
26
26
  _readIndex?(): number;
27
- _validate?(claimed: number): number;
28
27
  close(): void;
29
28
  }
30
29
  export declare abstract class CtpClient extends EventEmitter {
@@ -44,12 +43,13 @@ export declare abstract class CtpClient extends EventEmitter {
44
43
  private started;
45
44
  private readonly pending;
46
45
  private reqSeq;
47
- /** Event ids whose requestId-0 response should resolve the oldest pending
48
- * request. Needed only for SimNow market-data login/logout, which don't echo
49
- * the id; scoping to those events means an unrelated id-0 response
50
- * (sub/unsub/error) can't hijack them. The trader echoes ids and leaves this
51
- * empty. */
52
- protected readonly zeroIdFallbackEvents: Set<number>;
46
+ private queryQueue;
47
+ private lastQuerySentAt;
48
+ private requestContextEpoch;
49
+ private explicitRequestTransitionSeq;
50
+ private queryInvalidationReason;
51
+ private scheduledQueries;
52
+ private cancelQueryDelay?;
53
53
  /** A request that goes idle this long (no response and, for multi-row queries,
54
54
  * no further rows) rejects, so awaiters don't hang forever. The timer resets
55
55
  * on each row, so a large streaming query isn't cut off by total duration. */
@@ -57,6 +57,26 @@ export declare abstract class CtpClient extends EventEmitter {
57
57
  protected constructor(native: any, layoutBlob: Int32Array, events: Map<number, string>);
58
58
  /** Reject and clear every in-flight request (on disconnect / close). */
59
59
  private rejectAllPending;
60
+ /** Invalidate all work tied to the previous connection/login context.
61
+ * Subclasses call this immediately before a login/logout transition. */
62
+ protected invalidateRequestContext(reason: string): void;
63
+ /** Begin a deliberate login/logout transition. Generated/manual public
64
+ * transition methods use this rather than calling invalidate directly. */
65
+ protected beginRequestContextTransition(reason: string): void;
66
+ /** Capture/validate the connection-login epoch across a compound async
67
+ * operation. QueryRequest protects one queued send; session/sync helpers use
68
+ * this token so a later step cannot silently continue on a new front. */
69
+ protected requestContextToken(): number;
70
+ protected requestTransitionToken(): number;
71
+ protected assertRequestContext(token: number, operation: string): void;
72
+ /** Internal state hook for a response that actually matched and successfully
73
+ * settled the current request. Streaming stale callbacks are still emitted to
74
+ * users, but cannot mutate a subclass's confirmed session identity. */
75
+ protected onRequestResolved(_eventName: string | undefined, _value: unknown, _options: CallbackOptions): void;
76
+ /** Linearize a session-request idle timeout with native login/logout state.
77
+ * Subclasses return false when the final native callback already won the
78
+ * race and its non-droppable response is merely waiting to be drained. */
79
+ protected shouldTimeoutRequest(_requestId: number, _sessionTransition: boolean): boolean;
60
80
  /** Wire up the ring view + doorbell. Subclasses call this in their ctor. */
61
81
  protected start(): void;
62
82
  /** Records dropped under backpressure (ring full). Monitor this. */
@@ -70,15 +90,15 @@ export declare abstract class CtpClient extends EventEmitter {
70
90
  * listener, just deferred so the data plane stays consistent. */
71
91
  private surfaceHandlerError;
72
92
  private decoderFor;
93
+ /** Decode one struct's raw bytes (e.g. a native snapshot) into a plain object,
94
+ * reusing the lazily-built per-struct decoder — the same codec the ring uses,
95
+ * so the result is identical to a streamed record. */
96
+ protected decodeStruct(structId: number, bytes: Uint8Array): Record<string, unknown>;
73
97
  private drain;
74
98
  /**
75
- * Drop-oldest drain (market data). The producer overwrites the oldest unread
76
- * record when full and never blocks, so the consumer can be lapped mid-read.
77
- * We therefore decode the whole claimed batch first, then ask the channel how
78
- * many of the oldest records it overwrote *during* that decode (validate()),
79
- * discard those (they hold torn bytes), and only then deliver the rest — so a
80
- * torn record never reaches a handler. The records we do deliver are always the
81
- * freshest available, and conservation holds (received + dropped == produced).
99
+ * Keep-newest drain (market data). Overflow is copied into native staging,
100
+ * never over a slot JS may be reading. A claimed batch is owned until release,
101
+ * so newer records can displace only the unclaimed logical window.
82
102
  */
83
103
  private drainOldest;
84
104
  private dispatch;
@@ -99,7 +119,12 @@ export declare abstract class CtpClient extends EventEmitter {
99
119
  * Send a request and resolve when its response arrives (matched by id).
100
120
  * `single` resolves with the one row; otherwise with the accumulated rows.
101
121
  */
102
- protected request<T>(send: (id: number) => number, single?: boolean): Promise<T>;
122
+ protected request<T>(send: (id: number) => number, single?: boolean, zeroIdEvent?: number, sessionTransition?: boolean): Promise<T>;
123
+ /** Serialize every ReqQry* / ReqQuery* call on this CTP client.
124
+ * CTP commonly allows about one query per second; putting the scheduler below
125
+ * the generated surface means raw concurrent reqQry* calls are covered too,
126
+ * not only the higher-level sync helpers. */
127
+ protected queryRequest<T>(send: (id: number) => number, single?: boolean): Promise<T>;
103
128
  /** (Re)arm a pending request's idle timeout. Called at send and reset on each
104
129
  * row, so a long streaming query isn't cut off by total elapsed time. */
105
130
  private armRequestTimer;
@@ -1 +1 @@
1
- {"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAYA,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AA+B3C,MAAM,WAAW,OAAO;IACtB,OAAO,EAAE,MAAM,CAAC;IAChB,QAAQ,EAAE,MAAM,CAAC;CAClB;AAED,MAAM,WAAW,eAAe;IAC9B,gEAAgE;IAChE,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,uDAAuD;IACvD,MAAM,CAAC,EAAE,OAAO,CAAC;IACjB,+DAA+D;IAC/D,OAAO,CAAC,EAAE,OAAO,CAAC;CACnB;AAED,MAAM,WAAW,YAAY;IAC3B,MAAM,CAAC,KAAK,EAAE,MAAM,IAAI,GAAG,IAAI,CAAC;IAChC,OAAO,IAAI,WAAW,CAAC;IACvB,MAAM,IAAI,MAAM,CAAC;IACjB,QAAQ,CAAC,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC1B,KAAK,IAAI;QACP,QAAQ,EAAE,MAAM,CAAC;QACjB,QAAQ,EAAE,MAAM,CAAC;QACjB,UAAU,EAAE,MAAM,CAAC;QACnB,UAAU,EAAE,OAAO,CAAC;KACrB,CAAC;IACF,UAAU,IAAI,MAAM,CAAC;IAErB,UAAU,CAAC,IAAI,MAAM,CAAC;IACtB,SAAS,CAAC,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM,CAAC;IACpC,KAAK,IAAI,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AC,GAAG,UAAU;IAS5E,SAAS,CAAC,aAAa,IAAI,MAAM;IAcjC;;0EAEsE;IACtE,OAAO,CAAC,iBAAiB;IA6BzB;;;OAGG;IACH,SAAS,CAAC,OAAO,CAAC,CAAC,EACjB,IAAI,EAAE,CAAC,EAAE,EAAE,MAAM,KAAK,MAAM,EAC5B,MAAM,UAAQ,EACd,WAAW,CAAC,EAAE,MAAM,EACpB,iBAAiB,UAAQ,GACxB,OAAO,CAAC,CAAC,CAAC;IAoCb;;;kDAG8C;IAC9C,SAAS,CAAC,YAAY,CAAC,CAAC,EACtB,IAAI,EAAE,CAAC,EAAE,EAAE,MAAM,KAAK,MAAM,EAC5B,MAAM,UAAQ,GACb,OAAO,CAAC,CAAC,CAAC;IA4Eb;8EAC0E;IAC1E,OAAO,CAAC,eAAe;IA0BvB;;;;;;OAMG;IACH,SAAS,CAAC,MAAM,CAAC,IAAI,EAAE,CAAC,EAAE,EAAE,MAAM,KAAK,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;CAa9D"}
package/dist/client.js CHANGED
@@ -32,11 +32,13 @@ const S_ERRID = 12;
32
32
  const S_SID = 16;
33
33
  const S_PLEN = 20;
34
34
  const S_ERRMSG = 24;
35
+ // At one send per 1.1 s, an accidental Promise.all over thousands of queries
36
+ // otherwise creates a multi-hour, unbounded Promise backlog. Normal sequential
37
+ // use and bounded concurrency stay fully automatic.
38
+ const MAX_SCHEDULED_QUERIES = 256;
35
39
  // --- Lifecycle tripwire (dev aid) --------------------------------------------
36
- // The CTP vendor DLLs deadlock inside Release() after a handful of
37
- // Init()->Release() cycles in one process - a long-standing limitation of the
38
- // vendor SDK (its api objects are not safe to create/Init/Release repeatedly),
39
- // NOT a bug in this binding. Correct usage is to create each MarketData/Trader
40
+ // Repeated Init()->Release() cycles have been observed to hang inside the
41
+ // Windows CTP vendor DLL. Correct usage is to create each MarketData/Trader
40
42
  // ONCE and reuse it, handling reconnects in place; a "reconnect by destroy-and-
41
43
  // recreate" bug instead churns through clients and will eventually wedge the
42
44
  // whole process. We count clients that were started (Init) and then closed
@@ -47,10 +49,8 @@ const S_ERRMSG = 24;
47
49
  // for any sane app (a few long-lived clients) and for the test suite. See
48
50
  // docs/native-hooks.md ("Process lifecycle").
49
51
  function recreateWarnThreshold(raw) {
50
- // Default 3: the vendor DLL deadlocks inside Release() after only ~4
51
- // Init()/Release() cycles, so a higher threshold would never fire before the
52
- // very hang it warns about. 3 lets the warning print on the close() that
53
- // precedes the typical wedge, while a create-once app (one or two long-lived
52
+ // Default 3: this warns before the low cycle counts at which hangs have been
53
+ // observed, while a create-once app (one or two long-lived
54
54
  // clients closed at shutdown) stays under it. 0 disables.
55
55
  const DEFAULT = 3;
56
56
  if (raw === undefined)
@@ -68,8 +68,8 @@ function noteClientReleased() {
68
68
  startedThenClosed > RECREATE_WARN_THRESHOLD) {
69
69
  recreateWarned = true;
70
70
  console.warn(`[ctp-node] ${startedThenClosed} CTP clients have been created and closed ` +
71
- `in this process. The CTP vendor DLLs deadlock inside Release() after a few ` +
72
- `Init()/Release() cycles, so a MarketData/Trader must be created ONCE and ` +
71
+ `in this process. Repeated CTP Init()/Release() cycles have been observed ` +
72
+ `to hang inside the vendor DLL's Release(), so a MarketData/Trader must be created ONCE and ` +
73
73
  `reused: handle reconnects in place (re-run your front-connected handshake), ` +
74
74
  `never destroy and recreate the client. Set CTP_RECREATE_WARN=0 to silence, ` +
75
75
  `or to another number to retune. See docs/native-hooks.md (Process lifecycle).`);
@@ -90,12 +90,11 @@ export class CtpClient extends EventEmitter {
90
90
  headerSize = 0;
91
91
  readPos = 0;
92
92
  // Overflow policy of the underlying channel (from _info()). Drop-oldest (market
93
- // data) takes the buffered drainOldest() path; drop-newest (trader) the inline
93
+ // data) takes the buffered drainOldest() path; lossless Trader uses inline
94
94
  // drain(). See src/native/channel.h.
95
95
  dropOldest = false;
96
96
  // Reused scratch holding a whole decoded batch for the drop-oldest path, so we
97
- // can validate against producer overruns *after* decoding and before delivering
98
- // (a torn record never reaches a handler). Indices 0..count-1 are live per drain.
97
+ // can validate logical displacement after decoding and before delivery.
99
98
  batch = [];
100
99
  // Set the instant close() begins. close() frees the native ring synchronously,
101
100
  // so if an event handler invoked from drain() calls close() mid-batch, the
@@ -108,12 +107,18 @@ export class CtpClient extends EventEmitter {
108
107
  started = false;
109
108
  pending = new Map();
110
109
  reqSeq = 0;
111
- /** Event ids whose requestId-0 response should resolve the oldest pending
112
- * request. Needed only for SimNow market-data login/logout, which don't echo
113
- * the id; scoping to those events means an unrelated id-0 response
114
- * (sub/unsub/error) can't hijack them. The trader echoes ids and leaves this
115
- * empty. */
116
- zeroIdFallbackEvents = new Set();
110
+ queryQueue = Promise.resolve();
111
+ // The first query must be eligible immediately even during the first 1.1 s
112
+ // of process uptime. Later sends replace this with a monotonic timestamp.
113
+ lastQuerySentAt = Number.NEGATIVE_INFINITY;
114
+ requestContextEpoch = 0;
115
+ // Counts only deliberate login/logout transitions. Front callbacks advance
116
+ // the context epoch but not this counter, which lets a compound handshake
117
+ // distinguish the one expected login invalidation from an inline disconnect.
118
+ explicitRequestTransitionSeq = 0;
119
+ queryInvalidationReason = "client context changed";
120
+ scheduledQueries = 0;
121
+ cancelQueryDelay;
117
122
  /** A request that goes idle this long (no response and, for multi-row queries,
118
123
  * no further rows) rejects, so awaiters don't hang forever. The timer resets
119
124
  * on each row, so a large streaming query isn't cut off by total duration. */
@@ -127,8 +132,11 @@ export class CtpClient extends EventEmitter {
127
132
  this.layouts = parseLayouts(layoutBlob);
128
133
  this.decoders = new Array(this.layouts.length);
129
134
  this.events = events;
130
- // A dropped connection won't deliver in-flight responses - fail them fast.
131
- this.on("front-disconnected", () => this.rejectAllPending("front disconnected"));
135
+ // A front transition invalidates both in-flight requests and query calls
136
+ // which are still queued behind them. This also covers providers that emit
137
+ // a new connected event without a preceding disconnected callback.
138
+ this.on("front-connected", () => this.invalidateRequestContext("front connected"));
139
+ this.on("front-disconnected", () => this.invalidateRequestContext("front disconnected"));
132
140
  }
133
141
  /** Reject and clear every in-flight request (on disconnect / close). */
134
142
  rejectAllPending(reason) {
@@ -142,6 +150,50 @@ export class CtpClient extends EventEmitter {
142
150
  p.reject(err);
143
151
  }
144
152
  }
153
+ /** Invalidate all work tied to the previous connection/login context.
154
+ * Subclasses call this immediately before a login/logout transition. */
155
+ invalidateRequestContext(reason) {
156
+ this.requestContextEpoch++;
157
+ this.queryInvalidationReason = reason;
158
+ // Wake the sole query currently waiting for its spacing deadline so it can
159
+ // observe the new epoch. Tail entries then reject in queue order without
160
+ // ever reaching native code.
161
+ this.cancelQueryDelay?.();
162
+ this.cancelQueryDelay = undefined;
163
+ this.rejectAllPending(reason);
164
+ }
165
+ /** Begin a deliberate login/logout transition. Generated/manual public
166
+ * transition methods use this rather than calling invalidate directly. */
167
+ beginRequestContextTransition(reason) {
168
+ this.explicitRequestTransitionSeq++;
169
+ this.invalidateRequestContext(reason);
170
+ }
171
+ /** Capture/validate the connection-login epoch across a compound async
172
+ * operation. QueryRequest protects one queued send; session/sync helpers use
173
+ * this token so a later step cannot silently continue on a new front. */
174
+ requestContextToken() {
175
+ return this.requestContextEpoch;
176
+ }
177
+ requestTransitionToken() {
178
+ return this.explicitRequestTransitionSeq;
179
+ }
180
+ assertRequestContext(token, operation) {
181
+ if (this.closing)
182
+ throw new Error("client closed");
183
+ if (token !== this.requestContextEpoch) {
184
+ throw new Error(`${operation} invalidated: ${this.queryInvalidationReason}`);
185
+ }
186
+ }
187
+ /** Internal state hook for a response that actually matched and successfully
188
+ * settled the current request. Streaming stale callbacks are still emitted to
189
+ * users, but cannot mutate a subclass's confirmed session identity. */
190
+ onRequestResolved(_eventName, _value, _options) { }
191
+ /** Linearize a session-request idle timeout with native login/logout state.
192
+ * Subclasses return false when the final native callback already won the
193
+ * race and its non-droppable response is merely waiting to be drained. */
194
+ shouldTimeoutRequest(_requestId, _sessionTransition) {
195
+ return true;
196
+ }
145
197
  /** Wire up the ring view + doorbell. Subclasses call this in their ctor. */
146
198
  start() {
147
199
  const info = this.native._info();
@@ -163,7 +215,7 @@ export class CtpClient extends EventEmitter {
163
215
  if (this.closing)
164
216
  return; // idempotent; also stops any in-progress drain
165
217
  this.closing = true;
166
- this.rejectAllPending("client closed");
218
+ this.invalidateRequestContext("client closed");
167
219
  if (this.started)
168
220
  noteClientReleased(); // dev tripwire (see top of file)
169
221
  this.native.close();
@@ -190,6 +242,13 @@ export class CtpClient extends EventEmitter {
190
242
  }
191
243
  return d;
192
244
  }
245
+ /** Decode one struct's raw bytes (e.g. a native snapshot) into a plain object,
246
+ * reusing the lazily-built per-struct decoder — the same codec the ring uses,
247
+ * so the result is identical to a streamed record. */
248
+ decodeStruct(structId, bytes) {
249
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
250
+ return this.decoderFor(structId)(view, bytes, 0);
251
+ }
193
252
  drain() {
194
253
  let count = this.native._claim();
195
254
  while (count > 0) {
@@ -220,20 +279,16 @@ export class CtpClient extends EventEmitter {
220
279
  }
221
280
  }
222
281
  /**
223
- * Drop-oldest drain (market data). The producer overwrites the oldest unread
224
- * record when full and never blocks, so the consumer can be lapped mid-read.
225
- * We therefore decode the whole claimed batch first, then ask the channel how
226
- * many of the oldest records it overwrote *during* that decode (validate()),
227
- * discard those (they hold torn bytes), and only then deliver the rest — so a
228
- * torn record never reaches a handler. The records we do deliver are always the
229
- * freshest available, and conservation holds (received + dropped == produced).
282
+ * Keep-newest drain (market data). Overflow is copied into native staging,
283
+ * never over a slot JS may be reading. A claimed batch is owned until release,
284
+ * so newer records can displace only the unclaimed logical window.
230
285
  */
231
286
  drainOldest() {
232
287
  let count = this.native._claim();
233
288
  while (count > 0) {
234
289
  if (this.closing)
235
290
  return;
236
- // claim() may have advanced readIdx_ past lapped records; resync our slot
291
+ // claim() may have advanced readIdx_ past displaced records; resync our slot
237
292
  // cursor to the channel's authoritative read index before decoding.
238
293
  this.readPos = this.native._readIndex();
239
294
  const numSlots = this.numSlots;
@@ -243,18 +298,12 @@ export class CtpClient extends EventEmitter {
243
298
  const slot = ((this.readPos + i) % numSlots) * slotSize;
244
299
  batch[i] = this.decodeSlot(slot);
245
300
  }
246
- // How many leading (oldest) records did the producer overwrite while we
247
- // were decoding? Those are torn — discard them (validate() counts them as
248
- // drops). The remainder were provably untouched during decode.
249
- const torn = this.native._validate(count);
250
- for (let i = 0; i < torn; i++)
251
- batch[i] = undefined; // release torn refs
252
301
  if (this.closing) {
253
- for (let i = torn; i < count; i++)
302
+ for (let i = 0; i < count; i++)
254
303
  batch[i] = undefined;
255
304
  return;
256
305
  }
257
- for (let i = torn; i < count; i++) {
306
+ for (let i = 0; i < count; i++) {
258
307
  const rec = batch[i];
259
308
  batch[i] = undefined;
260
309
  // A handler from an earlier record this batch may have called close(),
@@ -291,15 +340,10 @@ export class CtpClient extends EventEmitter {
291
340
  const plen = v.getInt32(slot + S_PLEN, true);
292
341
  const base = slot + this.headerSize;
293
342
  let value;
294
- // sid bounds check (sid < layouts.length): under the drop-oldest path a slot
295
- // may be overwritten while we decode it (a torn read). The header int32s are
296
- // normally read old-or-new intact, but DataView.getInt32 atomicity isn't
297
- // guaranteed, so a torn sid could land out of range; decoderFor() would then
298
- // build over an undefined layout and throw. The torn record is discarded by
299
- // validate() afterward, but the throw would escape the decode loop (which is
300
- // not wrapped) and crash the doorbell callback. Bounding sid keeps decodeSlot
301
- // total: an out-of-range sid yields an undefined value, harmlessly dropped.
302
- if (plen > 0 && sid >= 0 && sid < this.layouts.length)
343
+ // Keep the decoder total even if a native/provider record contains a corrupt
344
+ // struct id. Staged overflow no longer mutates ring bytes during this read.
345
+ if (plen > 0 && sid >= 0 && sid < this.layouts.length &&
346
+ plen >= this.layouts[sid].size)
303
347
  value = this.decoderFor(sid)(v, u8, base);
304
348
  else if (sid === -2 && plen >= 4)
305
349
  value = v.getInt32(base, true);
@@ -324,14 +368,22 @@ export class CtpClient extends EventEmitter {
324
368
  const rspInfo = options.rspInfo;
325
369
  // Responses (Rsp*) carry isLast (0/1 -> boolean); streaming pushes (Rtn*,
326
370
  // front, …) use -1 (-> undefined). Correlate a response to its pending
327
- // request by requestId; only for the configured zeroIdFallbackEvent
328
- // (MarketData's login) do we resolve a server requestId of 0 against the
329
- // oldest pending request — SimNow's MD login doesn't echo the id. Scoping to
330
- // that one event keeps an unrelated id-0 response from hijacking a request.
371
+ // request by requestId. SimNow's MD login/logout don't echo the id (server
372
+ // requestId 0), so those requests tag themselves with the event they await
373
+ // (zeroIdEvent); an id-0 response then matches only the pending request
374
+ // expecting THIS event — see the id-0 branch below.
331
375
  if (options.isLast !== undefined && this.pending.size > 0) {
332
376
  let key = reqId !== 0 && this.pending.has(reqId) ? reqId : undefined;
333
- if (key === undefined && reqId === 0 && this.zeroIdFallbackEvents.has(evt)) {
334
- key = this.pending.keys().next().value;
377
+ if (key === undefined && reqId === 0) {
378
+ // SimNow MD login/logout may return requestId 0. Match only a request
379
+ // that explicitly expects THIS response event; a concurrent logout can
380
+ // no longer consume a login response (or vice versa).
381
+ for (const [candidate, pending] of this.pending) {
382
+ if (pending.zeroIdEvent === evt) {
383
+ key = candidate;
384
+ break;
385
+ }
386
+ }
335
387
  }
336
388
  const p = key !== undefined ? this.pending.get(key) : undefined;
337
389
  if (p && key !== undefined) {
@@ -348,7 +400,14 @@ export class CtpClient extends EventEmitter {
348
400
  if (p.timer)
349
401
  clearTimeout(p.timer);
350
402
  this.pending.delete(key);
351
- p.resolve(p.single ? p.rows[0] : p.rows);
403
+ const result = p.single ? p.rows[0] : p.rows;
404
+ try {
405
+ this.onRequestResolved(this.events.get(evt), result, options);
406
+ p.resolve(result);
407
+ }
408
+ catch (error) {
409
+ p.reject(error);
410
+ }
352
411
  }
353
412
  else {
354
413
  this.armRequestTimer(key, p); // more rows expected: reset idle timeout
@@ -368,9 +427,12 @@ export class CtpClient extends EventEmitter {
368
427
  // getInt32, so the pending-map key MUST stay within positive int32 or it
369
428
  // would stop matching the echoed wire id past 2^31 requests (responses would
370
429
  // then only ever reject on the idle timeout). Cycle 1..2^31-1; skip 0, which
371
- // is the "no id" / zeroIdFallback sentinel. (Reuse can't collide: nothing
372
- // stays pending across 2^31 requests — the idle timeout is seconds.)
373
- this.reqSeq = this.reqSeq >= 0x7fffffff ? 1 : this.reqSeq + 1;
430
+ // is the "no id" / zeroIdFallback sentinel. Trader armed orders reserve the
431
+ // upper positive-int half (0x40000000..0x7fffffff), so a native arm error can
432
+ // never settle an unrelated JS request with the same id. Reuse cannot
433
+ // collide: nothing stays pending across a billion requests (idle timeout is
434
+ // seconds).
435
+ this.reqSeq = this.reqSeq >= 0x3fffffff ? 1 : this.reqSeq + 1;
374
436
  return this.reqSeq;
375
437
  }
376
438
  /** Message for a non-zero send code. Risk sentinels get a specific message;
@@ -386,9 +448,19 @@ export class CtpClient extends EventEmitter {
386
448
  case -10002:
387
449
  return "rate limited (order rate exceeded)";
388
450
  case -10003:
389
- return "blocked by max position cost";
451
+ return "blocked by position margin limit";
390
452
  case -10004:
391
453
  return "blocked by max position volume (lots)";
454
+ case -10005:
455
+ return "duplicate orderRef in this front/session";
456
+ case -10006:
457
+ return "request is unavailable in the current risk mode or cannot be fully covered by configured local risk controls";
458
+ case -10007:
459
+ return "required risk state or metadata unavailable (reconcile positions/orders and refresh price, multiplier and margin inputs)";
460
+ case -10008:
461
+ return "invalid order direction/hedge flag or unsupported combOffsetFlag (single-leg only)";
462
+ case -10009:
463
+ return "session transition already in flight or ambiguous; await it, or reconnect after a timeout";
392
464
  default:
393
465
  return undefined;
394
466
  }
@@ -397,7 +469,9 @@ export class CtpClient extends EventEmitter {
397
469
  * Send a request and resolve when its response arrives (matched by id).
398
470
  * `single` resolves with the one row; otherwise with the accumulated rows.
399
471
  */
400
- request(send, single = false) {
472
+ request(send, single = false, zeroIdEvent, sessionTransition = false) {
473
+ if (this.closing)
474
+ return Promise.reject(new Error("client closed"));
401
475
  const id = this.nextRequestId();
402
476
  return new Promise((resolve, reject) => {
403
477
  const entry = {
@@ -405,6 +479,8 @@ export class CtpClient extends EventEmitter {
405
479
  resolve: resolve,
406
480
  reject,
407
481
  single,
482
+ zeroIdEvent,
483
+ sessionTransition,
408
484
  };
409
485
  this.pending.set(id, entry);
410
486
  let rc;
@@ -419,13 +495,96 @@ export class CtpClient extends EventEmitter {
419
495
  if (rc !== 0) {
420
496
  this.pending.delete(id);
421
497
  const msg = this.riskRejectMessage(rc) ?? `request rejected by CTP API (code ${rc})`;
422
- reject(new Error(msg));
498
+ reject(Object.assign(new Error(msg), { ctpReturnCode: rc }));
423
499
  return;
424
500
  }
425
501
  // Backstop: if the request goes idle (no response / no further rows for a
426
502
  // multi-row query), fail rather than hang forever.
427
- this.armRequestTimer(id, entry);
503
+ // A provider is allowed to invoke the response callback inline from
504
+ // send(). In that case deliver() has already settled and removed this
505
+ // entry; do not leave a dead timeout behind for another 30 seconds.
506
+ if (this.pending.get(id) === entry)
507
+ this.armRequestTimer(id, entry);
508
+ });
509
+ }
510
+ /** Serialize every ReqQry* / ReqQuery* call on this CTP client.
511
+ * CTP commonly allows about one query per second; putting the scheduler below
512
+ * the generated surface means raw concurrent reqQry* calls are covered too,
513
+ * not only the higher-level sync helpers. */
514
+ queryRequest(send, single = false) {
515
+ if (this.closing)
516
+ return Promise.reject(new Error("client closed"));
517
+ if (this.scheduledQueries >= MAX_SCHEDULED_QUERIES) {
518
+ return Promise.reject(new Error(`query queue is full (${MAX_SCHEDULED_QUERIES}); await earlier queries before submitting more`));
519
+ }
520
+ this.scheduledQueries++;
521
+ const epoch = this.requestContextEpoch;
522
+ let resolveOuter;
523
+ let rejectOuter;
524
+ const outer = new Promise((resolve, reject) => {
525
+ resolveOuter = resolve;
526
+ rejectOuter = reject;
527
+ });
528
+ const run = this.queryQueue.then(async () => {
529
+ const invalidReason = () => this.closing
530
+ ? "client closed"
531
+ : epoch !== this.requestContextEpoch
532
+ ? this.queryInvalidationReason
533
+ : undefined;
534
+ let reason = invalidReason();
535
+ if (reason !== undefined) {
536
+ rejectOuter(new Error(reason));
537
+ return;
538
+ }
539
+ // performance.now() is monotonic; a wall-clock adjustment must not turn a
540
+ // one-second query interval into an hours-long delay or a rate-limit burst.
541
+ // Re-check after every timer: Node may round or wake a timer slightly
542
+ // early, and the public contract is AT LEAST 1100 ms between attempts.
543
+ for (;;) {
544
+ reason = invalidReason();
545
+ if (reason !== undefined) {
546
+ rejectOuter(new Error(reason));
547
+ return;
548
+ }
549
+ const wait = 1100 - (performance.now() - this.lastQuerySentAt);
550
+ if (wait <= 0)
551
+ break;
552
+ await new Promise((resolve) => {
553
+ let settled = false;
554
+ const finish = () => {
555
+ if (settled)
556
+ return;
557
+ settled = true;
558
+ clearTimeout(timer);
559
+ if (this.cancelQueryDelay === finish)
560
+ this.cancelQueryDelay = undefined;
561
+ resolve();
562
+ };
563
+ const timer = setTimeout(finish, Math.ceil(wait));
564
+ this.cancelQueryDelay = finish;
565
+ });
566
+ }
567
+ reason = invalidReason();
568
+ if (reason !== undefined) {
569
+ rejectOuter(new Error(reason));
570
+ return;
571
+ }
572
+ this.lastQuerySentAt = performance.now();
573
+ try {
574
+ resolveOuter(await this.request(send, single));
575
+ }
576
+ catch (error) {
577
+ rejectOuter(error);
578
+ }
428
579
  });
580
+ // Keep failures in scheduler plumbing observable by the caller too. The
581
+ // queue itself deliberately recovers below so one failed query cannot
582
+ // poison every later query.
583
+ void run.then(undefined, rejectOuter);
584
+ const releaseScheduledSlot = () => { this.scheduledQueries--; };
585
+ void run.then(releaseScheduledSlot, releaseScheduledSlot);
586
+ this.queryQueue = run.then(() => undefined, () => undefined);
587
+ return outer;
429
588
  }
430
589
  /** (Re)arm a pending request's idle timeout. Called at send and reset on each
431
590
  * row, so a long streaming query isn't cut off by total elapsed time. */
@@ -435,6 +594,24 @@ export class CtpClient extends EventEmitter {
435
594
  if (entry.timer)
436
595
  clearTimeout(entry.timer);
437
596
  entry.timer = setTimeout(() => {
597
+ if (this.pending.get(id) !== entry)
598
+ return;
599
+ let shouldTimeout;
600
+ try {
601
+ shouldTimeout = this.shouldTimeoutRequest(id, entry.sessionTransition === true);
602
+ }
603
+ catch (error) {
604
+ if (this.pending.delete(id))
605
+ entry.reject(error);
606
+ return;
607
+ }
608
+ if (!shouldTimeout) {
609
+ // Native final processing already happened under its state lock. The
610
+ // control response is lossless, so wait for the queued row instead of
611
+ // manufacturing a timeout/native-session split brain.
612
+ this.armRequestTimer(id, entry);
613
+ return;
614
+ }
438
615
  if (this.pending.delete(id))
439
616
  entry.reject(new Error("request timed out"));
440
617
  }, this.requestTimeoutMs);
@@ -449,6 +626,8 @@ export class CtpClient extends EventEmitter {
449
626
  * rtn-trade events, correlating by orderRef.
450
627
  */
451
628
  submit(send) {
629
+ if (this.closing)
630
+ return Promise.reject(new Error("client closed"));
452
631
  const id = this.nextRequestId();
453
632
  let rc;
454
633
  try {
@@ -460,7 +639,7 @@ export class CtpClient extends EventEmitter {
460
639
  if (rc === 0)
461
640
  return Promise.resolve();
462
641
  const msg = this.riskRejectMessage(rc) ?? `order rejected by CTP API (code ${rc})`;
463
- return Promise.reject(new Error(msg));
642
+ return Promise.reject(Object.assign(new Error(msg), { ctpReturnCode: rc }));
464
643
  }
465
644
  }
466
645
  //# sourceMappingURL=client.js.map