You are viewing a plain text version of this content. The canonical link for it is here.
Posted to dev@ignite.apache.org by "JohnSColeman (via GitHub)" <gi...@apache.org> on 2026/04/05 12:04:54 UTC

[PR] Fix four bugs in ClientSocket, Cursor and Errors [ignite-nodejs-thin-client]

JohnSColeman opened a new pull request, #10:
URL: https://github.com/apache/ignite-nodejs-thin-client/pull/10

   ## Summary
   
   - **ClientSocket: serialize concurrent `data` event processing** — the `data` handler was `async` but Node.js does not await async event listeners before firing the next event. Under parallel scan workloads, a second TCP frame could arrive while `_processResponse` was suspended at `await _finalizeResponse`, corrupting shared `_buffer`/`_offset` state. Fixed by chaining each invocation onto a `_processingQueue` promise so frames are always processed serially.
   
   - **ClientSocket: fix per-message buffer position tracking** — when two complete Ignite messages arrive in a single TCP segment, the `while` loop read the second message's length from `buffer.position` (wherever the previous payloadReader left it) rather than from `this._offset` (the actual start of the second message). Fixed by resetting `buffer.position = this._offset` at the top of each loop iteration.
   
   - **ClientSocket: fix cursor MessageBuffer aliasing** — two cursors created from the same TCP segment were both handed a reference to the same `MessageBuffer` object. When they concurrently called `_read()` under `Promise.all`, they shared the single `_position` field and interleaved reads at wrong offsets. Fixed by carving a fresh independent `MessageBuffer.from(slice)` copy for each message's payload before passing it to `_finalizeResponse`.
   
   - **ClientSocket: silently discard unsolicited server notification frames** — Ignite 2.14+ sends topology-change and heartbeat frames with IDs that do not match any pending client request. The original code had no handler for this case; the missing branch caused a crash. Fixed by logging and discarding such frames.
   
   - **Cursor: fix `hasMore()` returning false on a freshly-opened cursor** — `_hasNext` starts as `false` and `_values` starts as `null`, so `hasMore()` incorrectly returned `false` before the first `_getValues()` call. Fixed by also returning `true` when `_buffer != null` (the initial scan page is buffered at construction time).
   
   - **Cursor: fix `_getValues()` null-buffer crash on cursor exhaustion** — after the last page was read, `_getValues()` called `_read(null)` which crashed with `Cannot read properties of null`. Fixed with a null-guard that sets `_values = null` instead.
   
   - **Errors: fix `BinaryUtils.getTypeName is not a function`** — `Errors.ts` used bare `require('./internal/BinaryUtils')` which, for an `export default class`, returns the module namespace object rather than the class. Fixed by adding `.default` to all three require calls.
   
   ## Test plan
   
   - All 103 tests in `npm test` pass against a live Ignite 2.15 instance
   - Scan query suite (`spec/query/ScanQuery.spec.js`) passes including multi-page cursor iteration
   - Cache key/value suite passes including put/get of all primitive and complex types
   
   🤖 Generated with [Claude Code](https://claude.com/claude-code)


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: dev-unsubscribe@ignite.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Fix four bugs in ClientSocket, Cursor and Errors [ignite-nodejs-thin-client]

Posted by "Copilot (via GitHub)" <gi...@apache.org>.
Copilot commented on code in PR #10:
URL: https://github.com/apache/ignite-nodejs-thin-client/pull/10#discussion_r3405368687


##########
src/internal/ClientSocket.ts:
##########
@@ -288,23 +299,50 @@ export default class ClientSocket {
 
             this._logMessage(requestId, false, buffer.getSlice(this._offset - length, length));
 
+            // Record boundaries before the socket buffer is potentially cleared.
+            const msgEnd = this._offset;
+            const msgStart = msgEnd - length;
+
             if (this._offset === buffer.length) {
                 this._buffer = null;
                 this._offset = 0;
             }
 
+            // Carve a fresh, independent MessageBuffer from just this message's
+            // payload bytes (after length field + request-id).  Passing a copy
+            // rather than the shared socket buffer prevents two cursors created
+            // from the same TCP segment from aliasing the same position pointer
+            // and corrupting each other's reads under parallel scan workloads.
+            const headerConsumed = isHandshake
+                ? BinaryUtils.getSize(BinaryUtils.TYPE_CODE.INTEGER)           // 4 B: length only
+                : BinaryUtils.getSize(BinaryUtils.TYPE_CODE.INTEGER) +         // 4 B: length
+                  BinaryUtils.getSize(BinaryUtils.TYPE_CODE.LONG);             // 8 B: request-id
+            const freshBuffer = MessageBuffer.from(
+                buffer.getSlice(msgStart + headerConsumed, msgEnd),
+                0
+            );
+
             if (this._requests.has(requestId)) {
                 const request = this._requests.get(requestId);
                 this._requests.delete(requestId);
                 if (isHandshake) {
-                    await this._finalizeHandshake(buffer, request);
+                    await this._finalizeHandshake(freshBuffer, request);
                 }
                 else {
-                    await this._finalizeResponse(buffer, request);
+                    await this._finalizeResponse(freshBuffer, request);
                 }
             }
             else {
-                throw IgniteClientError.internalError('Invalid response id: ' + requestId);
+                // No pending request matches this response id. At the protocol
+                // version this client negotiates (<= 1.4.0) the server has no reason
+                // to send an unsolicited frame: affinity-topology updates ride on
+                // response flags (handled in _finalizeResponse), and notification /
+                // heartbeat frames only exist in later protocol versions this client
+                // does not speak. An unmatched id therefore most likely indicates a
+                // parsing desync. Discard it so the connection survives instead of
+                // crashing, but warn (when debug is enabled) so the anomaly is
+                // diagnosable rather than silently masked.
+                Logger.logWarning('Discarding response frame with unmatched request id: ' + requestId);

Review Comment:
   Discarding unmatched response frames can leave the client in an inconsistent state: the real pending request may never be completed (potentially leaking entries in `_requests` / hanging callers), and if this indicates a parsing desync, continuing may cause subsequent frames to be mis-parsed. Consider treating this as fatal (set `_error` + disconnect) like before, or (if you want resiliency) explicitly fail/clear all pending requests and reset parsing state after logging so callers don’t hang indefinitely.



##########
src/internal/ClientSocket.ts:
##########
@@ -288,23 +299,50 @@ export default class ClientSocket {
 
             this._logMessage(requestId, false, buffer.getSlice(this._offset - length, length));
 
+            // Record boundaries before the socket buffer is potentially cleared.
+            const msgEnd = this._offset;
+            const msgStart = msgEnd - length;
+
             if (this._offset === buffer.length) {
                 this._buffer = null;
                 this._offset = 0;
             }
 
+            // Carve a fresh, independent MessageBuffer from just this message's
+            // payload bytes (after length field + request-id).  Passing a copy
+            // rather than the shared socket buffer prevents two cursors created
+            // from the same TCP segment from aliasing the same position pointer
+            // and corrupting each other's reads under parallel scan workloads.
+            const headerConsumed = isHandshake
+                ? BinaryUtils.getSize(BinaryUtils.TYPE_CODE.INTEGER)           // 4 B: length only
+                : BinaryUtils.getSize(BinaryUtils.TYPE_CODE.INTEGER) +         // 4 B: length
+                  BinaryUtils.getSize(BinaryUtils.TYPE_CODE.LONG);             // 8 B: request-id
+            const freshBuffer = MessageBuffer.from(
+                buffer.getSlice(msgStart + headerConsumed, msgEnd),
+                0
+            );

Review Comment:
   The comment says you’re passing a *copy*, but `buffer.getSlice(...)` often implies a view/slice rather than a deep copy (depending on `MessageBuffer.getSlice` implementation). Since the main goal is to avoid sharing the `position` pointer (i.e., independent `MessageBuffer` instances), either adjust the comment to reflect that, or ensure the bytes are actually copied if that’s required for correctness.



##########
src/internal/Logger.ts:
##########
@@ -41,4 +41,10 @@ export default class Logger {
             console.log('ERROR: ' + data, ...args);
         }
     }
+
+    static logWarning(data: string, ...args: any[]) {
+        if (Logger._debug) {
+            console.log('WARNING: ' + data, ...args);
+        }
+    }

Review Comment:
   For warnings, prefer `console.warn(...)` over `console.log(...)` so log level filtering/formatting works as expected in many runtimes and log collectors. This also aligns better with the semantics of a `logWarning` API.



##########
src/Cursor.ts:
##########
@@ -160,8 +175,15 @@ export abstract class BaseCursor<T> {
         if (!this._buffer && this._hasNext) {
             await this._getNext();
         }
-        await this._read(this._buffer)
-        this._buffer = null;
+        if (this._buffer) {
+            await this._read(this._buffer);
+            this._buffer = null;
+        } else {
+            // No buffer and no next page — cursor is exhausted.
+            // Set _values to null so getValue() returns null and
+            // hasMore() returns false rather than replaying old entries.
+            this._values = null;
+        }
         return this._values;

Review Comment:
   Setting `_values = null` changes the observable return value of this method (it now returns `null` when exhausted), which can be surprising for a method that appears to return a collection. If the public/declared return type is `T[]` (or callers expect an array), return an empty array instead; `getValue()` can still return `null` naturally when `_valueIndex >= _values.length`, and `hasMore()` will remain false. If `null` is intended, consider documenting it explicitly in the method’s JSDoc/typing.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: dev-unsubscribe@ignite.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Fix four bugs in ClientSocket, Cursor and Errors [ignite-nodejs-thin-client]

Posted by "zstan (via GitHub)" <gi...@apache.org>.
zstan commented on PR #10:
URL: https://github.com/apache/ignite-nodejs-thin-client/pull/10#issuecomment-5164546501

   @JohnSColeman hi, i see some comments, do you plan to fix them ?


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: dev-unsubscribe@ignite.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Fix four bugs in ClientSocket, Cursor and Errors [ignite-nodejs-thin-client]

Posted by "JohnSColeman (via GitHub)" <gi...@apache.org>.
JohnSColeman commented on code in PR #10:
URL: https://github.com/apache/ignite-nodejs-thin-client/pull/10#discussion_r3468466045


##########
src/Cursor.ts:
##########
@@ -160,8 +175,15 @@ export abstract class BaseCursor<T> {
         if (!this._buffer && this._hasNext) {
             await this._getNext();
         }
-        await this._read(this._buffer)
-        this._buffer = null;
+        if (this._buffer) {
+            await this._read(this._buffer);
+            this._buffer = null;
+        } else {
+            // No buffer and no next page — cursor is exhausted.
+            // Set _values to null so getValue() returns null and
+            // hasMore() returns false rather than replaying old entries.
+            this._values = null;
+        }
         return this._values;

Review Comment:
   I think this is already safe — this is a style nit.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: dev-unsubscribe@ignite.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Fix four bugs in ClientSocket, Cursor and Errors [ignite-nodejs-thin-client]

Posted by "Copilot (via GitHub)" <gi...@apache.org>.
Copilot commented on code in PR #10:
URL: https://github.com/apache/ignite-nodejs-thin-client/pull/10#discussion_r3371018099


##########
src/Cursor.ts:
##########
@@ -27,7 +26,7 @@ import {CacheEntry} from "./CacheClient";
 
 export abstract class BaseCursor<T> {
 
-    protected _id: Long;
+    protected _id: any;

Review Comment:
   Changing `_id` from `Long` to `any` removes type-safety in the generated `.d.ts` and makes it easier to accidentally pass non-Long values into `_write()` / cursor-close requests. Since the code already reads/writes cursor IDs as `Long` values, keep the `Long` type and add a type-only import instead of using `any`.



##########
src/Cursor.ts:
##########
@@ -74,8 +73,13 @@ export abstract class BaseCursor<T> {
      * @return {boolean} - true if more cache entries are available, false otherwise.
      */
     hasMore(): boolean {
+        // _buffer is set on a freshly-opened cursor and holds the first page of
+        // results before _getValues() has been called for the first time.
+        // Without this check, hasMore() incorrectly returns false on a new cursor
+        // because _hasNext starts as false and _values starts as null.
         return this._hasNext ||
-            this._values && this._valueIndex < this._values.length;
+            (this._values != null && this._valueIndex < this._values.length) ||
+            this._buffer != null;

Review Comment:
   `hasMore()` now returns `true` whenever `_buffer` is non-null, even if the first (buffered) page contains `rowCount = 0` and `hasNext = false` (i.e. a query returning zero rows). In that case callers may see `hasMore() === true` but `getValue()` returns `null`, which violates the method contract (“more cache entries are available”). Consider peeking the buffered page’s `rowCount` (and the trailing `hasNext` boolean when `rowCount === 0`) without consuming it, instead of treating any non-null buffer as “more entries”.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: dev-unsubscribe@ignite.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Fix four bugs in ClientSocket, Cursor and Errors [ignite-nodejs-thin-client]

Posted by "FrankKanBear (via GitHub)" <gi...@apache.org>.
FrankKanBear commented on PR #10:
URL: https://github.com/apache/ignite-nodejs-thin-client/pull/10#issuecomment-4638310062

   Nice — this is the more complete, source-level fix (incl. unsolicited-frame handling). For folks pinned to the published npm 1.0.0 who can't wait for a release, we shipped a narrow, dependency-free runtime patch for just the _processResponse race: https://www.npmjs.com/package/@frankbearguard/ignite-client-14550-fix. Hope this PR lands.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: dev-unsubscribe@ignite.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Fix four bugs in ClientSocket, Cursor and Errors [ignite-nodejs-thin-client]

Posted by "JohnSColeman (via GitHub)" <gi...@apache.org>.
JohnSColeman commented on code in PR #10:
URL: https://github.com/apache/ignite-nodejs-thin-client/pull/10#discussion_r3468491237


##########
src/internal/ClientSocket.ts:
##########
@@ -296,15 +311,40 @@ export default class ClientSocket {
             if (this._requests.has(requestId)) {
                 const request = this._requests.get(requestId);
                 this._requests.delete(requestId);
+
+                // Carve a fresh, independent MessageBuffer from just this message's
+                // payload bytes (after length field + request-id).  Passing a copy
+                // rather than the shared socket buffer prevents two cursors created
+                // from the same TCP segment from aliasing the same position pointer
+                // and corrupting each other's reads under parallel scan workloads.
+                // Built only on the matched-request path so unmatched frames cost no copy.
+                const headerConsumed = isHandshake
+                    ? BinaryUtils.getSize(BinaryUtils.TYPE_CODE.INTEGER)           // 4 B: length only
+                    : BinaryUtils.getSize(BinaryUtils.TYPE_CODE.INTEGER) +         // 4 B: length
+                      BinaryUtils.getSize(BinaryUtils.TYPE_CODE.LONG);             // 8 B: request-id
+                const freshBuffer = MessageBuffer.from(
+                    buffer.getSlice(msgStart + headerConsumed, msgEnd),
+                    0
+                );
+
                 if (isHandshake) {
-                    await this._finalizeHandshake(buffer, request);
+                    await this._finalizeHandshake(freshBuffer, request);
                 }
                 else {
-                    await this._finalizeResponse(buffer, request);
+                    await this._finalizeResponse(freshBuffer, request);
                 }
             }
             else {
-                throw IgniteClientError.internalError('Invalid response id: ' + requestId);
+                // No pending request matches this response id. At the protocol
+                // version this client negotiates (<= 1.4.0) the server has no reason
+                // to send an unsolicited frame: affinity-topology updates ride on
+                // response flags (handled in _finalizeResponse), and notification /
+                // heartbeat frames only exist in later protocol versions this client
+                // does not speak. An unmatched id therefore most likely indicates a
+                // parsing desync. Discard it so the connection survives instead of
+                // crashing, but warn (when debug is enabled) so the anomaly is
+                // diagnosable rather than silently masked.
+                Logger.logWarning('Discarding response frame with unmatched request id: ' + requestId);

Review Comment:
   fixed



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: dev-unsubscribe@ignite.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Fix four bugs in ClientSocket, Cursor and Errors [ignite-nodejs-thin-client]

Posted by "zstan (via GitHub)" <gi...@apache.org>.
zstan merged PR #10:
URL: https://github.com/apache/ignite-nodejs-thin-client/pull/10


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: dev-unsubscribe@ignite.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Fix four bugs in ClientSocket, Cursor and Errors [ignite-nodejs-thin-client]

Posted by "FrankKanBear (via GitHub)" <gi...@apache.org>.
FrankKanBear commented on PR #10:
URL: https://github.com/apache/ignite-nodejs-thin-client/pull/10#issuecomment-4726619144

   Thanks for the fixes — the per-message buffer isolation, the `hasMore()` peek, the `_getValues()` exhaustion guard, and the `Errors.ts` `.default` fix looks fine to me, and the earlier review feedback (the `_id: Long` typing and the zero-row `hasMore()` case) is fully addressed in the current revision.
   
   I do think there is **one blocker** that should be resolved before merge, plus a couple of smaller items.
   
   ## Blocker: the serialization queue can deadlock the connection
   
   Serializing `data`-event processing onto `_processingQueue` (`ClientSocket._connectSocket`) makes `_processResponse` hold the queue across its `await _finalizeResponse(...)`. The problem is that a `payloadReader` can issue a **nested request on the same socket and await it** — which can now never complete.
   
   Concretely, for a `cache.get` / `getAll` / `localPeek` of a value that is a `COMPLEX_OBJECT` whose binary type is **not already cached** in this client's `BinaryTypeStorage._types`:
   
   1. The value is read **inline** in the payloadReader (`CacheClient` get/getAll/`_localPeek`), which runs inside `await request.payloadReader(buffer)` in `_finalizeResponse` — i.e. inside the queued `_processResponse`.
   2. `readObject` → `_readComplexObject` → `BinaryObject._readHeader` → `BinaryTypeBuilder.fromTypeId` → `typeStorage.getType` (miss) → `_getBinaryType` → `communicator.send(GET_BINARY_TYPE)`.
   3. `Router.send` is called with no `affinityHint`, so it routes to `_getAllConnections()[0].sendRequest(...)` — **the same socket** in the default single-connection case — and awaits the reply.
   4. That `GET_BINARY_TYPE` reply arrives as a **future `data` event**, which is chained behind the still-pending `_processResponse` from step 1. That queue entry only completes once the reply is processed; the reply can only be processed by a later queue entry → circular wait → the socket stops parsing and `get()` never resolves. The `.catch` never fires, so there is no timeout/disconnect escape.
   
   The pre-PR `async (data) => { await this._processResponse(data); }` handler avoided this because Node does not serialize async listeners — the nested reply was processed by a concurrent re-entrant `_processResponse`. (That concurrency is exactly the `_buffer`/`_offset` race this PR set out to fix; the fix just needs to keep the race closed without serializing the *nested-request* path.)
   
   **Why the 103 tests don't catch it:** the suites `put`/`fromObject` the complex value before reading it, which registers the type in the same client's `_types` (`addType`), so `getType` is a cache hit and no nested request is issued. The bug surfaces for the normal production pattern of a read-only / freshly-started client reading complex objects it did not itself write.
   
   ### Minimal, deterministic repro (no cluster needed)
   
   This models the exact async topology (single socket, one response whose payloadReader awaits a nested same-socket request whose reply arrives on a later event):
   
   ```
   BASE       -> cache.get() of uncached complex object: RESOLVED
   PR #10     -> cache.get() of uncached complex object: DEADLOCK (hung)
   PROPOSED   -> cache.get() of uncached complex object: RESOLVED
   ```
   
   ### Suggested fix
   
   The PR already carves an **independent** `MessageBuffer` per message, so `_finalizeResponse` no longer needs to be inside the serialized section to be race-free — the queue only needs to protect the synchronous frame-splitting that touches `this._buffer`/`this._offset`. Dispatch `_finalizeResponse` **off** the queue (don't await it in the chain):
   
   ```ts
   if (isHandshake) {
       // single-in-flight, transitions _state, issues no nested request → await inline
       await this._finalizeHandshake(freshBuffer, request);
   }
   else {
       // Do NOT await: the payloadReader may issue a nested same-socket request
       // (e.g. GET_BINARY_TYPE for an uncached complex type) and await it; awaiting
       // here would deadlock the queue. freshBuffer is an independent copy, so
       // finalizing off the parse chain cannot corrupt _buffer/_offset.
       this._finalizeResponse(freshBuffer, request).catch(err => {
           this._error = err.message;
           this._disconnect();
       });
   }
   ```
   
   With finalize detached, the CONNECTED path of `_processResponse` has no `await`, so it runs to completion synchronously and two invocations still cannot interleave on `_buffer`/`_offset` — the race stays fixed, and nested replies can be parsed by subsequent queue entries. (In the repro above this is the `PROPOSED` case.)
   
   ## Description no longer matches the code
   
   The summary still says *"silently discard unsolicited server notification frames … Fixed by logging and discarding such frames,"* but the final commit (`Fail fast on response stream desync…`) **throws** on an unmatched request id instead. Throwing is actually the right call here — this client caps the protocol at ≤ 1.4.0 and exposes no notification/continuous-query operation, so an unmatched id genuinely means stream desync where fail-fast beats hanging. But two parts of the description are now inaccurate and worth fixing:
   - it describes discard/log, while the code throws (→ disconnect + reject all pending);
   - it states *"The original code had no handler for this case; the missing branch caused a crash"* — the base already threw `Invalid response id` on this exact path, so no branch was missing.
   
   ## Minor
   
   - **`hasMore()` is now a throwing method.** The peek calls `readInteger()` / `readBoolean()`, which throw via `_ensureSize` on a short/truncated page; and on that throw the `this._buffer.position = savedPosition` restore is skipped, leaving the buffer position advanced. Low impact (only on a malformed page), but a `try { … } finally { this._buffer.position = saved }` makes it total again and keeps the previous non-throwing contract.
   - **Bundled, undocumented refactors.** The `import Long = require('long')` change, the `PROTOCOL_VERSION_1_0_0` dead-const removal, and the `statusCode` local cleanup are all fine, but they aren't among the four advertised fixes — worth a line in the description so reviewers know the diff intentionally exceeds them. (Note: the `import Long` change is purely an emit cleanup — it removes a now-dead `const Long = require('long')` from the compiled `Cursor.js` since `Long` is used only as a type; the generated `Cursor.d.ts` is unchanged, `protected _id: Long` in both base and PR. It does not change type safety.)
   - **Per-page copy cost (informational).** `MessageBuffer.from(getSlice(...))` now copies each matched response's full payload (`Buffer.from`). Worth it for the correctness gain (it also de-aliases lazily-decoded `BinaryObject`s, not just cursors), but worth noting as a deliberate new allocation on the query hot path.
   - Pre-existing, not introduced here: `_logMessage(..., buffer.getSlice(this._offset - length, length))` passes `length` where `getSlice(start, end)` wants an end offset, so it logs empty bytes for any 2nd+ frame in a segment. Debug-only; trivially fixable now that `msgStart`/`msgEnd` are in scope (`getSlice(msgStart, msgEnd)`).


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: dev-unsubscribe@ignite.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Fix four bugs in ClientSocket, Cursor and Errors [ignite-nodejs-thin-client]

Posted by "zstan (via GitHub)" <gi...@apache.org>.
zstan commented on PR #10:
URL: https://github.com/apache/ignite-nodejs-thin-client/pull/10#issuecomment-5267387761

   @JohnSColeman thank you for this issue !
   @chesnokoff, @vldpyatkov  thank you for review ! 


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: dev-unsubscribe@ignite.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Fix four bugs in ClientSocket, Cursor and Errors [ignite-nodejs-thin-client]

Posted by "FrankKanBear (via GitHub)" <gi...@apache.org>.
FrankKanBear commented on PR #10:
URL: https://github.com/apache/ignite-nodejs-thin-client/pull/10#issuecomment-4905275860

   Then congrats to your leadership. A different way to contribute but
   nevertheless contribution. Long live the fork!
   
   Aleksandr Chesnokov ***@***.***> schrieb am Di., 7. Juli
   2026, 16:50:
   
   > *chesnokoff* left a comment (apache/ignite-nodejs-thin-client#10)
   > <https://github.com/apache/ignite-nodejs-thin-client/pull/10#issuecomment-4905118346>
   >
   > Let's not discuss who has had more impact on the client.
   >
   > This is still an Apache Software Foundation project, not a personal
   > repository. We should follow the Apache Ignite contribution process.
   >
   > The Ignite CONTRIBUTING guide asks contributors to use the dev mailing
   > list and says that Apache Ignite prefers to make decisions by consensus.
   > That is why I asked about the version bump. It looks like something that
   > should be discussed on the dev mailing list.
   >
   > —
   > Reply to this email directly, view it on GitHub
   > <https://github.com/apache/ignite-nodejs-thin-client/pull/10?email_source=notifications&email_token=BWDDIVRZYYSFMVWCF53SWFT5DUE3DA5CNFSNUABFM5UWIORPF5TWS5BNNB2WEL2JONZXKZKDN5WW2ZLOOQXTIOJQGUYTCOBTGQ3KM4TFMFZW63VHNVSW45DJN5XKKZLWMVXHJLDGN5XXIZLSL5RWY2LDNM#issuecomment-4905118346>,
   > or unsubscribe
   > <https://github.com/notifications/unsubscribe-auth/BWDDIVX77SF27SYWBZLOYXD5DUE3DAVCNFSNUABFKJSXA33TNF2G64TZHMZTCNBTGA3TSMRWHNEXG43VMU5TIMRQG4ZTMMJQGY4KC5QC>
   > .
   > Triage notifications, keep track of coding agent tasks and review pull
   > requests on the go with GitHub Mobile for iOS
   > <https://github.com/notifications/mobile/ios/BWDDIVTPUGLNT6ONQEA2DEL5DUE3DA5CNFSNUABFM5UWIORPF5TWS5BNNB2WEL2JONZXKZKDN5WW2ZLOOQXTIOJQGUYTCOBTGQ3KM4TFMFZW63VHNVSW45DJN5XKKZLWMVXHJKTGN5XXIZLSL5UW64Y>
   > and Android
   > <https://github.com/notifications/mobile/android/BWDDIVSPR5YQEUUHDLPFOYT5DUE3DA5CNFSNUABFM5UWIORPF5TWS5BNNB2WEL2JONZXKZKDN5WW2ZLOOQXTIOJQGUYTCOBTGQ3KM4TFMFZW63VHNVSW45DJN5XKKZLWMVXHJLTGN5XXIZLSL5QW4ZDSN5UWI>.
   > Download it today!
   > You are receiving this because you were mentioned.Message ID:
   > ***@***.***>
   >
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: dev-unsubscribe@ignite.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Fix four bugs in ClientSocket, Cursor and Errors [ignite-nodejs-thin-client]

Posted by "JohnSColeman (via GitHub)" <gi...@apache.org>.
JohnSColeman commented on code in PR #10:
URL: https://github.com/apache/ignite-nodejs-thin-client/pull/10#discussion_r3468479292


##########
src/internal/ClientSocket.ts:
##########
@@ -296,15 +311,40 @@ export default class ClientSocket {
             if (this._requests.has(requestId)) {
                 const request = this._requests.get(requestId);
                 this._requests.delete(requestId);
+
+                // Carve a fresh, independent MessageBuffer from just this message's
+                // payload bytes (after length field + request-id).  Passing a copy
+                // rather than the shared socket buffer prevents two cursors created
+                // from the same TCP segment from aliasing the same position pointer
+                // and corrupting each other's reads under parallel scan workloads.
+                // Built only on the matched-request path so unmatched frames cost no copy.
+                const headerConsumed = isHandshake
+                    ? BinaryUtils.getSize(BinaryUtils.TYPE_CODE.INTEGER)           // 4 B: length only
+                    : BinaryUtils.getSize(BinaryUtils.TYPE_CODE.INTEGER) +         // 4 B: length
+                      BinaryUtils.getSize(BinaryUtils.TYPE_CODE.LONG);             // 8 B: request-id
+                const freshBuffer = MessageBuffer.from(
+                    buffer.getSlice(msgStart + headerConsumed, msgEnd),
+                    0
+                );

Review Comment:
   `getSlice(start, end)` wraps `Buffer.slice(start, end)`, so the second argument is an end offset, not a length — `getSlice(msgStart + headerConsumed, msgEnd)` is correct. The `getSlice(this._offset - length, length)` call referenced here was itself the bug fixed in this PR (the `_logMessage` empty-bytes issue, now `getSlice(msgStart, msgEnd)`), so it is not a valid reference for the intended contract. Applying the suggested change (passing a computed length as the second arg) would slice too few bytes for any 2nd+ frame in a TCP segment and actually corrupt parsing. Covered by the passing scan/SQL cursor suites, which deserialize multi-row pages directly out of `freshBuffer`.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: dev-unsubscribe@ignite.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Fix four bugs in ClientSocket, Cursor and Errors [ignite-nodejs-thin-client]

Posted by "JohnSColeman (via GitHub)" <gi...@apache.org>.
JohnSColeman commented on code in PR #10:
URL: https://github.com/apache/ignite-nodejs-thin-client/pull/10#discussion_r3468501537


##########
src/internal/Logger.ts:
##########
@@ -41,4 +41,10 @@ export default class Logger {
             console.log('ERROR: ' + data, ...args);
         }
     }
+
+    static logWarning(data: string, ...args: any[]) {
+        if (Logger._debug) {
+            console.log('WARNING: ' + data, ...args);
+        }
+    }

Review Comment:
   Outdated — `logWarning` was introduced in an intermediate commit and removed again in `92a22d6` when the unmatched-id path switched to fail-fast `throw`. The final PR makes no net change to `Logger.ts` (it only defines `logDebug`/`logError`), so there is no `console.log` vs `console.warn` choice to revisit here.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: dev-unsubscribe@ignite.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Fix four bugs in ClientSocket, Cursor and Errors [ignite-nodejs-thin-client]

Posted by "zstan (via GitHub)" <gi...@apache.org>.
zstan commented on PR #10:
URL: https://github.com/apache/ignite-nodejs-thin-client/pull/10#issuecomment-4904253742

   @JohnSColeman @FrankKanBear seems all copilot suggestions are minor and possibly we can merge it ? 


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: dev-unsubscribe@ignite.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Fix four bugs in ClientSocket, Cursor and Errors [ignite-nodejs-thin-client]

Posted by "FrankKanBear (via GitHub)" <gi...@apache.org>.
FrankKanBear commented on PR #10:
URL: https://github.com/apache/ignite-nodejs-thin-client/pull/10#issuecomment-4904812823

   Would this not make sense as only John did care about the Node Client for a
   long time and all important stuff had been fixed now? If other devs do not
   care about fixes for years why ask them?
   
   Aleksandr Chesnokov ***@***.***> schrieb am Di., 7. Juli
   2026, 15:59:
   
   > ***@***.**** commented on this pull request.
   > ------------------------------
   >
   > In package.json
   > <https://github.com/apache/ignite-nodejs-thin-client/pull/10#discussion_r3537043890>
   > :
   >
   > > @@ -1,6 +1,6 @@
   >  {
   >    "name": "apache-ignite-client",
   > -  "version": "1.1.0",
   > +  "version": "1.1.1",
   >
   > Why do we update the version in this PR? I can see this PR was only for
   > bug fixes
   >
   > Also, shouldn't the version update be done separately and discussed on the
   > Apache Ignite dev list?
   >
   > —
   > Reply to this email directly, view it on GitHub
   > <https://github.com/apache/ignite-nodejs-thin-client/pull/10?email_source=notifications&email_token=BWDDIVQIV4ZRBJ65Q6UXGO35DT623A5CNFSNUABKM5UWIORPF5TWS5BNNB2WEL2QOVWGYUTFOF2WK43UKJSXM2LFO4XTINRUGU4DINBXG4Y2M4TFMFZW63VHNVSW45DJN5XKKZLWMVXHJLDGN5XXIZLSL5RWY2LDNM#pullrequestreview-4645844771>,
   > or unsubscribe
   > <https://github.com/notifications/unsubscribe-auth/BWDDIVUPS77UBGHGY4O6I6L5DT623AVCNFSNUABFKJSXA33TNF2G64TZHMZTCNBTGA3TSMRWHNEXG43VMU5TIMRQG4ZTMMJQGY4KC5QC>
   > .
   > Triage notifications, keep track of coding agent tasks and review pull
   > requests on the go with GitHub Mobile for iOS
   > <https://github.com/notifications/mobile/ios/BWDDIVTGQVLZNROF3JBM5HD5DT623A5CNFSNUABKM5UWIORPF5TWS5BNNB2WEL2QOVWGYUTFOF2WK43UKJSXM2LFO4XTINRUGU4DINBXG4Y2M4TFMFZW63VHNVSW45DJN5XKKZLWMVXHJKTGN5XXIZLSL5UW64Y>
   > and Android
   > <https://github.com/notifications/mobile/android/BWDDIVWG73JH7VZRXXE6D4T5DT623A5CNFSNUABKM5UWIORPF5TWS5BNNB2WEL2QOVWGYUTFOF2WK43UKJSXM2LFO4XTINRUGU4DINBXG4Y2M4TFMFZW63VHNVSW45DJN5XKKZLWMVXHJLTGN5XXIZLSL5QW4ZDSN5UWI>.
   > Download it today!
   > You are receiving this because you were mentioned.Message ID:
   > ***@***.***>
   >
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: dev-unsubscribe@ignite.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Fix four bugs in ClientSocket, Cursor and Errors [ignite-nodejs-thin-client]

Posted by "FrankKanBear (via GitHub)" <gi...@apache.org>.
FrankKanBear commented on code in PR #10:
URL: https://github.com/apache/ignite-nodejs-thin-client/pull/10#discussion_r3372391171


##########
src/Cursor.ts:
##########
@@ -74,8 +73,13 @@ export abstract class BaseCursor<T> {
      * @return {boolean} - true if more cache entries are available, false otherwise.
      */
     hasMore(): boolean {
+        // _buffer is set on a freshly-opened cursor and holds the first page of
+        // results before _getValues() has been called for the first time.
+        // Without this check, hasMore() incorrectly returns false on a new cursor
+        // because _hasNext starts as false and _values starts as null.
         return this._hasNext ||
-            this._values && this._valueIndex < this._values.length;
+            (this._values != null && this._valueIndex < this._values.length) ||
+            this._buffer != null;

Review Comment:
   Good catch — this is correct. With || this._buffer != null, a zero-row first page (rowCount = 0, trailing hasNext = false) makes hasMore() return true while the next getValue() returns null, so a while (cursor.hasMore()) { … } loop runs one spurious iteration on any empty result.
   
   Peeking the buffered page's rowCount (and the trailing hasNext when rowCount === 0) without consuming it fixes it — MessageBuffer exposes position get/set, so save → peek → restore is safe and stays synchronous:
   
           if (this._hasNext) {
               return true;
           }
           if (this._values != null && this._valueIndex < this._values.length) {
               return true;
           }
           if (this._buffer != null) {
               // Peek the buffered first page without consuming it. A page is laid out as
               // [rowCount:int][rows...][hasNext:bool]; rowCount === 0 with a trailing
               // hasNext === false is an empty result, so hasMore() must be false here.
               const savedPosition = this._buffer.position;
               const rowCount = this._buffer.readInteger();
               const more = rowCount > 0 || this._buffer.readBoolean();
               this._buffer.position = savedPosition;
               return more;
           }
           return false;



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: dev-unsubscribe@ignite.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Fix four bugs in ClientSocket, Cursor and Errors [ignite-nodejs-thin-client]

Posted by "zstan (via GitHub)" <gi...@apache.org>.
zstan commented on code in PR #10:
URL: https://github.com/apache/ignite-nodejs-thin-client/pull/10#discussion_r3394466511


##########
src/Cursor.ts:
##########
@@ -27,7 +26,7 @@ import {CacheEntry} from "./CacheClient";
 
 export abstract class BaseCursor<T> {
 
-    protected _id: Long;
+    protected _id: any;

Review Comment:
   So, it need to be fixed ?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: dev-unsubscribe@ignite.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Fix four bugs in ClientSocket, Cursor and Errors [ignite-nodejs-thin-client]

Posted by "JohnSColeman (via GitHub)" <gi...@apache.org>.
JohnSColeman commented on PR #10:
URL: https://github.com/apache/ignite-nodejs-thin-client/pull/10#issuecomment-4679716077

   @zstan @FrankKanBear I will take a look at the review points on the weekend.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: dev-unsubscribe@ignite.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Fix four bugs in ClientSocket, Cursor and Errors [ignite-nodejs-thin-client]

Posted by "JohnSColeman (via GitHub)" <gi...@apache.org>.
JohnSColeman commented on code in PR #10:
URL: https://github.com/apache/ignite-nodejs-thin-client/pull/10#discussion_r3540701598


##########
package.json:
##########
@@ -1,6 +1,6 @@
 {
   "name": "apache-ignite-client",
-  "version": "1.1.0",
+  "version": "1.1.1",

Review Comment:
   Dropped the version bump — reverted `package.json` to 1.1.0 in ac6092a so this PR is scoped to the fixes. The version change can be proposed and discussed separately on the dev list.



##########
src/Cursor.ts:
##########
@@ -160,8 +180,15 @@ export abstract class BaseCursor<T> {
         if (!this._buffer && this._hasNext) {
             await this._getNext();
         }
-        await this._read(this._buffer)
-        this._buffer = null;
+        if (this._buffer) {
+            await this._read(this._buffer);
+            this._buffer = null;
+        } else {
+            // No buffer and no next page — cursor is exhausted.
+            // Set _values to null so getValue() returns null and
+            // hasMore() returns false rather than replaying old entries.
+            this._values = null;
+        }

Review Comment:
   Fixed in bfcf03d — `_getValues()` now returns an empty array on exhaustion instead of `null`, honouring the declared `Promise<T[]>` (and the generated `.d.ts`). `getValue()` still returns `null` naturally (length 0) and `hasMore()` stays `false`, so exhausted cursors do not replay entries.



##########
src/internal/ClientSocket.ts:
##########
@@ -296,15 +316,66 @@ export default class ClientSocket {
             if (this._requests.has(requestId)) {
                 const request = this._requests.get(requestId);
                 this._requests.delete(requestId);
+
+                // Carve a fresh, independent MessageBuffer from just this message's
+                // payload bytes (after length field + request-id). getSlice() returns
+                // a view over the shared socket buffer, but MessageBuffer.from() copies
+                // those bytes (via Buffer.from), so freshBuffer owns an independent
+                // buffer with its own position pointer. That independence prevents two
+                // cursors created from the same TCP segment from aliasing the same
+                // position and corrupting each other's reads under parallel scan
+                // workloads. Built only on the matched-request path so unmatched frames
+                // cost no copy.
+                const headerConsumed = isHandshake
+                    ? BinaryUtils.getSize(BinaryUtils.TYPE_CODE.INTEGER)           // 4 B: length only
+                    : BinaryUtils.getSize(BinaryUtils.TYPE_CODE.INTEGER) +         // 4 B: length
+                      BinaryUtils.getSize(BinaryUtils.TYPE_CODE.LONG);             // 8 B: request-id
+                const freshBuffer = MessageBuffer.from(
+                    buffer.getSlice(msgStart + headerConsumed, msgEnd),
+                    0
+                );
+
                 if (isHandshake) {
-                    await this._finalizeHandshake(buffer, request);
+                    // Handshake is single-in-flight, transitions _state and issues no
+                    // nested request, so it is safe to await inline on the queue.
+                    await this._finalizeHandshake(freshBuffer, request);
                 }
                 else {
-                    await this._finalizeResponse(buffer, request);
+                    // Do NOT await on the processing queue: a payloadReader may issue a
+                    // nested request on this same socket and await its reply (e.g.
+                    // GET_BINARY_TYPE when reading a COMPLEX_OBJECT whose type is not yet
+                    // cached in this client's BinaryTypeStorage). That reply arrives as a
+                    // later 'data' event chained behind this very queue entry, so awaiting
+                    // here would deadlock — the entry can only complete once the reply is
+                    // processed, but the reply can only be processed by a later entry.
+                    // freshBuffer is an independent copy of this message's payload, so
+                    // finalizing it off the parse chain cannot corrupt _buffer/_offset.
+                    // With finalize detached the CONNECTED path of _processResponse has no
+                    // remaining await and runs to completion synchronously, so two
+                    // invocations still cannot interleave on _buffer/_offset and the parse
+                    // race stays closed.
+                    this._finalizeResponse(freshBuffer, request).catch(err => {
+                        this._error = err.message;
+                        this._disconnect();
+                    });
                 }
             }
             else {
-                throw IgniteClientError.internalError('Invalid response id: ' + requestId);
+                // No pending request matches this response id. At the protocol version
+                // this client negotiates (<= 1.4.0) the server never sends unsolicited
+                // frames: affinity-topology updates ride on response flags (handled in
+                // _finalizeResponse), and notification / heartbeat frames only exist in
+                // later protocol versions this client does not speak. Requests are also
+                // never removed while still awaiting a response (there is no client-side
+                // timeout), so an unmatched id cannot be a late or duplicate reply.
+                // It therefore means the response byte stream has desynced, after which
+                // every subsequent frame is garbage and the originating request would
+                // otherwise hang forever. Fail fast: throwing propagates to the socket
+                // 'data' handler's catch, which disconnects and rejects all pending
+                // requests with LostConnectionError so callers can recover instead of
+                // hanging.
+                throw IgniteClientError.internalError(
+                    'Response stream desync: received a frame with unmatched request id ' + requestId);

Review Comment:
   Aligned the PR description with the implemented behaviour: the unmatched-`requestId` path fails fast (throws → disconnect → rejects pending requests), and the description now documents that fail-fast behaviour rather than "log and discard".



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: dev-unsubscribe@ignite.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Fix four bugs in ClientSocket, Cursor and Errors [ignite-nodejs-thin-client]

Posted by "zstan (via GitHub)" <gi...@apache.org>.
zstan commented on PR #10:
URL: https://github.com/apache/ignite-nodejs-thin-client/pull/10#issuecomment-4726326033

   @JohnSColeman do you plan to resolve all suggestions from Copilot?


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: dev-unsubscribe@ignite.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Fix four bugs in ClientSocket, Cursor and Errors [ignite-nodejs-thin-client]

Posted by "JohnSColeman (via GitHub)" <gi...@apache.org>.
JohnSColeman commented on PR #10:
URL: https://github.com/apache/ignite-nodejs-thin-client/pull/10#issuecomment-4910672796

   > Let's not discuss who has had more impact on the client.
   > 
   > This is still an Apache Software Foundation project, not a personal repository. We should follow the Apache Ignite contribution process.
   > 
   > The Ignite CONTRIBUTING guide asks contributors to use the dev mailing list and says that Apache Ignite prefers to make decisions by consensus. That is why I asked about the version bump. It looks like something that should be discussed on the dev mailing list.
   
   I have other higher priorities than chat about this contribution by email about a repo that has been dormant for a long time. But I am happy to make any revisions requested. I have tried to address all the PR review issues and have reverted the version bump.
   
   Please let me know what other changes you would like, or feel free to take this work and make what you will of it.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: dev-unsubscribe@ignite.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Fix four bugs in ClientSocket, Cursor and Errors [ignite-nodejs-thin-client]

Posted by "Copilot (via GitHub)" <gi...@apache.org>.
Copilot commented on code in PR #10:
URL: https://github.com/apache/ignite-nodejs-thin-client/pull/10#discussion_r3405296321


##########
src/internal/ClientSocket.ts:
##########
@@ -288,23 +299,44 @@ export default class ClientSocket {
 
             this._logMessage(requestId, false, buffer.getSlice(this._offset - length, length));
 
+            // Record boundaries before the socket buffer is potentially cleared.
+            const msgEnd = this._offset;
+            const msgStart = msgEnd - length;
+
             if (this._offset === buffer.length) {
                 this._buffer = null;
                 this._offset = 0;
             }
 
+            // Carve a fresh, independent MessageBuffer from just this message's
+            // payload bytes (after length field + request-id).  Passing a copy
+            // rather than the shared socket buffer prevents two cursors created
+            // from the same TCP segment from aliasing the same position pointer
+            // and corrupting each other's reads under parallel scan workloads.
+            const headerConsumed = isHandshake
+                ? BinaryUtils.getSize(BinaryUtils.TYPE_CODE.INTEGER)           // 4 B: length only
+                : BinaryUtils.getSize(BinaryUtils.TYPE_CODE.INTEGER) +         // 4 B: length
+                  BinaryUtils.getSize(BinaryUtils.TYPE_CODE.LONG);             // 8 B: request-id
+            const freshBuffer = MessageBuffer.from(
+                buffer.buffer.slice(msgStart + headerConsumed, msgEnd),
+                0
+            );
+
             if (this._requests.has(requestId)) {
                 const request = this._requests.get(requestId);
                 this._requests.delete(requestId);

Review Comment:
   A `freshBuffer` is allocated for every parsed frame, even when `requestId` isn't present in `_requests` (e.g., unsolicited notifications). To reduce avoidable allocations and copying, construct `freshBuffer` only inside the `if (this._requests.has(requestId))` branch (or lazily when needed).



##########
src/internal/ClientSocket.ts:
##########
@@ -288,23 +299,44 @@ export default class ClientSocket {
 
             this._logMessage(requestId, false, buffer.getSlice(this._offset - length, length));
 
+            // Record boundaries before the socket buffer is potentially cleared.
+            const msgEnd = this._offset;
+            const msgStart = msgEnd - length;
+
             if (this._offset === buffer.length) {
                 this._buffer = null;
                 this._offset = 0;
             }
 
+            // Carve a fresh, independent MessageBuffer from just this message's
+            // payload bytes (after length field + request-id).  Passing a copy
+            // rather than the shared socket buffer prevents two cursors created

Review Comment:
   The comment says the payload bytes are passed as a 'copy', but `slice(...)` may produce a view (sharing underlying memory) depending on the underlying buffer type. Either update the comment to describe what is actually happening (independent `MessageBuffer` state vs copied bytes), or use an explicit copy operation if the intent is to duplicate the bytes.



##########
src/internal/ClientSocket.ts:
##########
@@ -288,23 +299,44 @@ export default class ClientSocket {
 
             this._logMessage(requestId, false, buffer.getSlice(this._offset - length, length));
 
+            // Record boundaries before the socket buffer is potentially cleared.
+            const msgEnd = this._offset;
+            const msgStart = msgEnd - length;
+
             if (this._offset === buffer.length) {
                 this._buffer = null;
                 this._offset = 0;
             }
 
+            // Carve a fresh, independent MessageBuffer from just this message's
+            // payload bytes (after length field + request-id).  Passing a copy
+            // rather than the shared socket buffer prevents two cursors created
+            // from the same TCP segment from aliasing the same position pointer
+            // and corrupting each other's reads under parallel scan workloads.
+            const headerConsumed = isHandshake
+                ? BinaryUtils.getSize(BinaryUtils.TYPE_CODE.INTEGER)           // 4 B: length only
+                : BinaryUtils.getSize(BinaryUtils.TYPE_CODE.INTEGER) +         // 4 B: length
+                  BinaryUtils.getSize(BinaryUtils.TYPE_CODE.LONG);             // 8 B: request-id
+            const freshBuffer = MessageBuffer.from(
+                buffer.buffer.slice(msgStart + headerConsumed, msgEnd),
+                0
+            );

Review Comment:
   The comment says the payload bytes are passed as a 'copy', but `slice(...)` may produce a view (sharing underlying memory) depending on the underlying buffer type. Either update the comment to describe what is actually happening (independent `MessageBuffer` state vs copied bytes), or use an explicit copy operation if the intent is to duplicate the bytes.



##########
src/internal/ClientSocket.ts:
##########
@@ -288,23 +299,44 @@ export default class ClientSocket {
 
             this._logMessage(requestId, false, buffer.getSlice(this._offset - length, length));
 
+            // Record boundaries before the socket buffer is potentially cleared.
+            const msgEnd = this._offset;
+            const msgStart = msgEnd - length;
+
             if (this._offset === buffer.length) {
                 this._buffer = null;
                 this._offset = 0;
             }
 
+            // Carve a fresh, independent MessageBuffer from just this message's
+            // payload bytes (after length field + request-id).  Passing a copy
+            // rather than the shared socket buffer prevents two cursors created
+            // from the same TCP segment from aliasing the same position pointer
+            // and corrupting each other's reads under parallel scan workloads.
+            const headerConsumed = isHandshake
+                ? BinaryUtils.getSize(BinaryUtils.TYPE_CODE.INTEGER)           // 4 B: length only
+                : BinaryUtils.getSize(BinaryUtils.TYPE_CODE.INTEGER) +         // 4 B: length
+                  BinaryUtils.getSize(BinaryUtils.TYPE_CODE.LONG);             // 8 B: request-id
+            const freshBuffer = MessageBuffer.from(
+                buffer.buffer.slice(msgStart + headerConsumed, msgEnd),
+                0
+            );
+
             if (this._requests.has(requestId)) {
                 const request = this._requests.get(requestId);
                 this._requests.delete(requestId);
                 if (isHandshake) {
-                    await this._finalizeHandshake(buffer, request);
+                    await this._finalizeHandshake(freshBuffer, request);
                 }
                 else {
-                    await this._finalizeResponse(buffer, request);
+                    await this._finalizeResponse(freshBuffer, request);
                 }
             }
             else {
-                throw IgniteClientError.internalError('Invalid response id: ' + requestId);
+                // Ignite 2.14+ sends unsolicited server-side notification frames
+                // (topology changes, heartbeats) whose request IDs do not match any
+                // pending client request. Silently discard them and continue reading.
+                Logger.logDebug('Discarding server notification frame with id: ' + requestId);

Review Comment:
   The client now discards *all* frames with unknown `requestId`s. If an unexpected/invalid response-id occurs (protocol mismatch, client bookkeeping bug, etc.), this can mask the error and potentially leave the originating client operation waiting indefinitely. Consider only discarding frames that can be positively identified as notifications (e.g., by parsing a notification type/opcode), and otherwise failing fast (disconnect + reject pending requests) or at least surfacing a warning/error and terminating the connection.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: dev-unsubscribe@ignite.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Fix four bugs in ClientSocket, Cursor and Errors [ignite-nodejs-thin-client]

Posted by "Copilot (via GitHub)" <gi...@apache.org>.
Copilot commented on code in PR #10:
URL: https://github.com/apache/ignite-nodejs-thin-client/pull/10#discussion_r3405280207


##########
src/internal/ClientSocket.ts:
##########
@@ -288,23 +299,44 @@ export default class ClientSocket {
 
             this._logMessage(requestId, false, buffer.getSlice(this._offset - length, length));
 
+            // Record boundaries before the socket buffer is potentially cleared.
+            const msgEnd = this._offset;
+            const msgStart = msgEnd - length;
+
             if (this._offset === buffer.length) {
                 this._buffer = null;
                 this._offset = 0;
             }
 
+            // Carve a fresh, independent MessageBuffer from just this message's
+            // payload bytes (after length field + request-id).  Passing a copy
+            // rather than the shared socket buffer prevents two cursors created
+            // from the same TCP segment from aliasing the same position pointer
+            // and corrupting each other's reads under parallel scan workloads.
+            const headerConsumed = isHandshake
+                ? BinaryUtils.getSize(BinaryUtils.TYPE_CODE.INTEGER)           // 4 B: length only
+                : BinaryUtils.getSize(BinaryUtils.TYPE_CODE.INTEGER) +         // 4 B: length
+                  BinaryUtils.getSize(BinaryUtils.TYPE_CODE.LONG);             // 8 B: request-id
+            const freshBuffer = MessageBuffer.from(
+                buffer.buffer.slice(msgStart + headerConsumed, msgEnd),
+                0
+            );

Review Comment:
   `buffer.buffer` is an `ArrayBuffer` (and may require `byteOffset` adjustments when the underlying Node.js `Buffer` is a view). Slicing it with `msgStart/msgEnd` indices risks extracting the wrong bytes (and may hand `MessageBuffer.from` an unexpected type), which can corrupt response parsing. Prefer slicing the actual byte sequence (e.g., via the underlying `Buffer` slice API or an existing `MessageBuffer` slicing helper) so offsets account for `byteOffset` and the result type matches what `MessageBuffer.from` expects.



##########
src/internal/ClientSocket.ts:
##########
@@ -288,23 +299,44 @@ export default class ClientSocket {
 
             this._logMessage(requestId, false, buffer.getSlice(this._offset - length, length));
 
+            // Record boundaries before the socket buffer is potentially cleared.
+            const msgEnd = this._offset;
+            const msgStart = msgEnd - length;
+
             if (this._offset === buffer.length) {
                 this._buffer = null;
                 this._offset = 0;
             }
 
+            // Carve a fresh, independent MessageBuffer from just this message's
+            // payload bytes (after length field + request-id).  Passing a copy
+            // rather than the shared socket buffer prevents two cursors created
+            // from the same TCP segment from aliasing the same position pointer
+            // and corrupting each other's reads under parallel scan workloads.
+            const headerConsumed = isHandshake
+                ? BinaryUtils.getSize(BinaryUtils.TYPE_CODE.INTEGER)           // 4 B: length only
+                : BinaryUtils.getSize(BinaryUtils.TYPE_CODE.INTEGER) +         // 4 B: length
+                  BinaryUtils.getSize(BinaryUtils.TYPE_CODE.LONG);             // 8 B: request-id
+            const freshBuffer = MessageBuffer.from(
+                buffer.buffer.slice(msgStart + headerConsumed, msgEnd),
+                0
+            );
+
             if (this._requests.has(requestId)) {
                 const request = this._requests.get(requestId);
                 this._requests.delete(requestId);
                 if (isHandshake) {
-                    await this._finalizeHandshake(buffer, request);
+                    await this._finalizeHandshake(freshBuffer, request);
                 }
                 else {
-                    await this._finalizeResponse(buffer, request);
+                    await this._finalizeResponse(freshBuffer, request);
                 }
             }
             else {
-                throw IgniteClientError.internalError('Invalid response id: ' + requestId);
+                // Ignite 2.14+ sends unsolicited server-side notification frames
+                // (topology changes, heartbeats) whose request IDs do not match any
+                // pending client request. Silently discard them and continue reading.
+                Logger.logDebug('Discarding server notification frame with id: ' + requestId);

Review Comment:
   Silently discarding any frame with an unknown `requestId` can mask real protocol/desync bugs (e.g., a client-side request tracking issue) and make failures much harder to diagnose. Consider narrowing this behavior to known notification frame types (or gating it by protocol version/feature negotiation) and keeping a stricter fallback (e.g., disconnect or raise an internal error) for truly unexpected frames.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: dev-unsubscribe@ignite.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Fix four bugs in ClientSocket, Cursor and Errors [ignite-nodejs-thin-client]

Posted by "FrankKanBear (via GitHub)" <gi...@apache.org>.
FrankKanBear commented on code in PR #10:
URL: https://github.com/apache/ignite-nodejs-thin-client/pull/10#discussion_r3372386130


##########
src/Cursor.ts:
##########
@@ -27,7 +26,7 @@ import {CacheEntry} from "./CacheClient";
 
 export abstract class BaseCursor<T> {
 
-    protected _id: Long;
+    protected _id: any;

Review Comment:
   Agreed — _id is genuinely a Long (this._id = buffer.readLong()) and it's protected, so any leaks into the shipped dist/**.d.ts. Keeping the type via a type-only import is the right fix: it erases at compile time (no runtime require('long'), so the goal of dropping the value-import is preserved) and keeps the declaration typed.
   
   Suggestion on the _id line:
   protected _id: Long;
   
   And — since the PR removed const Long = require('long'); — re-add the type-only import. Suggestion on the import BinaryUtils, { OPERATION } from './internal/BinaryUtils'; line:
   import type Long from 'long';
   import BinaryUtils, { OPERATION } from './internal/BinaryUtils';



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: dev-unsubscribe@ignite.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Fix four bugs in ClientSocket, Cursor and Errors [ignite-nodejs-thin-client]

Posted by "vldpyatkov (via GitHub)" <gi...@apache.org>.
vldpyatkov commented on code in PR #10:
URL: https://github.com/apache/ignite-nodejs-thin-client/pull/10#discussion_r3596298751


##########
spec/cache/ColdComplexReadDeadlock.spec.js:
##########
@@ -0,0 +1,165 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+'use strict';
+
+require('jasmine-expect');
+
+const net = require('net');
+const EventEmitter = require('events');
+const Long = require('long');
+
+// Drive the REAL ClientSocket against a mock TCP socket so this regression is
+// deterministic and needs no cluster. It reproduces the exact async topology of
+// the cold complex-object read: a single socket, one response whose payloadReader
+// issues a nested request on that same socket and awaits its reply, where the
+// reply only arrives as a later 'data' event. If response finalization is awaited
+// on the socket's serialized processing queue, the nested reply is chained behind
+// the still-pending outer entry and can never be processed -> the outer request
+// hangs forever. With finalization dispatched off the queue, it resolves.
+const ClientSocket = require('apache-ignite-client/dist/internal/ClientSocket').default;
+const MessageBuffer = require('apache-ignite-client/dist/internal/MessageBuffer').default;
+
+const HANDSHAKE_SUCCESS_STATUS_CODE = 1;
+const OP_OUTER = 2001;
+const OP_INNER = 2002;
+const DEADLOCK_TIMEOUT_MS = 5000;
+
+// Handshake reply frame: [length:int][status:byte]. The >= 1.4.0 path then reads a
+// node-UUID via communicator.readObject, which the mock communicator stubs out, so
+// no UUID bytes are required (frames are length-delimited, not reader-position
+// delimited).
+function buildHandshakeResponse() {
+    const buf = new MessageBuffer();
+    buf.position = 4;
+    buf.writeByte(HANDSHAKE_SUCCESS_STATUS_CODE);
+    const len = buf.length - 4;
+    buf.position = 0;
+    buf.writeInteger(len);
+    return buf.data;
+}
+
+// Success response frame for protocol >= 1.4.0: [length:int][requestId:long][flags:short=0].
+function buildResponse(requestId) {
+    const buf = new MessageBuffer();
+    buf.position = 4;
+    buf.writeLong(requestId);
+    buf.writeShort(0);
+    const len = buf.length - 4;
+    buf.position = 0;
+    buf.writeInteger(len);
+    return buf.data;
+}
+
+// Outgoing request frame layout (see ClientSocket Request.getMessage):
+// [length:int][opCode:short][requestId:long][payload].
+function parseOutgoing(data) {
+    const buf = MessageBuffer.from(data, 0);
+    buf.readInteger();
+    const opCode = buf.readShort();
+    const requestId = buf.readLong();
+    return { opCode, requestId };
+}
+
+function withTimeout(promise, ms, message) {
+    let timer;
+    const guard = new Promise((resolve, reject) => {
+        timer = setTimeout(() => reject(new Error(message)), ms);
+    });
+    return Promise.race([promise, guard]).finally(() => clearTimeout(timer));

Review Comment:
   Here and follow Promise.finally() constructions are used, but it is implemented only in Node.js 10 (Node.js >= 8 is declared). So, it ought to be rewritten to a plain try - finally.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: dev-unsubscribe@ignite.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Fix four bugs in ClientSocket, Cursor and Errors [ignite-nodejs-thin-client]

Posted by "chesnokoff (via GitHub)" <gi...@apache.org>.
chesnokoff commented on PR #10:
URL: https://github.com/apache/ignite-nodejs-thin-client/pull/10#issuecomment-4905118346

   Let's not discuss who has had more impact on the client.
   
   This is still an Apache Software Foundation project, not a personal repository. We should follow the Apache Ignite contribution process.
   
   The Ignite CONTRIBUTING guide asks contributors to use the dev mailing list and says that Apache Ignite prefers to make decisions by consensus. That is why I asked about the version bump. It looks like something that should be discussed on the dev mailing list.
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: dev-unsubscribe@ignite.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Fix four bugs in ClientSocket, Cursor and Errors [ignite-nodejs-thin-client]

Posted by "JohnSColeman (via GitHub)" <gi...@apache.org>.
JohnSColeman commented on code in PR #10:
URL: https://github.com/apache/ignite-nodejs-thin-client/pull/10#discussion_r3742478568


##########
src/internal/ClientSocket.ts:
##########
@@ -296,15 +316,66 @@ export default class ClientSocket {
             if (this._requests.has(requestId)) {
                 const request = this._requests.get(requestId);
                 this._requests.delete(requestId);
+
+                // Carve a fresh, independent MessageBuffer from just this message's
+                // payload bytes (after length field + request-id). getSlice() returns
+                // a view over the shared socket buffer, but MessageBuffer.from() copies
+                // those bytes (via Buffer.from), so freshBuffer owns an independent
+                // buffer with its own position pointer. That independence prevents two
+                // cursors created from the same TCP segment from aliasing the same
+                // position and corrupting each other's reads under parallel scan
+                // workloads. Built only on the matched-request path so unmatched frames
+                // cost no copy.
+                const headerConsumed = isHandshake
+                    ? BinaryUtils.getSize(BinaryUtils.TYPE_CODE.INTEGER)           // 4 B: length only
+                    : BinaryUtils.getSize(BinaryUtils.TYPE_CODE.INTEGER) +         // 4 B: length
+                      BinaryUtils.getSize(BinaryUtils.TYPE_CODE.LONG);             // 8 B: request-id
+                const freshBuffer = MessageBuffer.from(
+                    buffer.getSlice(msgStart + headerConsumed, msgEnd),
+                    0
+                );
+
                 if (isHandshake) {
-                    await this._finalizeHandshake(buffer, request);
+                    // Handshake is single-in-flight, transitions _state and issues no
+                    // nested request, so it is safe to await inline on the queue.
+                    await this._finalizeHandshake(freshBuffer, request);
                 }
                 else {
-                    await this._finalizeResponse(buffer, request);
+                    // Do NOT await on the processing queue: a payloadReader may issue a
+                    // nested request on this same socket and await its reply (e.g.
+                    // GET_BINARY_TYPE when reading a COMPLEX_OBJECT whose type is not yet
+                    // cached in this client's BinaryTypeStorage). That reply arrives as a
+                    // later 'data' event chained behind this very queue entry, so awaiting
+                    // here would deadlock — the entry can only complete once the reply is
+                    // processed, but the reply can only be processed by a later entry.
+                    // freshBuffer is an independent copy of this message's payload, so
+                    // finalizing it off the parse chain cannot corrupt _buffer/_offset.
+                    // With finalize detached the CONNECTED path of _processResponse has no
+                    // remaining await and runs to completion synchronously, so two
+                    // invocations still cannot interleave on _buffer/_offset and the parse
+                    // race stays closed.
+                    this._finalizeResponse(freshBuffer, request).catch(err => {
+                        this._error = err.message;
+                        this._disconnect();
+                    });

Review Comment:
   Good catch — fixed in 85ff8ca. You're right: `request` is removed from `_requests` before the detached `_finalizeResponse` runs, so `_disconnect()` in the catch can't reject it, and `_finalizeResponse` has throw paths *outside* its own try/catch (the pre-`try` header reads `readShort`/`readInteger`/`readString`, and the awaited `_onAffinityTopologyChange`). On any of those a throw would leave the caller awaiting the request forever.
   
   The catch now rejects the request before disconnecting:
   
   ```ts
   this._finalizeResponse(freshBuffer, request).catch(err => {
       request.reject(err);   // request already removed from _requests; _disconnect() can't reject it
       this._error = err.message;
       this._disconnect();
   });
   ```
   
   `request.reject` is the raw Promise reject fn, so if `_finalizeResponse` already settled the request on its handled paths (`!isSuccess`, or the payloadReader catch) this is a harmless no-op. Verified: `ColdComplexRead` (live) and `ColdComplexReadDeadlock` (mock socket) specs both still pass.



##########
spec/cache/ColdComplexReadDeadlock.spec.js:
##########
@@ -0,0 +1,165 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+'use strict';
+
+require('jasmine-expect');
+
+const net = require('net');
+const EventEmitter = require('events');
+const Long = require('long');
+
+// Drive the REAL ClientSocket against a mock TCP socket so this regression is
+// deterministic and needs no cluster. It reproduces the exact async topology of
+// the cold complex-object read: a single socket, one response whose payloadReader
+// issues a nested request on that same socket and awaits its reply, where the
+// reply only arrives as a later 'data' event. If response finalization is awaited
+// on the socket's serialized processing queue, the nested reply is chained behind
+// the still-pending outer entry and can never be processed -> the outer request
+// hangs forever. With finalization dispatched off the queue, it resolves.
+const ClientSocket = require('apache-ignite-client/dist/internal/ClientSocket').default;
+const MessageBuffer = require('apache-ignite-client/dist/internal/MessageBuffer').default;
+
+const HANDSHAKE_SUCCESS_STATUS_CODE = 1;
+const OP_OUTER = 2001;
+const OP_INNER = 2002;
+const DEADLOCK_TIMEOUT_MS = 5000;
+
+// Handshake reply frame: [length:int][status:byte]. The >= 1.4.0 path then reads a
+// node-UUID via communicator.readObject, which the mock communicator stubs out, so
+// no UUID bytes are required (frames are length-delimited, not reader-position
+// delimited).
+function buildHandshakeResponse() {
+    const buf = new MessageBuffer();
+    buf.position = 4;
+    buf.writeByte(HANDSHAKE_SUCCESS_STATUS_CODE);
+    const len = buf.length - 4;
+    buf.position = 0;
+    buf.writeInteger(len);
+    return buf.data;
+}
+
+// Success response frame for protocol >= 1.4.0: [length:int][requestId:long][flags:short=0].
+function buildResponse(requestId) {
+    const buf = new MessageBuffer();
+    buf.position = 4;
+    buf.writeLong(requestId);
+    buf.writeShort(0);
+    const len = buf.length - 4;
+    buf.position = 0;
+    buf.writeInteger(len);
+    return buf.data;
+}
+
+// Outgoing request frame layout (see ClientSocket Request.getMessage):
+// [length:int][opCode:short][requestId:long][payload].
+function parseOutgoing(data) {
+    const buf = MessageBuffer.from(data, 0);
+    buf.readInteger();
+    const opCode = buf.readShort();
+    const requestId = buf.readLong();
+    return { opCode, requestId };
+}
+
+function withTimeout(promise, ms, message) {
+    let timer;
+    const guard = new Promise((resolve, reject) => {
+        timer = setTimeout(() => reject(new Error(message)), ms);
+    });
+    return Promise.race([promise, guard]).finally(() => clearTimeout(timer));

Review Comment:
   Fixed in 85ff8ca. `Promise.prototype.finally` is Node 10+ while `package.json` declares `engines.node >= 8.0.0`, so `withTimeout` is now `async` with a plain `try/finally` — `clearTimeout` still runs on both resolve and reject:
   
   ```js
   async function withTimeout(promise, ms, message) {
       let timer;
       const guard = new Promise((resolve, reject) => {
           timer = setTimeout(() => reject(new Error(message)), ms);
       });
       try {
           return await Promise.race([promise, guard]);
       } finally {
           clearTimeout(timer);
       }
   }
   ```
   
   Applied identically here and in `ColdComplexRead.spec.js` (the only two `.finally` uses in the PR). Both specs still pass.



##########
spec/cache/ColdComplexRead.spec.js:
##########
@@ -0,0 +1,130 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+'use strict';
+
+require('jasmine-expect');
+
+const TestingHelper = require('../TestingHelper');
+const {
+    IgniteClientConfiguration, ObjectType, ComplexObjectType
+} = require('apache-ignite-client');
+
+const CACHE_NAME = '__test_cold_complex_read';
+
+// Deadlock guard: a fresh client reading a complex object whose binary type is
+// not yet in its own BinaryTypeStorage must issue a nested GET_BINARY_TYPE on the
+// same socket from inside the get() payloadReader. If response finalization is
+// awaited on the socket processing queue, that nested reply can never be parsed
+// and get() hangs forever, so we race it against an explicit timeout.
+const DEADLOCK_TIMEOUT_MS = 10000;
+
+class ColdValue {
+    constructor() {
+        this.id = null;
+        this.name = null;
+    }
+}
+
+function coldValueType() {
+    return new ComplexObjectType(new ColdValue(), 'ColdValue').
+        setFieldType('id', ObjectType.PRIMITIVE_TYPE.INTEGER).
+        setFieldType('name', ObjectType.PRIMITIVE_TYPE.STRING);
+}
+
+function withTimeout(promise, ms, message) {
+    let timer;
+    const guard = new Promise((resolve, reject) => {
+        timer = setTimeout(() => reject(new Error(message)), ms);
+    });
+    return Promise.race([promise, guard]).finally(() => clearTimeout(timer));

Review Comment:
   Fixed in 85ff8ca — same change as the `ColdComplexReadDeadlock.spec.js` thread: `withTimeout` is now `async` + `try/finally` instead of `Promise.prototype.finally` (Node 10+), honouring `engines.node >= 8.0.0`. `clearTimeout` still runs on both resolve and reject. Spec still passes.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: dev-unsubscribe@ignite.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Fix four bugs in ClientSocket, Cursor and Errors [ignite-nodejs-thin-client]

Posted by "zstan (via GitHub)" <gi...@apache.org>.
zstan commented on code in PR #10:
URL: https://github.com/apache/ignite-nodejs-thin-client/pull/10#discussion_r3750266791


##########
spec/cache/ColdComplexReadDeadlock.spec.js:
##########
@@ -75,12 +75,18 @@ function parseOutgoing(data) {
     return { opCode, requestId };
 }
 
-function withTimeout(promise, ms, message) {
+async function withTimeout(promise, ms, message) {
     let timer;
     const guard = new Promise((resolve, reject) => {
         timer = setTimeout(() => reject(new Error(message)), ms);
     });
-    return Promise.race([promise, guard]).finally(() => clearTimeout(timer));
+    // try/finally rather than Promise.prototype.finally, which is Node 10+
+    // (package.json declares engines.node >= 8.0.0).
+    try {

Review Comment:
   looks good



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: dev-unsubscribe@ignite.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Fix four bugs in ClientSocket, Cursor and Errors [ignite-nodejs-thin-client]

Posted by "Copilot (via GitHub)" <gi...@apache.org>.
Copilot commented on code in PR #10:
URL: https://github.com/apache/ignite-nodejs-thin-client/pull/10#discussion_r3520398418


##########
src/Cursor.ts:
##########
@@ -160,8 +180,15 @@ export abstract class BaseCursor<T> {
         if (!this._buffer && this._hasNext) {
             await this._getNext();
         }
-        await this._read(this._buffer)
-        this._buffer = null;
+        if (this._buffer) {
+            await this._read(this._buffer);
+            this._buffer = null;
+        } else {
+            // No buffer and no next page — cursor is exhausted.
+            // Set _values to null so getValue() returns null and
+            // hasMore() returns false rather than replaying old entries.
+            this._values = null;
+        }

Review Comment:
   `_getValues()` is declared to return `Promise<T[]>`, but in the exhaustion branch it sets `_values = null` and returns it. This violates the method’s declared contract (and any generated `.d.ts`) and can cause runtime errors for callers that assume an array. Prefer returning an empty array (or change the return type/JSDoc to include `null`).



##########
src/internal/ClientSocket.ts:
##########
@@ -296,15 +316,66 @@ export default class ClientSocket {
             if (this._requests.has(requestId)) {
                 const request = this._requests.get(requestId);
                 this._requests.delete(requestId);
+
+                // Carve a fresh, independent MessageBuffer from just this message's
+                // payload bytes (after length field + request-id). getSlice() returns
+                // a view over the shared socket buffer, but MessageBuffer.from() copies
+                // those bytes (via Buffer.from), so freshBuffer owns an independent
+                // buffer with its own position pointer. That independence prevents two
+                // cursors created from the same TCP segment from aliasing the same
+                // position and corrupting each other's reads under parallel scan
+                // workloads. Built only on the matched-request path so unmatched frames
+                // cost no copy.
+                const headerConsumed = isHandshake
+                    ? BinaryUtils.getSize(BinaryUtils.TYPE_CODE.INTEGER)           // 4 B: length only
+                    : BinaryUtils.getSize(BinaryUtils.TYPE_CODE.INTEGER) +         // 4 B: length
+                      BinaryUtils.getSize(BinaryUtils.TYPE_CODE.LONG);             // 8 B: request-id
+                const freshBuffer = MessageBuffer.from(
+                    buffer.getSlice(msgStart + headerConsumed, msgEnd),
+                    0
+                );
+
                 if (isHandshake) {
-                    await this._finalizeHandshake(buffer, request);
+                    // Handshake is single-in-flight, transitions _state and issues no
+                    // nested request, so it is safe to await inline on the queue.
+                    await this._finalizeHandshake(freshBuffer, request);
                 }
                 else {
-                    await this._finalizeResponse(buffer, request);
+                    // Do NOT await on the processing queue: a payloadReader may issue a
+                    // nested request on this same socket and await its reply (e.g.
+                    // GET_BINARY_TYPE when reading a COMPLEX_OBJECT whose type is not yet
+                    // cached in this client's BinaryTypeStorage). That reply arrives as a
+                    // later 'data' event chained behind this very queue entry, so awaiting
+                    // here would deadlock — the entry can only complete once the reply is
+                    // processed, but the reply can only be processed by a later entry.
+                    // freshBuffer is an independent copy of this message's payload, so
+                    // finalizing it off the parse chain cannot corrupt _buffer/_offset.
+                    // With finalize detached the CONNECTED path of _processResponse has no
+                    // remaining await and runs to completion synchronously, so two
+                    // invocations still cannot interleave on _buffer/_offset and the parse
+                    // race stays closed.
+                    this._finalizeResponse(freshBuffer, request).catch(err => {
+                        this._error = err.message;
+                        this._disconnect();
+                    });
                 }
             }
             else {
-                throw IgniteClientError.internalError('Invalid response id: ' + requestId);
+                // No pending request matches this response id. At the protocol version
+                // this client negotiates (<= 1.4.0) the server never sends unsolicited
+                // frames: affinity-topology updates ride on response flags (handled in
+                // _finalizeResponse), and notification / heartbeat frames only exist in
+                // later protocol versions this client does not speak. Requests are also
+                // never removed while still awaiting a response (there is no client-side
+                // timeout), so an unmatched id cannot be a late or duplicate reply.
+                // It therefore means the response byte stream has desynced, after which
+                // every subsequent frame is garbage and the originating request would
+                // otherwise hang forever. Fail fast: throwing propagates to the socket
+                // 'data' handler's catch, which disconnects and rejects all pending
+                // requests with LostConnectionError so callers can recover instead of
+                // hanging.
+                throw IgniteClientError.internalError(
+                    'Response stream desync: received a frame with unmatched request id ' + requestId);

Review Comment:
   The PR description says unsolicited server notification/heartbeat frames (Ignite 2.14+) are logged and discarded, but this code still treats an unmatched `requestId` as a fatal stream desync and throws (disconnecting the socket). Please align the PR description with the implemented fail-fast behavior, or adjust this branch to actually discard known unsolicited frames if that’s required for the targeted protocol/server versions.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: dev-unsubscribe@ignite.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Fix four bugs in ClientSocket, Cursor and Errors [ignite-nodejs-thin-client]

Posted by "FrankKanBear (via GitHub)" <gi...@apache.org>.
FrankKanBear commented on PR #10:
URL: https://github.com/apache/ignite-nodejs-thin-client/pull/10#issuecomment-4679910063

   That sounds great. Thank you John.
   
   John Coleman ***@***.***> schrieb am Do., 11. Juni 2026,
   12:44:
   
   > *JohnSColeman* left a comment (apache/ignite-nodejs-thin-client#10)
   > <https://github.com/apache/ignite-nodejs-thin-client/pull/10#issuecomment-4679716077>
   >
   > @zstan <https://github.com/zstan> @FrankKanBear
   > <https://github.com/FrankKanBear> I will take a look at the review points
   > on the weekend.
   >
   > —
   > Reply to this email directly, view it on GitHub
   > <https://github.com/apache/ignite-nodejs-thin-client/pull/10?email_source=notifications&email_token=BWDDIVUGB5HWFUAXD5E55V347KESHA5CNFSNUABFM5UWIORPF5TWS5BNNB2WEL2JONZXKZKDN5WW2ZLOOQXTINRXHE3TCNRQG432M4TFMFZW63VHNVSW45DJN5XKKZLWMVXHJLDGN5XXIZLSL5RWY2LDNM#issuecomment-4679716077>,
   > or unsubscribe
   > <https://github.com/notifications/unsubscribe-auth/BWDDIVQE3PVABI2GSWZKEA347KESHAVCNFSNUABFKJSXA33TNF2G64TZHMZTCNBTGA3TSMRWHNEXG43VMU5TIMRQG4ZTMMJQGY4KC5QC>
   > .
   > Triage notifications, keep track of coding agent tasks and review pull
   > requests on the go with GitHub Mobile for iOS
   > <https://github.com/notifications/mobile/ios/BWDDIVUXUOIKCOTNOIKF65L47KESHA5CNFSNUABFM5UWIORPF5TWS5BNNB2WEL2JONZXKZKDN5WW2ZLOOQXTINRXHE3TCNRQG432M4TFMFZW63VHNVSW45DJN5XKKZLWMVXHJKTGN5XXIZLSL5UW64Y>
   > and Android
   > <https://github.com/notifications/mobile/android/BWDDIVSFPFHV746XVLW6FFL47KESHA5CNFSNUABFM5UWIORPF5TWS5BNNB2WEL2JONZXKZKDN5WW2ZLOOQXTINRXHE3TCNRQG432M4TFMFZW63VHNVSW45DJN5XKKZLWMVXHJLTGN5XXIZLSL5QW4ZDSN5UWI>.
   > Download it today!
   > You are receiving this because you were mentioned.Message ID:
   > ***@***.***>
   >
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: dev-unsubscribe@ignite.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Fix four bugs in ClientSocket, Cursor and Errors [ignite-nodejs-thin-client]

Posted by "Copilot (via GitHub)" <gi...@apache.org>.
Copilot commented on code in PR #10:
URL: https://github.com/apache/ignite-nodejs-thin-client/pull/10#discussion_r3405385459


##########
src/internal/ClientSocket.ts:
##########
@@ -296,15 +311,40 @@ export default class ClientSocket {
             if (this._requests.has(requestId)) {
                 const request = this._requests.get(requestId);
                 this._requests.delete(requestId);
+
+                // Carve a fresh, independent MessageBuffer from just this message's
+                // payload bytes (after length field + request-id).  Passing a copy
+                // rather than the shared socket buffer prevents two cursors created
+                // from the same TCP segment from aliasing the same position pointer
+                // and corrupting each other's reads under parallel scan workloads.
+                // Built only on the matched-request path so unmatched frames cost no copy.
+                const headerConsumed = isHandshake
+                    ? BinaryUtils.getSize(BinaryUtils.TYPE_CODE.INTEGER)           // 4 B: length only
+                    : BinaryUtils.getSize(BinaryUtils.TYPE_CODE.INTEGER) +         // 4 B: length
+                      BinaryUtils.getSize(BinaryUtils.TYPE_CODE.LONG);             // 8 B: request-id
+                const freshBuffer = MessageBuffer.from(
+                    buffer.getSlice(msgStart + headerConsumed, msgEnd),
+                    0
+                );

Review Comment:
   `buffer.getSlice` appears to take `(start, length)` (as used earlier with `buffer.getSlice(this._offset - length, length)`), but here it’s being called with `(start, endOffset)` (`msgEnd`). This will likely slice the wrong number of bytes (potentially too many) and can corrupt response parsing. Calculate the payload length explicitly (e.g., `msgEnd - (msgStart + headerConsumed)` or `length - headerConsumed`) and pass that as the second argument.



##########
src/internal/Logger.ts:
##########
@@ -41,4 +41,10 @@ export default class Logger {
             console.log('ERROR: ' + data, ...args);
         }
     }
+
+    static logWarning(data: string, ...args: any[]) {
+        if (Logger._debug) {
+            console.log('WARNING: ' + data, ...args);
+        }
+    }

Review Comment:
   For warning-level logs, `console.warn(...)` is generally preferred over `console.log(...)` so warnings go to stderr and can be filtered/collected separately in many runtimes. If you want consistent stream behavior, consider documenting that choice; otherwise switching to `console.warn` would better match the method’s intent.



##########
src/internal/ClientSocket.ts:
##########
@@ -296,15 +311,40 @@ export default class ClientSocket {
             if (this._requests.has(requestId)) {
                 const request = this._requests.get(requestId);
                 this._requests.delete(requestId);
+
+                // Carve a fresh, independent MessageBuffer from just this message's
+                // payload bytes (after length field + request-id).  Passing a copy
+                // rather than the shared socket buffer prevents two cursors created
+                // from the same TCP segment from aliasing the same position pointer
+                // and corrupting each other's reads under parallel scan workloads.
+                // Built only on the matched-request path so unmatched frames cost no copy.
+                const headerConsumed = isHandshake
+                    ? BinaryUtils.getSize(BinaryUtils.TYPE_CODE.INTEGER)           // 4 B: length only
+                    : BinaryUtils.getSize(BinaryUtils.TYPE_CODE.INTEGER) +         // 4 B: length
+                      BinaryUtils.getSize(BinaryUtils.TYPE_CODE.LONG);             // 8 B: request-id
+                const freshBuffer = MessageBuffer.from(
+                    buffer.getSlice(msgStart + headerConsumed, msgEnd),
+                    0
+                );
+
                 if (isHandshake) {
-                    await this._finalizeHandshake(buffer, request);
+                    await this._finalizeHandshake(freshBuffer, request);
                 }
                 else {
-                    await this._finalizeResponse(buffer, request);
+                    await this._finalizeResponse(freshBuffer, request);
                 }
             }
             else {
-                throw IgniteClientError.internalError('Invalid response id: ' + requestId);
+                // No pending request matches this response id. At the protocol
+                // version this client negotiates (<= 1.4.0) the server has no reason
+                // to send an unsolicited frame: affinity-topology updates ride on
+                // response flags (handled in _finalizeResponse), and notification /
+                // heartbeat frames only exist in later protocol versions this client
+                // does not speak. An unmatched id therefore most likely indicates a
+                // parsing desync. Discard it so the connection survives instead of
+                // crashing, but warn (when debug is enabled) so the anomaly is
+                // diagnosable rather than silently masked.
+                Logger.logWarning('Discarding response frame with unmatched request id: ' + requestId);

Review Comment:
   The comment indicates an unmatched request id is most likely a parsing desync, but the code now discards the frame and keeps the connection alive. In a desync scenario, continuing can lead to repeated misparsing and undefined client behavior. Consider failing fast by setting `_error` and disconnecting on the first unmatched frame (or after a small threshold), and/or logging at a level that is visible even when debug is disabled so operators can detect and act on this condition.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: dev-unsubscribe@ignite.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Fix four bugs in ClientSocket, Cursor and Errors [ignite-nodejs-thin-client]

Posted by "chesnokoff (via GitHub)" <gi...@apache.org>.
chesnokoff commented on code in PR #10:
URL: https://github.com/apache/ignite-nodejs-thin-client/pull/10#discussion_r3537043890


##########
package.json:
##########
@@ -1,6 +1,6 @@
 {
   "name": "apache-ignite-client",
-  "version": "1.1.0",
+  "version": "1.1.1",

Review Comment:
   Why do we update the version in this PR? I can see this PR was only for bug fixes
   
   Also, shouldn't the version update be done separately and discussed on the Apache Ignite dev list?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: dev-unsubscribe@ignite.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Fix four bugs in ClientSocket, Cursor and Errors [ignite-nodejs-thin-client]

Posted by "Copilot (via GitHub)" <gi...@apache.org>.
Copilot commented on code in PR #10:
URL: https://github.com/apache/ignite-nodejs-thin-client/pull/10#discussion_r3542403431


##########
src/internal/ClientSocket.ts:
##########
@@ -296,15 +316,66 @@ export default class ClientSocket {
             if (this._requests.has(requestId)) {
                 const request = this._requests.get(requestId);
                 this._requests.delete(requestId);
+
+                // Carve a fresh, independent MessageBuffer from just this message's
+                // payload bytes (after length field + request-id). getSlice() returns
+                // a view over the shared socket buffer, but MessageBuffer.from() copies
+                // those bytes (via Buffer.from), so freshBuffer owns an independent
+                // buffer with its own position pointer. That independence prevents two
+                // cursors created from the same TCP segment from aliasing the same
+                // position and corrupting each other's reads under parallel scan
+                // workloads. Built only on the matched-request path so unmatched frames
+                // cost no copy.
+                const headerConsumed = isHandshake
+                    ? BinaryUtils.getSize(BinaryUtils.TYPE_CODE.INTEGER)           // 4 B: length only
+                    : BinaryUtils.getSize(BinaryUtils.TYPE_CODE.INTEGER) +         // 4 B: length
+                      BinaryUtils.getSize(BinaryUtils.TYPE_CODE.LONG);             // 8 B: request-id
+                const freshBuffer = MessageBuffer.from(
+                    buffer.getSlice(msgStart + headerConsumed, msgEnd),
+                    0
+                );
+
                 if (isHandshake) {
-                    await this._finalizeHandshake(buffer, request);
+                    // Handshake is single-in-flight, transitions _state and issues no
+                    // nested request, so it is safe to await inline on the queue.
+                    await this._finalizeHandshake(freshBuffer, request);
                 }
                 else {
-                    await this._finalizeResponse(buffer, request);
+                    // Do NOT await on the processing queue: a payloadReader may issue a
+                    // nested request on this same socket and await its reply (e.g.
+                    // GET_BINARY_TYPE when reading a COMPLEX_OBJECT whose type is not yet
+                    // cached in this client's BinaryTypeStorage). That reply arrives as a
+                    // later 'data' event chained behind this very queue entry, so awaiting
+                    // here would deadlock — the entry can only complete once the reply is
+                    // processed, but the reply can only be processed by a later entry.
+                    // freshBuffer is an independent copy of this message's payload, so
+                    // finalizing it off the parse chain cannot corrupt _buffer/_offset.
+                    // With finalize detached the CONNECTED path of _processResponse has no
+                    // remaining await and runs to completion synchronously, so two
+                    // invocations still cannot interleave on _buffer/_offset and the parse
+                    // race stays closed.
+                    this._finalizeResponse(freshBuffer, request).catch(err => {
+                        this._error = err.message;
+                        this._disconnect();
+                    });

Review Comment:
   The detached `_finalizeResponse(...).catch(...)` disconnects on error, but it does not reject the in-flight `request`. Because the request is removed from `_requests` before finalization, `_disconnect()` will not reject it either, so if `_finalizeResponse` ever throws (e.g. malformed frame, short buffer, or an exception in affinity-topology handling), the caller can hang forever awaiting this request. Reject the request in this catch before disconnecting.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: dev-unsubscribe@ignite.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Fix four bugs in ClientSocket, Cursor and Errors [ignite-nodejs-thin-client]

Posted by "JohnSColeman (via GitHub)" <gi...@apache.org>.
JohnSColeman commented on PR #10:
URL: https://github.com/apache/ignite-nodejs-thin-client/pull/10#issuecomment-5164708747

   > @JohnSColeman hi, i see some comments, do you plan to fix them ?
   @zstan 
   
   Hi, I expect I will look at this again on the weekend.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: dev-unsubscribe@ignite.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Fix four bugs in ClientSocket, Cursor and Errors [ignite-nodejs-thin-client]

Posted by "vldpyatkov (via GitHub)" <gi...@apache.org>.
vldpyatkov commented on code in PR #10:
URL: https://github.com/apache/ignite-nodejs-thin-client/pull/10#discussion_r3596306765


##########
spec/cache/ColdComplexRead.spec.js:
##########
@@ -0,0 +1,130 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+'use strict';
+
+require('jasmine-expect');
+
+const TestingHelper = require('../TestingHelper');
+const {
+    IgniteClientConfiguration, ObjectType, ComplexObjectType
+} = require('apache-ignite-client');
+
+const CACHE_NAME = '__test_cold_complex_read';
+
+// Deadlock guard: a fresh client reading a complex object whose binary type is
+// not yet in its own BinaryTypeStorage must issue a nested GET_BINARY_TYPE on the
+// same socket from inside the get() payloadReader. If response finalization is
+// awaited on the socket processing queue, that nested reply can never be parsed
+// and get() hangs forever, so we race it against an explicit timeout.
+const DEADLOCK_TIMEOUT_MS = 10000;
+
+class ColdValue {
+    constructor() {
+        this.id = null;
+        this.name = null;
+    }
+}
+
+function coldValueType() {
+    return new ComplexObjectType(new ColdValue(), 'ColdValue').
+        setFieldType('id', ObjectType.PRIMITIVE_TYPE.INTEGER).
+        setFieldType('name', ObjectType.PRIMITIVE_TYPE.STRING);
+}
+
+function withTimeout(promise, ms, message) {
+    let timer;
+    const guard = new Promise((resolve, reject) => {
+        timer = setTimeout(() => reject(new Error(message)), ms);
+    });
+    return Promise.race([promise, guard]).finally(() => clearTimeout(timer));

Review Comment:
   Promise.finally has to be rewritten.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: dev-unsubscribe@ignite.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org