@hydranium/protocol 1.0.0-next.14 → 1.0.0-next.140

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