@hydranium/protocol 1.0.0-next.10 → 1.0.0-next.104

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 (132) hide show
  1. package/README.md +35 -1
  2. package/lib/client/data-connection.d.ts +152 -0
  3. package/lib/client/data-connection.d.ts.map +1 -0
  4. package/lib/client/data-connection.js +214 -0
  5. package/lib/client/data-connection.js.map +1 -0
  6. package/lib/client/data-events.d.ts +9 -1
  7. package/lib/client/data-events.d.ts.map +1 -1
  8. package/lib/client/data-events.js +14 -0
  9. package/lib/client/data-events.js.map +1 -1
  10. package/lib/client/data-port.d.ts +17 -22
  11. package/lib/client/data-port.d.ts.map +1 -1
  12. package/lib/client/data-session.d.ts +154 -76
  13. package/lib/client/data-session.d.ts.map +1 -1
  14. package/lib/client/data-session.js +194 -109
  15. package/lib/client/data-session.js.map +1 -1
  16. package/lib/client/index.d.ts +10 -7
  17. package/lib/client/index.d.ts.map +1 -1
  18. package/lib/client/index.js +10 -7
  19. package/lib/client/index.js.map +1 -1
  20. package/lib/client/message-relay.d.ts +8 -2
  21. package/lib/client/message-relay.d.ts.map +1 -1
  22. package/lib/client/message-relay.js +10 -4
  23. package/lib/client/message-relay.js.map +1 -1
  24. package/lib/client/rpc-connection.d.ts +143 -0
  25. package/lib/client/rpc-connection.d.ts.map +1 -0
  26. package/lib/client/rpc-connection.js +171 -0
  27. package/lib/client/rpc-connection.js.map +1 -0
  28. package/lib/client-ids.d.ts +41 -0
  29. package/lib/client-ids.d.ts.map +1 -0
  30. package/lib/client-ids.js +44 -0
  31. package/lib/client-ids.js.map +1 -0
  32. package/lib/data/data-protocol-methods.d.ts +2 -2
  33. package/lib/data/data-protocol-methods.d.ts.map +1 -1
  34. package/lib/data/data-protocol-methods.js +6 -1
  35. package/lib/data/data-protocol-methods.js.map +1 -1
  36. package/lib/data/data-server-protocol.d.ts +35 -2
  37. package/lib/data/data-server-protocol.d.ts.map +1 -1
  38. package/lib/data/events.d.ts +70 -3
  39. package/lib/data/events.d.ts.map +1 -1
  40. package/lib/errors.d.ts +28 -11
  41. package/lib/errors.d.ts.map +1 -1
  42. package/lib/errors.js +35 -17
  43. package/lib/errors.js.map +1 -1
  44. package/lib/index.d.ts +2 -0
  45. package/lib/index.d.ts.map +1 -1
  46. package/lib/index.js +5 -0
  47. package/lib/index.js.map +1 -1
  48. package/lib/latency-collector.d.ts +8 -4
  49. package/lib/latency-collector.d.ts.map +1 -1
  50. package/lib/latency-collector.js.map +1 -1
  51. package/lib/messages/index.d.ts +28 -0
  52. package/lib/messages/index.d.ts.map +1 -0
  53. package/lib/messages/index.js +52 -0
  54. package/lib/messages/index.js.map +1 -0
  55. package/lib/messages/primitives.d.ts +141 -0
  56. package/lib/messages/primitives.d.ts.map +1 -0
  57. package/lib/messages/primitives.js +138 -0
  58. package/lib/messages/primitives.js.map +1 -0
  59. package/lib/model-server.d.ts +27 -10
  60. package/lib/model-server.d.ts.map +1 -1
  61. package/lib/model-server.js +4 -2
  62. package/lib/model-server.js.map +1 -1
  63. package/lib/model-service/args.d.ts +14 -13
  64. package/lib/model-service/args.d.ts.map +1 -1
  65. package/lib/model-service/based-on.d.ts +55 -0
  66. package/lib/model-service/based-on.d.ts.map +1 -0
  67. package/lib/model-service/based-on.js +34 -0
  68. package/lib/model-service/based-on.js.map +1 -0
  69. package/lib/model-service/index.d.ts +1 -0
  70. package/lib/model-service/index.d.ts.map +1 -1
  71. package/lib/model-service/index.js +1 -0
  72. package/lib/model-service/index.js.map +1 -1
  73. package/lib/profile-session.d.ts +8 -4
  74. package/lib/profile-session.d.ts.map +1 -1
  75. package/lib/profile-session.js.map +1 -1
  76. package/lib/rpc/bind-rpc-methods.d.ts +29 -3
  77. package/lib/rpc/bind-rpc-methods.d.ts.map +1 -1
  78. package/lib/rpc/bind-rpc-methods.js +22 -3
  79. package/lib/rpc/bind-rpc-methods.js.map +1 -1
  80. package/lib/rpc/create-rpc-proxy.d.ts +7 -0
  81. package/lib/rpc/create-rpc-proxy.d.ts.map +1 -1
  82. package/lib/rpc/create-rpc-proxy.js +6 -1
  83. package/lib/rpc/create-rpc-proxy.js.map +1 -1
  84. package/lib/testing/catalogue-audit.d.ts +80 -0
  85. package/lib/testing/catalogue-audit.d.ts.map +1 -0
  86. package/lib/testing/catalogue-audit.js +94 -0
  87. package/lib/testing/catalogue-audit.js.map +1 -0
  88. package/lib/testing/data-doubles.d.ts +11 -12
  89. package/lib/testing/data-doubles.d.ts.map +1 -1
  90. package/lib/testing/data-doubles.js +14 -5
  91. package/lib/testing/data-doubles.js.map +1 -1
  92. package/lib/testing/index.d.ts +1 -0
  93. package/lib/testing/index.d.ts.map +1 -1
  94. package/lib/testing/index.js +4 -1
  95. package/lib/testing/index.js.map +1 -1
  96. package/lib/transfer-diagnostic.d.ts +33 -0
  97. package/lib/transfer-diagnostic.d.ts.map +1 -1
  98. package/lib/transfer-diagnostic.js +23 -0
  99. package/lib/transfer-diagnostic.js.map +1 -1
  100. package/lib/transfer-document.d.ts +15 -5
  101. package/lib/transfer-document.d.ts.map +1 -1
  102. package/lib/transfer-document.js +14 -1
  103. package/lib/transfer-document.js.map +1 -1
  104. package/package.json +11 -2
  105. package/src/client/data-connection.ts +266 -0
  106. package/src/client/data-events.ts +24 -1
  107. package/src/client/data-port.ts +17 -23
  108. package/src/client/data-session.ts +279 -131
  109. package/src/client/index.ts +10 -7
  110. package/src/client/message-relay.ts +28 -6
  111. package/src/client/rpc-connection.ts +235 -0
  112. package/src/client-ids.ts +45 -0
  113. package/src/data/data-protocol-methods.ts +6 -3
  114. package/src/data/data-server-protocol.ts +46 -2
  115. package/src/data/events.ts +74 -3
  116. package/src/errors.ts +41 -19
  117. package/src/index.ts +5 -0
  118. package/src/latency-collector.ts +8 -3
  119. package/src/messages/index.ts +35 -0
  120. package/src/messages/primitives.ts +215 -0
  121. package/src/model-server.ts +30 -11
  122. package/src/model-service/args.ts +15 -13
  123. package/src/model-service/based-on.ts +60 -0
  124. package/src/model-service/index.ts +1 -0
  125. package/src/profile-session.ts +9 -4
  126. package/src/rpc/bind-rpc-methods.ts +49 -4
  127. package/src/rpc/create-rpc-proxy.ts +14 -1
  128. package/src/testing/catalogue-audit.ts +111 -0
  129. package/src/testing/data-doubles.ts +33 -17
  130. package/src/testing/index.ts +4 -1
  131. package/src/transfer-diagnostic.ts +40 -0
  132. package/src/transfer-document.ts +22 -6
@@ -7,106 +7,158 @@
7
7
  * SPDX-License-Identifier: MIT
8
8
  ********************************************************************************/
9
9
 
10
- import type { MessageConnection } from 'vscode-jsonrpc';
11
- import { DATA_CLIENT_PROTOCOL_METHODS, DATA_SERVER_WIRE_PREFIX, type DataClientProtocol, type DataServerProtocol } from '../data';
12
- import { type RpcProxy, createRpcProxy } from '../rpc';
10
+ import type { DataServerProtocol, DiagnosticOf } from '../data';
11
+ import type { RpcProxy } from '../rpc';
13
12
  import type { TransferDocument } from '../transfer-document';
14
13
  import type { TransferElement } from '../transfer-element';
15
- import type { DataPort } from './data-port';
16
14
 
17
- /** Options for {@link DataSession}. */
18
- export interface DataSessionOptions {
19
- /**
20
- * Wire namespace the server is addressed under. Defaults to the
21
- * framework's {@link DATA_SERVER_WIRE_PREFIX}, which is what an unmodified
22
- * `DataServer` binds. Override only alongside the server's own
23
- * `methodNamespace` option — a mismatch turns every request into
24
- * "Unhandled method" rather than failing at wire-up.
25
- */
26
- readonly methodNamespace?: string;
15
+ /**
16
+ * What one of `TServer`'s document methods takes, minus the `clientId` a
17
+ * {@link DataSession} stamps itself.
18
+ *
19
+ * Read off the SERVER's signature, not off the framework's own arg type: an
20
+ * adopter server widens these, and a wrapper declared against the narrow
21
+ * shape rejects the extra field on a fresh object literal, so that call
22
+ * cannot go through a session at all.
23
+ */
24
+ export type DataSessionArgs<TMethod extends (args: never) => unknown> = Omit<Parameters<TMethod>[0], 'clientId'>;
25
+
26
+ /** Open a document through a session; the session supplies `clientId`. */
27
+ export type DataSessionOpenArgs<
28
+ TTransfer extends TransferElement,
29
+ TServer extends DataServerProtocol<TTransfer, DiagnosticOf<TServer>> = DataServerProtocol<TTransfer>
30
+ > = DataSessionArgs<TServer['openModelDocument']>;
31
+
32
+ /** Close a document through a session; the session supplies `clientId`. */
33
+ export type DataSessionCloseArgs<
34
+ TTransfer extends TransferElement,
35
+ TServer extends DataServerProtocol<TTransfer, DiagnosticOf<TServer>> = DataServerProtocol<TTransfer>
36
+ > = DataSessionArgs<TServer['closeModelDocument']>;
37
+
38
+ /** Update a document through a session; the session supplies `clientId`. */
39
+ export type DataSessionUpdateArgs<
40
+ TTransfer extends TransferElement,
41
+ TServer extends DataServerProtocol<TTransfer, DiagnosticOf<TServer>> = DataServerProtocol<TTransfer>
42
+ > = DataSessionArgs<TServer['updateModelDocument']>;
43
+
44
+ /** Persist a document through a session; the session supplies `clientId`. */
45
+ export type DataSessionSaveArgs<
46
+ TTransfer extends TransferElement,
47
+ TServer extends DataServerProtocol<TTransfer, DiagnosticOf<TServer>> = DataServerProtocol<TTransfer>
48
+ > = DataSessionArgs<TServer['saveModelDocument']>;
49
+
50
+ /** The document a session hands back, carrying its server's diagnostic shape. */
51
+ export type DataSessionDocument<
52
+ TTransfer extends TransferElement,
53
+ TServer extends DataServerProtocol<TTransfer, DiagnosticOf<TServer>> = DataServerProtocol<TTransfer>
54
+ > = TransferDocument<TTransfer, DiagnosticOf<TServer>>;
55
+
56
+ /**
57
+ * The {@link DataSession.openDocument} calls running against one URI, and
58
+ * whether any of them has taken a server hold that no open has claimed yet.
59
+ *
60
+ * One record per URI rather than per call, because the hold is per
61
+ * `(uri, clientId)`: the server has one, however many opens are in flight, so
62
+ * one flag is the accurate model of it.
63
+ */
64
+ export interface OpeningDocument {
65
+ /** Opens still running for this URI. The last one out answers for the hold. */
66
+ inFlight: number;
67
+ /** An open succeeded, and no open has since claimed the hold via `openUris`. */
68
+ holdTaken: boolean;
27
69
  }
28
70
 
29
- /** One connection generation: its connection, its proxy, and its readiness. */
30
- interface Generation<TTransfer extends TransferElement> {
31
- readonly connection: Promise<MessageConnection>;
32
- readonly server: RpcProxy<DataServerProtocol<TTransfer>>;
33
- /** Set on first use; the shared readiness gate for this generation. */
34
- ready?: Promise<void>;
71
+ /**
72
+ * What a {@link DataSession} needs from the connection that minted it.
73
+ *
74
+ * Narrower than the connection itself so the dependency points one way:
75
+ * `DataConnection` constructs sessions, and nothing here imports it back.
76
+ */
77
+ export interface DataSessionHost<TTransfer extends TransferElement, TServer extends DataServerProtocol<TTransfer, DiagnosticOf<TServer>>> {
78
+ connected(): Promise<RpcProxy<TServer>>;
79
+ releaseSession(session: DataSession<TTransfer, TServer>): void;
80
+ /**
81
+ * Take over a `(uri, clientId)` hold a session could not release, so it is
82
+ * retried while the wire is still up.
83
+ *
84
+ * A session that has been disposed has already drained and will not read its
85
+ * own tracking again, so a close it issues and the server refuses leaves the
86
+ * hold with nobody to answer for it. The host outlives every session it
87
+ * mints, which is what makes it the one thing that still can.
88
+ *
89
+ * Optional so a host predating it keeps working; without it such a hold falls
90
+ * to the server's connection-close cleanup, which on a shared connection is
91
+ * as long as every other participant's session.
92
+ */
93
+ orphanHold?(uri: string, clientId: string): void;
35
94
  }
36
95
 
37
96
  /**
38
- * The host-invariant half of talking to the data head: everything above
39
- * {@link DataPort} that would otherwise be re-derived by every host
40
- * adapter.
97
+ * One participant on a data connection: a properties panel, a tree, a
98
+ * form editor.
41
99
  *
42
- * Three jobs, and deliberately no fourth:
100
+ * The server keys every hold and watch per `(uri, clientId)`, so the identity
101
+ * belongs to the participant rather than to the wire — several sessions share
102
+ * one connection, and two participants forced to share one identity cannot
103
+ * distinguish each other's writes from their own echoes.
43
104
  *
44
- * 1. **Build the typed proxy** over the port's connection, with the framework's
45
- * wire prefix and its drift-proof client-method allowlist.
46
- * 2. **Own the readiness gate** — `waitForReady` once per connection, shared
47
- * across concurrent callers. A socket client can connect before the
48
- * workspace walk finishes, and an early request is then answered correctly
49
- * from an empty registry, which reads as a broken project tier rather than
50
- * as a race.
51
- * 3. **Own the reconnect policy**, by dropping its connection generation when
52
- * the port disposes and building a fresh one on the next request.
105
+ * Every document operation stamps {@link clientId} itself. A caller that
106
+ * passed its own could pass another participant's, and the server would
107
+ * attribute the write and release the hold accordingly.
53
108
  *
54
- * It does **not** wrap the protocol methods; callers reach them through
55
- * {@link connected}. The one exception is {@link openDocument}, which exists
56
- * because the open/watch *order* is silently wrong the other way round — see
57
- * its own doc.
109
+ * Generic over the transfer root so this file names no grammar.
58
110
  *
59
- * Generic over the transfer root so this file names no grammar. An adopter
60
- * binds the concrete root (or the union of them, for a multi-grammar head) at
61
- * its own edge.
111
+ * `TServer` is bound to a server answering with ITS OWN diagnostic shape, read
112
+ * back off the parameter being bound. Simplifying that to
113
+ * `DataServerProtocol<TTransfer>` compiles and costs the wrappers their
114
+ * return type: every call through `TServer` would resolve against that looser
115
+ * bound, so an adopter's diagnostics would come back as the framework's and
116
+ * the document would have to be cast on the way out.
62
117
  */
63
- export class DataSession<TTransfer extends TransferElement> {
64
- protected readonly methodNamespace: string;
65
- /** The current generation, or `undefined` before the first request / after a teardown. */
66
- protected generation?: Generation<TTransfer>;
118
+ export class DataSession<
119
+ TTransfer extends TransferElement,
120
+ TServer extends DataServerProtocol<TTransfer, DiagnosticOf<TServer>> = DataServerProtocol<TTransfer>
121
+ > {
122
+ /** URIs this session holds open, so {@link dispose} can release exactly those. */
123
+ protected readonly openUris = new Set<string>();
124
+ /**
125
+ * The in-flight {@link openDocument} group per URI, while one is running.
126
+ *
127
+ * A hold is one per `(uri, clientId)`, and {@link openUris} is filled only
128
+ * once an open has fully returned — so overlapping opens of one URI all read
129
+ * it as unheld and all believe the hold is theirs to release. Tracking the
130
+ * group lets the last of them answer for it once, knowing what the rest did.
131
+ */
132
+ protected readonly openingUris = new Map<string, OpeningDocument>();
67
133
  protected disposed = false;
68
- protected readonly portDisposeListener: { dispose(): void };
134
+ /**
135
+ * Disposed through {@link detach} rather than {@link dispose}, so nothing may
136
+ * be sent. Folding it into {@link disposed} costs {@link openDocument} the
137
+ * distinction, and its close would then go out on a detached session.
138
+ */
139
+ protected detached = false;
69
140
 
70
141
  constructor(
71
- protected readonly port: DataPort,
72
- protected readonly client: DataClientProtocol<TTransfer>,
73
- options: DataSessionOptions = {}
74
- ) {
75
- this.methodNamespace = options.methodNamespace ?? DATA_SERVER_WIRE_PREFIX;
76
- this.portDisposeListener = this.port.onDispose(() => this.dropGeneration());
77
- }
78
-
79
- /** The identity every request is made under — the port's, not a second one. */
80
- get clientId(): string {
81
- return this.port.clientId;
82
- }
142
+ readonly clientId: string,
143
+ protected readonly host: DataSessionHost<TTransfer, TServer>
144
+ ) {}
83
145
 
84
146
  /**
85
- * The connected, READY server proxy.
86
- *
87
- * Returns the proxy rather than `void` on purpose. A reconnect replaces the
88
- * proxy, so a caller that cached one from an earlier call would go on
89
- * addressing a dead connection with no error — handing it back per call
90
- * makes the stale reference unrepresentable.
91
- *
92
- * Concurrent callers share one readiness promise, so `waitForReady` is
93
- * awaited once per generation and not once per caller.
147
+ * The connected, READY server proxy, for protocol methods this session does
148
+ * not wrap — the ones carrying no `clientId`, so no identity can be got
149
+ * wrong through them.
94
150
  */
95
- async connected(): Promise<RpcProxy<DataServerProtocol<TTransfer>>> {
96
- if (this.disposed) {
97
- throw new Error('DataSession is disposed');
98
- }
99
- const generation = this.currentGeneration();
100
- if (!generation.ready) {
101
- generation.ready = this.awaitReady(generation);
102
- }
103
- await generation.ready;
104
- return generation.server;
151
+ async connected(): Promise<RpcProxy<TServer>> {
152
+ // `async` so a disposed session REJECTS rather than throwing
153
+ // synchronously: the connection's own `connected` rejects, and a caller
154
+ // reaching for `.catch` on one of them would not catch the other.
155
+ this.assertLive();
156
+ return this.host.connected();
105
157
  }
106
158
 
107
159
  /**
108
- * Open `uri` for editing and start watching it, in that order, returning
109
- * the opened snapshot.
160
+ * Open `args.uri` for editing and start watching it, in that order,
161
+ * returning the opened snapshot.
110
162
  *
111
163
  * **The order is the whole reason this method exists.**
112
164
  * `watchModelDocument` baselines its dedup fingerprint from the *current*
@@ -121,25 +173,135 @@ export class DataSession<TTransfer extends TransferElement> {
121
173
  * valid: `open` settles at the integrity landmark, not at validation.
122
174
  * Validity arrives asynchronously on `onDocumentUpdated`, or synchronously
123
175
  * from `getModelDocument({ includeDiagnostics: true })`.
176
+ *
177
+ * A dispose landing between the two awaits is handled here rather than in
178
+ * {@link dispose}, which cannot release a hold that does not exist yet: it
179
+ * reads {@link openUris}, and this method fills it only once both calls have
180
+ * returned. Left to `dispose`, the hold and its watch outlive the participant
181
+ * and go only when the connection closes.
182
+ *
183
+ * A watch that REJECTS is the same problem arriving by a different door: the
184
+ * open already took a hold, and the caller sees only a failed open, so
185
+ * nothing on its side will ever issue the close.
186
+ *
187
+ * Which call releases it is decided by {@link finishOpening} rather than by
188
+ * the one that failed, because a hold is per `(uri, clientId)` and any number
189
+ * of this session's opens share it. A failing open that closed on its own
190
+ * behalf would revoke a peer's; one that deferred to a peer would leak the
191
+ * hold whenever that peer fails at its OWN open, having then taken no hold to
192
+ * roll back and having no rollback path to run. Making the last open for the
193
+ * URI answer for it is the only rule that holds in both directions.
124
194
  */
125
- async openDocument(uri: string): Promise<TransferDocument<TTransfer>> {
195
+ async openDocument(args: DataSessionOpenArgs<TTransfer, TServer>): Promise<DataSessionDocument<TTransfer, TServer>> {
126
196
  const server = await this.connected();
127
- const document = await server.openModelDocument({ uri, clientId: this.clientId });
128
- await server.watchModelDocument({ uri, clientId: this.clientId });
129
- return document;
197
+ const opening = this.beginOpening(args.uri);
198
+ try {
199
+ const document = await server.openModelDocument({ ...args, clientId: this.clientId });
200
+ // From here a hold exists. It belongs to the URI rather than to this
201
+ // call, so the flag lives on the shared per-URI record.
202
+ opening.holdTaken = true;
203
+ await server.watchModelDocument({ uri: args.uri, clientId: this.clientId });
204
+ if (this.disposed) {
205
+ // Registering the URI BEFORE the open, so `dispose` could close on
206
+ // intent, is NOT the same fix and can invert into the leak it is meant
207
+ // to prevent: the close would then be issued while the open is still in
208
+ // flight, and a peer that does not serialise the two can complete the
209
+ // close first, after which the open re-registers the hold. Closing
210
+ // strictly after the open has resolved is the only ordering with no
211
+ // losing interleaving.
212
+ if (!this.detached) {
213
+ void server.closeModelDocument({ uri: args.uri, clientId: this.clientId }).catch(() => undefined);
214
+ }
215
+ // Answered for here, so the group's own release sends no second one.
216
+ opening.holdTaken = false;
217
+ // Returned rather than thrown: the caller that reaches this window is
218
+ // one that never awaited the open, so a rejection here surfaces as an
219
+ // unhandled one against a participant already gone.
220
+ return document;
221
+ }
222
+ this.openUris.add(args.uri);
223
+ return document;
224
+ } finally {
225
+ await this.finishOpening(args.uri, server);
226
+ }
227
+ }
228
+
229
+ /** Join (or start) the in-flight group for `uri`, counting this call into it. */
230
+ protected beginOpening(uri: string): OpeningDocument {
231
+ const opening = this.openingUris.get(uri) ?? { inFlight: 0, holdTaken: false };
232
+ opening.inFlight += 1;
233
+ this.openingUris.set(uri, opening);
234
+ return opening;
235
+ }
236
+
237
+ /**
238
+ * Count this call out of the in-flight group for `uri` and, if it was the
239
+ * last one, answer for whatever hold the group took.
240
+ *
241
+ * The last call is the only one that can see the group's whole outcome, which
242
+ * is what makes it the right one to decide. A hold that some open took and no
243
+ * open claimed — `openUris` is the claim — belongs to nobody, and closing it
244
+ * here is the only release that will ever be issued for it.
245
+ */
246
+ protected async finishOpening(uri: string, server: RpcProxy<TServer>): Promise<void> {
247
+ const opening = this.openingUris.get(uri);
248
+ if (opening === undefined) {
249
+ return;
250
+ }
251
+ opening.inFlight -= 1;
252
+ if (opening.inFlight > 0) {
253
+ return;
254
+ }
255
+ this.openingUris.delete(uri);
256
+ // `detached` means the wire is going away and the server's connection-close
257
+ // cleanup owns the release, so a close here would travel over a connection
258
+ // that is already leaving. A claimed URI is one an open is keeping.
259
+ if (!opening.holdTaken || this.detached || this.openUris.has(uri)) {
260
+ return;
261
+ }
262
+ await server.closeModelDocument({ uri, clientId: this.clientId }).catch(() => {
263
+ // Hand it to `dispose` while there is still a `dispose` to come. Once
264
+ // that has run it has already drained `openUris` and will not read it
265
+ // again, so tracking would read as handled while nothing released it —
266
+ // there the host is the owner, being the one thing that outlives this
267
+ // session and can still reach the server.
268
+ if (this.disposed) {
269
+ this.host.orphanHold?.(uri, this.clientId);
270
+ } else {
271
+ this.openUris.add(uri);
272
+ }
273
+ });
130
274
  }
131
275
 
132
276
  /**
133
- * Close `uri`. The server unwatches implicitly, so this is the dual of
277
+ * Close `args.uri`. The server unwatches implicitly, so this is the dual of
134
278
  * {@link openDocument} and needs no separate unwatch.
135
279
  */
136
- async closeDocument(uri: string): Promise<void> {
280
+ async closeDocument(args: DataSessionCloseArgs<TTransfer, TServer>): Promise<void> {
281
+ const server = await this.connected();
282
+ await server.closeModelDocument({ ...args, clientId: this.clientId });
283
+ // Untracked only once the close has actually landed. Dropping it first
284
+ // gives a FAILED close the same effect as a successful one: the hold
285
+ // survives on the server and `dispose` no longer knows to retry it.
286
+ // A `dispose` racing this therefore closes the same URI twice, which the
287
+ // server answers as a no-op for a client that no longer holds it.
288
+ this.openUris.delete(args.uri);
289
+ }
290
+
291
+ /** Write `args.model` back as this session. */
292
+ async updateDocument(args: DataSessionUpdateArgs<TTransfer, TServer>): Promise<DataSessionDocument<TTransfer, TServer>> {
293
+ const server = await this.connected();
294
+ return server.updateModelDocument({ ...args, clientId: this.clientId });
295
+ }
296
+
297
+ /** Persist `args.model` to disk as this session. */
298
+ async saveDocument(args: DataSessionSaveArgs<TTransfer, TServer>): Promise<DataSessionDocument<TTransfer, TServer>> {
137
299
  const server = await this.connected();
138
- await server.closeModelDocument({ uri, clientId: this.clientId });
300
+ return server.saveModelDocument({ ...args, clientId: this.clientId });
139
301
  }
140
302
 
141
303
  /**
142
- * Whether `event.sourceClientId` identifies this session's own write.
304
+ * Whether `sourceClientId` identifies this session's own write.
143
305
  *
144
306
  * Every watcher needs this and the check is one comparison, so getting it
145
307
  * wrong is cheap to do and expensive to find: an unfiltered echo looks
@@ -149,61 +311,47 @@ export class DataSession<TTransfer extends TransferElement> {
149
311
  return sourceClientId === this.clientId;
150
312
  }
151
313
 
152
- /** Tear down the current connection and stop tracking the port. Idempotent. */
314
+ /**
315
+ * Release this session's holds and detach it from the connection.
316
+ * Idempotent, and leaves the connection usable by its other sessions.
317
+ *
318
+ * The closes are fired without being awaited, because a `Disposable` cannot
319
+ * be: a host disposing a widget has nowhere to put the promise. A close
320
+ * that fails is no worse than the leak this exists to prevent, so the
321
+ * rejection is swallowed rather than surfaced from a teardown.
322
+ */
153
323
  dispose(): void {
154
324
  if (this.disposed) {
155
325
  return;
156
326
  }
157
327
  this.disposed = true;
158
- this.portDisposeListener.dispose();
159
- this.dropGeneration();
160
- }
161
-
162
- /** The live generation, building one if there is none. */
163
- protected currentGeneration(): Generation<TTransfer> {
164
- if (this.generation) {
165
- return this.generation;
166
- }
167
- const connection = this.port.connect();
168
- // Rejection is reported here rather than left to float: an unhandled
169
- // rejection on a connection promise is the failure mode that reads as
170
- // "the model is empty" instead of "the transport never opened".
171
- connection.catch((error: unknown) => this.port.reportError(error, 'connecting to the data server'));
172
- const server = createRpcProxy<DataServerProtocol<TTransfer>, DataClientProtocol<TTransfer>>(connection, {
173
- methodNamespace: this.methodNamespace,
174
- localTarget: this.client,
175
- localMethods: DATA_CLIENT_PROTOCOL_METHODS
176
- });
177
- this.generation = { connection, server };
178
- return this.generation;
179
- }
180
-
181
- /** Await the connection and the server's startup gate for one generation. */
182
- protected async awaitReady(generation: Generation<TTransfer>): Promise<void> {
183
- try {
184
- await generation.connection;
185
- await generation.server.waitForReady();
186
- } catch (error: unknown) {
187
- // Drop the generation so the next request retries rather than
188
- // re-awaiting a settled rejection forever.
189
- if (this.generation === generation) {
190
- this.generation = undefined;
191
- }
192
- this.port.reportError(error, 'waiting for the data server to become ready');
193
- throw error;
328
+ const uris = [...this.openUris];
329
+ this.openUris.clear();
330
+ this.host.releaseSession(this);
331
+ for (const uri of uris) {
332
+ void this.host
333
+ .connected()
334
+ .then(server => server.closeModelDocument({ uri, clientId: this.clientId }))
335
+ .catch(() => undefined);
194
336
  }
195
337
  }
196
338
 
197
339
  /**
198
- * Discard the current generation, disposing its connection if it opened.
199
- * The next {@link connected} builds a fresh one.
340
+ * Come off the connection because it is going away.
341
+ *
342
+ * Sends no close, unlike {@link dispose}: the server releases every hold on
343
+ * a connection it sees close, and the close would travel over the very
344
+ * connection being disposed.
200
345
  */
201
- protected dropGeneration(): void {
202
- const generation = this.generation;
203
- this.generation = undefined;
204
- if (!generation) {
205
- return;
346
+ detach(): void {
347
+ this.disposed = true;
348
+ this.detached = true;
349
+ this.openUris.clear();
350
+ }
351
+
352
+ protected assertLive(): void {
353
+ if (this.disposed) {
354
+ throw new Error('DataSession is disposed');
206
355
  }
207
- generation.connection.then(connection => connection.dispose()).catch(() => undefined);
208
356
  }
209
357
  }
@@ -13,8 +13,9 @@
13
13
  *
14
14
  * Where `./data` is the wire *contract* and `./rpc` is the machinery that lowers
15
15
  * it onto a connection, this is what a client wraps around both: the seam a host
16
- * fills in (`DataPort`), the lifecycle above it (`DataSession` —
17
- * readiness gate, open/watch ordering, echo recognition, reconnect), the inbound
16
+ * fills in (`DataPort`), the connection above it (`DataConnection` — readiness
17
+ * gate and reconnect), the participants on that connection (`DataSession` —
18
+ * identity, open/watch ordering, echo recognition), the inbound
18
19
  * fan-out (`DataEvents`), and the two halves of the hop for hosts whose
19
20
  * client cannot hold a socket — `createPostMessageTransport` on the client
20
21
  * side and `relayToPostMessageChannel` on the side that does hold it.
@@ -26,15 +27,17 @@
26
27
  * carries the entries.
27
28
  *
28
29
  * The Theia-specific mounting of the same contract lives in
29
- * `@hydranium/data-client-theia`: its `AbstractDataServiceFrontend` solves the
30
- * same problem against Theia's channel transport, and its `EmitterDataClient`
31
- * is the Theia-bound counterpart of `DataEvents`. Prefer this tier for
32
- * anything new, and reach for the Theia package only for what genuinely needs
33
- * Theia DI.
30
+ * `@hydranium/data-client-theia`, and is now only the TRANSPORT: its
31
+ * `ChannelDataPort` fills the `DataPort` seam over a Theia channel, and its
32
+ * `EmitterDataClient` is the Theia-bound counterpart of `DataEvents`.
33
+ * Everything above the port is here, so a Theia frontend and a browser page
34
+ * differ by which port they construct and nothing else.
34
35
  */
35
36
 
37
+ export * from './data-connection';
36
38
  export * from './data-events';
37
39
  export * from './data-port';
38
40
  export * from './data-session';
39
41
  export * from './message-relay';
40
42
  export * from './post-message-transport';
43
+ export * from './rpc-connection';
@@ -8,8 +8,29 @@
8
8
  ********************************************************************************/
9
9
 
10
10
  import { Emitter, type Disposable, type Event, type Message, type MessageReader, type MessageWriter } from 'vscode-jsonrpc';
11
+ import { defineMessage, describeError, resolve, type ResolvedMessage } from '../messages/primitives';
11
12
  import type { PostMessageChannel } from './post-message-transport';
12
13
 
14
+ export const RELAY_TRANSPORT_OPEN_FAILED = defineMessage(
15
+ 'hydranium/protocol/relay-transport-open-failed',
16
+ 'Could not open the transport to relay: {detail}'
17
+ );
18
+
19
+ export const RELAY_TRANSPORT_READ_FAILED = defineMessage(
20
+ 'hydranium/protocol/relay-transport-read-failed',
21
+ 'Could not read from the relayed transport: {detail}'
22
+ );
23
+
24
+ export const RELAY_TRANSPORT_WRITE_FAILED = defineMessage(
25
+ 'hydranium/protocol/relay-transport-write-failed',
26
+ 'Could not write to the relayed transport: {detail}'
27
+ );
28
+
29
+ export const RELAY_REPLAY_FAILED = defineMessage(
30
+ 'hydranium/protocol/relay-replay-failed',
31
+ 'Could not replay a buffered message to the relayed transport: {detail}'
32
+ );
33
+
13
34
  /**
14
35
  * The framed side of a relay: the reader/writer pair over whatever transport the
15
36
  * host actually holds — a TCP socket to the data-server, a child process' stdio,
@@ -30,13 +51,14 @@ export interface RelayTransport {
30
51
  export interface MessageRelayOptions {
31
52
  /**
32
53
  * Surface a failure the way the host does. Same contract as
33
- * `DataPort.reportError`: `context` names what was being attempted.
54
+ * `DataPort.reportError`: `reported` is a complete sentence plus the identity
55
+ * needed to render it in another language.
34
56
  *
35
57
  * A relay has no other way to report — it sits between two transports and
36
58
  * owns neither, so a swallowed error here presents as a form that never
37
59
  * populates.
38
60
  */
39
- readonly reportError?: (error: unknown, context: string) => void;
61
+ readonly reportError?: (error: unknown, reported: ResolvedMessage) => void;
40
62
  }
41
63
 
42
64
  /** A live relay. Dispose to tear both directions down. */
@@ -143,7 +165,7 @@ export function relayToPostMessageChannel(
143
165
  bufferSubscription?.dispose();
144
166
  bufferSubscription = undefined;
145
167
  buffered.length = 0;
146
- options.reportError?.(error, 'opening the transport to relay');
168
+ options.reportError?.(error, resolve(RELAY_TRANSPORT_OPEN_FAILED, { detail: describeError(error) }));
147
169
  closeFramedSide();
148
170
  return false;
149
171
  }
@@ -166,12 +188,12 @@ export function relayToPostMessageChannel(
166
188
  opened.reader.listen(message => channel.post(message)),
167
189
  opened.reader.onClose(() => closeFramedSide()),
168
190
  opened.reader.onError(error => {
169
- options.reportError?.(error, 'reading from the relayed transport');
191
+ options.reportError?.(error, resolve(RELAY_TRANSPORT_READ_FAILED, { detail: describeError(error) }));
170
192
  closeFramedSide();
171
193
  }),
172
194
  channel.onMessage(message => {
173
195
  void opened.writer.write(message).catch((error: unknown) => {
174
- options.reportError?.(error, 'writing to the relayed transport');
196
+ options.reportError?.(error, resolve(RELAY_TRANSPORT_WRITE_FAILED, { detail: describeError(error) }));
175
197
  });
176
198
  })
177
199
  );
@@ -183,7 +205,7 @@ export function relayToPostMessageChannel(
183
205
 
184
206
  for (const message of buffered) {
185
207
  void opened.writer.write(message).catch((error: unknown) => {
186
- options.reportError?.(error, 'replaying a buffered message to the relayed transport');
208
+ options.reportError?.(error, resolve(RELAY_REPLAY_FAILED, { detail: describeError(error) }));
187
209
  });
188
210
  }
189
211
  buffered.length = 0;