Skip to content

feat(node): expose client lifecycle events through on and once - #4552

Open
Arham-Begani wants to merge 12 commits into
apache:masterfrom
Arham-Begani:feat/node-client-events
Open

Arham-Begani wants to merge 12 commits into
apache:masterfrom
Arham-Begani:feat/node-client-events

Conversation

@Arham-Begani

@Arham-Begani Arham-Begani commented Oct 15, 2026 •

Copy link
Copy Markdown

Which issue does this PR address?

Closes #2396, assigned to Arham-Begani. This updates the existing contribution after the requested rebase following #4561.

Rationale

Contributor-supplied rationale:

The rationale behind this patch is to provide observability into network link state changes and guarantee clean asynchronous resource teardown.

What changed?

Client and SingleClient expose typed, chainable on, once, off and removeListener methods for connecting, connected, error and end. Lazy connections, replica routing and session recovery remain supported.

  • Destruction immediately cancels requests, prevents new links and emits one final end after all sockets close. Raw destruction stays synchronous; the high-level client returns a shared completion promise, including after direct raw-client closure.
  • connecting fires once across failed retries until a connection succeeds. Intentional session teardown does not emit a public error.
  • Listeners receive the public client as this. A weak callback map preserves listener identity for removal, duplicate registrations and self-removal from once.
  • connected and end dispatch outside the transport promise chain, so a throwing application listener retains EventEmitter exception behavior instead of entering connection recovery.

The README documents the four-method interface, which is not a complete Node.js EventEmitter implementation. It also explains that getClient() returns SimpleClient without lifecycle listeners, and that command errors can wrap connection errors in cause.

Local Execution

Current source: 4f0b105e9420010ebcc90cf246a231da10b2a53b; tree: 7d5b1e2b4812894d8e3a45fd4e0df154b77c668f.

GitHub reported a merge conflict, so this update normally merges upstream af99cd9f7 without rewriting the published history. The two conflict resolutions retain upstream operation constants and readiness groups alongside the reviewed lifecycle interface.

Windows, Node 24:

  • TypeScript build, VSR protocol mirror check and direct ESLint passed.
  • The full unit run reported 950 passes and two failures. One failed identically on the untouched upstream base; the other passed when rerun in isolation. These Windows results are not represented as a fully passing suite.
  • The actual prek run encountered Windows shell/symlink limitations, so the same unmodified hooks were run on Linux below.

Separate Ubuntu validation of this exact source:

  • Node 24.22.1 and 26.13.0: all 952 unit tests passed on each version; canonical lint and build passed.
  • All nine applicable, unmodified prek hooks passed on Node 24. Commit/tree assertions and clean-tree checks passed after hooks and tests.
  • The first Node 24 attempt failed during Git source setup, before tests. Only that failed job was retried; its successful retry tested the same source.

This run covers the SDK and hooks. It does not rerun the real-server TCP/TLS/BDD suites. The earlier October 23 real-server validation and green upstream CI apply to 672e5ff1, not this new merge. Fresh upstream CI must validate the updated head.

AI Usage

Claude Code wrote the original feature, tests and documentation. OpenAI Codex adapted the feature to #4561, implemented review corrections, resolved the two textual merge conflicts, prepared the validation harness and this description, and ran the recorded checks.

The user-invoked team-review-slim review examined the feature using four roles. Its applicable findings led to regression tests and corrections for listener context and exception dispatch. The report's original changes-requested verdict is retained; no independent approval of the subsequent corrections is claimed.

The contributor supplied the rationale above, personally reviewed the October 22 patch, and subsequently confirmed that they reviewed and understood the October 23 corrections and can explain them before this update was published.

@github-actions

Copy link
Copy Markdown

This PR is closed because #2396 is not assigned to you.

Good first issues are assigned before work starts. Comment on an issue, wait for a maintainer to assign it to you, and then open a PR. See CONTRIBUTING.md.

@github-actions github-actions Bot closed this Oct 15, 2026
@Arham-Begani

Copy link
Copy Markdown
Author

Hi! I’d like to work on this. I got ahead of myself and opened #4552 before being assigned, which the bot closed. Sorry about that. @dajneem23 offered back in April, so I’m happy to step back if they’re still on it.

#4552 adds typed on/once to Client for connecting, connected, error and end, as T1B0 and spetz asked for on #4061. end fires once after destroy(), and error is only re-emitted when someone listens. It includes unit tests and an e2e test.

A few questions before it goes further:

  1. Is it OK to also add off/removeListener? Without them a listener can’t be removed, and events.once(client, ...) breaks.
  2. Should disconnected be included? The internal event also fires for dials that never connected, so it needs agreed rules first. Should it go in this PR or a follow-up?
  3. Should eviction go in this set of events, or is it better as a separate session event?
  4. I noticed reconnect maxRetries exceeded is emitted twice for one outage. Would you like a separate issue for that?

If the approach looks fine, could you assign me? I’ll reopen or open a new PR from the same branch.

@justinmclean

Copy link
Copy Markdown
Member

Re "Is it OK to also add off/removeListener" - yep, if they are needed, or anything else, you should add them. Re 3 and 4, I'd make them separate issues.

@justinmclean justinmclean reopened this Oct 15, 2026
@hubcio hubcio closed this Oct 15, 2026
@hubcio hubcio reopened this Oct 15, 2026
@Arham-Begani

Copy link
Copy Markdown
Author

Re "Is it OK to also add off/removeListener" - yep, if they are needed, or anything else, you should add them. Re 3 and 4, I'd make them separate issues.

Thanks @justinmclean! off/removeListener are already in this PR. I’ll open separate issues for 3 and 4, and fold disconnected into the eviction one since T1B0 suggested them together.

@codecov

codecov Bot commented Oct 15, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 99.16667% with 1 line in your changes missing coverage. Please review.
✅ Project coverage is 74.53%. Comparing base (d9bb423) to head (60fed2f).

Files with missing lines Patch % Lines
foreign/node/src/client/client.socket.ts 97.82% 1 Missing ⚠️
Additional details and impacted files
@@             Coverage Diff              @@
##             master    #4552      +/-   ##
============================================
- Coverage     75.98%   74.53%   -1.45%     
+ Complexity     4357     4319      -38     
============================================
  Files          1558     1497      -61     
  Lines        248509   228664   -19845     
  Branches     177088   158806   -18282     
============================================
- Hits         188820   170440   -18380     
+ Misses        53689    52938     -751     
+ Partials       6000     5286     -714     
Components Coverage Δ
Rust Core 68.50% <ø> (-2.74%) ⬇️
Java SDK 80.95% <ø> (-0.05%) ⬇️
C# SDK 86.17% <ø> (-0.25%) ⬇️
Python SDK 86.59% <ø> (+1.07%) ⬆️
PHP SDK 91.86% <ø> (+1.51%) ⬆️
Node SDK 97.23% <99.16%> (+0.02%) ⬆️
Go SDK 73.49% <ø> (-0.30%) ⬇️
C++ SDK 85.47% <ø> (+0.17%) ⬆️
Files with missing lines Coverage Δ
foreign/node/src/client/client.connection.ts 99.73% <100.00%> (+<0.01%) ⬆️
foreign/node/src/client/client.ts 97.39% <100.00%> (+5.39%) ⬆️
foreign/node/src/client/client.type.ts 100.00% <100.00%> (ø)
foreign/node/src/client/client.socket.ts 97.42% <97.82%> (+0.06%) ⬆️

... and 280 files with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@hubcio

hubcio commented Oct 15, 2026

Copy link
Copy Markdown
Contributor

/skill team-review-slim

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Summary: The new lifecycle events land on the pooled Client only, and a leader move that races destroy() can leave a dialing socket open and report connected after end, which the new contract forbids. A low-confidence concern about generic-pool teardown stayed out, because the library source is not in this checkout to prove it.

Counts: critical 0, warning 3, nit 2, simplification 0


This review was generated by Claude Code 2.1.284 on deepseek-flash[1m]. Review the output before you act on it.

Comment thread foreign/node/src/client/client.type.ts Resolved
Comment thread foreign/node/src/client/client.ts Resolved
Comment thread foreign/node/src/client/client.ts Resolved
Comment thread foreign/node/README.md Resolved
Comment thread foreign/node/README.md Resolved
@github-actions github-actions Bot added the S-waiting-on-author PR is waiting on author response label Oct 15, 2026
@Arham-Begani

Copy link
Copy Markdown
Author

/ready

@github-actions github-actions Bot added S-waiting-on-review PR is waiting on a reviewer and removed S-waiting-on-author PR is waiting on author response labels Oct 15, 2026
@Arham-Begani

Copy link
Copy Markdown
Author

@justinmclean Could you clarify the remaining issue-ownership requirement? This PR is assigned to Arham-Begani, but linked issue #2396 is still unassigned. If the issue itself must also be assigned under CONTRIBUTING, could you assign it, or confirm whether the existing PR assignment is sufficient?

The review findings were addressed in b79775b, and hubcio resolved the inline threads. The branch is mergeable with no failed reported checks. It has been left behind master in accordance with the instruction to avoid update-only rebases unless a maintainer requests one or a conflict occurs.

This ownership-status follow-up was prepared with OpenAI Codex assistance.

@hubcio

hubcio commented Oct 20, 2026

Copy link
Copy Markdown
Contributor

@Arham-Begani i assigned #2396 to you. also i merged #4561 which introduced conflicts here. could you please rebase?

Client gave applications no way to observe its connection: only the
internal CommandResponseStream is an EventEmitter. Add typed on, once,
off and removeListener to Client, backed by the pooled connection, for
four events:

- connecting: once per dial. Each dial gets its own socket, so the
  announcement is made once per installed socket, deferred one tick so
  the constructor's first dial reaches listeners attached after it.
- connected: the dialed socket is ready (TCP connect or TLS handshake),
  before login.
- error: every error the connection reports. Re-emitted only when a
  listener exists, because EventEmitter throws on an unheard 'error'
  and these errors used to reach callers only through failed commands.
- end: once, after destroy() closes the socket, so no lifecycle event
  can follow it. destroy() now resolves after 'end'.

The RawClient type is unchanged, so custom RawClient implementations
passed to SimpleClient still type-check.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01KqEXKVMqfFH6hmLUyQvjdS
@Arham-Begani
Arham-Begani marked this pull request as draft October 20, 2026 11:30
@Arham-Begani

Arham-Begani commented Oct 20, 2026 •

Copy link
Copy Markdown
Author

The requested rebase is now pushed at fc31fa2eec9cea7c9750e7c0920b706623afe463, preserving the replica routing and session architecture from #4561.

Review also caught and fixed deliberate login/logout teardown appearing as public errors, the raw factory's shutdown return type, and compatibility with custom socket-returning destructors. Regression tests cover all three.

Exact-source Ubuntu validation passed:

  • Node 23 and 24: 576 unit tests each, lint and build.
  • All nine applicable unmodified prek hooks, with no source changes.
  • Matching real server: 73 TCP E2E tests, eight TLS tests, and all four Node-supported BDD scenarios / 31 steps.

Local Windows build, direct ESLint and all 14 focused regressions also passed. The PR description records the platform limitations and distinguishes this hosted validation from upstream PR CI. New-head upstream checks still require separate verification.

GitHub reports the new head as mergeable. Its upstream Pre-merge and PR Title workflows currently report action_required and await maintainer workflow approval; no upstream test pass is claimed.

The contributor supplied the rationale in the PR and personally confirmed review and understanding of the final changes. Claude Code assisted with the original implementation; OpenAI Codex assisted with the rebase, corrections, tests and this update.

@github-actions github-actions Bot removed the S-waiting-on-review PR is waiting on a reviewer label Oct 20, 2026
Arham-Begani and others added 3 commits October 20, 2026 17:01
Adapt the earlier redirect/shutdown and wrapper fixes to the replica-link
architecture introduced by apache#4561. Keep immediate request cancellation and
wait for every physical socket close before one final end event. Refuse new
links after destruction, retain listener removal, and await custom raw-client
destruction through SimpleClient. SingleClient now inherits Client's events.

Separate link diagnostics from the raw stream's special error event so internal
events.once recovery waits are not rejected by an expected replica failure.
Add focused wrapper and routing/destruction regression coverage and update the
lazy first-dial and all-replica event documentation.

Preserve the original contribution's AI attribution below. OpenAI Codex ported
the feature and tests to the new architecture and prepared this rebase. Local
validation and environment limitations are recorded separately; this commit
does not attest to human review or claim the PR is ready.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01KqEXKVMqfFH6hmLUyQvjdS
AI-Assistance: OpenAI Codex
Do not forward deliberate link teardown as a public connection error. Expose the raw-client shutdown promise while accepting synchronous injected clients. Cover login, relogin, logout and factory shutdown completion with regression tests.

AI-Assistance: OpenAI Codex
Keep the void callback branch for existing RawClient implementations whose
destructor returns a value, while allowing asynchronous shutdown. Add a
compile and runtime regression for a custom destructor returning Socket.

AI-Assistance: OpenAI Codex
@Arham-Begani
Arham-Begani force-pushed the feat/node-client-events branch from b79775b to fc31fa2 Compare October 21, 2026 05:26
@Arham-Begani
Arham-Begani marked this pull request as ready for review October 21, 2026 05:26
@github-actions github-actions Bot added the S-waiting-on-review PR is waiting on a reviewer label Oct 21, 2026
@Arham-Begani

Copy link
Copy Markdown
Author

@hubcio, the requested rebase is now at fc31fa2eec9cea7c9750e7c0920b706623afe463 and is ready for review. Could you or an authorized committer approve the pending GitHub workflows for this head when convenient?

Pre-merge and PR Title currently report action_required. The separate validation run passed 576 unit tests on each of Node 23/24, all applicable hooks, and the real-server TCP/TLS/BDD suites. Local execution and review corrections are recorded above; these results do not replace upstream CI.

This follow-up was prepared with AI assistance.

@Arham-Begani

Copy link
Copy Markdown
Author

Thanks for enabling CI. Upstream Pre-merge now passes on fc31fa2: 576 Node unit tests, 73 TCP tests, 8 TLS tests, and 4 BDD scenarios / 31 steps. Node lint/build, examples, common checks and PR Title also pass; Codecov reports full coverage of the added coverable lines.

@hubcio, could you take another look when convenient? The requested rebase and review corrections are complete, and there are no unresolved inline threads. GitHub reports the branch as mergeable but behind master; following CONTRIBUTING.md, I'll leave the final branch update to a maintainer unless a conflict appears or you request another rebase.

This status update was prepared with AI assistance.

@hubcio

hubcio commented Oct 21, 2026

Copy link
Copy Markdown
Contributor

@T1B0 could you please check?

Comment thread foreign/node/README.md Resolved
Keep raw destroy synchronous, settle socket closures before scheduling end, and emit one connecting event until a dial succeeds. Document getClient event availability and cover listener exception semantics and command retry recovery.

AI-Assistance: OpenAI Codex
Observe end from construction so facade destruction completes when callers already closed the public raw client. Cover the public provider path and document wrapped command errors.

AI-Assistance: OpenAI Codex
@Arham-Begani

Copy link
Copy Markdown
Author

The four review corrections are pushed at 63c8f036; each thread has a reply describing its fix and regression coverage. Could an authorized maintainer approve the fresh Pre-merge and PR Title runs for this head? Both currently report action_required.

Separate exact-source Ubuntu validation passed 579 unit tests on each of Node 23/24, lint/build, all applicable hooks and the real-server TCP/TLS/BDD suites. The updated PR description records local Windows results and limitations as well. These results do not replace upstream CI.

This update was prepared with AI assistance.

@Arham-Begani

Copy link
Copy Markdown
Author

Thanks for enabling CI. Upstream Pre-merge now passes on 63c8f036: 579 unit tests, 73 TCP tests, 8 TLS tests, and 4 BDD scenarios / 31 steps. Lint, build, examples, common checks and PR Title also pass. Codecov reports all added coverable lines covered.

The four requested corrections have individual replies and regression coverage. This head is ready for re-review; the branch is mergeable, so I have left the final synchronization to a maintainer per CONTRIBUTING.md.

/request-review @T1B0

This status update was prepared with AI assistance.

@github-actions
github-actions Bot requested a review from T1B0 October 22, 2026 16:50
Arham-Begani and others added 2 commits October 23, 2026 15:15
Resolve the reported merge conflicts without rewriting branch history.
Keep upstream connection-error classification and sign-in state while
preserving lifecycle events and socket-close completion.

Adapt two lifecycle tests to the upstream cancellation error and explicit
bootstrap retry budget. All 715 SDK unit tests and 24 example unit tests
pass on Node 24. Build, protocol mirror, lint, and all nine applicable
prek hooks pass.

Co-authored-by: OpenAI Codex <[email protected]>
@hubcio

hubcio commented Oct 23, 2026

Copy link
Copy Markdown
Contributor

we'll merge this PR next week. right now we're merging critical VSR fixes.

@Arham-Begani

Copy link
Copy Markdown
Author

Thanks for the scheduling update. Two final lifecycle corrections are pushed at 672e5ff1, directly extending 029fdf28:

  • Listeners now receive the public client as this, with callback identity preserved for removal, duplicate registrations and once self-removal.
  • A throwing connected listener no longer enters transport retry handling. The new regressions failed on the published parent and pass with these corrections.

Validation of this exact source passed 717 unit tests on each of Node 23/24, lint/build, all nine applicable unmodified hooks, 82 TCP tests, 17 TLS tests and 16 BDD scenarios / 114 steps. Windows build, protocol mirror, direct ESLint and 18 focused lifecycle tests also passed. The PR description now records this source and separates these results from upstream CI.

Could an authorized maintainer approve the fresh Pre-merge and PR Title runs when ready? Both report action_required on this new head. The earlier green runs apply to 029fdf28.

This update was prepared with AI assistance, as disclosed in the PR.

@Arham-Begani

Copy link
Copy Markdown
Author

Current-head upstream CI is now green at 672e5ff11df234f1e8999d7a31426ec823ec9588: Pre-merge and PR Title passed. I checked the individual jobs: Node unit tests, lint, build, e2e, BDD and examples executed successfully; these are upstream results for the submitted corrections, separate from the earlier fork validation.

The reviewed source is unchanged. This is ready for re-review when the VSR queue permits; no further CI authorization request is needed for this head.

This update was prepared with AI assistance.

Upstream added operation constants and raw readiness groups beside the
lifecycle changes. Preserve both interfaces while resolving the two
textual merge conflicts without rewriting the published branch history.

Prepared with OpenAI Codex assistance.
@Arham-Begani

Arham-Begani commented Oct 31, 2026 •

Copy link
Copy Markdown
Author

The two merge conflicts are resolved in 4f0b105e9420010ebcc90cf246a231da10b2a53b, a normal merge of upstream af99cd9f7 that preserves the published branch history. GitHub now reports the PR as mergeable. The conflict resolutions retain the upstream operation constants/readiness groups alongside the reviewed lifecycle changes.

Exact-source Ubuntu validation passed all 952 unit tests on both Node 24.22.1 and 26.13.0, canonical lint/build, and all nine applicable unmodified prek hooks. Commit/tree and clean-source checks passed after hooks and tests. One Node 24 Git setup failure was retried before obtaining these results. This run covers the SDK/hooks; it does not claim fresh TCP/TLS/BDD results for the merge.

Could an authorized maintainer approve the new Pre-merge and PR Title runs? Both report action_required for this head. Earlier green upstream checks apply to 672e5ff1; the PR description now separates the new SDK validation from those earlier results.

This update was prepared with AI assistance.

@hubcio hubcio left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

please address the issues below.

@github-actions github-actions Bot added S-waiting-on-author PR is waiting on author response and removed S-waiting-on-review PR is waiting on a reviewer labels Nov 4, 2026
A server eviction reaches the client from inside the link's onData
handler, which fails the link and re-emits its error and eviction events
synchronously. A public eviction listener that threw was taken for a
transport failure, and a throwing connectionError listener hit the
second, guarded fail() and was dropped without a trace.

Public listeners now run on the next tick, like connected already does,
so their exceptions surface as ordinary uncaught EventEmitter errors.
The client lifetime guard is checked both when the link reports and
when the listener runs, so no event follows destroy().
@Arham-Begani
Arham-Begani force-pushed the feat/node-client-events branch from 3b7d8af to 2aa5fb3 Compare November 6, 2026 05:44
@Arham-Begani

Copy link
Copy Markdown
Author

@hubcio that was the last open thread on my side. Could you take another look?

@github-actions

Copy link
Copy Markdown

This pull request has been automatically marked as stale because it has not had recent activity. It will be closed in 7 days if no further activity occurs.

If you need a review, please ensure CI is green and the PR is rebased on the latest master. Don't hesitate to ping the maintainers - either @core on Discord or by mentioning them directly here on the PR.

Thank you for your contribution!

@github-actions github-actions Bot added the S-stale Inactive issue or pull request label Nov 19, 2026
@Arham-Begani

Copy link
Copy Markdown
Author

/ready

@github-actions github-actions Bot added S-waiting-on-review PR is waiting on a reviewer and removed S-waiting-on-author PR is waiting on author response labels Nov 19, 2026
The contributor branch used the localhost fixture that expired on November 17. Include upstream apache#4745 so the Node TLS tests can validate the lifecycle changes using a current certificate.
@github-actions github-actions Bot removed the S-stale Inactive issue or pull request label Nov 22, 2026
Exercise both socket data listener orderings so an eviction racing with destroy cannot escape after shutdown begins. The tests fail when the two eviction lifetime guards are removed.

Co-authored-by: Codex <[email protected]>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

S-waiting-on-review PR is waiting on a reviewer

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Nodejs SDK] should Client expose event handler for events through on/once

4 participants