@hydranium/protocol 1.0.0-next.12 → 1.0.0-next.123

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 (142) hide show
  1. package/README.md +35 -1
  2. package/lib/client/data-connection.d.ts +114 -0
  3. package/lib/client/data-connection.d.ts.map +1 -0
  4. package/lib/client/data-connection.js +143 -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 +235 -82
  13. package/lib/client/data-session.d.ts.map +1 -1
  14. package/lib/client/data-session.js +337 -108
  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 +4 -4
  33. package/lib/data/data-protocol-methods.d.ts.map +1 -1
  34. package/lib/data/data-protocol-methods.js +10 -1
  35. package/lib/data/data-protocol-methods.js.map +1 -1
  36. package/lib/data/data-server-protocol.d.ts +100 -31
  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/data/requests.d.ts +67 -11
  41. package/lib/data/requests.d.ts.map +1 -1
  42. package/lib/errors.d.ts +91 -12
  43. package/lib/errors.d.ts.map +1 -1
  44. package/lib/errors.js +127 -18
  45. package/lib/errors.js.map +1 -1
  46. package/lib/index.d.ts +2 -0
  47. package/lib/index.d.ts.map +1 -1
  48. package/lib/index.js +5 -0
  49. package/lib/index.js.map +1 -1
  50. package/lib/latency-collector.d.ts +8 -4
  51. package/lib/latency-collector.d.ts.map +1 -1
  52. package/lib/latency-collector.js.map +1 -1
  53. package/lib/messages/index.d.ts +29 -0
  54. package/lib/messages/index.d.ts.map +1 -0
  55. package/lib/messages/index.js +55 -0
  56. package/lib/messages/index.js.map +1 -0
  57. package/lib/messages/primitives.d.ts +188 -0
  58. package/lib/messages/primitives.d.ts.map +1 -0
  59. package/lib/messages/primitives.js +161 -0
  60. package/lib/messages/primitives.js.map +1 -0
  61. package/lib/model-server.d.ts +44 -13
  62. package/lib/model-server.d.ts.map +1 -1
  63. package/lib/model-server.js +4 -2
  64. package/lib/model-server.js.map +1 -1
  65. package/lib/model-service/based-on.d.ts +57 -0
  66. package/lib/model-service/based-on.d.ts.map +1 -0
  67. package/lib/model-service/based-on.js +37 -0
  68. package/lib/model-service/based-on.js.map +1 -0
  69. package/lib/model-service/index.d.ts +1 -1
  70. package/lib/model-service/index.d.ts.map +1 -1
  71. package/lib/model-service/index.js +4 -5
  72. package/lib/model-service/index.js.map +1 -1
  73. package/lib/patch-merge.d.ts +28 -27
  74. package/lib/patch-merge.d.ts.map +1 -1
  75. package/lib/patch-merge.js +66 -22
  76. package/lib/patch-merge.js.map +1 -1
  77. package/lib/profile-session.d.ts +8 -4
  78. package/lib/profile-session.d.ts.map +1 -1
  79. package/lib/profile-session.js.map +1 -1
  80. package/lib/rpc/bind-rpc-methods.d.ts +29 -3
  81. package/lib/rpc/bind-rpc-methods.d.ts.map +1 -1
  82. package/lib/rpc/bind-rpc-methods.js +22 -3
  83. package/lib/rpc/bind-rpc-methods.js.map +1 -1
  84. package/lib/rpc/create-rpc-proxy.d.ts +7 -0
  85. package/lib/rpc/create-rpc-proxy.d.ts.map +1 -1
  86. package/lib/rpc/create-rpc-proxy.js +6 -1
  87. package/lib/rpc/create-rpc-proxy.js.map +1 -1
  88. package/lib/testing/catalogue-audit.d.ts +80 -0
  89. package/lib/testing/catalogue-audit.d.ts.map +1 -0
  90. package/lib/testing/catalogue-audit.js +94 -0
  91. package/lib/testing/catalogue-audit.js.map +1 -0
  92. package/lib/testing/data-doubles.d.ts +11 -12
  93. package/lib/testing/data-doubles.d.ts.map +1 -1
  94. package/lib/testing/data-doubles.js +14 -5
  95. package/lib/testing/data-doubles.js.map +1 -1
  96. package/lib/testing/index.d.ts +1 -0
  97. package/lib/testing/index.d.ts.map +1 -1
  98. package/lib/testing/index.js +4 -1
  99. package/lib/testing/index.js.map +1 -1
  100. package/lib/transfer-diagnostic.d.ts +33 -0
  101. package/lib/transfer-diagnostic.d.ts.map +1 -1
  102. package/lib/transfer-diagnostic.js +23 -0
  103. package/lib/transfer-diagnostic.js.map +1 -1
  104. package/lib/transfer-document.d.ts +14 -5
  105. package/lib/transfer-document.d.ts.map +1 -1
  106. package/lib/transfer-document.js +14 -1
  107. package/lib/transfer-document.js.map +1 -1
  108. package/package.json +11 -2
  109. package/src/client/data-connection.ts +216 -0
  110. package/src/client/data-events.ts +24 -1
  111. package/src/client/data-port.ts +17 -23
  112. package/src/client/data-session.ts +447 -128
  113. package/src/client/index.ts +10 -7
  114. package/src/client/message-relay.ts +28 -6
  115. package/src/client/rpc-connection.ts +235 -0
  116. package/src/client-ids.ts +45 -0
  117. package/src/data/data-protocol-methods.ts +10 -3
  118. package/src/data/data-server-protocol.ts +119 -31
  119. package/src/data/events.ts +74 -3
  120. package/src/data/requests.ts +71 -11
  121. package/src/errors.ts +139 -20
  122. package/src/index.ts +5 -0
  123. package/src/latency-collector.ts +8 -3
  124. package/src/messages/index.ts +36 -0
  125. package/src/messages/primitives.ts +271 -0
  126. package/src/model-server.ts +47 -18
  127. package/src/model-service/based-on.ts +63 -0
  128. package/src/model-service/index.ts +4 -5
  129. package/src/patch-merge.ts +90 -37
  130. package/src/profile-session.ts +9 -4
  131. package/src/rpc/bind-rpc-methods.ts +49 -4
  132. package/src/rpc/create-rpc-proxy.ts +14 -1
  133. package/src/testing/catalogue-audit.ts +111 -0
  134. package/src/testing/data-doubles.ts +33 -17
  135. package/src/testing/index.ts +4 -1
  136. package/src/transfer-diagnostic.ts +40 -0
  137. package/src/transfer-document.ts +21 -6
  138. package/lib/model-service/args.d.ts +0 -64
  139. package/lib/model-service/args.d.ts.map +0 -1
  140. package/lib/model-service/args.js +0 -11
  141. package/lib/model-service/args.js.map +0 -1
  142. package/src/model-service/args.ts +0 -67
@@ -7,106 +7,229 @@
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 { SnapshotVersion } from '../model-service/based-on';
12
+ import { type ResolvedMessage, defineMessage, describeError, resolve } from '../messages/primitives';
13
+ import type { OpenModelArgs } from '../model-server';
14
+ import type { MaybePromise } from '../util';
15
+ import type { RpcProxy } from '../rpc';
13
16
  import type { TransferDocument } from '../transfer-document';
14
17
  import type { TransferElement } from '../transfer-element';
15
- import type { DataPort } from './data-port';
16
18
 
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;
27
- }
19
+ /**
20
+ * A session could not re-open a document it had open after its connection
21
+ * dropped.
22
+ */
23
+ export const DATA_SESSION_RESTORE_FAILED = defineMessage(
24
+ 'hydranium/protocol/data-session-restore-failed',
25
+ 'Could not restore {uri} after reconnecting to the data server: {detail}'
26
+ );
27
+
28
+ /**
29
+ * A session re-opened documents after its connection dropped whose version had
30
+ * moved on since the session's last unsaved write to them: another client
31
+ * edited them, even while the session was still connected, the server reverted
32
+ * them to what is on disk, or the server restarted. The session's unsaved edits
33
+ * may be gone.
34
+ */
35
+ export const DATA_SESSION_UNSAVED_LOST = defineMessage(
36
+ 'hydranium/protocol/data-session-unsaved-lost',
37
+ 'Unsaved changes to {uris} may have been lost when the connection to the data server dropped.'
38
+ );
39
+
40
+ /**
41
+ * What one of `TServer`'s document methods takes, minus the `clientId` a
42
+ * {@link DataSession} stamps itself.
43
+ *
44
+ * Read off the SERVER's signature, not off the framework's own arg type: an
45
+ * adopter server widens these, and a wrapper declared against the narrow
46
+ * shape rejects the extra field on a fresh object literal, so that call
47
+ * cannot go through a session at all.
48
+ */
49
+ export type DataSessionArgs<TMethod extends (args: never) => unknown> = Omit<Parameters<TMethod>[0], 'clientId'>;
50
+
51
+ /**
52
+ * Open a document through a session; the session supplies `clientId`. Only the
53
+ * URI and the open's options: a session's open reads the file, and the server
54
+ * ignores the `languageId`, `version` and `text` seeds of `OpenModelArgs`, so
55
+ * accepting them here would let a caller believe they took effect.
56
+ */
57
+ export type DataSessionOpenArgs<
58
+ TTransfer extends TransferElement,
59
+ TServer extends DataServerProtocol<TTransfer, DiagnosticOf<TServer>> = DataServerProtocol<TTransfer>
60
+ > = Pick<OpenModelArgs, 'uri' | 'options'>;
28
61
 
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>;
62
+ /** Create a document through a session; the session supplies `clientId`. */
63
+ export type DataSessionCreateArgs<
64
+ TTransfer extends TransferElement,
65
+ TServer extends DataServerProtocol<TTransfer, DiagnosticOf<TServer>> = DataServerProtocol<TTransfer>
66
+ > = DataSessionArgs<TServer['createModelDocument']>;
67
+
68
+ /** Close a document through a session; the session supplies `clientId`. */
69
+ export type DataSessionCloseArgs<
70
+ TTransfer extends TransferElement,
71
+ TServer extends DataServerProtocol<TTransfer, DiagnosticOf<TServer>> = DataServerProtocol<TTransfer>
72
+ > = DataSessionArgs<TServer['closeModelDocument']>;
73
+
74
+ /** Update a document through a session; the session supplies `clientId`. */
75
+ export type DataSessionUpdateArgs<
76
+ TTransfer extends TransferElement,
77
+ TServer extends DataServerProtocol<TTransfer, DiagnosticOf<TServer>> = DataServerProtocol<TTransfer>
78
+ > = DataSessionArgs<TServer['updateModelDocument']>;
79
+
80
+ /** Update several documents at once through a session; the session supplies `clientId`. */
81
+ export type DataSessionUpdatesArgs<
82
+ TTransfer extends TransferElement,
83
+ TServer extends DataServerProtocol<TTransfer, DiagnosticOf<TServer>> = DataServerProtocol<TTransfer>
84
+ > = DataSessionArgs<TServer['updateModelDocuments']>;
85
+
86
+ /** Persist a document through a session; the session supplies `clientId`. */
87
+ export type DataSessionSaveArgs<
88
+ TTransfer extends TransferElement,
89
+ TServer extends DataServerProtocol<TTransfer, DiagnosticOf<TServer>> = DataServerProtocol<TTransfer>
90
+ > = DataSessionArgs<TServer['saveModelDocument']>;
91
+
92
+ /** The document a session hands back, carrying its server's diagnostic shape. */
93
+ export type DataSessionDocument<
94
+ TTransfer extends TransferElement,
95
+ TServer extends DataServerProtocol<TTransfer, DiagnosticOf<TServer>> = DataServerProtocol<TTransfer>
96
+ > = TransferDocument<TTransfer, DiagnosticOf<TServer>>;
97
+
98
+ /**
99
+ * What a {@link DataSession} needs from the connection that minted it.
100
+ *
101
+ * Narrower than the connection itself so the dependency points one way:
102
+ * `DataConnection` constructs sessions, and nothing here imports it back.
103
+ */
104
+ export interface DataSessionHost<TTransfer extends TransferElement, TServer extends DataServerProtocol<TTransfer, DiagnosticOf<TServer>>> {
105
+ /** The connected, READY proxy of the current connection; a new object after each reconnect. */
106
+ connected(): Promise<RpcProxy<TServer>>;
107
+ releaseSession(session: DataSession<TTransfer, TServer>): void;
108
+ /** Surface a failure no caller is waiting on, such as restoring a document after a reconnect. */
109
+ reportError?(error: unknown, reported: ResolvedMessage): void;
35
110
  }
36
111
 
37
112
  /**
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.
113
+ * Builds the session `DataConnection.createSession` hands out, for an adopter
114
+ * that extends {@link DataSession}. The connection has minted `clientId` and
115
+ * checked it by then.
116
+ */
117
+ export type DataSessionFactory<TTransfer extends TransferElement, TServer extends DataServerProtocol<TTransfer, DiagnosticOf<TServer>>> = (
118
+ clientId: string,
119
+ host: DataSessionHost<TTransfer, TServer>,
120
+ label: string
121
+ ) => DataSession<TTransfer, TServer>;
122
+
123
+ /**
124
+ * One participant on a data connection: a properties panel, a tree, a form
125
+ * editor. The client side of a server client session, registered over the
126
+ * wire under {@link clientId}.
41
127
  *
42
- * Three jobs, and deliberately no fourth:
128
+ * The session writes only what it has open: the server refuses its update or
129
+ * save of a document it has not opened with a `DocumentNotOpenError` code.
130
+ * Every call waits for the registration, so the first can be issued at once.
43
131
  *
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.
132
+ * Every document operation stamps {@link clientId} itself. A caller that
133
+ * passed its own could pass another participant's, and the server would
134
+ * attribute the write and close the document accordingly.
53
135
  *
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.
136
+ * {@link closeDocument} and {@link dispose} first wait, up to
137
+ * {@link settleBeforeCloseMs}, for this session's calls still in flight on the
138
+ * URI, or on any URI for `dispose`: a save sent just before its close would
139
+ * otherwise reach the server after it, and fail as not open.
58
140
  *
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.
141
+ * After the connection drops, the session registers again under the same id,
142
+ * re-opens and re-watches what it had open, and reports the documents whose
143
+ * unsaved edits did not survive; see {@link restore}. The connection does this at
144
+ * once for a session with documents open, and any session's next call does it
145
+ * too.
146
+ *
147
+ * Generic over the transfer root so this file names no grammar.
148
+ *
149
+ * `TServer` is bound to a server answering with ITS OWN diagnostic shape, read
150
+ * back off the parameter being bound. Simplifying that to
151
+ * `DataServerProtocol<TTransfer>` compiles and costs the wrappers their
152
+ * return type: every call through `TServer` would resolve against that looser
153
+ * bound, so an adopter's diagnostics would come back as the framework's and
154
+ * the document would have to be cast on the way out.
62
155
  */
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>;
156
+ export class DataSession<
157
+ TTransfer extends TransferElement,
158
+ TServer extends DataServerProtocol<TTransfer, DiagnosticOf<TServer>> = DataServerProtocol<TTransfer>
159
+ > {
160
+ /**
161
+ * How long {@link closeDocument} and {@link dispose} wait for this session's
162
+ * calls in flight before closing anyway. Long, because the wait only runs
163
+ * out when a call hangs, and a close sent while a save is still running
164
+ * fails that save.
165
+ */
166
+ protected readonly settleBeforeCloseMs: number = 10_000;
167
+ /** URIs this session has open, re-opened after a reconnect. */
168
+ protected readonly openUris = new Set<string>();
169
+ /**
170
+ * Per URI, how many opens of it this session has under way. Such a URI
171
+ * counts as open for {@link withOpenDocument}, which would otherwise close
172
+ * it under the open that is still being made.
173
+ */
174
+ protected readonly openingUris = new Map<string, number>();
175
+ /**
176
+ * Per URI written since its last save, the version the server answered this
177
+ * session's last write with; see {@link restore}.
178
+ */
179
+ protected readonly unsavedWrites = new Map<string, SnapshotVersion>();
180
+ /** Per URI, this session's calls still in flight on it, which a close waits for. */
181
+ protected readonly inFlight = new Map<string, Set<Promise<unknown>>>();
182
+ /**
183
+ * Sent with every registration, so the server lets this session register
184
+ * its id again while the dropped connection's session is still live there:
185
+ * a server that has not yet noticed the drop would otherwise refuse the id
186
+ * as a duplicate until it does.
187
+ */
188
+ protected readonly resumeToken: string = globalThis.crypto.randomUUID();
189
+ /** The proxy the session is registered on; another one means the connection was replaced. */
190
+ protected registeredOn?: RpcProxy<TServer>;
191
+ protected registration?: Promise<void>;
67
192
  protected disposed = false;
68
- protected readonly portDisposeListener: { dispose(): void };
193
+ /**
194
+ * Disposed through {@link detach} rather than {@link dispose}, so nothing may
195
+ * be sent. Folding it into {@link disposed} would send the session's close
196
+ * over a connection that is going away.
197
+ */
198
+ protected detached = false;
69
199
 
70
200
  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
- }
201
+ readonly clientId: string,
202
+ protected readonly host: DataSessionHost<TTransfer, TServer>,
203
+ readonly label: string
204
+ ) {}
83
205
 
84
206
  /**
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.
207
+ * The connected, READY server proxy once this session is registered on it,
208
+ * for protocol methods this session does not wrap. The proxy stamps
209
+ * nothing: pass this session's {@link clientId} to any method that carries
210
+ * one.
94
211
  */
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);
212
+ async connected(): Promise<RpcProxy<TServer>> {
213
+ // `async` so a disposed session REJECTS rather than throwing
214
+ // synchronously: the connection's own `connected` rejects, and a caller
215
+ // reaching for `.catch` on one of them would not catch the other.
216
+ this.assertLive();
217
+ const server = await this.host.connected();
218
+ // Again after the wait: a session disposed meanwhile must not register,
219
+ // since its dispose found nothing registered to end.
220
+ this.assertLive();
221
+ if (this.registeredOn !== server) {
222
+ const reconnected = this.registeredOn !== undefined;
223
+ this.registeredOn = server;
224
+ this.registration = this.register(server, reconnected);
102
225
  }
103
- await generation.ready;
104
- return generation.server;
226
+ await this.registration;
227
+ return server;
105
228
  }
106
229
 
107
230
  /**
108
- * Open `uri` for editing and start watching it, in that order, returning
109
- * the opened snapshot.
231
+ * Open `args.uri` for editing and start watching it, in that order,
232
+ * returning the opened snapshot.
110
233
  *
111
234
  * **The order is the whole reason this method exists.**
112
235
  * `watchModelDocument` baselines its dedup fingerprint from the *current*
@@ -114,32 +237,129 @@ export class DataSession<TTransfer extends TransferElement> {
114
237
  * baseline, and the first phase event after the open arrives as a spurious
115
238
  * `'changed'` — which a widget that resets its in-memory root to the server
116
239
  * view misreads as a concurrent third-party write, losing whatever the user
117
- * had typed. Nothing about the wrong order fails loudly, so it is encoded
118
- * here rather than documented and re-derived.
240
+ * had typed.
119
241
  *
120
242
  * Note that the returned snapshot's empty `diagnostics` does not mean
121
243
  * valid: `open` settles at the integrity landmark, not at validation.
122
244
  * Validity arrives asynchronously on `onDocumentUpdated`, or synchronously
123
245
  * from `getModelDocument({ includeDiagnostics: true })`.
124
246
  */
125
- async openDocument(uri: string): Promise<TransferDocument<TTransfer>> {
126
- const server = await this.connected();
127
- const document = await server.openModelDocument({ uri, clientId: this.clientId });
128
- await server.watchModelDocument({ uri, clientId: this.clientId });
247
+ openDocument(args: DataSessionOpenArgs<TTransfer, TServer>): Promise<DataSessionDocument<TTransfer, TServer>> {
248
+ return this.trackOpen(args.uri, async () => {
249
+ const server = await this.connected();
250
+ return this.watchOpened(server, args.uri, await server.openModelDocument({ ...args, clientId: this.clientId }));
251
+ });
252
+ }
253
+
254
+ /**
255
+ * Create a document that exists nowhere yet, open and watched for this
256
+ * session; it reaches disk with the first {@link saveDocument}. The server
257
+ * refuses a URI that exists on disk or that any client has open.
258
+ */
259
+ createDocument(args: DataSessionCreateArgs<TTransfer, TServer>): Promise<DataSessionDocument<TTransfer, TServer>> {
260
+ return this.trackOpen(args.uri, async () => {
261
+ const server = await this.connected();
262
+ return this.watchOpened(server, args.uri, await server.createModelDocument({ ...args, clientId: this.clientId }));
263
+ });
264
+ }
265
+
266
+ /**
267
+ * Watch a document this session just opened, and record it as open. A
268
+ * failed watch closes it again: the caller sees a failed open and so would
269
+ * never close it.
270
+ */
271
+ protected async watchOpened(
272
+ server: RpcProxy<TServer>,
273
+ uri: string,
274
+ document: DataSessionDocument<TTransfer, TServer>
275
+ ): Promise<DataSessionDocument<TTransfer, TServer>> {
276
+ try {
277
+ await server.watchModelDocument({ uri, clientId: this.clientId });
278
+ } catch (error: unknown) {
279
+ await server.closeModelDocument({ uri, clientId: this.clientId }).catch(() => undefined);
280
+ throw error;
281
+ }
282
+ this.openUris.add(uri);
129
283
  return document;
130
284
  }
131
285
 
132
286
  /**
133
- * Close `uri`. The server unwatches implicitly, so this is the dual of
134
- * {@link openDocument} and needs no separate unwatch.
287
+ * Close `args.uri`, once this session's calls on it have settled or
288
+ * {@link settleBeforeCloseMs} has passed. The server unwatches implicitly,
289
+ * so this is the dual of {@link openDocument} and needs no separate unwatch.
135
290
  */
136
- async closeDocument(uri: string): Promise<void> {
291
+ async closeDocument(args: DataSessionCloseArgs<TTransfer, TServer>): Promise<void> {
292
+ this.assertLive();
293
+ await this.settle(this.inFlight.get(args.uri));
294
+ // Forgotten before the close is sent, so a reconnect in between does not
295
+ // re-open a document the caller has closed; after the wait, so an open
296
+ // of it that was still in flight does not record it again.
297
+ this.openUris.delete(args.uri);
298
+ this.unsavedWrites.delete(args.uri);
137
299
  const server = await this.connected();
138
- await server.closeModelDocument({ uri, clientId: this.clientId });
300
+ await server.closeModelDocument({ ...args, clientId: this.clientId });
301
+ }
302
+
303
+ /**
304
+ * Open `args.uri`, run `fn` with the opened snapshot, and close it once
305
+ * `fn` settles, whether it returned or threw. A URI this session already
306
+ * had open, or is still opening through another call, stays open: the close
307
+ * undoes only the open this call made.
308
+ */
309
+ async withOpenDocument<T>(
310
+ args: DataSessionOpenArgs<TTransfer, TServer>,
311
+ fn: (document: DataSessionDocument<TTransfer, TServer>) => MaybePromise<T>
312
+ ): Promise<T> {
313
+ const alreadyOpen = this.openUris.has(args.uri) || this.openingUris.has(args.uri);
314
+ const document = await this.openDocument(args);
315
+ try {
316
+ return await fn(document);
317
+ } finally {
318
+ if (!alreadyOpen && !this.disposed) {
319
+ await this.closeDocument({ uri: args.uri } as DataSessionCloseArgs<TTransfer, TServer>);
320
+ }
321
+ }
322
+ }
323
+
324
+ /** Write `args.model` back as this session. The session must have `args.uri` open. */
325
+ updateDocument(args: DataSessionUpdateArgs<TTransfer, TServer>): Promise<DataSessionDocument<TTransfer, TServer>> {
326
+ return this.track([args.uri], async () => {
327
+ const server = await this.connected();
328
+ const document = await server.updateModelDocument({ ...args, clientId: this.clientId });
329
+ this.unsavedWrites.set(args.uri, document.version);
330
+ return document;
331
+ });
332
+ }
333
+
334
+ /**
335
+ * Write several documents this session has open, all or none: the server
336
+ * refuses the whole set, before any text applies, when one is stale or not
337
+ * open. Resolves to the documents in the order given.
338
+ */
339
+ updateDocuments(args: DataSessionUpdatesArgs<TTransfer, TServer>): Promise<DataSessionDocument<TTransfer, TServer>[]> {
340
+ return this.track(
341
+ args.updates.map(update => update.uri),
342
+ async () => {
343
+ const server = await this.connected();
344
+ const documents = await server.updateModelDocuments({ ...args, clientId: this.clientId });
345
+ args.updates.forEach((update, i) => this.unsavedWrites.set(update.uri, documents[i].version));
346
+ return documents;
347
+ }
348
+ );
349
+ }
350
+
351
+ /** Persist `args.model` to disk as this session. The session must have `args.uri` open. */
352
+ saveDocument(args: DataSessionSaveArgs<TTransfer, TServer>): Promise<DataSessionDocument<TTransfer, TServer>> {
353
+ return this.track([args.uri], async () => {
354
+ const server = await this.connected();
355
+ const document = await server.saveModelDocument({ ...args, clientId: this.clientId });
356
+ this.unsavedWrites.delete(args.uri);
357
+ return document;
358
+ });
139
359
  }
140
360
 
141
361
  /**
142
- * Whether `event.sourceClientId` identifies this session's own write.
362
+ * Whether `sourceClientId` identifies this session's own write.
143
363
  *
144
364
  * Every watcher needs this and the check is one comparison, so getting it
145
365
  * wrong is cheap to do and expensive to find: an unfiltered echo looks
@@ -149,61 +369,160 @@ export class DataSession<TTransfer extends TransferElement> {
149
369
  return sourceClientId === this.clientId;
150
370
  }
151
371
 
152
- /** Tear down the current connection and stop tracking the port. Idempotent. */
372
+ /**
373
+ * End the session: detach it from the connection at once, and once its
374
+ * calls in flight have settled or {@link settleBeforeCloseMs} has passed,
375
+ * end it on the server, which closes everything it has open. Idempotent,
376
+ * and leaves the connection usable by its other sessions.
377
+ *
378
+ * Every later call rejects. The server close is not awaited, because a
379
+ * `Disposable` cannot be; a close that fails leaves the session to the
380
+ * server's connection-close cleanup.
381
+ */
153
382
  dispose(): void {
154
383
  if (this.disposed) {
155
384
  return;
156
385
  }
157
386
  this.disposed = true;
158
- this.portDisposeListener.dispose();
159
- this.dropGeneration();
387
+ this.host.releaseSession(this);
388
+ const pending = [...this.inFlight.values()].flatMap(calls => [...calls]);
389
+ void (async () => {
390
+ await this.settle(pending);
391
+ await this.registration;
392
+ // The proxy the session registered on, never a fresh connection: a
393
+ // connection that dropped already ended the session on the server.
394
+ if (!this.detached && this.registeredOn) {
395
+ await this.registeredOn.closeSession({ clientId: this.clientId });
396
+ }
397
+ })().catch(() => undefined);
398
+ }
399
+
400
+ /**
401
+ * Come off the connection because it is going away.
402
+ *
403
+ * Sends nothing, unlike {@link dispose}: the server ends every session on a
404
+ * connection it sees close, and the close would travel over the very
405
+ * connection being disposed.
406
+ */
407
+ detach(): void {
408
+ this.disposed = true;
409
+ this.detached = true;
410
+ this.openUris.clear();
411
+ this.unsavedWrites.clear();
160
412
  }
161
413
 
162
- /** The live generation, building one if there is none. */
163
- protected currentGeneration(): Generation<TTransfer> {
164
- if (this.generation) {
165
- return this.generation;
414
+ /**
415
+ * Register again and restore now, after the connection dropped, instead of
416
+ * on the next call. A no-op for a session with nothing open, which the next
417
+ * call restores anyway. A failure is left to that next call, which meets it
418
+ * again.
419
+ */
420
+ reconnect(): void {
421
+ if (!this.disposed && this.openUris.size > 0) {
422
+ this.connected().catch(() => undefined);
166
423
  }
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
424
  }
180
425
 
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;
426
+ /**
427
+ * Register on `server`, and after a reconnect restore what the ended session
428
+ * had. Calls issued meanwhile wait for this.
429
+ */
430
+ protected async register(server: RpcProxy<TServer>, reconnected: boolean): Promise<void> {
431
+ await server.createSession({ clientId: this.clientId, label: this.label, resumeToken: this.resumeToken });
432
+ if (reconnected) {
433
+ await this.restore(server);
194
434
  }
195
435
  }
196
436
 
197
437
  /**
198
- * Discard the current generation, disposing its connection if it opened.
199
- * The next {@link connected} builds a fresh one.
438
+ * Re-open and re-watch every document the session had open, and tell the
439
+ * host which of them lost what the session wrote since their last save.
440
+ *
441
+ * The unsaved text is not sent again. A document whose re-opened version is
442
+ * the one the session's last write was answered with still holds that
443
+ * write. Any other version means the text changed after that write:
444
+ * another client edited it, even while the session was still connected;
445
+ * the server reverted it to disk when the session's open closed as the
446
+ * document's last; or the server restarted and numbers versions afresh.
447
+ * Re-sending based on the write's own version then always conflicts, and
448
+ * based on the re-opened version it would overwrite whatever changed, so
449
+ * neither is done.
450
+ *
451
+ * No caller is waiting, so both outcomes go through the host: one report
452
+ * naming every document whose unsaved text is gone, whose record is then
453
+ * dropped, and one per document that could not be re-opened, which is
454
+ * forgotten.
200
455
  */
201
- protected dropGeneration(): void {
202
- const generation = this.generation;
203
- this.generation = undefined;
204
- if (!generation) {
456
+ protected async restore(server: RpcProxy<TServer>): Promise<void> {
457
+ const lost: string[] = [];
458
+ for (const uri of [...this.openUris]) {
459
+ try {
460
+ const document = await server.openModelDocument({ uri, clientId: this.clientId });
461
+ await server.watchModelDocument({ uri, clientId: this.clientId });
462
+ const written = this.unsavedWrites.get(uri);
463
+ if (written !== undefined && written !== document.version) {
464
+ lost.push(uri);
465
+ this.unsavedWrites.delete(uri);
466
+ }
467
+ } catch (error: unknown) {
468
+ this.openUris.delete(uri);
469
+ this.unsavedWrites.delete(uri);
470
+ this.host.reportError?.(error, resolve(DATA_SESSION_RESTORE_FAILED, { uri, detail: describeError(error) }));
471
+ }
472
+ }
473
+ if (lost.length > 0) {
474
+ const reported = resolve(DATA_SESSION_UNSAVED_LOST, { uris: lost.join(', ') });
475
+ this.host.reportError?.(new Error(reported.text), reported);
476
+ }
477
+ }
478
+
479
+ /** Run `call`, counted as in flight on each of `uris` until it settles. */
480
+ protected track<T>(uris: readonly string[], call: () => Promise<T>): Promise<T> {
481
+ const running = call();
482
+ for (const uri of uris) {
483
+ this.inFlight.set(uri, (this.inFlight.get(uri) ?? new Set<Promise<unknown>>()).add(running));
484
+ }
485
+ const done = (): void => uris.forEach(uri => this.inFlight.get(uri)?.delete(running));
486
+ running.then(done, done);
487
+ return running;
488
+ }
489
+
490
+ /** {@link track} an open of `uri`, counted in {@link openingUris} until it settles. */
491
+ protected trackOpen<T>(uri: string, call: () => Promise<T>): Promise<T> {
492
+ this.openingUris.set(uri, (this.openingUris.get(uri) ?? 0) + 1);
493
+ const done = (): void => {
494
+ const remaining = (this.openingUris.get(uri) ?? 1) - 1;
495
+ if (remaining > 0) {
496
+ this.openingUris.set(uri, remaining);
497
+ } else {
498
+ this.openingUris.delete(uri);
499
+ }
500
+ };
501
+ const running = this.track([uri], call);
502
+ running.then(done, done);
503
+ return running;
504
+ }
505
+
506
+ /** Wait until `calls` have settled, or {@link settleBeforeCloseMs} has passed. */
507
+ protected async settle(calls: Iterable<Promise<unknown>> | undefined): Promise<void> {
508
+ const pending = [...(calls ?? [])];
509
+ if (pending.length === 0) {
205
510
  return;
206
511
  }
207
- generation.connection.then(connection => connection.dispose()).catch(() => undefined);
512
+ let timer: ReturnType<typeof setTimeout> | undefined;
513
+ const bound = new Promise<void>(resolveBound => {
514
+ timer = setTimeout(resolveBound, this.settleBeforeCloseMs);
515
+ });
516
+ try {
517
+ await Promise.race([Promise.allSettled(pending), bound]);
518
+ } finally {
519
+ clearTimeout(timer);
520
+ }
521
+ }
522
+
523
+ protected assertLive(): void {
524
+ if (this.disposed) {
525
+ throw new Error('DataSession is disposed');
526
+ }
208
527
  }
209
528
  }