@zukhruf/rpc 0.0.0-stage → 0.8.181

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (87) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +202 -2
  3. package/dist/call/client.d.ts +34 -0
  4. package/dist/call/client.d.ts.map +1 -0
  5. package/dist/call/client.js +114 -0
  6. package/dist/call/client.js.map +1 -0
  7. package/dist/call/methods.d.ts +20 -0
  8. package/dist/call/methods.d.ts.map +1 -0
  9. package/dist/call/methods.js +2 -0
  10. package/dist/call/methods.js.map +1 -0
  11. package/dist/call/pending-calls.d.ts +66 -0
  12. package/dist/call/pending-calls.d.ts.map +1 -0
  13. package/dist/call/pending-calls.js +105 -0
  14. package/dist/call/pending-calls.js.map +1 -0
  15. package/dist/call/rpc-message.d.ts +30 -0
  16. package/dist/call/rpc-message.d.ts.map +1 -0
  17. package/dist/call/rpc-message.js +17 -0
  18. package/dist/call/rpc-message.js.map +1 -0
  19. package/dist/call/server.d.ts +24 -0
  20. package/dist/call/server.d.ts.map +1 -0
  21. package/dist/call/server.js +67 -0
  22. package/dist/call/server.js.map +1 -0
  23. package/dist/channel/child-process-connection.d.ts +17 -0
  24. package/dist/channel/child-process-connection.d.ts.map +1 -0
  25. package/dist/channel/child-process-connection.js +39 -0
  26. package/dist/channel/child-process-connection.js.map +1 -0
  27. package/dist/channel/envelope.d.ts +18 -0
  28. package/dist/channel/envelope.d.ts.map +1 -0
  29. package/dist/channel/envelope.js +18 -0
  30. package/dist/channel/envelope.js.map +1 -0
  31. package/dist/channel/parent-port-connection.d.ts +20 -0
  32. package/dist/channel/parent-port-connection.d.ts.map +1 -0
  33. package/dist/channel/parent-port-connection.js +30 -0
  34. package/dist/channel/parent-port-connection.js.map +1 -0
  35. package/dist/channel/process-channel-connection.d.ts +19 -0
  36. package/dist/channel/process-channel-connection.d.ts.map +1 -0
  37. package/dist/channel/process-channel-connection.js +31 -0
  38. package/dist/channel/process-channel-connection.js.map +1 -0
  39. package/dist/channel/shared-channel-connection.d.ts +29 -0
  40. package/dist/channel/shared-channel-connection.d.ts.map +1 -0
  41. package/dist/channel/shared-channel-connection.js +43 -0
  42. package/dist/channel/shared-channel-connection.js.map +1 -0
  43. package/dist/channel/worker-connection.d.ts +18 -0
  44. package/dist/channel/worker-connection.d.ts.map +1 -0
  45. package/dist/channel/worker-connection.js +31 -0
  46. package/dist/channel/worker-connection.js.map +1 -0
  47. package/dist/connection/connection-closed-error.d.ts +5 -0
  48. package/dist/connection/connection-closed-error.d.ts.map +1 -0
  49. package/dist/connection/connection-closed-error.js +8 -0
  50. package/dist/connection/connection-closed-error.js.map +1 -0
  51. package/dist/connection/connection-supervisor.d.ts +40 -0
  52. package/dist/connection/connection-supervisor.d.ts.map +1 -0
  53. package/dist/connection/connection-supervisor.js +202 -0
  54. package/dist/connection/connection-supervisor.js.map +1 -0
  55. package/dist/connection/connection.d.ts +27 -0
  56. package/dist/connection/connection.d.ts.map +1 -0
  57. package/dist/connection/connection.js +2 -0
  58. package/dist/connection/connection.js.map +1 -0
  59. package/dist/connection/connector.d.ts +11 -0
  60. package/dist/connection/connector.d.ts.map +1 -0
  61. package/dist/connection/connector.js +2 -0
  62. package/dist/connection/connector.js.map +1 -0
  63. package/dist/error/connection-lost-error.d.ts +10 -0
  64. package/dist/error/connection-lost-error.d.ts.map +1 -0
  65. package/dist/error/connection-lost-error.js +13 -0
  66. package/dist/error/connection-lost-error.js.map +1 -0
  67. package/dist/error/error-codec.d.ts +37 -0
  68. package/dist/error/error-codec.d.ts.map +1 -0
  69. package/dist/error/error-codec.js +120 -0
  70. package/dist/error/error-codec.js.map +1 -0
  71. package/dist/error/server-error.d.ts +9 -0
  72. package/dist/error/server-error.d.ts.map +1 -0
  73. package/dist/error/server-error.js +12 -0
  74. package/dist/error/server-error.js.map +1 -0
  75. package/dist/error/server-warning.d.ts +9 -0
  76. package/dist/error/server-warning.d.ts.map +1 -0
  77. package/dist/error/server-warning.js +11 -0
  78. package/dist/error/server-warning.js.map +1 -0
  79. package/dist/index.d.ts +19 -0
  80. package/dist/index.d.ts.map +1 -0
  81. package/dist/index.js +19 -0
  82. package/dist/index.js.map +1 -0
  83. package/dist/shared/is-record.d.ts +3 -0
  84. package/dist/shared/is-record.d.ts.map +1 -0
  85. package/dist/shared/is-record.js +3 -0
  86. package/dist/shared/is-record.js.map +1 -0
  87. package/package.json +48 -4
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 ezzabuzaid
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,203 @@
1
- # Temporary Holding Version
1
+ # @zukhruf/rpc
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ One end of a program calls methods of another end: a worker thread, a child process, or a process across a socket. This package gives what each such program writes again: a connection that comes back after a loss, calls that wait for their answers by id, a rule for a call that was in flight when the peer went away, and errors that keep their class and their fields across the boundary. Its names come from Go's `net/rpc` (`Client`, `Server`, `ServerError`) and .NET's StreamJsonRpc (`ConnectionLostException`).
4
+
5
+ The words in these documents have one meaning each. See the glossary in [CONTEXT.md](./CONTEXT.md).
6
+
7
+ ## Use it
8
+
9
+ ```sh
10
+ npm install @zukhruf/rpc
11
+ ```
12
+
13
+ The host starts a worker thread and calls its `greet` method. The thread serves the method on its port.
14
+
15
+ ```ts title="host.ts"
16
+ import { Worker } from 'node:worker_threads';
17
+
18
+ import {
19
+ Client,
20
+ ConnectionSupervisor,
21
+ ErrorCodec,
22
+ type RpcMessage,
23
+ WorkerConnection,
24
+ } from '@zukhruf/rpc';
25
+
26
+ interface Greeter {
27
+ greet(name: string): string;
28
+ }
29
+
30
+ const link = new ConnectionSupervisor<RpcMessage>({
31
+ connect: async () =>
32
+ new WorkerConnection(new Worker(new URL('./greeter.ts', import.meta.url)), {
33
+ tag: '@greeter',
34
+ }),
35
+ });
36
+ await using client = new Client<Greeter>(link, {
37
+ errors: new ErrorCodec([]),
38
+ answers: { greet: (answer): answer is string => typeof answer === 'string' },
39
+ });
40
+ console.log(await client.call('greet', ['Ada']));
41
+ ```
42
+
43
+ ```ts title="greeter.ts"
44
+ import { parentPort } from 'node:worker_threads';
45
+
46
+ import { ErrorCodec, ParentPortConnection, Server } from '@zukhruf/rpc';
47
+
48
+ const connection = new ParentPortConnection(parentPort!, { tag: '@greeter' });
49
+ connection.ref();
50
+ new Server(
51
+ { greet: (name: string) => `Hello, ${name}` },
52
+ {
53
+ methods: {
54
+ greet: (params): params is [string] =>
55
+ params.length === 1 && typeof params[0] === 'string',
56
+ },
57
+ errors: new ErrorCodec([]),
58
+ },
59
+ ).serve(connection);
60
+ ```
61
+
62
+ ## Call a method of the other end
63
+
64
+ `client.call(method, params, { signal })` sends a request and waits for its answer. The answer is checked by the client's `answers` check of that method before the call gives it its type: it comes from another thread or process (mutex ADR 0017). A call made while no connection is open goes on the next one. A call that went out on a connection that is lost rejects at once with `ConnectionLostError`, and it is not sent again: the peer may have run it, as a lost Postgres commit may have committed. A call whose `signal` aborts rejects with the signal's reason, and a later answer settles nothing.
65
+
66
+ `client.notify(method, params)` runs the method on the other end and waits for no answer. A notification made before the connection opens goes once it opens.
67
+
68
+ ## Serve the methods of an object
69
+
70
+ `server.serve(connection)` answers each request on `connection` with the value of the method, or with the error that it threw. It serves only the methods that `methods` names, each with the check of its parameters: a method of the target with no check is refused, as is a request whose parameters fail the check. Serving does not keep the process alive; the owner of the connection refs it. A notification's method that throws emits a `ServerWarning` (`ZUKHRUF_RPC_NOTIFICATION_FAILED`), because nothing answers a notification.
71
+
72
+ Each end can run a `Client` and a `Server` on one connection, as StreamJsonRpc's `JsonRpc` does: the client reads the responses and the server reads the requests.
73
+
74
+ ## Keep a connection across a loss
75
+
76
+ `ConnectionSupervisor` keeps one connection open at a time. It connects on `open`, replaces a connection that is lost, and stops for good when its `Connector` gives `undefined`. It emits `connected`, `message`, `disconnected`, `unavailable` and `failed`. It keeps the last `ref()` or `unref()` for each connection that replaces a lost one.
77
+
78
+ ## Decide what happens to a call that was in flight
79
+
80
+ `PendingCalls` is the table of the calls that wait for an answer, for a protocol of its own (the mutex's lock requests, the single flight's runs). The owner reports each loss (`interrupt()`) and each new connection (`resume()`), so it can send its own messages first. Each call has a policy for a loss:
81
+
82
+ | Policy | What happens | Who uses it |
83
+ | ----------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------- |
84
+ | `'resend'` | The call goes again on the next connection. | The mutex's acquire and look, the single flight's run |
85
+ | `{ atLoss }` | The call leaves the table at the loss, and `atLoss` settles it. | `Client`: `ConnectionLostError` |
86
+ | `{ atReconnect }` | The call waits, unsent, and `atReconnect` settles it when the next connection opens. A reconnect that fails or cannot come rejects it with the other calls. | The mutex's try: busy |
87
+
88
+ A call keeps the connection ref'd from its add until it is taken, so the process exits only when no call waits. Give every table on one connection the same `RefCount`.
89
+
90
+ ## Carry errors across
91
+
92
+ `new ErrorCodec(classes)` encodes a thrown value as `{ name, message, stack, fields, cause }`, and rebuilds it on the other end. `structuredClone` and `v8.serialize` rebuild every error as its native base class and drop own fields such as `code`. The codec rebuilds an error of a listed class, or of a native class (`Error`, `TypeError`, `RangeError` and the others that HTML's structured clone keeps), as an instance of that class with the peer's message, stack, cause and own fields. It does not run the class's constructor. An error of a class that the codec does not list arrives as a `ServerError` with the peer's name, message and fields. A thrown value that is not an error arrives as it is.
93
+
94
+ ## Share a channel with the application
95
+
96
+ `WorkerConnection`, `ParentPortConnection`, `ChildProcessConnection` and `ProcessChannelConnection` carry each message in the envelope of their `tag`: `{ [tag]: message }`. The application's own messages, and those of another tag, are not read, so they share the channel. The mutex's tag is `'@lock'`.
97
+
98
+ | Adapter | End | Tells of a lost peer by | Keeps the process alive |
99
+ | -------------------------- | -------------------------------- | -------------------------------------- | ----------------------- |
100
+ | `WorkerConnection` | The thread that started a worker | `exit` | The worker does |
101
+ | `ParentPortConnection` | A worker thread | never: the thread ends with its parent | While ref'd |
102
+ | `ChildProcessConnection` | A parent process | `disconnect` | The child does |
103
+ | `ProcessChannelConnection` | A child process | `disconnect` | While ref'd |
104
+
105
+ ## Errors
106
+
107
+ | Error | When |
108
+ | ----------------------- | ------------------------------------------------------------------------------------------------------- |
109
+ | `ConnectionLostError` | A call was in flight on a connection that was lost, the client was disposed, or no peer can come again. |
110
+ | `ServerError` | The peer threw an error of a class that this end's codec does not list. |
111
+ | `ConnectionClosedError` | A send of an adapter cannot reach the peer, because the connection is closed. |
112
+ | `TypeError` | The server has no such method, the parameters fail its check, or the answer fails the client's check. |
113
+ | `RangeError` | Two classes of an `ErrorCodec` have one name, or `PendingCalls.add` gets an id that waits already. |
114
+
115
+ ## What the package does not do
116
+
117
+ - **It does not tell the server that a call was cancelled.** A call whose signal aborts stops only its own wait. A protocol that must stop the work sends its own notification, as JSON-RPC's `$/cancelRequest`.
118
+ - **It does not send a lost `Client` call again.** Only the caller knows whether the call may run twice.
119
+ - **It does not speak JSON on the wire.** The messages use the member names of JSON-RPC 2.0 and travel as the channel clones them; a socket protocol frames them itself.
120
+
121
+ ## Who uses it
122
+
123
+ | Consumer | How | Record |
124
+ | ------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------ |
125
+ | `@zukhruf/mutex` | The thread and IPC lock stores connect through its adapters with the tag `'@lock'`; `RemoteLockClient` keeps its acquires, tries and looks in `PendingCalls`. | #4984, #2496 |
126
+ | `@zukhruf/single-flight` | `FlightClient` keeps its runs in `PendingCalls` over the supervisor. | #4984, #2520 |
127
+
128
+ ## The same concepts in other systems
129
+
130
+ | Concept | Other systems |
131
+ | ------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- |
132
+ | Client and server | Go [`net/rpc`](https://pkg.go.dev/net/rpc) `Client`, `Server`; StreamJsonRpc [`JsonRpc`](https://github.com/microsoft/vs-streamjsonrpc) |
133
+ | A lost call | StreamJsonRpc `ConnectionLostException`; Go `rpc.ErrShutdown` |
134
+ | A remote error | Go `rpc.ServerError`; StreamJsonRpc `RemoteInvocationException` |
135
+ | The message shape | [JSON-RPC 2.0](https://www.jsonrpc.org/specification), sections 4 and 5 |
136
+ | The errors that survive a clone | HTML [structured clone](https://html.spec.whatwg.org/multipage/structured-data.html#structuredserializeinternal) of `[[ErrorData]]` |
137
+
138
+ comlink 4.4.2, birpc 4.2.0 and vscode-jsonrpc 10.0.2 were probed on Node 26.13.1 (#4984, paper v2): each leaves a call pending after its thread exits, and each loses the `code` of a thrown error.
139
+
140
+ ## API
141
+
142
+ ```ts
143
+ export class ConnectionSupervisor<
144
+ Outgoing,
145
+ > extends EventEmitter<SupervisorEvents> {
146
+ constructor(connector: Connector<Outgoing>);
147
+ readonly status: SupervisorStatus;
148
+ open(): void;
149
+ send(message: Outgoing): boolean;
150
+ ref(): void;
151
+ unref(): void;
152
+ close(): Promise<void>;
153
+ }
154
+ export class PendingCalls<Request, Answer> {
155
+ constructor(link: ConnectionSupervisor<Request>, refs: RefCount);
156
+ add(
157
+ id: string,
158
+ request: Request,
159
+ onLost: LostCallPolicy<Answer>,
160
+ ): Promise<Answer>;
161
+ get(id: string): Request | undefined;
162
+ update(id: string, request: Request): void;
163
+ send(id: string): void;
164
+ take(id: string): TakenCall<Request, Answer> | undefined;
165
+ resume(): void;
166
+ interrupt(): void;
167
+ rejectAll(reason: (request: Request) => unknown): void;
168
+ }
169
+ export class Client<Remote extends Methods<Remote>> implements AsyncDisposable {
170
+ constructor(
171
+ link: ConnectionSupervisor<RpcMessage>,
172
+ options: { errors: ErrorCodec; answers: AnswerChecks<Remote> },
173
+ );
174
+ call<M extends keyof Remote & string>(
175
+ method: M,
176
+ params: Parameters<Remote[M]>,
177
+ options?: { signal?: AbortSignal },
178
+ ): Promise<Awaited<ReturnType<Remote[M]>>>;
179
+ notify<M extends keyof Remote & string>(
180
+ method: M,
181
+ params: Parameters<Remote[M]>,
182
+ ): void;
183
+ }
184
+ export class Server<Local extends Methods<Local>> {
185
+ constructor(
186
+ target: Local,
187
+ options: { methods: ParamChecks<Local>; errors: ErrorCodec },
188
+ );
189
+ serve(connection: Connection<RpcMessage>): void;
190
+ }
191
+ export class ErrorCodec {
192
+ constructor(classes: readonly ErrorClass[]);
193
+ encode(reason: unknown): EncodedReason;
194
+ decode(encoded: EncodedReason): unknown;
195
+ }
196
+ ```
197
+
198
+ ## Documentation
199
+
200
+ - [ADR 0001](./docs/adr/0001-a-lost-call-follows-the-policy-that-its-caller-gives.md): a lost call follows the policy that its caller gives.
201
+ - [ADR 0002](./docs/adr/0002-an-error-crosses-as-data-and-is-rebuilt-from-a-list-of-classes-without-its-constructor.md): an error crosses as data and is rebuilt from a list of classes, without its constructor.
202
+ - [ADR 0003](./docs/adr/0003-each-end-checks-what-it-receives.md): each end checks what it receives.
203
+ - [Copied code](./docs/copied-code.md)
@@ -0,0 +1,34 @@
1
+ import type { ConnectionSupervisor } from '../connection/connection-supervisor.ts';
2
+ import type { ErrorCodec } from '../error/error-codec.ts';
3
+ import type { AnswerChecks, Methods } from './methods.ts';
4
+ import { type RpcMessage } from './rpc-message.ts';
5
+ export interface ClientOptions<Remote extends Methods<Remote>> {
6
+ /** Rebuilds the errors that the peer's methods throw. */
7
+ errors: ErrorCodec;
8
+ answers: AnswerChecks<Remote>;
9
+ }
10
+ export interface CallOptions {
11
+ /** Stops the wait: the call rejects with the signal's reason, and a later answer settles nothing. */
12
+ signal?: AbortSignal | undefined;
13
+ }
14
+ /**
15
+ * Calls the methods of a peer's `Server` over a supervised connection. A
16
+ * call waits for its answer, or rejects with `ConnectionLostError` as soon as
17
+ * the connection it went out on is lost. A call made while no connection is
18
+ * open goes on the next one. The connection keeps the process alive only
19
+ * while a call or a notification waits.
20
+ */
21
+ export declare class Client<Remote extends Methods<Remote>> implements AsyncDisposable {
22
+ #private;
23
+ constructor(link: ConnectionSupervisor<RpcMessage>, { errors, answers }: ClientOptions<Remote>);
24
+ call<M extends keyof Remote & string>(method: M, params: Parameters<Remote[M]>, { signal }?: CallOptions): Promise<Awaited<ReturnType<Remote[M]>>>;
25
+ /**
26
+ * Runs `method` on the peer and waits for no answer. It goes on the open
27
+ * connection, or on the next one. A notification that went out is never
28
+ * sent again, and what its method throws stays with the peer.
29
+ */
30
+ notify<M extends keyof Remote & string>(method: M, params: Parameters<Remote[M]>): void;
31
+ /** Closes the connection. Each call that waits rejects with `ConnectionLostError`. */
32
+ [Symbol.asyncDispose](): Promise<void>;
33
+ }
34
+ //# sourceMappingURL=client.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../../src/call/client.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,wCAAwC,CAAC;AAEnF,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,yBAAyB,CAAC;AAC1D,OAAO,KAAK,EAAE,YAAY,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AAE1D,OAAO,EACL,KAAK,UAAU,EAKhB,MAAM,kBAAkB,CAAC;AAE1B,MAAM,WAAW,aAAa,CAAC,MAAM,SAAS,OAAO,CAAC,MAAM,CAAC;IAC3D,yDAAyD;IACzD,MAAM,EAAE,UAAU,CAAC;IACnB,OAAO,EAAE,YAAY,CAAC,MAAM,CAAC,CAAC;CAC/B;AAED,MAAM,WAAW,WAAW;IAC1B,qGAAqG;IACrG,MAAM,CAAC,EAAE,WAAW,GAAG,SAAS,CAAC;CAClC;AAOD;;;;;;GAMG;AACH,qBAAa,MAAM,CAAC,MAAM,SAAS,OAAO,CAAC,MAAM,CAAC,CAAE,YAAW,eAAe;;IAU5E,YACE,IAAI,EAAE,oBAAoB,CAAC,UAAU,CAAC,EACtC,EAAE,MAAM,EAAE,OAAO,EAAE,EAAE,aAAa,CAAC,MAAM,CAAC,EAiB3C;IAEK,IAAI,CAAC,CAAC,SAAS,MAAM,MAAM,GAAG,MAAM,EACxC,MAAM,EAAE,CAAC,EACT,MAAM,EAAE,UAAU,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,EAC7B,EAAE,MAAM,EAAE,GAAE,WAAgB,GAC3B,OAAO,CAAC,OAAO,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAmBzC;IAED;;;;OAIG;IACH,MAAM,CAAC,CAAC,SAAS,MAAM,MAAM,GAAG,MAAM,EACpC,MAAM,EAAE,CAAC,EACT,MAAM,EAAE,UAAU,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,QAO9B;IAED,sFAAsF;IAChF,CAAC,MAAM,CAAC,YAAY,CAAC,kBAI1B;CA+BF"}
@@ -0,0 +1,114 @@
1
+ import { RefCount, untilAborted } from '@zukhruf/async';
2
+ import { ConnectionLostError } from '../error/connection-lost-error.js';
3
+ import { PendingCalls } from './pending-calls.js';
4
+ import { isRpcResponse, } from './rpc-message.js';
5
+ /** The peer may have run a call that was in flight, so the call is not sent again. */
6
+ const rejectLost = {
7
+ atLoss: (call) => call.reject(new ConnectionLostError()),
8
+ };
9
+ /**
10
+ * Calls the methods of a peer's `Server` over a supervised connection. A
11
+ * call waits for its answer, or rejects with `ConnectionLostError` as soon as
12
+ * the connection it went out on is lost. A call made while no connection is
13
+ * open goes on the next one. The connection keeps the process alive only
14
+ * while a call or a notification waits.
15
+ */
16
+ export class Client {
17
+ #link;
18
+ #errors;
19
+ #refs;
20
+ #answers;
21
+ #calls;
22
+ /** The notifications made while no connection was open, each with the hold that keeps the process alive until it goes. */
23
+ #outbox = [];
24
+ #nextId = 0;
25
+ constructor(link, { errors, answers }) {
26
+ this.#link = link;
27
+ this.#errors = errors;
28
+ this.#answers = answers;
29
+ this.#refs = new RefCount(link);
30
+ this.#calls = new PendingCalls(link, this.#refs);
31
+ link.on('connected', () => {
32
+ this.#flush();
33
+ this.#calls.resume();
34
+ });
35
+ link.on('message', (message) => {
36
+ if (isRpcResponse(message))
37
+ this.#receive(message);
38
+ });
39
+ link.on('disconnected', () => this.#calls.interrupt());
40
+ link.on('unavailable', () => this.#fail(new ConnectionLostError()));
41
+ link.on('failed', (error) => this.#fail(error));
42
+ }
43
+ async call(method, params, { signal } = {}) {
44
+ signal?.throwIfAborted();
45
+ this.#assertOpen();
46
+ const id = String(this.#nextId++);
47
+ const request = { id, method, params };
48
+ const answer = this.#calls.add(id, request, rejectLost);
49
+ let value;
50
+ try {
51
+ value = await untilAborted(answer, signal);
52
+ }
53
+ catch (error) {
54
+ if (signal?.aborted)
55
+ this.#calls.take(id);
56
+ throw error;
57
+ }
58
+ if (!this.#answers[method](value)) {
59
+ throw new TypeError(`The peer answered "${method}" with a value that its check refused.`);
60
+ }
61
+ return value;
62
+ }
63
+ /**
64
+ * Runs `method` on the peer and waits for no answer. It goes on the open
65
+ * connection, or on the next one. A notification that went out is never
66
+ * sent again, and what its method throws stays with the peer.
67
+ */
68
+ notify(method, params) {
69
+ this.#assertOpen();
70
+ const notification = { method, params };
71
+ this.#link.open();
72
+ if (this.#outbox.length === 0 && this.#link.send(notification))
73
+ return;
74
+ this.#outbox.push({ notification, held: this.#refs.hold() });
75
+ }
76
+ /** Closes the connection. Each call that waits rejects with `ConnectionLostError`. */
77
+ async [Symbol.asyncDispose]() {
78
+ const closing = this.#link.close();
79
+ this.#fail(new ConnectionLostError());
80
+ await closing;
81
+ }
82
+ #assertOpen() {
83
+ const { status } = this.#link;
84
+ if (status === 'closed' || status === 'unavailable') {
85
+ throw new ConnectionLostError();
86
+ }
87
+ }
88
+ #receive(response) {
89
+ const call = this.#calls.take(response.id);
90
+ if (!call)
91
+ return;
92
+ if ('error' in response)
93
+ call.reject(this.#errors.decode(response.error));
94
+ else
95
+ call.resolve(response.result);
96
+ }
97
+ /** Sends what waited for this connection, in order, until a send does not reach it. */
98
+ #flush() {
99
+ while (this.#outbox.length > 0) {
100
+ const next = this.#outbox[0];
101
+ if (!this.#link.send(next.notification))
102
+ return;
103
+ this.#outbox.shift();
104
+ next.held[Symbol.dispose]();
105
+ }
106
+ }
107
+ #fail(reason) {
108
+ for (const { held } of this.#outbox)
109
+ held[Symbol.dispose]();
110
+ this.#outbox = [];
111
+ this.#calls.rejectAll(() => reason);
112
+ }
113
+ }
114
+ //# sourceMappingURL=client.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.js","sourceRoot":"","sources":["../../src/call/client.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAGxD,OAAO,EAAE,mBAAmB,EAAE,MAAM,mCAAmC,CAAC;AAGxE,OAAO,EAAuB,YAAY,EAAE,MAAM,oBAAoB,CAAC;AACvE,OAAO,EAKL,aAAa,GACd,MAAM,kBAAkB,CAAC;AAa1B,sFAAsF;AACtF,MAAM,UAAU,GAA4B;IAC1C,MAAM,EAAE,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,MAAM,CAAC,IAAI,mBAAmB,EAAE,CAAC;CACzD,CAAC;AAEF;;;;;;GAMG;AACH,MAAM,O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,CAAC,EAAE,CAAC;QAC9B,CAAC;IACH,CAAC;IAED,KAAK,CAAC,MAAe;QACnB,KAAK,MAAM,EAAE,IAAI,EAAE,IAAI,IAAI,CAAC,OAAO;YAAE,IAAI,CAAC,MAAM,CAAC,OAAO,CAAC,EAAE,CAAC;QAC5D,IAAI,CAAC,OAAO,GAAG,EAAE,CAAC;QAClB,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,GAAG,EAAE,CAAC,MAAM,CAAC,CAAC;IACtC,CAAC;CACF"}
@@ -0,0 +1,20 @@
1
+ /** An object whose every member is a method: the calls that one end can make of the other. */
2
+ export type Methods<T> = {
3
+ [K in keyof T]: (...params: never[]) => unknown;
4
+ };
5
+ /**
6
+ * For each method of the peer, the check of its answer. An answer arrives
7
+ * from another thread or process, so its shape is checked before it is
8
+ * given its type (mutex ADR 0017).
9
+ */
10
+ export type AnswerChecks<Remote extends Methods<Remote>> = {
11
+ [M in keyof Remote]: (answer: unknown) => answer is Awaited<ReturnType<Remote[M]>>;
12
+ };
13
+ /**
14
+ * For each method that peers may call, the check of its parameters. A method
15
+ * with no check is not served, also when the target has it.
16
+ */
17
+ export type ParamChecks<Local extends Methods<Local>> = {
18
+ [M in keyof Local]?: (params: readonly unknown[]) => params is Parameters<Local[M]>;
19
+ };
20
+ //# sourceMappingURL=methods.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"methods.d.ts","sourceRoot":"","sources":["../../src/call/methods.ts"],"names":[],"mappings":"AAAA,8FAA8F;AAC9F,MAAM,MAAM,OAAO,CAAC,CAAC,IAAI;KAAG,CAAC,IAAI,MAAM,CAAC,GAAG,CAAC,GAAG,MAAM,EAAE,KAAK,EAAE,KAAK,OAAO;CAAE,CAAC;AAE7E;;;;GAIG;AACH,MAAM,MAAM,YAAY,CAAC,MAAM,SAAS,OAAO,CAAC,MAAM,CAAC,IAAI;KACxD,CAAC,IAAI,MAAM,MAAM,GAAG,CACnB,MAAM,EAAE,OAAO,KACZ,MAAM,IAAI,OAAO,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC;CAC9C,CAAC;AAEF;;;GAGG;AACH,MAAM,MAAM,WAAW,CAAC,KAAK,SAAS,OAAO,CAAC,KAAK,CAAC,IAAI;KACrD,CAAC,IAAI,MAAM,KAAK,CAAC,CAAC,EAAE,CACnB,MAAM,EAAE,SAAS,OAAO,EAAE,KACvB,MAAM,IAAI,UAAU,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;CACpC,CAAC"}
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=methods.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"methods.js","sourceRoot":"","sources":["../../src/call/methods.ts"],"names":[],"mappings":""}
@@ -0,0 +1,66 @@
1
+ import type { RefCount } from '@zukhruf/async';
2
+ import type { ConnectionSupervisor } from '../connection/connection-supervisor.ts';
3
+ /** What settles the promise of one call; the caller keeps the promise. */
4
+ export interface Settler<Answer> {
5
+ resolve(answer: Answer): void;
6
+ reject(reason: unknown): void;
7
+ }
8
+ /** What happens to a call that went out on a connection that was lost before the answer came. */
9
+ export type LostCallPolicy<Answer> =
10
+ /** The call goes again on the next connection: it is safe to repeat (a lock request, a look). */
11
+ 'resend'
12
+ /**
13
+ * The call leaves the table at the loss, and `atLoss` settles it at once:
14
+ * the peer may have run it, so the caller decides whether to make it again
15
+ * (StreamJsonRpc's `ConnectionLostException`).
16
+ */
17
+ | {
18
+ atLoss(call: Settler<Answer>): void;
19
+ }
20
+ /**
21
+ * The call waits, unsent, until the next connection opens, and
22
+ * `atReconnect` settles it then: its answer needs a peer, and a reconnect
23
+ * that fails or can never come rejects it as it rejects each call that
24
+ * waits (a lock try, which the next coordinator answers busy).
25
+ */
26
+ | {
27
+ atReconnect(call: Settler<Answer>): void;
28
+ };
29
+ /** A call taken out of the table, to be settled by whoever took it. */
30
+ export interface TakenCall<Request, Answer> extends Settler<Answer> {
31
+ readonly request: Request;
32
+ /** Whether the call went out on the open connection, so its peer may answer it or act on it. */
33
+ readonly sent: boolean;
34
+ }
35
+ /**
36
+ * The calls that wait for an answer over a supervised connection, by id. A
37
+ * call goes out when it is added, or on the next connection when none is
38
+ * open. The owner reports each loss and each new connection, so it can send
39
+ * its own messages first (a reassertion, a marker). A call keeps the
40
+ * connection ref'd from its add until it is taken, so the process exits only
41
+ * when no call waits.
42
+ */
43
+ export declare class PendingCalls<Request, Answer> {
44
+ #private;
45
+ /** `refs` counts on `link` for every owner of work on it, so one owner's last call does not unref another's. */
46
+ constructor(link: ConnectionSupervisor<Request>, refs: RefCount);
47
+ /** Opens the connection and sends `request`, or keeps it for the next connection. One id is one call. */
48
+ add(id: string, request: Request, onLost: LostCallPolicy<Answer>): Promise<Answer>;
49
+ /** The request of the call that waits under `id`. */
50
+ get(id: string): Request | undefined;
51
+ /** The request that the call of `id` sends from now on, when it goes again. */
52
+ update(id: string, request: Request): void;
53
+ /** Sends the call of `id` again now, or on the next connection when none is open: its answer asked for another try. */
54
+ send(id: string): void;
55
+ /** Removes the call of `id`, so a late answer to it settles nothing. */
56
+ take(id: string): TakenCall<Request, Answer> | undefined;
57
+ /**
58
+ * A new connection is open: in the order of their adds, sends each call that
59
+ * waits for one, and settles each lost call whose policy waits for it.
60
+ */
61
+ resume(): void;
62
+ /** The open connection is lost: each call that went out on it follows its policy. */
63
+ interrupt(): void;
64
+ rejectAll(reason: (request: Request) => unknown): void;
65
+ }
66
+ //# sourceMappingURL=pending-calls.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pending-calls.d.ts","sourceRoot":"","sources":["../../src/call/pending-calls.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,gBAAgB,CAAC;AAE/C,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,wCAAwC,CAAC;AAEnF,0EAA0E;AAC1E,MAAM,WAAW,OAAO,CAAC,MAAM;IAC7B,OAAO,CAAC,MAAM,EAAE,MAAM,GAAG,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M,SAQL;IAED,qFAAqF;IACrF,SAAS,SAQR;IAED,SAAS,CAAC,MAAM,EAAE,CAAC,OAAO,EAAE,OAAO,KAAK,OAAO,QAK9C;CAKF"}
@@ -0,0 +1,105 @@
1
+ const queued = { kind: 'queued' };
2
+ const sent = { kind: 'sent' };
3
+ /**
4
+ * The calls that wait for an answer over a supervised connection, by id. A
5
+ * call goes out when it is added, or on the next connection when none is
6
+ * open. The owner reports each loss and each new connection, so it can send
7
+ * its own messages first (a reassertion, a marker). A call keeps the
8
+ * connection ref'd from its add until it is taken, so the process exits only
9
+ * when no call waits.
10
+ */
11
+ export class PendingCalls {
12
+ #link;
13
+ #refs;
14
+ #calls = new Map();
15
+ /** `refs` counts on `link` for every owner of work on it, so one owner's last call does not unref another's. */
16
+ constructor(link, refs) {
17
+ this.#link = link;
18
+ this.#refs = refs;
19
+ }
20
+ /** Opens the connection and sends `request`, or keeps it for the next connection. One id is one call. */
21
+ add(id, request, onLost) {
22
+ if (this.#calls.has(id)) {
23
+ throw new RangeError(`A call with the id "${id}" already waits.`);
24
+ }
25
+ const { promise, resolve, reject } = Promise.withResolvers();
26
+ const call = {
27
+ request,
28
+ onLost,
29
+ delivery: queued,
30
+ settler: { resolve, reject },
31
+ held: this.#refs.hold(),
32
+ };
33
+ this.#calls.set(id, call);
34
+ this.#link.open();
35
+ this.#dispatch(call);
36
+ return promise;
37
+ }
38
+ /** The request of the call that waits under `id`. */
39
+ get(id) {
40
+ return this.#calls.get(id)?.request;
41
+ }
42
+ /** The request that the call of `id` sends from now on, when it goes again. */
43
+ update(id, request) {
44
+ const call = this.#calls.get(id);
45
+ if (call)
46
+ call.request = request;
47
+ }
48
+ /** Sends the call of `id` again now, or on the next connection when none is open: its answer asked for another try. */
49
+ send(id) {
50
+ const call = this.#calls.get(id);
51
+ if (call)
52
+ this.#dispatch(call);
53
+ }
54
+ /** Removes the call of `id`, so a late answer to it settles nothing. */
55
+ take(id) {
56
+ const call = this.#calls.get(id);
57
+ if (!call)
58
+ return undefined;
59
+ this.#calls.delete(id);
60
+ call.held[Symbol.dispose]();
61
+ return {
62
+ ...call.settler,
63
+ request: call.request,
64
+ sent: call.delivery.kind === 'sent',
65
+ };
66
+ }
67
+ /**
68
+ * A new connection is open: in the order of their adds, sends each call that
69
+ * waits for one, and settles each lost call whose policy waits for it.
70
+ */
71
+ resume() {
72
+ for (const [id, call] of this.#calls) {
73
+ if (call.delivery.kind === 'lost') {
74
+ call.delivery.atReconnect(this.take(id));
75
+ }
76
+ else if (call.delivery.kind === 'queued') {
77
+ this.#dispatch(call);
78
+ }
79
+ }
80
+ }
81
+ /** The open connection is lost: each call that went out on it follows its policy. */
82
+ interrupt() {
83
+ for (const [id, call] of this.#calls) {
84
+ if (call.delivery.kind !== 'sent')
85
+ continue;
86
+ const { onLost } = call;
87
+ if (onLost === 'resend')
88
+ call.delivery = queued;
89
+ else if ('atLoss' in onLost)
90
+ onLost.atLoss(this.take(id));
91
+ else
92
+ call.delivery = { kind: 'lost', atReconnect: onLost.atReconnect };
93
+ }
94
+ }
95
+ rejectAll(reason) {
96
+ for (const id of [...this.#calls.keys()]) {
97
+ const call = this.take(id);
98
+ call.reject(reason(call.request));
99
+ }
100
+ }
101
+ #dispatch(call) {
102
+ call.delivery = this.#link.send(call.request) ? sent : queued;
103
+ }
104
+ }
105
+ //# sourceMappingURL=pending-calls.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pending-calls.js","sourceRoot":"","sources":["../../src/call/pending-calls.ts"],"names":[],"mappings":"AA4CA,MAAM,MAAM,GAAG,EAAE,IAAI,EAAE,QAAQ,EAAW,CAAC;AAC3C,MAAM,IAAI,GAAG,EAAE,IAAI,EAAE,MAAM,EAAW,CAAC;AAWvC;;;;;;;GAOG;AACH,MAAM,OAAO,YAAY;IACd,KAAK,CAAgC;IACrC,KAAK,CAAW;IAChB,MAAM,GAAG,IAAI,GAAG,EAAoC,CAAC;IAE9D,gHAAgH;IAChH,YAAY,IAAmC,EAAE,IAAc;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,IAAI,CAAC,QAAQ,GAAG,MAAM,CAAC;iBAC3C,IAAI,QAAQ,IAAI,MAAM;gBAAE,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAE,CAAC,CAAC;;gBACtD,IAAI,CAAC,QAAQ,GAAG,EAAE,IAAI,EAAE,MAAM,EAAE,WAAW,EAAE,MAAM,CAAC,WAAW,EAAE,CAAC;QACzE,CAAC;IACH,CAAC;IAED,SAAS,CAAC,MAAqC;QAC7C,KAAK,MAAM,EAAE,IAAI,CAAC,GAAG,IAAI,CAAC,MAAM,CAAC,IAAI,EAAE,CAAC,EAAE,CAAC;YACzC,MAAM,IAAI,GAAG,IAAI,CAAC,IAAI,CAAC,EAAE,CAAE,CAAC;YAC5B,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC,CAAC;QACpC,CAAC;IACH,CAAC;IAED,SAAS,CAAC,IAA8B;QACtC,IAAI,CAAC,QAAQ,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,MAAM,CAAC;IAChE,CAAC;CACF"}
@@ -0,0 +1,30 @@
1
+ import { type EncodedReason } from '../error/error-codec.ts';
2
+ /**
3
+ * The messages of a call, with the member names of JSON-RPC 2.0 (sections 4
4
+ * and 5) and without its `jsonrpc` member: the values cross as the channel
5
+ * clones them, not as JSON text.
6
+ */
7
+ export type RpcMessage = RpcRequest | RpcNotification | RpcResponse;
8
+ export interface RpcRequest {
9
+ id: string;
10
+ method: string;
11
+ params: readonly unknown[];
12
+ }
13
+ /** A request with no id: nothing answers it. */
14
+ export interface RpcNotification {
15
+ id?: undefined;
16
+ method: string;
17
+ params: readonly unknown[];
18
+ }
19
+ export type RpcResponse = {
20
+ id: string;
21
+ result: unknown;
22
+ } | {
23
+ id: string;
24
+ error: EncodedReason;
25
+ };
26
+ /** A received request or notification, checked before the server reads it. */
27
+ export declare function isRpcCall(message: unknown): message is RpcRequest | RpcNotification;
28
+ /** A received response, checked before the client reads it. A JSON line drops a `result` that is `undefined`. */
29
+ export declare function isRpcResponse(message: unknown): message is RpcResponse;
30
+ //# sourceMappingURL=rpc-message.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"rpc-message.d.ts","sourceRoot":"","sources":["../../src/call/rpc-message.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,aAAa,EAAmB,MAAM,yBAAyB,CAAC;AAG9E;;;;GAIG;AACH,MAAM,MAAM,UAAU,GAAG,UAAU,GAAG,eAAe,GAAG,WAAW,CAAC;AAEpE,MAAM,WAAW,UAAU;IACzB,EAAE,EAAE,MAAM,CAAC;IACX,MAAM,EAAE,MAAM,CAAC;IACf,MAAM,EAAE,SAAS,OAAO,EAAE,CAAC;CAC5B;AAED,gDAAgD;AAChD,MAAM,WAAW,eAAe;IAC9B,EAAE,CAAC,EAAE,SAAS,CAAC;IACf,MAAM,EAAE,MAAM,CAAC;IACf,MAAM,EAAE,SAAS,OAAO,EAAE,CAAC;CAC5B;AAED,MAAM,MAAM,WAAW,GACrB;IAAE,EAAE,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,OAAO,CAAA;CAAE,GAAG;IAAE,EAAE,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,aAAa,CAAA;CAAE,CAAC;AAEzE,8EAA8E;AAC9E,wBAAgB,SAAS,CACvB,OAAO,EAAE,OAAO,GACf,OAAO,IAAI,UAAU,GAAG,eAAe,CAOzC;AAED,iHAAiH;AACjH,wBAAgB,aAAa,CAAC,OAAO,EAAE,OAAO,GAAG,OAAO,IAAI,WAAW,CAOtE"}