@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
@@ -39,38 +39,25 @@ void EventChannel::stop() {
39
39
  }
40
40
  }
41
41
 
42
- bool EventChannel::push(int32_t eventType, int32_t requestId, int32_t isLast,
43
- int32_t errorId, const char *errorMsg, int32_t structId,
44
- const void *payload, int32_t payloadLen) {
45
- const uint64_t w = writeIdx_.load(std::memory_order_relaxed);
46
- if (policy_ == DropPolicy::Newest) {
47
- // Reliable: refuse (and count) the newest record when full so nothing
48
- // already queued is lost. Only the producer touches drops_ in this mode.
49
- const uint64_t r = readIdx_.load(std::memory_order_acquire);
50
- if (w - r >= numSlots_) {
51
- drops_.fetch_add(1, std::memory_order_relaxed);
52
- return false;
53
- }
54
- }
55
- // DropPolicy::Oldest: never refuse. When full this overwrites the slot holding
56
- // the oldest unread record (slot (w % numSlots) == slot (readIdx % numSlots)
57
- // once w - readIdx == numSlots). The producer stays wait-free and deliberately
58
- // does NOT read/advance readIdx_ or touch drops_ - doing so from the producer
59
- // would race the consumer, the sole writer of both. The consumer reconciles
60
- // the overrun in claim() (skip lapped records) and validate() (discard a read
61
- // torn mid-overwrite), and owns the drop counter.
62
-
63
- uint8_t *slot = ring_.data() + (w % numSlots_) * slotSize_;
42
+ void EventChannel::writeRecord(uint8_t *slot, int32_t eventType,
43
+ int32_t requestId, int32_t isLast,
44
+ int32_t errorId, const char *errorMsg,
45
+ int32_t structId, const void *payload,
46
+ int32_t payloadLen, bool droppable) {
64
47
  putI32(slot + SLOT_EVENT_TYPE, eventType);
65
48
  putI32(slot + SLOT_REQUEST_ID, requestId);
66
49
  putI32(slot + SLOT_IS_LAST, isLast);
67
50
  putI32(slot + SLOT_ERROR_ID, errorId);
68
51
  putI32(slot + SLOT_STRUCT_ID, structId);
52
+ putI32(slot + SLOT_INTERNAL_FLAGS,
53
+ droppable ? SLOT_FLAG_DROPPABLE : 0);
69
54
 
70
55
  if (errorMsg && errorMsg[0]) {
71
- std::strncpy(reinterpret_cast<char *>(slot + SLOT_ERROR_MSG), errorMsg,
72
- SLOT_ERROR_MSG_CAP - 1);
73
- slot[SLOT_ERROR_MSG + SLOT_ERROR_MSG_CAP - 1] = 0;
56
+ size_t messageBytes = 0;
57
+ while (messageBytes < SLOT_ERROR_MSG_CAP - 1 && errorMsg[messageBytes])
58
+ ++messageBytes;
59
+ std::memcpy(slot + SLOT_ERROR_MSG, errorMsg, messageBytes);
60
+ slot[SLOT_ERROR_MSG + messageBytes] = 0;
74
61
  } else {
75
62
  slot[SLOT_ERROR_MSG] = 0;
76
63
  }
@@ -81,13 +68,181 @@ bool EventChannel::push(int32_t eventType, int32_t requestId, int32_t isLast,
81
68
  std::memcpy(slot + SLOT_HEADER_SIZE, payload, static_cast<size_t>(n));
82
69
  }
83
70
  putI32(slot + SLOT_PAYLOAD_LEN, n);
71
+ }
84
72
 
85
- writeIdx_.store(w + 1, std::memory_order_release);
73
+ bool EventChannel::recordDroppable(const uint8_t *slot) {
74
+ int32_t flags = 0;
75
+ std::memcpy(&flags, slot + SLOT_INTERNAL_FLAGS, sizeof(flags));
76
+ return (flags & SLOT_FLAG_DROPPABLE) != 0;
77
+ }
78
+
79
+ std::vector<uint8_t> EventChannel::stageRecord(
80
+ int32_t eventType, int32_t requestId, int32_t isLast, int32_t errorId,
81
+ const char *errorMsg, int32_t structId, const void *payload,
82
+ int32_t payloadLen, bool droppable) {
83
+ const size_t payloadBytes = payload && payloadLen > 0
84
+ ? std::min<size_t>(
85
+ static_cast<size_t>(payloadLen),
86
+ maxPayload_)
87
+ : 0;
88
+ std::vector<uint8_t> record(align8(SLOT_HEADER_SIZE + payloadBytes), 0);
89
+ writeRecord(record.data(), eventType, requestId, isLast, errorId, errorMsg,
90
+ structId, payload, payloadLen, droppable);
91
+ return record;
92
+ }
86
93
 
87
- if (!pending_.exchange(true, std::memory_order_acq_rel) && tsfn_) {
94
+ void EventChannel::ringDoorbell() {
95
+ if (!pending_.exchange(true, std::memory_order_acq_rel) && tsfn_)
88
96
  napi_call_threadsafe_function(tsfn_, nullptr, napi_tsfn_nonblocking);
97
+ }
98
+
99
+ void EventChannel::migrateUnclaimedRingLocked(uint64_t write, uint64_t read) {
100
+ // A claimed batch belongs to JS until release() and must never be moved or
101
+ // displaced. Move every later ring record into the stable staging list when
102
+ // Oldest first enters overflow mode. This is what lets a tick behind an
103
+ // interleaved control record displace an older ring tick without overwriting
104
+ // memory JS may currently be decoding.
105
+ const size_t physical = static_cast<size_t>(write - read);
106
+ const size_t unclaimed = physical > claimedOldest_
107
+ ? physical - claimedOldest_
108
+ : 0;
109
+ for (size_t i = 0; i < unclaimed; ++i) {
110
+ const uint64_t index = read + claimedOldest_ + i;
111
+ const uint8_t *slot = ring_.data() + (index % numSlots_) * slotSize_;
112
+ int32_t payloadLen = 0;
113
+ std::memcpy(&payloadLen, slot + SLOT_PAYLOAD_LEN, sizeof(payloadLen));
114
+ const size_t payloadBytes =
115
+ payloadLen > 0
116
+ ? std::min<size_t>(static_cast<size_t>(payloadLen), maxPayload_)
117
+ : 0;
118
+ std::vector<uint8_t> record(
119
+ slot, slot + align8(SLOT_HEADER_SIZE + payloadBytes));
120
+ appendOverflowLocked(std::move(record), recordDroppable(slot));
121
+ }
122
+ skippedRing_ += unclaimed;
123
+ }
124
+
125
+ void EventChannel::appendOverflowLocked(std::vector<uint8_t> record,
126
+ bool droppable) {
127
+ overflow_.push_back(std::move(record));
128
+ if (policy_ == DropPolicy::Oldest && droppable) {
129
+ auto it = overflow_.end();
130
+ --it;
131
+ droppableOverflow_.push_back(it);
132
+ }
133
+ }
134
+
135
+ void EventChannel::makeRoomForOldestLocked(bool incomingDroppable) {
136
+ if (!incomingDroppable || droppableOverflow_.size() < numSlots_)
137
+ return;
138
+
139
+ // Control responses do not consume the bounded tick capacity. Stable list
140
+ // iterators make this O(1), irrespective of how many controls precede the
141
+ // oldest retained tick.
142
+ overflow_.erase(droppableOverflow_.front());
143
+ droppableOverflow_.pop_front();
144
+ drops_.fetch_add(1, std::memory_order_relaxed);
145
+ }
146
+
147
+ bool EventChannel::push(int32_t eventType, int32_t requestId, int32_t isLast,
148
+ int32_t errorId, const char *errorMsg, int32_t structId,
149
+ const void *payload, int32_t payloadLen,
150
+ bool droppable) {
151
+ for (;;) {
152
+ // Once overflow starts, preserve ordering by staging every later producer
153
+ // record until the consumer has copied the queue back into the ring.
154
+ if (policy_ != DropPolicy::Newest &&
155
+ overflowing_.load(std::memory_order_acquire)) {
156
+ std::lock_guard<std::mutex> lk(overflowMutex_);
157
+ if (!overflowing_.load(std::memory_order_relaxed))
158
+ continue; // consumer emptied it while we waited; retry the ring path
159
+ std::vector<uint8_t> rec =
160
+ stageRecord(eventType, requestId, isLast, errorId, errorMsg,
161
+ structId, payload, payloadLen, droppable);
162
+ if (policy_ == DropPolicy::Oldest)
163
+ makeRoomForOldestLocked(droppable);
164
+ appendOverflowLocked(std::move(rec), droppable);
165
+ ringDoorbell();
166
+ return true;
167
+ }
168
+
169
+ const uint64_t w = writeIdx_.load(std::memory_order_relaxed);
170
+ const uint64_t r = readIdx_.load(std::memory_order_acquire);
171
+ if (w - r >= numSlots_) {
172
+ if (policy_ == DropPolicy::Newest) {
173
+ drops_.fetch_add(1, std::memory_order_relaxed);
174
+ return false;
175
+ }
176
+ // Serialize the transition to staged mode with a possible consumer refill.
177
+ std::lock_guard<std::mutex> lk(overflowMutex_);
178
+ if (writeIdx_.load(std::memory_order_relaxed) -
179
+ readIdx_.load(std::memory_order_acquire) <
180
+ numSlots_)
181
+ continue; // consumer freed a slot before we acquired the handoff lock
182
+ const uint64_t w2 = writeIdx_.load(std::memory_order_relaxed);
183
+ const uint64_t r2 = readIdx_.load(std::memory_order_acquire);
184
+ overflowing_.store(true, std::memory_order_release);
185
+ if (policy_ == DropPolicy::Oldest)
186
+ migrateUnclaimedRingLocked(w2, r2);
187
+ std::vector<uint8_t> rec =
188
+ stageRecord(eventType, requestId, isLast, errorId, errorMsg,
189
+ structId, payload, payloadLen, droppable);
190
+ if (policy_ == DropPolicy::Oldest)
191
+ makeRoomForOldestLocked(droppable);
192
+ appendOverflowLocked(std::move(rec), droppable);
193
+ ringDoorbell();
194
+ return true;
195
+ }
196
+
197
+ uint8_t *slot = ring_.data() + (w % numSlots_) * slotSize_;
198
+ writeRecord(slot, eventType, requestId, isLast, errorId, errorMsg,
199
+ structId, payload, payloadLen, droppable);
200
+ writeIdx_.store(w + 1, std::memory_order_release);
201
+ ringDoorbell();
202
+ return true;
203
+ }
204
+ }
205
+
206
+ void EventChannel::refillFromOverflow() {
207
+ if (!overflowing_.load(std::memory_order_acquire))
208
+ return;
209
+ std::lock_guard<std::mutex> lk(overflowMutex_);
210
+ refillFromOverflowLocked();
211
+ }
212
+
213
+ void EventChannel::refillFromOverflowLocked() {
214
+ if (!overflowing_.load(std::memory_order_relaxed))
215
+ return;
216
+ uint64_t w = writeIdx_.load(std::memory_order_relaxed);
217
+ uint64_t r = readIdx_.load(std::memory_order_acquire);
218
+ if (policy_ == DropPolicy::Oldest && skippedRing_ > 0) {
219
+ const size_t skip =
220
+ std::min(skippedRing_, static_cast<size_t>(w - r));
221
+ r += skip;
222
+ skippedRing_ -= skip;
223
+ readIdx_.store(r, std::memory_order_release);
224
+ }
225
+ size_t free = static_cast<size_t>(numSlots_ - (w - r));
226
+ while (free > 0 && !overflow_.empty()) {
227
+ auto front = overflow_.begin();
228
+ uint8_t *slot = ring_.data() + (w % numSlots_) * slotSize_;
229
+ std::memset(slot, 0, slotSize_);
230
+ std::memcpy(slot, front->data(), front->size());
231
+ if (policy_ == DropPolicy::Oldest && recordDroppable(front->data())) {
232
+ // Tick iterators follow list order, so a droppable list head is also the
233
+ // oldest tracked tick.
234
+ if (!droppableOverflow_.empty() && droppableOverflow_.front() == front)
235
+ droppableOverflow_.pop_front();
236
+ }
237
+ overflow_.erase(front);
238
+ ++w;
239
+ --free;
240
+ }
241
+ writeIdx_.store(w, std::memory_order_release);
242
+ if (overflow_.empty()) {
243
+ droppableOverflow_.clear();
244
+ overflowing_.store(false, std::memory_order_release);
89
245
  }
90
- return true;
91
246
  }
92
247
 
93
248
  uint32_t EventChannel::claim() {
@@ -99,65 +254,38 @@ uint32_t EventChannel::claim() {
99
254
  // misses -> a stranded record (lost wakeup). The producer's exchange() is a
100
255
  // locked RMW (already a full barrier), so only the consumer needs this.
101
256
  std::atomic_thread_fence(std::memory_order_seq_cst);
102
- const uint64_t w = writeIdx_.load(std::memory_order_acquire);
103
- uint64_t r = readIdx_.load(std::memory_order_relaxed);
104
- // DropPolicy::Oldest: if the producer lapped us while we were idle, the oldest
105
- // (w - r) - numSlots records have been overwritten and are gone. Skip them so
106
- // we only hand the consumer the freshest numSlots slots. Counting + advancing
107
- // readIdx_ here is safe because the consumer is the sole writer of both readIdx_
108
- // and (in this mode) drops_. Under DropPolicy::Newest the producer keeps
109
- // w - r <= numSlots, so this branch never fires.
110
- if (w - r > numSlots_) {
111
- const uint64_t skip = (w - r) - numSlots_;
112
- drops_.fetch_add(skip, std::memory_order_relaxed);
113
- r += skip;
114
- readIdx_.store(r, std::memory_order_release);
257
+ if (policy_ == DropPolicy::Oldest) {
258
+ std::lock_guard<std::mutex> lk(overflowMutex_);
259
+ // The normal JS consumer always releases before claiming again. If a raw
260
+ // caller violates that contract, do not create a second ownership window.
261
+ if (claimedOldest_ != 0)
262
+ return static_cast<uint32_t>(claimedOldest_);
263
+ refillFromOverflowLocked();
264
+ const uint64_t w = writeIdx_.load(std::memory_order_acquire);
265
+ const uint64_t r = readIdx_.load(std::memory_order_relaxed);
266
+ claimedOldest_ = static_cast<size_t>(w - r);
267
+ return static_cast<uint32_t>(claimedOldest_);
115
268
  }
116
- return static_cast<uint32_t>(w - r);
117
- }
118
-
119
- uint32_t EventChannel::validate(uint32_t claimed) {
120
- // Consumer thread. The producer may have lapped the ring while we decoded the
121
- // batch claim() handed us, overwriting the oldest records mid-read. Compare the
122
- // current write index against the batch start (readIdx_, unchanged since claim()
123
- // because only the consumer advances it, and we have not released yet): any
124
- // record at or below the in-flight write slot was (or is being) torn and must
125
- // be discarded.
126
- //
127
- // floor = w - numSlots + 1, NOT w - numSlots. push() writes physical slot
128
- // (idx % numSlots) BEFORE publishing writeIdx_ = idx+1, so when we observe
129
- // writeIdx_ == w the producer may be mid-overwriting the slot for index w —
130
- // which is the SAME physical slot that holds index (w - numSlots). We cannot
131
- // tell "finished w-1, idle" from "mid-writing w", so we conservatively treat
132
- // index (w - numSlots) as torn too. Using w - numSlots here would deliver that
133
- // boundary record while its slot is being overwritten — a torn quote reaching
134
- // a handler (silent corruption under sustained overflow).
135
- //
136
- // Cost of being conservative: whenever the ring is observed EXACTLY full
137
- // (w - r == numSlots) — including the producer simply being idle at a full ring,
138
- // not mid-writing — this drops the single oldest record in the batch even if its
139
- // slot was intact. That is one unnecessary drop of the *stalest* queued quote,
140
- // and only once the consumer has already fallen a full ring (numSlots) behind,
141
- // i.e. exactly the overload regime where drop-oldest is meant to shed the
142
- // stalest quotes. So it is never data corruption and never more than one drop
143
- // per drain, always the least-valuable record. The exact alternative (no
144
- // over-drop AND no torn delivery) is a per-slot seqlock generation stamp;
145
- // deemed not worth an extra producer atomic on the hot path to save one
146
- // already-stale quote at the full-ring boundary.
269
+ refillFromOverflow();
147
270
  const uint64_t w = writeIdx_.load(std::memory_order_acquire);
148
271
  const uint64_t r = readIdx_.load(std::memory_order_relaxed);
149
- const uint64_t floor = (w >= numSlots_) ? (w - numSlots_ + 1) : 0;
150
- if (floor <= r)
151
- return 0; // producer never reached our batch; every decoded record is clean
152
- uint64_t torn = floor - r;
153
- if (torn > claimed)
154
- torn = claimed; // producer raced far past the batch; whole batch is torn
155
- drops_.fetch_add(torn, std::memory_order_relaxed);
156
- return static_cast<uint32_t>(torn);
272
+ return static_cast<uint32_t>(w - r);
157
273
  }
158
274
 
159
275
  void EventChannel::release(uint32_t n) {
160
- readIdx_.store(readIdx_.load(std::memory_order_relaxed) + n,
276
+ if (policy_ == DropPolicy::Oldest) {
277
+ std::lock_guard<std::mutex> lk(overflowMutex_);
278
+ const uint64_t r = readIdx_.load(std::memory_order_relaxed);
279
+ const uint64_t w = writeIdx_.load(std::memory_order_acquire);
280
+ const uint64_t released =
281
+ std::min<uint64_t>(std::min<uint64_t>(n, claimedOldest_), w - r);
282
+ readIdx_.store(r + released, std::memory_order_release);
283
+ claimedOldest_ -= static_cast<size_t>(released);
284
+ return;
285
+ }
286
+ const uint64_t r = readIdx_.load(std::memory_order_relaxed);
287
+ const uint64_t w = writeIdx_.load(std::memory_order_acquire);
288
+ readIdx_.store(r + std::min<uint64_t>(n, w - r),
161
289
  std::memory_order_release);
162
290
  }
163
291
 
@@ -5,19 +5,22 @@
5
5
  * The producer only memcpy's bytes + bumps an atomic index, then rings a
6
6
  * coalesced doorbell (a threadsafe-function used purely as a wakeup). The JS
7
7
  * consumer drains a whole batch per wakeup and decodes straight from the ring
8
- * (zero-copy) into plain objects. The CTP thread is never blocked; what happens
9
- * on overflow is set per channel by DropPolicy:
8
+ * (zero-copy) into plain objects. The fixed-ring fast path is lock-free; the
9
+ * overload staging path may briefly take a mutex. Overflow behavior is set per
10
+ * channel by DropPolicy:
10
11
  *
11
- * - DropPolicy::Newest (the trader): when full the producer refuses the new
12
- * record and bumps a counter. Nothing already queued is discarded, so an
13
- * order/trade return is never silently lost - reliability over freshness.
14
- * - DropPolicy::Oldest (market data): when full the producer overwrites the
15
- * oldest unread record so the consumer always sees the freshest quotes.
16
- * The producer stays wait-free and never touches readIdx_/drops_; the
17
- * consumer detects the overrun (claim() skips lapped records, validate()
18
- * discards any read torn mid-overwrite) and owns the drop counter. This
19
- * keeps the SPSC single-writer invariant intact: producer writes only
20
- * writeIdx_, consumer writes only readIdx_ (and, in this mode, drops_).
12
+ * - DropPolicy::Newest: when full the producer refuses the incoming record.
13
+ * Retained for small self-tests; production clients do not use it.
14
+ * - DropPolicy::Oldest (market data): droppable tick overflow enters a bounded
15
+ * staging queue and displaces the oldest unread droppable tick. Control
16
+ * responses are never deliberately discarded; control records are excluded
17
+ * from the bounded keep-newest tick capacity. The
18
+ * ring is never overwritten while JS reads it.
19
+ * - DropPolicy::Lossless (trader): overflow records enter an unbounded staging
20
+ * queue and are copied back into the ring in order as the consumer frees
21
+ * slots. The allocation/lock path is reached only during overload; normal
22
+ * callbacks retain the zero-copy SPSC fast path. Critical order/trade/query
23
+ * responses are therefore never deliberately discarded.
21
24
  *
22
25
  * Slot header layout (fixed; the JS drain in client.ts must match):
23
26
  * [0] int32 eventType
@@ -27,6 +30,7 @@
27
30
  * [16] int32 structId (-1 = no payload struct)
28
31
  * [20] int32 payloadLen
29
32
  * [24] char errorMsg[81]
33
+ * [108]int32 internal flags (not exposed to JS)
30
34
  * [112] payload bytes (8-aligned start)
31
35
  */
32
36
 
@@ -37,6 +41,9 @@
37
41
 
38
42
  #include <atomic>
39
43
  #include <cstdint>
44
+ #include <deque>
45
+ #include <list>
46
+ #include <mutex>
40
47
  #include <vector>
41
48
 
42
49
  namespace ctp {
@@ -50,13 +57,17 @@ enum {
50
57
  SLOT_PAYLOAD_LEN = 20,
51
58
  SLOT_ERROR_MSG = 24,
52
59
  SLOT_ERROR_MSG_CAP = 81,
60
+ SLOT_INTERNAL_FLAGS = 108,
53
61
  SLOT_HEADER_SIZE = 112,
54
62
  };
55
63
 
64
+ enum { SLOT_FLAG_DROPPABLE = 1 };
65
+
56
66
  // Overflow behaviour, fixed per channel at construction. See the file header.
57
67
  enum class DropPolicy {
58
- Newest, // refuse the incoming record when full (reliable; trader)
59
- Oldest, // overwrite the oldest unread record when full (freshest; market data)
68
+ Newest, // refuse incoming record when full (test-only)
69
+ Oldest, // bounded staged overflow, discard oldest staged record
70
+ Lossless, // unbounded staged overflow, preserve every record (trader)
60
71
  };
61
72
 
62
73
  class EventChannel {
@@ -71,22 +82,17 @@ public:
71
82
  void stop();
72
83
 
73
84
  // Producer (CTP callback thread). Returns false only under DropPolicy::Newest
74
- // when the ring is full (the record was refused + counted); DropPolicy::Oldest
75
- // always returns true (it overwrites the oldest unread record).
85
+ // when the ring is full. Oldest/Lossless never touch slots the JS consumer may
86
+ // currently be reading. Under Oldest, only records explicitly marked
87
+ // `droppable` may be discarded; MD control responses use the default false.
76
88
  bool push(int32_t eventType, int32_t requestId, int32_t isLast,
77
89
  int32_t errorId, const char *errorMsg, int32_t structId,
78
- const void *payload, int32_t payloadLen);
90
+ const void *payload, int32_t payloadLen,
91
+ bool droppable = false);
79
92
 
80
93
  // Consumer (JS thread).
81
94
  uint32_t claim(); // clear pending, return available record count
82
95
  void release(uint32_t n); // free n drained slots
83
- // DropPolicy::Oldest only: after claim() returned `claimed` and the consumer
84
- // decoded that many records from the current readIdx_, report how many of the
85
- // OLDEST decoded records the producer overwrote *during* the decode (it lapped
86
- // the ring). Those records hold torn bytes and must be discarded; they are
87
- // added to the drop counter. Always 0 under DropPolicy::Newest (the producer
88
- // never overwrites unread slots).
89
- uint32_t validate(uint32_t claimed);
90
96
 
91
97
  uint64_t dropCount() const { return drops_.load(std::memory_order_relaxed); }
92
98
  uint64_t readIndex() const { return readIdx_.load(std::memory_order_relaxed); }
@@ -99,6 +105,24 @@ public:
99
105
 
100
106
  private:
101
107
  static void onDoorbell(napi_env env, napi_value jsCb, void *ctx, void *data);
108
+ void writeRecord(uint8_t *slot, int32_t eventType, int32_t requestId,
109
+ int32_t isLast, int32_t errorId, const char *errorMsg,
110
+ int32_t structId, const void *payload, int32_t payloadLen,
111
+ bool droppable);
112
+ static bool recordDroppable(const uint8_t *slot);
113
+ std::vector<uint8_t> stageRecord(int32_t eventType, int32_t requestId,
114
+ int32_t isLast, int32_t errorId,
115
+ const char *errorMsg, int32_t structId,
116
+ const void *payload, int32_t payloadLen,
117
+ bool droppable);
118
+ void ringDoorbell();
119
+ using StagedRecords = std::list<std::vector<uint8_t>>;
120
+ using StagedRecordIterator = StagedRecords::iterator;
121
+ void migrateUnclaimedRingLocked(uint64_t write, uint64_t read);
122
+ void appendOverflowLocked(std::vector<uint8_t> record, bool droppable);
123
+ void makeRoomForOldestLocked(bool incomingDroppable);
124
+ void refillFromOverflow(); // consumer thread
125
+ void refillFromOverflowLocked(); // overflowMutex_ held
102
126
 
103
127
  size_t numSlots_;
104
128
  size_t slotSize_;
@@ -109,6 +133,23 @@ private:
109
133
  std::atomic<uint64_t> readIdx_{0};
110
134
  std::atomic<uint64_t> drops_{0};
111
135
  std::atomic<bool> pending_{false};
136
+ // Slow-path handoff used only after the fixed ring fills. While overflowing_
137
+ // is true the producer writes exclusively to overflow_, allowing the consumer
138
+ // (under overflowMutex_) to become the temporary ring writer while refilling.
139
+ std::atomic<bool> overflowing_{false};
140
+ std::mutex overflowMutex_;
141
+ // A list gives each staged record a stable iterator. Oldest-policy tick
142
+ // iterators are also kept in FIFO order below, so displacing the oldest tick
143
+ // remains O(1) even when non-droppable control records are interleaved.
144
+ StagedRecords overflow_;
145
+ std::deque<StagedRecordIterator> droppableOverflow_;
146
+ // Number of oldest logical ring records displaced by staged Oldest records.
147
+ // Guarded by overflowMutex_; refill advances over them before the next claim.
148
+ size_t skippedRing_ = 0;
149
+ // Oldest-policy records returned by claim() are owned by JS until release().
150
+ // They may no longer be logically displaced while the decoded batch is being
151
+ // delivered. Guarded by overflowMutex_.
152
+ size_t claimedOldest_ = 0;
112
153
  napi_threadsafe_function tsfn_{nullptr};
113
154
  };
114
155
 
@@ -0,0 +1,23 @@
1
+ /* Bounded conversion for fixed-width CTP char arrays received from outside. */
2
+ #ifndef CTP_NATIVE_CTP_FIELD_H
3
+ #define CTP_NATIVE_CTP_FIELD_H
4
+
5
+ #include <cstddef>
6
+ #include <string>
7
+
8
+ namespace ctp {
9
+
10
+ template <size_t N>
11
+ inline bool boundedCtpField(const char (&field)[N], std::string &out) {
12
+ size_t length = 0;
13
+ while (length < N && field[length] != '\0')
14
+ ++length;
15
+ if (length == N)
16
+ return false;
17
+ out.assign(field, length);
18
+ return true;
19
+ }
20
+
21
+ } // namespace ctp
22
+
23
+ #endif /* CTP_NATIVE_CTP_FIELD_H */