@hydranium/protocol 1.0.0-next.22 → 1.0.0-next.220

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