@hydranium/protocol 1.0.0-next.117 → 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 (60) hide show
  1. package/lib/client/data-connection.d.ts +28 -66
  2. package/lib/client/data-connection.d.ts.map +1 -1
  3. package/lib/client/data-connection.js +41 -112
  4. package/lib/client/data-connection.js.map +1 -1
  5. package/lib/client/data-session.d.ts +168 -93
  6. package/lib/client/data-session.d.ts.map +1 -1
  7. package/lib/client/data-session.js +291 -147
  8. package/lib/client/data-session.js.map +1 -1
  9. package/lib/data/data-protocol-methods.d.ts +2 -2
  10. package/lib/data/data-protocol-methods.d.ts.map +1 -1
  11. package/lib/data/data-protocol-methods.js +4 -0
  12. package/lib/data/data-protocol-methods.js.map +1 -1
  13. package/lib/data/data-server-protocol.d.ts +66 -30
  14. package/lib/data/data-server-protocol.d.ts.map +1 -1
  15. package/lib/data/requests.d.ts +67 -11
  16. package/lib/data/requests.d.ts.map +1 -1
  17. package/lib/errors.d.ts +66 -4
  18. package/lib/errors.d.ts.map +1 -1
  19. package/lib/errors.js +96 -5
  20. package/lib/errors.js.map +1 -1
  21. package/lib/messages/index.d.ts +1 -0
  22. package/lib/messages/index.d.ts.map +1 -1
  23. package/lib/messages/index.js +4 -1
  24. package/lib/messages/index.js.map +1 -1
  25. package/lib/model-server.d.ts +13 -1
  26. package/lib/model-server.d.ts.map +1 -1
  27. package/lib/model-server.js.map +1 -1
  28. package/lib/model-service/based-on.d.ts +2 -0
  29. package/lib/model-service/based-on.d.ts.map +1 -1
  30. package/lib/model-service/based-on.js +3 -0
  31. package/lib/model-service/based-on.js.map +1 -1
  32. package/lib/model-service/index.d.ts +0 -1
  33. package/lib/model-service/index.d.ts.map +1 -1
  34. package/lib/model-service/index.js +3 -5
  35. package/lib/model-service/index.js.map +1 -1
  36. package/lib/patch-merge.d.ts +28 -27
  37. package/lib/patch-merge.d.ts.map +1 -1
  38. package/lib/patch-merge.js +66 -22
  39. package/lib/patch-merge.js.map +1 -1
  40. package/lib/transfer-document.d.ts +2 -3
  41. package/lib/transfer-document.d.ts.map +1 -1
  42. package/lib/transfer-document.js.map +1 -1
  43. package/package.json +1 -1
  44. package/src/client/data-connection.ts +69 -119
  45. package/src/client/data-session.ts +348 -177
  46. package/src/data/data-protocol-methods.ts +4 -0
  47. package/src/data/data-server-protocol.ts +74 -30
  48. package/src/data/requests.ts +71 -11
  49. package/src/errors.ts +101 -4
  50. package/src/messages/index.ts +1 -0
  51. package/src/model-server.ts +13 -5
  52. package/src/model-service/based-on.ts +3 -0
  53. package/src/model-service/index.ts +3 -5
  54. package/src/patch-merge.ts +90 -37
  55. package/src/transfer-document.ts +2 -3
  56. package/lib/model-service/args.d.ts +0 -65
  57. package/lib/model-service/args.d.ts.map +0 -1
  58. package/lib/model-service/args.js +0 -11
  59. package/lib/model-service/args.js.map +0 -1
  60. package/src/model-service/args.ts +0 -69
@@ -8,10 +8,35 @@
8
8
  ********************************************************************************/
9
9
 
10
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';
11
15
  import type { RpcProxy } from '../rpc';
12
16
  import type { TransferDocument } from '../transfer-document';
13
17
  import type { TransferElement } from '../transfer-element';
14
18
 
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
+
15
40
  /**
16
41
  * What one of `TServer`'s document methods takes, minus the `clientId` a
17
42
  * {@link DataSession} stamps itself.
@@ -23,11 +48,22 @@ import type { TransferElement } from '../transfer-element';
23
48
  */
24
49
  export type DataSessionArgs<TMethod extends (args: never) => unknown> = Omit<Parameters<TMethod>[0], 'clientId'>;
25
50
 
26
- /** Open a document through a session; the session supplies `clientId`. */
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
+ */
27
57
  export type DataSessionOpenArgs<
28
58
  TTransfer extends TransferElement,
29
59
  TServer extends DataServerProtocol<TTransfer, DiagnosticOf<TServer>> = DataServerProtocol<TTransfer>
30
- > = DataSessionArgs<TServer['openModelDocument']>;
60
+ > = Pick<OpenModelArgs, 'uri' | 'options'>;
61
+
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']>;
31
67
 
32
68
  /** Close a document through a session; the session supplies `clientId`. */
33
69
  export type DataSessionCloseArgs<
@@ -41,6 +77,12 @@ export type DataSessionUpdateArgs<
41
77
  TServer extends DataServerProtocol<TTransfer, DiagnosticOf<TServer>> = DataServerProtocol<TTransfer>
42
78
  > = DataSessionArgs<TServer['updateModelDocument']>;
43
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
+
44
86
  /** Persist a document through a session; the session supplies `clientId`. */
45
87
  export type DataSessionSaveArgs<
46
88
  TTransfer extends TransferElement,
@@ -53,21 +95,6 @@ export type DataSessionDocument<
53
95
  TServer extends DataServerProtocol<TTransfer, DiagnosticOf<TServer>> = DataServerProtocol<TTransfer>
54
96
  > = TransferDocument<TTransfer, DiagnosticOf<TServer>>;
55
97
 
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;
69
- }
70
-
71
98
  /**
72
99
  * What a {@link DataSession} needs from the connection that minted it.
73
100
  *
@@ -75,36 +102,47 @@ export interface OpeningDocument {
75
102
  * `DataConnection` constructs sessions, and nothing here imports it back.
76
103
  */
77
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. */
78
106
  connected(): Promise<RpcProxy<TServer>>;
79
107
  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;
108
+ /** Surface a failure no caller is waiting on, such as restoring a document after a reconnect. */
109
+ reportError?(error: unknown, reported: ResolvedMessage): void;
94
110
  }
95
111
 
96
112
  /**
97
- * One participant on a data connection: a properties panel, a tree, a
98
- * form editor.
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}.
99
127
  *
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.
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.
104
131
  *
105
132
  * Every document operation stamps {@link clientId} itself. A caller that
106
133
  * passed its own could pass another participant's, and the server would
107
- * attribute the write and release the hold accordingly.
134
+ * attribute the write and close the document accordingly.
135
+ *
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.
140
+ *
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.
108
146
  *
109
147
  * Generic over the transfer root so this file names no grammar.
110
148
  *
@@ -119,41 +157,74 @@ export class DataSession<
119
157
  TTransfer extends TransferElement,
120
158
  TServer extends DataServerProtocol<TTransfer, DiagnosticOf<TServer>> = DataServerProtocol<TTransfer>
121
159
  > {
122
- /** URIs this session holds open, so {@link dispose} can release exactly those. */
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. */
123
168
  protected readonly openUris = new Set<string>();
124
169
  /**
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.
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.
131
173
  */
132
- protected readonly openingUris = new Map<string, OpeningDocument>();
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>;
133
192
  protected disposed = false;
134
193
  /**
135
194
  * 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.
195
+ * be sent. Folding it into {@link disposed} would send the session's close
196
+ * over a connection that is going away.
138
197
  */
139
198
  protected detached = false;
140
199
 
141
200
  constructor(
142
201
  readonly clientId: string,
143
- protected readonly host: DataSessionHost<TTransfer, TServer>
202
+ protected readonly host: DataSessionHost<TTransfer, TServer>,
203
+ readonly label: string
144
204
  ) {}
145
205
 
146
206
  /**
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.
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.
150
211
  */
151
212
  async connected(): Promise<RpcProxy<TServer>> {
152
213
  // `async` so a disposed session REJECTS rather than throwing
153
214
  // synchronously: the connection's own `connected` rejects, and a caller
154
215
  // reaching for `.catch` on one of them would not catch the other.
155
216
  this.assertLive();
156
- return this.host.connected();
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);
225
+ }
226
+ await this.registration;
227
+ return server;
157
228
  }
158
229
 
159
230
  /**
@@ -166,138 +237,125 @@ export class DataSession<
166
237
  * baseline, and the first phase event after the open arrives as a spurious
167
238
  * `'changed'` — which a widget that resets its in-memory root to the server
168
239
  * view misreads as a concurrent third-party write, losing whatever the user
169
- * had typed. Nothing about the wrong order fails loudly, so it is encoded
170
- * here rather than documented and re-derived.
240
+ * had typed.
171
241
  *
172
242
  * Note that the returned snapshot's empty `diagnostics` does not mean
173
243
  * valid: `open` settles at the integrity landmark, not at validation.
174
244
  * Validity arrives asynchronously on `onDocumentUpdated`, or synchronously
175
245
  * 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.
194
246
  */
195
- async openDocument(args: DataSessionOpenArgs<TTransfer, TServer>): Promise<DataSessionDocument<TTransfer, TServer>> {
196
- const server = await this.connected();
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
- }
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
+ });
227
252
  }
228
253
 
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;
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
+ });
235
264
  }
236
265
 
237
266
  /**
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.
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.
245
270
  */
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;
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;
261
281
  }
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
- });
282
+ this.openUris.add(uri);
283
+ return document;
274
284
  }
275
285
 
276
286
  /**
277
- * Close `args.uri`. The server unwatches implicitly, so this is the dual of
278
- * {@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.
279
290
  */
280
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);
281
299
  const server = await this.connected();
282
300
  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
301
  }
290
302
 
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 });
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
+ }
295
322
  }
296
323
 
297
- /** Persist `args.model` to disk as this session. */
298
- async saveDocument(args: DataSessionSaveArgs<TTransfer, TServer>): Promise<DataSessionDocument<TTransfer, TServer>> {
299
- const server = await this.connected();
300
- return server.saveModelDocument({ ...args, clientId: this.clientId });
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
+ });
301
359
  }
302
360
 
303
361
  /**
@@ -312,41 +370,154 @@ export class DataSession<
312
370
  }
313
371
 
314
372
  /**
315
- * Release this session's holds and detach it from the connection.
316
- * Idempotent, and leaves the connection usable by its other sessions.
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.
317
377
  *
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.
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.
322
381
  */
323
382
  dispose(): void {
324
383
  if (this.disposed) {
325
384
  return;
326
385
  }
327
386
  this.disposed = true;
328
- const uris = [...this.openUris];
329
- this.openUris.clear();
330
387
  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);
336
- }
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);
337
398
  }
338
399
 
339
400
  /**
340
401
  * Come off the connection because it is going away.
341
402
  *
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
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
344
405
  * connection being disposed.
345
406
  */
346
407
  detach(): void {
347
408
  this.disposed = true;
348
409
  this.detached = true;
349
410
  this.openUris.clear();
411
+ this.unsavedWrites.clear();
412
+ }
413
+
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);
423
+ }
424
+ }
425
+
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);
434
+ }
435
+ }
436
+
437
+ /**
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.
455
+ */
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) {
510
+ return;
511
+ }
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
+ }
350
521
  }
351
522
 
352
523
  protected assertLive(): void {