@hydranium/protocol 1.0.0-next.19 → 1.0.0-next.193

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 (205) hide show
  1. package/README.md +35 -1
  2. package/lib/abstract-logger.d.ts.map +1 -1
  3. package/lib/abstract-logger.js.map +1 -1
  4. package/lib/client/data-connection.d.ts +157 -0
  5. package/lib/client/data-connection.d.ts.map +1 -0
  6. package/lib/client/data-connection.js +236 -0
  7. package/lib/client/data-connection.js.map +1 -0
  8. package/lib/client/data-events.d.ts +13 -1
  9. package/lib/client/data-events.d.ts.map +1 -1
  10. package/lib/client/data-events.js +21 -0
  11. package/lib/client/data-events.js.map +1 -1
  12. package/lib/client/data-port.d.ts +24 -22
  13. package/lib/client/data-port.d.ts.map +1 -1
  14. package/lib/client/data-session.d.ts +471 -81
  15. package/lib/client/data-session.d.ts.map +1 -1
  16. package/lib/client/data-session.js +737 -108
  17. package/lib/client/data-session.js.map +1 -1
  18. package/lib/client/index.d.ts +14 -9
  19. package/lib/client/index.d.ts.map +1 -1
  20. package/lib/client/index.js +14 -9
  21. package/lib/client/index.js.map +1 -1
  22. package/lib/client/message-relay.d.ts +9 -3
  23. package/lib/client/message-relay.d.ts.map +1 -1
  24. package/lib/client/message-relay.js +11 -5
  25. package/lib/client/message-relay.js.map +1 -1
  26. package/lib/client/post-message-transport.d.ts +64 -3
  27. package/lib/client/post-message-transport.d.ts.map +1 -1
  28. package/lib/client/post-message-transport.js +175 -1
  29. package/lib/client/post-message-transport.js.map +1 -1
  30. package/lib/client/rpc-connection.d.ts +149 -0
  31. package/lib/client/rpc-connection.d.ts.map +1 -0
  32. package/lib/client/rpc-connection.js +202 -0
  33. package/lib/client/rpc-connection.js.map +1 -0
  34. package/lib/client-ids.d.ts +45 -0
  35. package/lib/client-ids.d.ts.map +1 -0
  36. package/lib/client-ids.js +48 -0
  37. package/lib/client-ids.js.map +1 -0
  38. package/lib/clock.d.ts +38 -0
  39. package/lib/clock.d.ts.map +1 -1
  40. package/lib/clock.js +36 -1
  41. package/lib/clock.js.map +1 -1
  42. package/lib/data/data-protocol-methods.d.ts +4 -4
  43. package/lib/data/data-protocol-methods.d.ts.map +1 -1
  44. package/lib/data/data-protocol-methods.js +12 -1
  45. package/lib/data/data-protocol-methods.js.map +1 -1
  46. package/lib/data/data-server-protocol.d.ts +131 -41
  47. package/lib/data/data-server-protocol.d.ts.map +1 -1
  48. package/lib/data/events.d.ts +117 -21
  49. package/lib/data/events.d.ts.map +1 -1
  50. package/lib/data/requests.d.ts +69 -11
  51. package/lib/data/requests.d.ts.map +1 -1
  52. package/lib/debouncer.d.ts.map +1 -1
  53. package/lib/debouncer.js.map +1 -1
  54. package/lib/errors.d.ts +181 -29
  55. package/lib/errors.d.ts.map +1 -1
  56. package/lib/errors.js +261 -29
  57. package/lib/errors.js.map +1 -1
  58. package/lib/glsp-save-model-actions.d.ts +50 -0
  59. package/lib/glsp-save-model-actions.d.ts.map +1 -0
  60. package/lib/glsp-save-model-actions.js +28 -0
  61. package/lib/glsp-save-model-actions.js.map +1 -0
  62. package/lib/index.d.ts +4 -0
  63. package/lib/index.d.ts.map +1 -1
  64. package/lib/index.js +7 -0
  65. package/lib/index.js.map +1 -1
  66. package/lib/latency-collector.d.ts +8 -4
  67. package/lib/latency-collector.d.ts.map +1 -1
  68. package/lib/latency-collector.js.map +1 -1
  69. package/lib/logger.d.ts +22 -1
  70. package/lib/logger.d.ts.map +1 -1
  71. package/lib/logger.js +31 -3
  72. package/lib/logger.js.map +1 -1
  73. package/lib/messages/index.d.ts +29 -0
  74. package/lib/messages/index.d.ts.map +1 -0
  75. package/lib/messages/index.js +59 -0
  76. package/lib/messages/index.js.map +1 -0
  77. package/lib/messages/primitives.d.ts +188 -0
  78. package/lib/messages/primitives.d.ts.map +1 -0
  79. package/lib/messages/primitives.js +161 -0
  80. package/lib/messages/primitives.js.map +1 -0
  81. package/lib/model-server.d.ts +60 -13
  82. package/lib/model-server.d.ts.map +1 -1
  83. package/lib/model-server.js +4 -2
  84. package/lib/model-server.js.map +1 -1
  85. package/lib/model-service/base-version.d.ts +64 -0
  86. package/lib/model-service/base-version.d.ts.map +1 -0
  87. package/lib/model-service/base-version.js +43 -0
  88. package/lib/model-service/base-version.js.map +1 -0
  89. package/lib/model-service/index.d.ts +1 -1
  90. package/lib/model-service/index.d.ts.map +1 -1
  91. package/lib/model-service/index.js +4 -5
  92. package/lib/model-service/index.js.map +1 -1
  93. package/lib/model-service/reference-candidate.d.ts +5 -3
  94. package/lib/model-service/reference-candidate.d.ts.map +1 -1
  95. package/lib/noop-logger.d.ts.map +1 -1
  96. package/lib/noop-logger.js.map +1 -1
  97. package/lib/observable-value.js.map +1 -1
  98. package/lib/patch-merge.d.ts +35 -32
  99. package/lib/patch-merge.d.ts.map +1 -1
  100. package/lib/patch-merge.js +67 -23
  101. package/lib/patch-merge.js.map +1 -1
  102. package/lib/profile-session.d.ts +8 -4
  103. package/lib/profile-session.d.ts.map +1 -1
  104. package/lib/profile-session.js.map +1 -1
  105. package/lib/reconcile-write.d.ts +65 -0
  106. package/lib/reconcile-write.d.ts.map +1 -0
  107. package/lib/reconcile-write.js +67 -0
  108. package/lib/reconcile-write.js.map +1 -0
  109. package/lib/rpc/bind-rpc-methods.d.ts +29 -3
  110. package/lib/rpc/bind-rpc-methods.d.ts.map +1 -1
  111. package/lib/rpc/bind-rpc-methods.js +22 -3
  112. package/lib/rpc/bind-rpc-methods.js.map +1 -1
  113. package/lib/rpc/create-rpc-proxy.d.ts +10 -0
  114. package/lib/rpc/create-rpc-proxy.d.ts.map +1 -1
  115. package/lib/rpc/create-rpc-proxy.js +12 -2
  116. package/lib/rpc/create-rpc-proxy.js.map +1 -1
  117. package/lib/rpc/wire-prefix.js.map +1 -1
  118. package/lib/testing/catalogue-audit.d.ts +80 -0
  119. package/lib/testing/catalogue-audit.d.ts.map +1 -0
  120. package/lib/testing/catalogue-audit.js +94 -0
  121. package/lib/testing/catalogue-audit.js.map +1 -0
  122. package/lib/testing/data-doubles.d.ts +13 -12
  123. package/lib/testing/data-doubles.d.ts.map +1 -1
  124. package/lib/testing/data-doubles.js +19 -5
  125. package/lib/testing/data-doubles.js.map +1 -1
  126. package/lib/testing/fake-clock.d.ts +9 -1
  127. package/lib/testing/fake-clock.d.ts.map +1 -1
  128. package/lib/testing/fake-clock.js +54 -45
  129. package/lib/testing/fake-clock.js.map +1 -1
  130. package/lib/testing/index.d.ts +1 -0
  131. package/lib/testing/index.d.ts.map +1 -1
  132. package/lib/testing/index.js +5 -2
  133. package/lib/testing/index.js.map +1 -1
  134. package/lib/testing/node/duplex-connection.js.map +1 -1
  135. package/lib/testing/node/duplex-stream.js.map +1 -1
  136. package/lib/testing/node/index.d.ts +1 -0
  137. package/lib/testing/node/index.d.ts.map +1 -1
  138. package/lib/testing/node/index.js +2 -2
  139. package/lib/testing/node/index.js.map +1 -1
  140. package/lib/testing/node/message-port-pair.d.ts +25 -0
  141. package/lib/testing/node/message-port-pair.d.ts.map +1 -0
  142. package/lib/testing/node/message-port-pair.js +26 -0
  143. package/lib/testing/node/message-port-pair.js.map +1 -0
  144. package/lib/testing/wait-for.js.map +1 -1
  145. package/lib/tracer.d.ts.map +1 -1
  146. package/lib/tracer.js.map +1 -1
  147. package/lib/transfer-diagnostic.d.ts +33 -0
  148. package/lib/transfer-diagnostic.d.ts.map +1 -1
  149. package/lib/transfer-diagnostic.js +23 -0
  150. package/lib/transfer-diagnostic.js.map +1 -1
  151. package/lib/transfer-document.d.ts +70 -32
  152. package/lib/transfer-document.d.ts.map +1 -1
  153. package/lib/transfer-document.js +17 -9
  154. package/lib/transfer-document.js.map +1 -1
  155. package/lib/uri.d.ts.map +1 -1
  156. package/lib/uri.js.map +1 -1
  157. package/lib/util.d.ts +8 -0
  158. package/lib/util.d.ts.map +1 -1
  159. package/lib/util.js +32 -0
  160. package/lib/util.js.map +1 -1
  161. package/package.json +27 -18
  162. package/src/client/data-connection.ts +314 -0
  163. package/src/client/data-events.ts +33 -1
  164. package/src/client/data-port.ts +25 -23
  165. package/src/client/data-session.ts +945 -126
  166. package/src/client/index.ts +14 -9
  167. package/src/client/message-relay.ts +29 -7
  168. package/src/client/post-message-transport.ts +219 -4
  169. package/src/client/rpc-connection.ts +268 -0
  170. package/src/client-ids.ts +49 -0
  171. package/src/clock.ts +56 -0
  172. package/src/data/data-protocol-methods.ts +13 -4
  173. package/src/data/data-server-protocol.ts +156 -41
  174. package/src/data/events.ts +123 -21
  175. package/src/data/requests.ts +74 -11
  176. package/src/errors.ts +311 -36
  177. package/src/glsp-save-model-actions.ts +59 -0
  178. package/src/index.ts +7 -0
  179. package/src/latency-collector.ts +8 -3
  180. package/src/logger.ts +28 -2
  181. package/src/messages/index.ts +36 -0
  182. package/src/messages/primitives.ts +271 -0
  183. package/src/model-server.ts +63 -18
  184. package/src/model-service/base-version.ts +72 -0
  185. package/src/model-service/index.ts +4 -5
  186. package/src/model-service/reference-candidate.ts +5 -3
  187. package/src/patch-merge.ts +97 -42
  188. package/src/profile-session.ts +9 -4
  189. package/src/reconcile-write.ts +124 -0
  190. package/src/rpc/bind-rpc-methods.ts +49 -4
  191. package/src/rpc/create-rpc-proxy.ts +20 -2
  192. package/src/testing/catalogue-audit.ts +111 -0
  193. package/src/testing/data-doubles.ts +42 -17
  194. package/src/testing/fake-clock.ts +62 -47
  195. package/src/testing/index.ts +5 -2
  196. package/src/testing/node/index.ts +2 -2
  197. package/src/testing/node/message-port-pair.ts +40 -0
  198. package/src/transfer-diagnostic.ts +40 -0
  199. package/src/transfer-document.ts +87 -34
  200. package/src/util.ts +33 -0
  201. package/lib/model-service/args.d.ts +0 -64
  202. package/lib/model-service/args.d.ts.map +0 -1
  203. package/lib/model-service/args.js +0 -11
  204. package/lib/model-service/args.js.map +0 -1
  205. package/src/model-service/args.ts +0 -67
@@ -7,106 +7,354 @@
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';
13
- import type { TransferDocument } from '../transfer-document';
10
+ import { type Disposable, Emitter, type Event } from 'vscode-jsonrpc';
11
+ import { type Clock, SystemClock } from '../clock';
12
+ import type { DataServerProtocol, DiagnosticOf, TransferDocumentDirtyChangedEvent, TransferDocumentUpdatedEvent } from '../data';
13
+ import { isConflictError, SessionClosedError } from '../errors';
14
+ import { type BaseVersion, isModelVersion, type ModelVersion, type TextVersion, UNRECORDED_VERSION } from '../model-service/base-version';
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';
19
+ import type { TextState, TransferDocument, TransferSavedDocument } 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, and forgot it; or could not write it again for another reason than
25
+ * a conflict, and keeps its unsaved edits for the next restore.
26
+ */
27
+ export const DATA_SESSION_RESTORE_FAILED = defineMessage(
28
+ 'hydranium/protocol/data-session-restore-failed',
29
+ 'Could not restore {uri} after reconnecting to the data server: {detail}'
30
+ );
31
+
32
+ /** A write or open of `{uri}` that the data server answered without a model. */
33
+ export const DATA_SESSION_ANSWER_WITHOUT_MODEL = defineMessage(
34
+ 'hydranium/protocol/data-session-answer-without-model',
35
+ 'The data server answered a write of {uri} without a model; the session counts that answer as older than every version.'
36
+ );
37
+
38
+ /**
39
+ * A session re-opened documents after its connection dropped and cannot put
40
+ * back what it wrote to them since their last save: another client changed
41
+ * them, even while the session was still connected; the session could not
42
+ * tell the text its writes started from, or lost another document written with
43
+ * them; or the write it sent again conflicted. The session's unsaved edits may
44
+ * be gone, and it no longer holds them.
45
+ */
46
+ export const DATA_SESSION_UNSAVED_LOST = defineMessage(
47
+ 'hydranium/protocol/data-session-unsaved-lost',
48
+ 'Unsaved changes to {uris} may have been lost when the connection to the data server dropped.'
49
+ );
50
+
51
+ /**
52
+ * What one of `TServer`'s document methods takes, minus the `clientId` a
53
+ * {@link DataSession} stamps itself.
54
+ *
55
+ * Read off the SERVER's signature, not off the framework's own arg type: an
56
+ * adopter server widens these, and a wrapper declared against the narrow
57
+ * shape rejects the extra field on a fresh object literal, so that call
58
+ * cannot go through a session at all.
59
+ */
60
+ export type DataSessionArgs<TMethod extends (args: never) => unknown> = Omit<Parameters<TMethod>[0], 'clientId'>;
61
+
62
+ /**
63
+ * Open a document through a session; the session supplies `clientId`. Only the
64
+ * URI and the open's options: a session's open reads the file, and the server
65
+ * ignores the `languageId`, `version` and `text` seeds of `OpenModelArgs`, so
66
+ * accepting them here would let a caller believe they took effect.
67
+ */
68
+ export type DataSessionOpenArgs<
69
+ TTransfer extends TransferElement,
70
+ // oxlint-disable-next-line no-unused-vars -- TServer validates its own diagnostic constraint; Oxlint does not count that use.
71
+ TServer extends DataServerProtocol<TTransfer, DiagnosticOf<TServer>> = DataServerProtocol<TTransfer>
72
+ > = Pick<OpenModelArgs, 'uri' | 'options'>;
73
+
74
+ /** Create a document through a session; the session supplies `clientId`. */
75
+ export type DataSessionCreateArgs<
76
+ TTransfer extends TransferElement,
77
+ TServer extends DataServerProtocol<TTransfer, DiagnosticOf<TServer>> = DataServerProtocol<TTransfer>
78
+ > = DataSessionArgs<TServer['createModelDocument']>;
79
+
80
+ /** Close a document through a session; the session supplies `clientId`. */
81
+ export type DataSessionCloseArgs<
82
+ TTransfer extends TransferElement,
83
+ TServer extends DataServerProtocol<TTransfer, DiagnosticOf<TServer>> = DataServerProtocol<TTransfer>
84
+ > = DataSessionArgs<TServer['closeModelDocument']>;
85
+
86
+ /** Update a document through a session; the session supplies `clientId`. */
87
+ export type DataSessionUpdateArgs<
88
+ TTransfer extends TransferElement,
89
+ TServer extends DataServerProtocol<TTransfer, DiagnosticOf<TServer>> = DataServerProtocol<TTransfer>
90
+ > = DataSessionArgs<TServer['updateModelDocument']>;
91
+
92
+ /** Update several documents at once through a session; the session supplies `clientId`. */
93
+ export type DataSessionUpdatesArgs<
94
+ TTransfer extends TransferElement,
95
+ TServer extends DataServerProtocol<TTransfer, DiagnosticOf<TServer>> = DataServerProtocol<TTransfer>
96
+ > = DataSessionArgs<TServer['updateModelDocuments']>;
97
+
98
+ /** Persist a document through a session; the session supplies `clientId`. */
99
+ export type DataSessionSaveArgs<
100
+ TTransfer extends TransferElement,
101
+ TServer extends DataServerProtocol<TTransfer, DiagnosticOf<TServer>> = DataServerProtocol<TTransfer>
102
+ > = DataSessionArgs<TServer['saveModelDocument']>;
103
+
104
+ /** Persist the text the server holds through a session; the session supplies `clientId`. */
105
+ export type DataSessionPersistArgs<
106
+ TTransfer extends TransferElement,
107
+ TServer extends DataServerProtocol<TTransfer, DiagnosticOf<TServer>> = DataServerProtocol<TTransfer>
108
+ > = DataSessionArgs<TServer['persistModelDocument']>;
109
+
110
+ /** The document a session hands back, carrying its server's diagnostic shape. */
111
+ export type DataSessionDocument<
112
+ TTransfer extends TransferElement,
113
+ TServer extends DataServerProtocol<TTransfer, DiagnosticOf<TServer>> = DataServerProtocol<TTransfer>
114
+ > = TransferDocument<TTransfer, DiagnosticOf<TServer>>;
115
+
116
+ /**
117
+ * What a {@link DataSession} keeps of a URI it wrote since the URI's last save,
118
+ * to write it again after a reconnect that lost it.
119
+ */
120
+ export interface DataSessionUnsavedWrite<
121
+ TTransfer extends TransferElement,
122
+ TServer extends DataServerProtocol<TTransfer, DiagnosticOf<TServer>> = DataServerProtocol<TTransfer>
123
+ > {
19
124
  /**
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.
125
+ * The `text.hash` of the text the first of these writes was based on.
126
+ * `undefined` when the session could not tell, for a write based on
127
+ * `'any'` or on a version it could not read back, and such a write is
128
+ * never sent again: the session cannot tell another client's text from the
129
+ * text it wrote over.
25
130
  */
26
- readonly methodNamespace?: string;
131
+ readonly baseHash: string | undefined;
132
+ /**
133
+ * The model version the last of these writes was answered with, which
134
+ * orders its answers, and the `text.hash` of that answer.
135
+ */
136
+ readonly answer: { readonly version: ModelVersion; readonly hash?: string };
137
+ /**
138
+ * The call that made the last write, and for an `updateDocuments` call this
139
+ * URI's index in it. Records whose `updates` is the same object were
140
+ * written together and are sent again together, so a restore never applies
141
+ * part of a set.
142
+ */
143
+ readonly call:
144
+ | { readonly update: DataSessionUpdateArgs<TTransfer, TServer> }
145
+ | { readonly updates: DataSessionUpdatesArgs<TTransfer, TServer>; readonly index: number };
27
146
  }
28
147
 
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>;
148
+ /** Where `write` stands in the `updateDocuments` call it was last written by; `0` for a single update. */
149
+ function indexOf(write: DataSessionUnsavedWrite<TransferElement, DataServerProtocol<TransferElement>>): number {
150
+ return 'index' in write.call ? write.call.index : 0;
35
151
  }
36
152
 
37
153
  /**
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.
154
+ * What a {@link DataSession} needs from the connection that minted it.
41
155
  *
42
- * Three jobs, and deliberately no fourth:
156
+ * Narrower than the connection itself so the dependency points one way:
157
+ * `DataConnection` constructs sessions, and nothing here imports it back.
158
+ */
159
+ export interface DataSessionHost<TTransfer extends TransferElement, TServer extends DataServerProtocol<TTransfer, DiagnosticOf<TServer>>> {
160
+ /** The connected, READY proxy of the current connection; a new object after each reconnect. */
161
+ connected(): Promise<RpcProxy<TServer>>;
162
+ /** Surface a failure no caller is waiting on, such as restoring a document after a reconnect. */
163
+ reportError?(error: unknown, reported: ResolvedMessage): void;
164
+ /**
165
+ * Tell the connection's client the dirty state a restore read, unless it
166
+ * is what the client was last told of the URI since the URI's last open.
167
+ */
168
+ restoreDirty?(event: TransferDocumentDirtyChangedEvent): void;
169
+ /**
170
+ * Forget what the client was told of `uri`'s dirty state: an open just
171
+ * made answered its caller afresh, and the client heard none of it, or a
172
+ * close leaves nothing to restore. Forgetting a URI another session still
173
+ * has open costs at most one repeat of a state the client already has.
174
+ */
175
+ forgetDirty?(uri: string): void;
176
+ /**
177
+ * Fires with each flip of a document's dirty state the server sends. A
178
+ * session drops the unsaved write it keeps of a document that turns
179
+ * clean; without this event it keeps it, and a restore after another
180
+ * client's save of the document can report the write lost.
181
+ */
182
+ readonly onDidChangeDirty?: Event<TransferDocumentDirtyChangedEvent>;
183
+ /**
184
+ * Fires with each update event the server sends. A session drops the
185
+ * unsaved write it keeps of a document another client wrote over; without
186
+ * this event it keeps it, and a restore reports the write lost.
187
+ */
188
+ readonly onDidUpdateDocument?: Event<TransferDocumentUpdatedEvent<TTransfer, DiagnosticOf<TServer>>>;
189
+ }
190
+
191
+ /**
192
+ * Builds the session `DataConnection.createSession` hands out, for an adopter
193
+ * that extends {@link DataSession}. The connection has minted `clientId` and
194
+ * checked it by then.
195
+ */
196
+ export type DataSessionFactory<TTransfer extends TransferElement, TServer extends DataServerProtocol<TTransfer, DiagnosticOf<TServer>>> = (
197
+ clientId: string,
198
+ host: DataSessionHost<TTransfer, TServer>,
199
+ label: string
200
+ ) => DataSession<TTransfer, TServer>;
201
+
202
+ /**
203
+ * One participant on a data connection: a properties panel, a tree, a form
204
+ * editor. The client side of a server client session, registered over the
205
+ * wire under {@link clientId}.
206
+ *
207
+ * The session writes only what it has open: the server refuses its update or
208
+ * save of a document it has not opened with a `DocumentNotOpenError` code.
209
+ * Every call waits for the registration, so the first can be issued at once.
210
+ *
211
+ * Every document operation stamps {@link clientId} itself. A caller that
212
+ * passed its own could pass another participant's, and the server would
213
+ * attribute the write and close the document accordingly.
214
+ *
215
+ * {@link closeDocument} and {@link dispose} first wait, up to
216
+ * {@link settleBeforeCloseMs}, for this session's calls still in flight on the
217
+ * URI, or on any URI for `dispose`: a save sent just before its close would
218
+ * otherwise reach the server after it, and fail as not open.
43
219
  *
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.
220
+ * After the connection drops, the session registers again under the same id,
221
+ * re-opens and re-watches what it had open, tells the client of their dirty
222
+ * state where it changed, and reports the documents whose unsaved edits did
223
+ * not survive; see {@link restore}. The connection does this at
224
+ * once for a session with documents open, and any session's next call does it
225
+ * too.
53
226
  *
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.
227
+ * Generic over the transfer root so this file names no grammar.
58
228
  *
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.
229
+ * `TServer` is bound to a server answering with ITS OWN diagnostic shape, read
230
+ * back off the parameter being bound. Simplifying that to
231
+ * `DataServerProtocol<TTransfer>` compiles and costs the wrappers their
232
+ * return type: every call through `TServer` would resolve against that looser
233
+ * bound, so an adopter's diagnostics would come back as the framework's and
234
+ * the document would have to be cast on the way out.
62
235
  */
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>;
236
+ export class DataSession<
237
+ TTransfer extends TransferElement,
238
+ TServer extends DataServerProtocol<TTransfer, DiagnosticOf<TServer>> = DataServerProtocol<TTransfer>
239
+ > implements Disposable {
240
+ /**
241
+ * How long {@link closeDocument} and {@link dispose} wait for this session's
242
+ * calls in flight before closing anyway. Long, because the wait only runs
243
+ * out when a call hangs, and a close sent while a save is still running
244
+ * fails that save.
245
+ */
246
+ protected readonly settleBeforeCloseMs: number = 10_000;
247
+ /**
248
+ * The clock {@link settleBeforeCloseMs} runs on. {@link DataSessionHost}
249
+ * carries no {@link Clock}, so a subclass replaces this field as it
250
+ * replaces the bound.
251
+ */
252
+ protected readonly clock: Clock = new SystemClock();
253
+ /** URIs this session has open, re-opened after a reconnect. */
254
+ protected readonly openUris = new Set<string>();
255
+ /**
256
+ * Per URI in {@link openUris}, the URI the server's last answer to its open
257
+ * or re-open named. The server keys its notifications by it, and so does
258
+ * the host's record of what its client was told.
259
+ */
260
+ protected readonly serverUris = new Map<string, string>();
261
+ /**
262
+ * Per URI, how many opens of it this session has under way. Such a URI
263
+ * counts as open for {@link withOpenDocument}, which would otherwise close
264
+ * it under the open that is still being made.
265
+ */
266
+ protected readonly openingUris = new Map<string, number>();
267
+ /** Per URI written since its last save, what {@link restore} needs to write it again. */
268
+ protected readonly unsavedWrites = new Map<string, DataSessionUnsavedWrite<TTransfer, TServer>>();
269
+ /**
270
+ * Per URI this session has open, the text of the last document one of its
271
+ * own calls was answered with, which spares the read a first unsaved write
272
+ * otherwise makes for its base; see {@link baseHashOf}.
273
+ */
274
+ protected readonly lastAnswers = new Map<string, TextState>();
275
+ /**
276
+ * Per URI this session has open, the text version its last save or persist
277
+ * of it wrote, as its answer's `persisted` says; see {@link recordWrite}.
278
+ * Not the answer's model version, which can carry a write that landed
279
+ * after the text was taken. Only those set it: an open answers at the
280
+ * version of a write still in flight as well, and that write is not saved.
281
+ */
282
+ protected readonly savedVersions = new Map<string, TextVersion>();
283
+ /** Per URI, this session's calls still in flight on it, which a close waits for. */
284
+ protected readonly inFlight = new Map<string, Set<Promise<unknown>>>();
285
+ /** This session's saves still in flight, which a host's exit waits for; see {@link hasSavesInFlight}. */
286
+ protected readonly savesInFlight = new Set<Promise<unknown>>();
287
+ protected readonly disposeEmitter = new Emitter<void>();
288
+ /**
289
+ * Fires once when the session ends, by {@link dispose} or {@link detach}, as
290
+ * soon as it rejects further calls and before any close is sent. For a
291
+ * session its connection created, the connection's listener runs first, so
292
+ * the id is free again on that connection by the time any other listener
293
+ * runs; the server still holds it until the close arrives, and refuses a new
294
+ * session under it until then.
295
+ *
296
+ * A listener subscribed once the session has ended is never called, so a
297
+ * late subscriber checks {@link isDisposed} first.
298
+ */
299
+ readonly onDidDispose: Event<void> = this.disposeEmitter.event;
300
+ /**
301
+ * Sent with every registration, so the server lets this session register
302
+ * its id again while the dropped connection's session is still live there:
303
+ * a server that has not yet noticed the drop would otherwise refuse the id
304
+ * as a duplicate until it does.
305
+ */
306
+ protected readonly resumeToken: string = globalThis.crypto.randomUUID();
307
+ /** The proxy the session is registered on; another one means the connection was replaced. */
308
+ protected registeredOn?: RpcProxy<TServer>;
309
+ protected registration?: Promise<void>;
67
310
  protected disposed = false;
68
- protected readonly portDisposeListener: { dispose(): void };
311
+ /**
312
+ * Disposed through {@link detach} rather than {@link dispose}, so nothing may
313
+ * be sent. Folding it into {@link disposed} would send the session's close
314
+ * over a connection that is going away.
315
+ */
316
+ protected detached = false;
317
+ /** The subscription to the host's `onDidChangeDirty`, disposed with the session. */
318
+ protected readonly dirtySubscription?: Disposable;
319
+ /** The subscription to the host's `onDidUpdateDocument`, disposed with the session. */
320
+ protected readonly updateSubscription?: Disposable;
69
321
 
70
322
  constructor(
71
- protected readonly port: DataPort,
72
- protected readonly client: DataClientProtocol<TTransfer>,
73
- options: DataSessionOptions = {}
323
+ readonly clientId: string,
324
+ protected readonly host: DataSessionHost<TTransfer, TServer>,
325
+ readonly label: string
74
326
  ) {
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;
327
+ this.dirtySubscription = host.onDidChangeDirty?.(event => this.forgetSavedWrite(event));
328
+ this.updateSubscription = host.onDidUpdateDocument?.(event => this.forgetSupersededWrite(event));
82
329
  }
83
330
 
84
331
  /**
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.
332
+ * The connected, READY server proxy once this session is registered on it,
333
+ * for protocol methods this session does not wrap. The proxy stamps
334
+ * nothing: pass this session's {@link clientId} to any method that carries
335
+ * one.
94
336
  */
95
- async connected(): Promise<RpcProxy<DataServerProtocol<TTransfer>>> {
96
- if (this.disposed) {
97
- throw new Error('DataSession is disposed');
337
+ async connected(): Promise<RpcProxy<TServer>> {
338
+ // `async` so a disposed session REJECTS rather than throwing
339
+ // synchronously: the connection's own `connected` rejects, and a caller
340
+ // reaching for `.catch` on one of them would not catch the other.
341
+ this.assertLive();
342
+ const server = await this.host.connected();
343
+ // Again after the wait: a session disposed meanwhile must not register,
344
+ // since its dispose found nothing registered to end.
345
+ this.assertLive();
346
+ if (this.registeredOn !== server) {
347
+ const reconnected = this.registeredOn !== undefined;
348
+ this.registeredOn = server;
349
+ this.registration = this.register(server, reconnected);
98
350
  }
99
- const generation = this.currentGeneration();
100
- if (!generation.ready) {
101
- generation.ready = this.awaitReady(generation);
102
- }
103
- await generation.ready;
104
- return generation.server;
351
+ await this.registration;
352
+ return server;
105
353
  }
106
354
 
107
355
  /**
108
- * Open `uri` for editing and start watching it, in that order, returning
109
- * the opened snapshot.
356
+ * Open `args.uri` for editing and start watching it, in that order,
357
+ * returning the opened snapshot.
110
358
  *
111
359
  * **The order is the whole reason this method exists.**
112
360
  * `watchModelDocument` baselines its dedup fingerprint from the *current*
@@ -114,32 +362,200 @@ export class DataSession<TTransfer extends TransferElement> {
114
362
  * baseline, and the first phase event after the open arrives as a spurious
115
363
  * `'changed'` — which a widget that resets its in-memory root to the server
116
364
  * 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.
365
+ * had typed.
119
366
  *
120
- * Note that the returned snapshot's empty `diagnostics` does not mean
121
- * valid: `open` settles at the integrity landmark, not at validation.
367
+ * Note that the returned snapshot's model usually has no `diagnostics`:
368
+ * `open` settles at the integrity landmark, not at validation.
122
369
  * Validity arrives asynchronously on `onDocumentUpdated`, or synchronously
123
370
  * from `getModelDocument({ includeDiagnostics: true })`.
124
371
  */
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 });
372
+ openDocument(args: DataSessionOpenArgs<TTransfer, TServer>): Promise<DataSessionDocument<TTransfer, TServer>> {
373
+ return this.trackOpen(args.uri, async () => {
374
+ const server = await this.connected();
375
+ return this.watchOpened(server, args.uri, await server.openModelDocument({ ...args, clientId: this.clientId }));
376
+ });
377
+ }
378
+
379
+ /**
380
+ * Create a document that exists nowhere yet, open and watched for this
381
+ * session; it reaches disk with the first {@link saveDocument}. The server
382
+ * refuses a URI that exists on disk or that any client has open.
383
+ */
384
+ createDocument(args: DataSessionCreateArgs<TTransfer, TServer>): Promise<DataSessionDocument<TTransfer, TServer>> {
385
+ return this.trackOpen(args.uri, async () => {
386
+ const server = await this.connected();
387
+ return this.watchOpened(server, args.uri, await server.createModelDocument({ ...args, clientId: this.clientId }));
388
+ });
389
+ }
390
+
391
+ /**
392
+ * Watch a document this session just opened, and record it as open. A
393
+ * failed watch closes it again: the caller sees a failed open and so would
394
+ * never close it.
395
+ */
396
+ protected async watchOpened(
397
+ server: RpcProxy<TServer>,
398
+ uri: string,
399
+ document: DataSessionDocument<TTransfer, TServer>
400
+ ): Promise<DataSessionDocument<TTransfer, TServer>> {
401
+ try {
402
+ await server.watchModelDocument({ uri, clientId: this.clientId });
403
+ } catch (error: unknown) {
404
+ await server.closeModelDocument({ uri, clientId: this.clientId }).catch(() => undefined);
405
+ throw error;
406
+ }
407
+ this.openUris.add(uri);
408
+ this.serverUris.set(uri, document.uri);
409
+ this.recordText(uri, document);
410
+ // Keyed as the server keys its notifications, which may not be how the
411
+ // caller spelled the URI.
412
+ this.host.forgetDirty?.(document.uri);
129
413
  return document;
130
414
  }
131
415
 
132
416
  /**
133
- * Close `uri`. The server unwatches implicitly, so this is the dual of
134
- * {@link openDocument} and needs no separate unwatch.
417
+ * Close `args.uri`, once this session's calls on it have settled or
418
+ * {@link settleBeforeCloseMs} has passed. The server unwatches implicitly,
419
+ * so this is the dual of {@link openDocument} and needs no separate unwatch.
135
420
  */
136
- async closeDocument(uri: string): Promise<void> {
421
+ async closeDocument(args: DataSessionCloseArgs<TTransfer, TServer>): Promise<void> {
422
+ this.assertLive();
423
+ await this.settle(this.inFlight.get(args.uri));
424
+ // Forgotten before the close is sent, so a reconnect in between does not
425
+ // re-open a document the caller has closed; after the wait, so an open
426
+ // of it that was still in flight does not record it again.
427
+ const serverUri = this.serverUris.get(args.uri) ?? args.uri;
428
+ this.openUris.delete(args.uri);
429
+ this.serverUris.delete(args.uri);
430
+ this.unsavedWrites.delete(args.uri);
431
+ this.lastAnswers.delete(args.uri);
432
+ this.savedVersions.delete(args.uri);
433
+ this.host.forgetDirty?.(serverUri);
137
434
  const server = await this.connected();
138
- await server.closeModelDocument({ uri, clientId: this.clientId });
435
+ await server.closeModelDocument({ ...args, clientId: this.clientId });
436
+ }
437
+
438
+ /**
439
+ * Open `args.uri`, run `fn` with the opened snapshot, and close it once
440
+ * `fn` settles, whether it returned or threw. A URI this session already
441
+ * had open, or is still opening through another call, stays open: the close
442
+ * undoes only the open this call made.
443
+ */
444
+ async withOpenDocument<T>(
445
+ args: DataSessionOpenArgs<TTransfer, TServer>,
446
+ fn: (document: DataSessionDocument<TTransfer, TServer>) => MaybePromise<T>
447
+ ): Promise<T> {
448
+ const alreadyOpen = this.openUris.has(args.uri) || this.openingUris.has(args.uri);
449
+ const document = await this.openDocument(args);
450
+ try {
451
+ return await fn(document);
452
+ } finally {
453
+ if (!alreadyOpen && !this.disposed) {
454
+ await this.closeDocument({ uri: args.uri } as DataSessionCloseArgs<TTransfer, TServer>);
455
+ }
456
+ }
457
+ }
458
+
459
+ /** Write `args.model` back as this session. The session must have `args.uri` open. */
460
+ updateDocument(args: DataSessionUpdateArgs<TTransfer, TServer>): Promise<DataSessionDocument<TTransfer, TServer>> {
461
+ return this.track([args.uri], async () => {
462
+ const server = await this.connected();
463
+ const update = { ...args };
464
+ const baseHash = await this.baseHashOf(server, args.uri, args.baseVersion);
465
+ const document = await server.updateModelDocument({ ...args, clientId: this.clientId });
466
+ this.recordWrite(args.uri, document, baseHash, { update });
467
+ return document;
468
+ });
469
+ }
470
+
471
+ /**
472
+ * Write several documents this session has open, all or none: the server
473
+ * refuses the whole set, before any text applies, when one is stale or not
474
+ * open. Resolves to the documents in the order given.
475
+ */
476
+ updateDocuments(args: DataSessionUpdatesArgs<TTransfer, TServer>): Promise<DataSessionDocument<TTransfer, TServer>[]> {
477
+ return this.track(
478
+ args.updates.map(update => update.uri),
479
+ async () => {
480
+ // One copy for the whole call: the copy's identity is what ties its
481
+ // records together.
482
+ const updates = { ...args, updates: args.updates.map(update => ({ ...update })) };
483
+ const server = await this.connected();
484
+ const baseHashes = await Promise.all(args.updates.map(update => this.baseHashOf(server, update.uri, update.baseVersion)));
485
+ const documents = await server.updateModelDocuments({ ...args, clientId: this.clientId });
486
+ args.updates.forEach((update, index) => this.recordWrite(update.uri, documents[index], baseHashes[index], { updates, index }));
487
+ return documents;
488
+ }
489
+ );
490
+ }
491
+
492
+ /** Persist `args.model` to disk as this session. The session must have `args.uri` open. */
493
+ saveDocument(args: DataSessionSaveArgs<TTransfer, TServer>): Promise<TransferSavedDocument<TTransfer, DiagnosticOf<TServer>>> {
494
+ return this.trackSave(args.uri, server => server.saveModelDocument({ ...args, clientId: this.clientId }));
495
+ }
496
+
497
+ /**
498
+ * Persist the text the server holds for `args.uri` as this session, with no
499
+ * model of its own. The session must have `args.uri` open.
500
+ */
501
+ persistDocument(args: DataSessionPersistArgs<TTransfer, TServer>): Promise<TransferSavedDocument<TTransfer, DiagnosticOf<TServer>>> {
502
+ return this.trackSave(args.uri, server => server.persistModelDocument({ ...args, clientId: this.clientId }));
503
+ }
504
+
505
+ /** Run a save or persist of `uri` and record what it answered as saved. */
506
+ protected trackSave(
507
+ uri: string,
508
+ send: (server: RpcProxy<TServer>) => Promise<TransferSavedDocument<TTransfer, DiagnosticOf<TServer>>>
509
+ ): Promise<TransferSavedDocument<TTransfer, DiagnosticOf<TServer>>> {
510
+ const saving = this.track([uri], async () => {
511
+ const server = await this.connected();
512
+ const document = await send(server);
513
+ // Kept only when its last answer is newer than the text written. Kept
514
+ // whenever it changed while the save ran, a record the save covered
515
+ // survives, and a restore then reports it lost.
516
+ const unsaved = this.unsavedWrites.get(uri);
517
+ if (unsaved && unsaved.answer.version <= document.persisted.version) {
518
+ this.unsavedWrites.delete(uri);
519
+ }
520
+ this.recordText(uri, document);
521
+ // The higher of two saves' answers, which may arrive out of order.
522
+ const saved = this.savedVersions.get(uri);
523
+ if (saved === undefined || document.persisted.version > saved) {
524
+ this.savedVersions.set(uri, document.persisted.version);
525
+ }
526
+ return document;
527
+ });
528
+ this.savesInFlight.add(saving);
529
+ const done = (): boolean => this.savesInFlight.delete(saving);
530
+ saving.then(done, done);
531
+ return saving;
532
+ }
533
+
534
+ /** Whether the session has ended, by {@link dispose} or {@link detach}. */
535
+ get isDisposed(): boolean {
536
+ return this.disposed;
537
+ }
538
+
539
+ /**
540
+ * Whether a save of this session has not answered yet. Synchronous, for a
541
+ * host whose exit veto must decide within the tick, such as Theia's
542
+ * `onWillStop`.
543
+ */
544
+ get hasSavesInFlight(): boolean {
545
+ return this.savesInFlight.size > 0;
139
546
  }
140
547
 
141
548
  /**
142
- * Whether `event.sourceClientId` identifies this session's own write.
549
+ * Resolves once the saves in flight now have answered, or
550
+ * {@link settleBeforeCloseMs} has passed. Never rejects: a failed save has
551
+ * answered too.
552
+ */
553
+ whenSavesSettled(): Promise<void> {
554
+ return this.settle(this.savesInFlight);
555
+ }
556
+
557
+ /**
558
+ * Whether `sourceClientId` identifies this session's own write.
143
559
  *
144
560
  * Every watcher needs this and the check is one comparison, so getting it
145
561
  * wrong is cheap to do and expensive to find: an unfiltered echo looks
@@ -149,61 +565,464 @@ export class DataSession<TTransfer extends TransferElement> {
149
565
  return sourceClientId === this.clientId;
150
566
  }
151
567
 
152
- /** Tear down the current connection and stop tracking the port. Idempotent. */
568
+ /**
569
+ * End the session: detach it from the connection at once, and once its
570
+ * calls in flight have settled or {@link settleBeforeCloseMs} has passed,
571
+ * end it on the server, which closes everything it has open. Idempotent,
572
+ * and leaves the connection usable by its other sessions.
573
+ *
574
+ * Every later call rejects, and so does a call made earlier in the same
575
+ * tick, which has not reached the wire yet and is never sent. The server
576
+ * close is not awaited, because a `Disposable` cannot be; a close that fails
577
+ * leaves the session to the server's connection-close cleanup.
578
+ */
153
579
  dispose(): void {
154
580
  if (this.disposed) {
155
581
  return;
156
582
  }
157
583
  this.disposed = true;
158
- this.portDisposeListener.dispose();
159
- this.dropGeneration();
160
- }
161
-
162
- /** The live generation, building one if there is none. */
163
- protected currentGeneration(): Generation<TTransfer> {
164
- if (this.generation) {
165
- return this.generation;
166
- }
167
- const connection = this.port.connect();
168
- // Rejection is reported here rather than left to float: an unhandled
169
- // rejection on a connection promise is the failure mode that reads as
170
- // "the model is empty" instead of "the transport never opened".
171
- connection.catch((error: unknown) => this.port.reportError(error, 'connecting to the data server'));
172
- const server = createRpcProxy<DataServerProtocol<TTransfer>, DataClientProtocol<TTransfer>>(connection, {
173
- methodNamespace: this.methodNamespace,
174
- localTarget: this.client,
175
- localMethods: DATA_CLIENT_PROTOCOL_METHODS
176
- });
177
- this.generation = { connection, server };
178
- return this.generation;
584
+ this.fireDispose();
585
+ const pending = [...this.inFlight.values()].flatMap(calls => [...calls]);
586
+ void (async () => {
587
+ await this.settle(pending);
588
+ await this.registration;
589
+ // The proxy the session registered on, never a fresh connection: a
590
+ // connection that dropped already ended the session on the server.
591
+ if (!this.detached && this.registeredOn) {
592
+ await this.registeredOn.closeSession({ clientId: this.clientId });
593
+ }
594
+ })().catch(() => undefined);
595
+ }
596
+
597
+ /**
598
+ * Come off the connection because it is going away.
599
+ *
600
+ * Sends nothing, unlike {@link dispose}: the server ends every session on a
601
+ * connection it sees close, and the close would travel over the very
602
+ * connection being disposed.
603
+ *
604
+ * Public because the connection calls it; anyone else ends a session with
605
+ * {@link dispose}. It fires {@link onDidDispose} only if the session has not
606
+ * already ended, and after {@link dispose} it still cancels the close that
607
+ * dispose has not sent yet.
608
+ */
609
+ detach(): void {
610
+ this.detached = true;
611
+ this.openUris.clear();
612
+ this.serverUris.clear();
613
+ this.unsavedWrites.clear();
614
+ this.lastAnswers.clear();
615
+ this.savedVersions.clear();
616
+ if (!this.disposed) {
617
+ this.disposed = true;
618
+ this.fireDispose();
619
+ }
620
+ }
621
+
622
+ /**
623
+ * Dispose {@link dirtySubscription} and {@link updateSubscription}, fire
624
+ * {@link onDidDispose} and dispose its emitter, so a second call fires
625
+ * nothing.
626
+ */
627
+ protected fireDispose(): void {
628
+ this.dirtySubscription?.dispose();
629
+ this.updateSubscription?.dispose();
630
+ this.disposeEmitter.fire(undefined);
631
+ this.disposeEmitter.dispose();
632
+ }
633
+
634
+ /**
635
+ * Register again and restore now, after the connection dropped, instead of
636
+ * on the next call. A no-op for a session with nothing open, which the next
637
+ * call restores anyway. A failure is left to that next call, which meets it
638
+ * again.
639
+ */
640
+ reconnect(): void {
641
+ if (!this.disposed && this.openUris.size > 0) {
642
+ this.connected().catch(() => undefined);
643
+ }
644
+ }
645
+
646
+ /**
647
+ * Drop the record in {@link unsavedWrites} of a document this session has
648
+ * open once the server says it turned clean: it holds no unsaved text
649
+ * then, and a record kept would have a restore report the write lost once
650
+ * another client's save changed the file.
651
+ *
652
+ * The server sends a flip only for a document someone watches, so a
653
+ * document the session writes without watching it keeps its record, and
654
+ * can still be reported lost that way.
655
+ */
656
+ protected forgetSavedWrite(event: TransferDocumentDirtyChangedEvent): void {
657
+ if (event.text?.dirty) {
658
+ return;
659
+ }
660
+ // The flip names the server's key, which is not always the caller's
661
+ // spelling that the records are kept under.
662
+ for (const [uri, serverUri] of this.serverUris) {
663
+ if (serverUri === event.uri) {
664
+ this.unsavedWrites.delete(uri);
665
+ }
666
+ }
667
+ }
668
+
669
+ /**
670
+ * Drop the record in {@link unsavedWrites} of a document another client
671
+ * wrote over while the connection held: its write replaced the session's,
672
+ * so a restore has nothing of the session's to put back, and a record kept
673
+ * would have it report the write lost to the reconnect. A write superseded
674
+ * before its answer needs nothing: the answer names the other client's
675
+ * text, which the record then holds.
676
+ *
677
+ * Only a `'changed'` event from another client counts, and only where the
678
+ * document no longer holds the write: the session's own echo, and an
679
+ * integrity repair already in the write's answer, replaced nothing, and a
680
+ * `'rebuilt'` event carries no new text. Like {@link forgetSavedWrite}, it
681
+ * depends on the server sending the event, which it does only for a
682
+ * document someone watches.
683
+ */
684
+ protected forgetSupersededWrite(event: TransferDocumentUpdatedEvent<TTransfer, DiagnosticOf<TServer>>): void {
685
+ if (event.reason !== 'changed' || this.isOwnEcho(event.sourceClientId)) {
686
+ return;
687
+ }
688
+ for (const [uri, serverUri] of this.serverUris) {
689
+ const write = this.unsavedWrites.get(uri);
690
+ if (serverUri === event.document.uri && write && this.restoreOutcome(write, event.document) !== 'kept') {
691
+ this.unsavedWrites.delete(uri);
692
+ }
693
+ }
694
+ }
695
+
696
+ /**
697
+ * Register on `server`, and after a reconnect restore what the ended session
698
+ * had. Calls issued meanwhile wait for this.
699
+ */
700
+ protected async register(server: RpcProxy<TServer>, reconnected: boolean): Promise<void> {
701
+ await server.createSession({ clientId: this.clientId, label: this.label, resumeToken: this.resumeToken });
702
+ if (reconnected) {
703
+ await this.restore(server);
704
+ }
705
+ }
706
+
707
+ /**
708
+ * Re-open and re-watch every document the session had open, write again
709
+ * what it wrote since their last save where the re-open lost it, and tell
710
+ * the host which of them lost it for good.
711
+ *
712
+ * Decided per document by the re-opened document's `text.hash`,
713
+ * in {@link restoreOutcome}. Versions cannot decide a write: a revert moves
714
+ * the version on and a restarted server numbers afresh, so the version the
715
+ * last write was answered with never matches where a write is needed, and
716
+ * any other version may be another client's edit, which a write would
717
+ * overwrite.
718
+ *
719
+ * Only what the drop cost is reported: a write another client wrote over
720
+ * while the connection held has no record left by then, see
721
+ * {@link forgetSupersededWrite}.
722
+ *
723
+ * A write is sent again based on the re-opened version, as an ordinary
724
+ * write, so an edit arriving in between conflicts, and a conflict is not
725
+ * retried. Documents last written by one {@link updateDocuments} are sent
726
+ * again by one, and only when every one of them may be; a document that
727
+ * could not be re-opened blocks its set.
728
+ *
729
+ * No caller is waiting, so the outcomes go through the host: one report
730
+ * naming every document whose unsaved text is gone, whose record is then
731
+ * dropped, and one per document that could not be re-opened or written
732
+ * again for another reason than a conflict. A document that could not be
733
+ * re-opened is forgotten; a failed write keeps its record, for the next
734
+ * restore to decide again.
735
+ *
736
+ * Each document's dirty state goes to the host too, read once the watch is
737
+ * in place and any write is sent: a flip while the connection was down, or
738
+ * between the re-open and the watch, reached no one, and the re-open's own
739
+ * answer misses the second. Read before the write, it would tell the client
740
+ * a document is clean that the write is about to make dirty again.
741
+ */
742
+ protected async restore(server: RpcProxy<TServer>): Promise<void> {
743
+ const writes = [...this.unsavedWrites];
744
+ // No write sent before the drop answers any more, and a restarted
745
+ // server numbers afresh, below the versions saved before it.
746
+ this.savedVersions.clear();
747
+ const reopened = new Map<string, DataSessionDocument<TTransfer, TServer>>();
748
+ for (const uri of [...this.openUris]) {
749
+ try {
750
+ const document = await server.openModelDocument({ uri, clientId: this.clientId });
751
+ await server.watchModelDocument({ uri, clientId: this.clientId });
752
+ if (this.openUris.has(uri)) {
753
+ this.serverUris.set(uri, document.uri);
754
+ this.recordText(uri, document);
755
+ }
756
+ reopened.set(uri, document);
757
+ } catch (error: unknown) {
758
+ // Its record goes with its set's, in `reapply`, which it blocks.
759
+ this.openUris.delete(uri);
760
+ this.serverUris.delete(uri);
761
+ this.lastAnswers.delete(uri);
762
+ this.savedVersions.delete(uri);
763
+ this.host.reportError?.(error, resolve(DATA_SESSION_RESTORE_FAILED, { uri, detail: describeError(error) }));
764
+ }
765
+ }
766
+ const sets = new Map<object, [string, DataSessionUnsavedWrite<TTransfer, TServer>][]>();
767
+ for (const [uri, write] of writes) {
768
+ const call = 'update' in write.call ? write.call.update : write.call.updates;
769
+ sets.set(call, [...(sets.get(call) ?? []), [uri, write]]);
770
+ }
771
+ const lost: string[] = [];
772
+ for (const members of sets.values()) {
773
+ lost.push(...(await this.reapply(server, members, reopened)));
774
+ }
775
+ for (const uri of reopened.keys()) {
776
+ if (!this.openUris.has(uri)) {
777
+ continue;
778
+ }
779
+ // A failed read, or one without text, leaves the client's dirty
780
+ // state as it was; the document is restored all the same.
781
+ const current = await server.getModelDocument({ uri }).catch(() => undefined);
782
+ if (current?.text !== undefined) {
783
+ try {
784
+ this.host.restoreDirty?.({ uri: current.uri, text: current.text });
785
+ } catch {
786
+ // The client's listener failed, not the restore: the server
787
+ // has the document open and watched, so it stays restored.
788
+ }
789
+ }
790
+ }
791
+ if (lost.length > 0) {
792
+ const reported = resolve(DATA_SESSION_UNSAVED_LOST, { uris: lost.join(', ') });
793
+ this.host.reportError?.(new Error(reported.text), reported);
794
+ }
179
795
  }
180
796
 
181
- /** Await the connection and the server's startup gate for one generation. */
182
- protected async awaitReady(generation: Generation<TTransfer>): Promise<void> {
797
+ /**
798
+ * Whether the re-opened `document` still holds the session's unsaved
799
+ * `write` (`'kept'`), holds the text the write started from, so the write
800
+ * can be sent again (`'resend'`), or holds something else (`'lost'`).
801
+ *
802
+ * A document without `text` comes from a server that sends none, and
803
+ * counts as kept only at the version the write was answered with. One
804
+ * without a model has no version to send the write again on.
805
+ */
806
+ protected restoreOutcome(
807
+ write: DataSessionUnsavedWrite<TTransfer, TServer>,
808
+ document: DataSessionDocument<TTransfer, TServer>
809
+ ): 'kept' | 'resend' | 'lost' {
810
+ if (document.text === undefined) {
811
+ return document.model?.version === write.answer.version ? 'kept' : 'lost';
812
+ }
813
+ if (document.text.hash === write.answer.hash) {
814
+ return 'kept';
815
+ }
816
+ return document.model && write.baseHash !== undefined && document.text.hash === write.baseHash ? 'resend' : 'lost';
817
+ }
818
+
819
+ /**
820
+ * Write again, in one call and based on their `reopened` versions, the
821
+ * `members` of one write call that the re-open lost, all or none. Returns
822
+ * the URIs whose unsaved text is gone, and drops their records, and the
823
+ * record of a member that could not be re-opened.
824
+ *
825
+ * A member whose record is no longer the one the restore started with was
826
+ * closed, saved or disposed meanwhile, and is left out: writing it would
827
+ * put back text its caller discarded.
828
+ */
829
+ protected async reapply(
830
+ server: RpcProxy<TServer>,
831
+ members: readonly [string, DataSessionUnsavedWrite<TTransfer, TServer>][],
832
+ reopened: ReadonlyMap<string, DataSessionDocument<TTransfer, TServer>>
833
+ ): Promise<string[]> {
834
+ const current = (uri: string, write: DataSessionUnsavedWrite<TTransfer, TServer>): boolean =>
835
+ !this.disposed && this.unsavedWrites.get(uri) === write;
836
+ const outcomes = members
837
+ .filter(([uri, write]) => current(uri, write))
838
+ .map(([uri, write]) => {
839
+ const document = reopened.get(uri);
840
+ return { uri, write, document, outcome: document ? this.restoreOutcome(write, document) : 'failed' };
841
+ });
842
+ // A restarted server numbers afresh: the answers to later writes follow
843
+ // on from the re-opened version, not from the one the record holds.
844
+ for (const { uri, write, document, outcome } of outcomes) {
845
+ if (outcome === 'kept' && document) {
846
+ this.unsavedWrites.set(uri, { ...write, answer: this.answerOf(uri, document) });
847
+ }
848
+ }
849
+ // A document that could not be re-opened is forgotten, and was reported
850
+ // as such.
851
+ const lose = (): string[] => {
852
+ outcomes.filter(member => member.outcome !== 'kept').forEach(member => this.unsavedWrites.delete(member.uri));
853
+ return outcomes.filter(member => member.outcome === 'lost' || member.outcome === 'resend').map(member => member.uri);
854
+ };
855
+ if (outcomes.some(member => member.outcome === 'lost' || member.outcome === 'failed')) {
856
+ return lose();
857
+ }
858
+ // In the order of the call's updates, which is the order of its answers.
859
+ const resend = outcomes
860
+ .flatMap(({ uri, write, document, outcome }) =>
861
+ outcome === 'resend' && document?.model ? [{ uri, write, baseVersion: document.model.version }] : []
862
+ )
863
+ .sort((left, right) => indexOf(left.write) - indexOf(right.write));
864
+ if (resend.length === 0) {
865
+ return [];
866
+ }
867
+ let documents: DataSessionDocument<TTransfer, TServer>[];
183
868
  try {
184
- await generation.connection;
185
- await generation.server.waitForReady();
869
+ const { call } = resend[0].write;
870
+ if ('update' in call) {
871
+ documents = [await server.updateModelDocument({ ...call.update, baseVersion: resend[0].baseVersion, clientId: this.clientId })];
872
+ } else {
873
+ const baseVersion = new Map(resend.map(member => [indexOf(member.write), member.baseVersion]));
874
+ documents = await server.updateModelDocuments({
875
+ ...call.updates,
876
+ clientId: this.clientId,
877
+ updates: call.updates.updates.flatMap((update, index) => {
878
+ const version = baseVersion.get(index);
879
+ return version === undefined ? [] : [{ ...update, baseVersion: version }];
880
+ })
881
+ });
882
+ }
186
883
  } 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;
884
+ if (isConflictError(error)) {
885
+ return lose();
191
886
  }
192
- this.port.reportError(error, 'waiting for the data server to become ready');
193
- throw error;
887
+ for (const { uri, write, baseVersion } of resend) {
888
+ this.host.reportError?.(error, resolve(DATA_SESSION_RESTORE_FAILED, { uri, detail: describeError(error) }));
889
+ // Kept for the next restore, and numbered from the re-opened
890
+ // version, as the kept records are: a record numbered by a server
891
+ // that has since restarted would have later answers ignored.
892
+ if (current(uri, write)) {
893
+ this.unsavedWrites.set(uri, { ...write, answer: { ...write.answer, version: baseVersion } });
894
+ }
895
+ }
896
+ return [];
897
+ }
898
+ resend.forEach((member, index) => {
899
+ if (current(member.uri, member.write)) {
900
+ // Recorded afresh, since the answer of a restarted server may be
901
+ // numbered below the one it replaces.
902
+ this.unsavedWrites.delete(member.uri);
903
+ this.recordWrite(member.uri, documents[index], member.write.baseHash, member.write.call);
904
+ }
905
+ });
906
+ return [];
907
+ }
908
+
909
+ /**
910
+ * The text hash of the version `baseVersion` names for `uri`, for a write that
911
+ * starts the URI's record in {@link unsavedWrites}; `undefined` for any
912
+ * other write, whose record keeps the base it has.
913
+ *
914
+ * Taken from {@link lastAnswers} when that is at the version, otherwise
915
+ * read, and kept only when the read answers that version: a server's text
916
+ * changes only with its version, so the text at a version is the text the
917
+ * write, once it passes the gate, was applied to.
918
+ */
919
+ protected async baseHashOf(server: RpcProxy<TServer>, uri: string, baseVersion: BaseVersion): Promise<string | undefined> {
920
+ if (this.unsavedWrites.has(uri) || !isModelVersion(baseVersion)) {
921
+ return undefined;
922
+ }
923
+ const known = this.lastAnswers.get(uri);
924
+ if (known?.version === baseVersion) {
925
+ return known.hash;
194
926
  }
927
+ const read = await server.getModelDocument({ uri }).catch(() => undefined);
928
+ return read?.text?.version === baseVersion ? read.text.hash : undefined;
195
929
  }
196
930
 
197
931
  /**
198
- * Discard the current generation, disposing its connection if it opened.
199
- * The next {@link connected} builds a fresh one.
932
+ * Record `document` as the answer to a write of `uri`, keeping the base of
933
+ * the URI's record if it has one. An answer numbered below the record's is
934
+ * ignored: two writes of `uri` in flight at once may answer out of order,
935
+ * and the record holds the one applied last.
936
+ *
937
+ * So is one numbered at or below the URI's entry in {@link savedVersions}.
938
+ * The save came after that write was applied, so the save persisted its
939
+ * text or a later write replaced it, and its answer carries the text as it
940
+ * was when sent, which a restore would report as lost.
200
941
  */
201
- protected dropGeneration(): void {
202
- const generation = this.generation;
203
- this.generation = undefined;
204
- if (!generation) {
942
+ protected recordWrite(
943
+ uri: string,
944
+ document: DataSessionDocument<TTransfer, TServer>,
945
+ baseHash: string | undefined,
946
+ call: DataSessionUnsavedWrite<TTransfer, TServer>['call']
947
+ ): void {
948
+ const answer = this.answerOf(uri, document);
949
+ const kept = this.unsavedWrites.get(uri);
950
+ if (kept && answer.version < kept.answer.version) {
951
+ return;
952
+ }
953
+ const saved = this.savedVersions.get(uri);
954
+ if (saved !== undefined && answer.version <= saved) {
205
955
  return;
206
956
  }
207
- generation.connection.then(connection => connection.dispose()).catch(() => undefined);
957
+ this.unsavedWrites.set(uri, { baseHash: kept ? kept.baseHash : baseHash, answer, call });
958
+ this.recordText(uri, document);
959
+ }
960
+
961
+ /**
962
+ * What {@link DataSessionUnsavedWrite.answer} keeps of `document`. Every write
963
+ * and open answers with a model; one without is reported and counted older
964
+ * than every version, so it never replaces a real answer.
965
+ */
966
+ protected answerOf(
967
+ uri: string,
968
+ document: DataSessionDocument<TTransfer, TServer>
969
+ ): DataSessionUnsavedWrite<TTransfer, TServer>['answer'] {
970
+ if (!document.model) {
971
+ const reported = resolve(DATA_SESSION_ANSWER_WITHOUT_MODEL, { uri });
972
+ this.host.reportError?.(new Error(reported.text), reported);
973
+ return { version: UNRECORDED_VERSION, hash: document.text?.hash };
974
+ }
975
+ return { version: document.model.version, hash: document.text?.hash };
976
+ }
977
+
978
+ /** Keep `document`'s text in {@link lastAnswers}, or forget it for a server that sends none. */
979
+ protected recordText(uri: string, document: DataSessionDocument<TTransfer, TServer>): void {
980
+ if (document.text) {
981
+ this.lastAnswers.set(uri, document.text);
982
+ } else {
983
+ this.lastAnswers.delete(uri);
984
+ }
985
+ }
986
+
987
+ /** Run `call`, counted as in flight on each of `uris` until it settles. */
988
+ protected track<T>(uris: readonly string[], call: () => Promise<T>): Promise<T> {
989
+ const running = call();
990
+ for (const uri of uris) {
991
+ this.inFlight.set(uri, (this.inFlight.get(uri) ?? new Set<Promise<unknown>>()).add(running));
992
+ }
993
+ const done = (): void => uris.forEach(uri => this.inFlight.get(uri)?.delete(running));
994
+ running.then(done, done);
995
+ return running;
996
+ }
997
+
998
+ /** {@link track} an open of `uri`, counted in {@link openingUris} until it settles. */
999
+ protected trackOpen<T>(uri: string, call: () => Promise<T>): Promise<T> {
1000
+ this.openingUris.set(uri, (this.openingUris.get(uri) ?? 0) + 1);
1001
+ const done = (): void => {
1002
+ const remaining = (this.openingUris.get(uri) ?? 1) - 1;
1003
+ if (remaining > 0) {
1004
+ this.openingUris.set(uri, remaining);
1005
+ } else {
1006
+ this.openingUris.delete(uri);
1007
+ }
1008
+ };
1009
+ const running = this.track([uri], call);
1010
+ running.then(done, done);
1011
+ return running;
1012
+ }
1013
+
1014
+ /** Wait until `calls` have settled, or {@link settleBeforeCloseMs} has passed. */
1015
+ protected async settle(calls: Iterable<Promise<unknown>> | undefined): Promise<void> {
1016
+ const pending = [...(calls ?? [])];
1017
+ if (pending.length === 0) {
1018
+ return;
1019
+ }
1020
+ await this.clock.raceTimer(Promise.allSettled(pending), this.settleBeforeCloseMs);
1021
+ }
1022
+
1023
+ protected assertLive(): void {
1024
+ if (this.disposed) {
1025
+ throw new SessionClosedError(this.clientId);
1026
+ }
208
1027
  }
209
1028
  }