@hydranium/protocol 1.0.0-next.37 → 1.0.0-next.370

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 (294) hide show
  1. package/README.md +44 -83
  2. package/lib/abstract-logger.d.ts +11 -0
  3. package/lib/abstract-logger.d.ts.map +1 -1
  4. package/lib/abstract-logger.js +16 -0
  5. package/lib/abstract-logger.js.map +1 -1
  6. package/lib/client/data-connection.d.ts +303 -0
  7. package/lib/client/data-connection.d.ts.map +1 -0
  8. package/lib/client/data-connection.js +534 -0
  9. package/lib/client/data-connection.js.map +1 -0
  10. package/lib/client/data-events.d.ts +18 -1
  11. package/lib/client/data-events.d.ts.map +1 -1
  12. package/lib/client/data-events.js +26 -0
  13. package/lib/client/data-events.js.map +1 -1
  14. package/lib/client/data-port.d.ts +34 -24
  15. package/lib/client/data-port.d.ts.map +1 -1
  16. package/lib/client/data-session.d.ts +691 -89
  17. package/lib/client/data-session.d.ts.map +1 -1
  18. package/lib/client/data-session.js +1155 -115
  19. package/lib/client/data-session.js.map +1 -1
  20. package/lib/client/index.d.ts +15 -9
  21. package/lib/client/index.d.ts.map +1 -1
  22. package/lib/client/index.js +15 -9
  23. package/lib/client/index.js.map +1 -1
  24. package/lib/client/message-relay.d.ts +6 -4
  25. package/lib/client/message-relay.d.ts.map +1 -1
  26. package/lib/client/message-relay.js +4 -4
  27. package/lib/client/message-relay.js.map +1 -1
  28. package/lib/client/post-message-transport.d.ts +69 -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 +173 -0
  33. package/lib/client/rpc-connection.d.ts.map +1 -0
  34. package/lib/client/rpc-connection.js +225 -0
  35. package/lib/client/rpc-connection.js.map +1 -0
  36. package/lib/client/worker-handshake.d.ts +94 -0
  37. package/lib/client/worker-handshake.d.ts.map +1 -0
  38. package/lib/client/worker-handshake.js +51 -0
  39. package/lib/client/worker-handshake.js.map +1 -0
  40. package/lib/client-ids.d.ts +45 -0
  41. package/lib/client-ids.d.ts.map +1 -0
  42. package/lib/client-ids.js +48 -0
  43. package/lib/client-ids.js.map +1 -0
  44. package/lib/clock.d.ts +50 -10
  45. package/lib/clock.d.ts.map +1 -1
  46. package/lib/clock.js +36 -1
  47. package/lib/clock.js.map +1 -1
  48. package/lib/console-logger.d.ts +23 -0
  49. package/lib/console-logger.d.ts.map +1 -0
  50. package/lib/console-logger.js +39 -0
  51. package/lib/console-logger.js.map +1 -0
  52. package/lib/data/data-protocol-methods.d.ts +4 -4
  53. package/lib/data/data-protocol-methods.d.ts.map +1 -1
  54. package/lib/data/data-protocol-methods.js +13 -1
  55. package/lib/data/data-protocol-methods.js.map +1 -1
  56. package/lib/data/data-server-protocol.d.ts +171 -48
  57. package/lib/data/data-server-protocol.d.ts.map +1 -1
  58. package/lib/data/events.d.ts +144 -33
  59. package/lib/data/events.d.ts.map +1 -1
  60. package/lib/data/requests.d.ts +76 -11
  61. package/lib/data/requests.d.ts.map +1 -1
  62. package/lib/debouncer.d.ts +7 -4
  63. package/lib/debouncer.d.ts.map +1 -1
  64. package/lib/debouncer.js +10 -10
  65. package/lib/debouncer.js.map +1 -1
  66. package/lib/errors.d.ts +218 -41
  67. package/lib/errors.d.ts.map +1 -1
  68. package/lib/errors.js +364 -55
  69. package/lib/errors.js.map +1 -1
  70. package/lib/format-log-arg.d.ts +33 -0
  71. package/lib/format-log-arg.d.ts.map +1 -0
  72. package/lib/format-log-arg.js +158 -0
  73. package/lib/format-log-arg.js.map +1 -0
  74. package/lib/glsp-edits-settled-actions.d.ts +54 -0
  75. package/lib/glsp-edits-settled-actions.d.ts.map +1 -0
  76. package/lib/glsp-edits-settled-actions.js +28 -0
  77. package/lib/glsp-edits-settled-actions.js.map +1 -0
  78. package/lib/glsp-request-model-args.d.ts +16 -0
  79. package/lib/glsp-request-model-args.d.ts.map +1 -0
  80. package/lib/glsp-request-model-args.js +19 -0
  81. package/lib/glsp-request-model-args.js.map +1 -0
  82. package/lib/glsp-save-model-actions.d.ts +55 -0
  83. package/lib/glsp-save-model-actions.d.ts.map +1 -0
  84. package/lib/glsp-save-model-actions.js +28 -0
  85. package/lib/glsp-save-model-actions.js.map +1 -0
  86. package/lib/index.d.ts +11 -0
  87. package/lib/index.d.ts.map +1 -1
  88. package/lib/index.js +11 -0
  89. package/lib/index.js.map +1 -1
  90. package/lib/latency-collector.d.ts +10 -4
  91. package/lib/latency-collector.d.ts.map +1 -1
  92. package/lib/latency-collector.js +2 -0
  93. package/lib/latency-collector.js.map +1 -1
  94. package/lib/logger.d.ts +38 -7
  95. package/lib/logger.d.ts.map +1 -1
  96. package/lib/logger.js +42 -4
  97. package/lib/logger.js.map +1 -1
  98. package/lib/messages/index.d.ts +4 -2
  99. package/lib/messages/index.d.ts.map +1 -1
  100. package/lib/messages/index.js +16 -4
  101. package/lib/messages/index.js.map +1 -1
  102. package/lib/messages/primitives.d.ts +59 -4
  103. package/lib/messages/primitives.d.ts.map +1 -1
  104. package/lib/messages/primitives.js +97 -4
  105. package/lib/messages/primitives.js.map +1 -1
  106. package/lib/model-server.d.ts +60 -13
  107. package/lib/model-server.d.ts.map +1 -1
  108. package/lib/model-server.js +4 -2
  109. package/lib/model-server.js.map +1 -1
  110. package/lib/model-service/base-version.d.ts +67 -0
  111. package/lib/model-service/base-version.d.ts.map +1 -0
  112. package/lib/model-service/base-version.js +44 -0
  113. package/lib/model-service/base-version.js.map +1 -0
  114. package/lib/model-service/index.d.ts +1 -1
  115. package/lib/model-service/index.d.ts.map +1 -1
  116. package/lib/model-service/index.js +4 -5
  117. package/lib/model-service/index.js.map +1 -1
  118. package/lib/model-service/reference-candidate.d.ts +5 -3
  119. package/lib/model-service/reference-candidate.d.ts.map +1 -1
  120. package/lib/node/index.d.ts +10 -0
  121. package/lib/node/index.d.ts.map +1 -0
  122. package/lib/node/index.js +29 -0
  123. package/lib/node/index.js.map +1 -0
  124. package/lib/node/process-memory.d.ts +66 -0
  125. package/lib/node/process-memory.d.ts.map +1 -0
  126. package/lib/node/process-memory.js +291 -0
  127. package/lib/node/process-memory.js.map +1 -0
  128. package/lib/noop-logger.d.ts.map +1 -1
  129. package/lib/noop-logger.js.map +1 -1
  130. package/lib/observable-value.js.map +1 -1
  131. package/lib/patch-merge.d.ts +63 -35
  132. package/lib/patch-merge.d.ts.map +1 -1
  133. package/lib/patch-merge.js +171 -25
  134. package/lib/patch-merge.js.map +1 -1
  135. package/lib/pending-work-tracker.d.ts +30 -0
  136. package/lib/pending-work-tracker.d.ts.map +1 -0
  137. package/lib/pending-work-tracker.js +47 -0
  138. package/lib/pending-work-tracker.js.map +1 -0
  139. package/lib/profile-session.d.ts +24 -8
  140. package/lib/profile-session.d.ts.map +1 -1
  141. package/lib/profile-session.js +13 -4
  142. package/lib/profile-session.js.map +1 -1
  143. package/lib/profiling.d.ts +15 -2
  144. package/lib/profiling.d.ts.map +1 -1
  145. package/lib/profiling.js.map +1 -1
  146. package/lib/project.d.ts +4 -1
  147. package/lib/project.d.ts.map +1 -1
  148. package/lib/project.js.map +1 -1
  149. package/lib/random-uuid.d.ts +14 -0
  150. package/lib/random-uuid.d.ts.map +1 -0
  151. package/lib/random-uuid.js +24 -0
  152. package/lib/random-uuid.js.map +1 -0
  153. package/lib/reconcile-write.d.ts +70 -0
  154. package/lib/reconcile-write.d.ts.map +1 -0
  155. package/lib/reconcile-write.js +69 -0
  156. package/lib/reconcile-write.js.map +1 -0
  157. package/lib/rpc/bind-rpc-methods.d.ts +6 -2
  158. package/lib/rpc/bind-rpc-methods.d.ts.map +1 -1
  159. package/lib/rpc/bind-rpc-methods.js +17 -7
  160. package/lib/rpc/bind-rpc-methods.js.map +1 -1
  161. package/lib/rpc/create-rpc-proxy.d.ts +3 -0
  162. package/lib/rpc/create-rpc-proxy.d.ts.map +1 -1
  163. package/lib/rpc/create-rpc-proxy.js +6 -1
  164. package/lib/rpc/create-rpc-proxy.js.map +1 -1
  165. package/lib/rpc/index.d.ts +1 -0
  166. package/lib/rpc/index.d.ts.map +1 -1
  167. package/lib/rpc/index.js +1 -0
  168. package/lib/rpc/index.js.map +1 -1
  169. package/lib/rpc/send-by-method-name.d.ts +76 -0
  170. package/lib/rpc/send-by-method-name.d.ts.map +1 -0
  171. package/lib/rpc/send-by-method-name.js +120 -0
  172. package/lib/rpc/send-by-method-name.js.map +1 -0
  173. package/lib/rpc/wire-prefix.js.map +1 -1
  174. package/lib/save-text-document.d.ts +40 -0
  175. package/lib/save-text-document.d.ts.map +1 -0
  176. package/lib/save-text-document.js +34 -0
  177. package/lib/save-text-document.js.map +1 -0
  178. package/lib/testing/catalogue-audit.js.map +1 -1
  179. package/lib/testing/data-doubles.d.ts +41 -12
  180. package/lib/testing/data-doubles.d.ts.map +1 -1
  181. package/lib/testing/data-doubles.js +56 -8
  182. package/lib/testing/data-doubles.js.map +1 -1
  183. package/lib/testing/fake-clock.d.ts +17 -2
  184. package/lib/testing/fake-clock.d.ts.map +1 -1
  185. package/lib/testing/fake-clock.js +61 -46
  186. package/lib/testing/fake-clock.js.map +1 -1
  187. package/lib/testing/index.d.ts +1 -0
  188. package/lib/testing/index.d.ts.map +1 -1
  189. package/lib/testing/index.js +4 -3
  190. package/lib/testing/index.js.map +1 -1
  191. package/lib/testing/node/duplex-connection.d.ts.map +1 -1
  192. package/lib/testing/node/duplex-connection.js +3 -2
  193. package/lib/testing/node/duplex-connection.js.map +1 -1
  194. package/lib/testing/node/duplex-stream.js.map +1 -1
  195. package/lib/testing/node/index.d.ts +1 -0
  196. package/lib/testing/node/index.d.ts.map +1 -1
  197. package/lib/testing/node/index.js +2 -2
  198. package/lib/testing/node/index.js.map +1 -1
  199. package/lib/testing/node/message-port-pair.d.ts +25 -0
  200. package/lib/testing/node/message-port-pair.d.ts.map +1 -0
  201. package/lib/testing/node/message-port-pair.js +26 -0
  202. package/lib/testing/node/message-port-pair.js.map +1 -0
  203. package/lib/testing/transfer-node-builder.d.ts +81 -0
  204. package/lib/testing/transfer-node-builder.d.ts.map +1 -0
  205. package/lib/testing/transfer-node-builder.js +47 -0
  206. package/lib/testing/transfer-node-builder.js.map +1 -0
  207. package/lib/testing/wait-for.d.ts +9 -3
  208. package/lib/testing/wait-for.d.ts.map +1 -1
  209. package/lib/testing/wait-for.js +57 -11
  210. package/lib/testing/wait-for.js.map +1 -1
  211. package/lib/tracer.d.ts.map +1 -1
  212. package/lib/tracer.js +5 -9
  213. package/lib/tracer.js.map +1 -1
  214. package/lib/transfer-diagnostic.js.map +1 -1
  215. package/lib/transfer-document.d.ts +96 -32
  216. package/lib/transfer-document.d.ts.map +1 -1
  217. package/lib/transfer-document.js +17 -9
  218. package/lib/transfer-document.js.map +1 -1
  219. package/lib/transfer-element.d.ts +4 -4
  220. package/lib/types.d.ts +32 -0
  221. package/lib/types.d.ts.map +1 -0
  222. package/lib/{model-service/args.js → types.js} +2 -2
  223. package/lib/types.js.map +1 -0
  224. package/lib/uri.d.ts.map +1 -1
  225. package/lib/uri.js.map +1 -1
  226. package/lib/util.d.ts +8 -2
  227. package/lib/util.d.ts.map +1 -1
  228. package/lib/util.js +32 -4
  229. package/lib/util.js.map +1 -1
  230. package/package.json +24 -40
  231. package/src/abstract-logger.ts +18 -0
  232. package/src/client/data-connection.ts +654 -0
  233. package/src/client/data-events.ts +38 -1
  234. package/src/client/data-port.ts +36 -25
  235. package/src/client/data-session.ts +1476 -137
  236. package/src/client/index.ts +15 -9
  237. package/src/client/message-relay.ts +6 -4
  238. package/src/client/post-message-transport.ts +224 -4
  239. package/src/client/rpc-connection.ts +302 -0
  240. package/src/client/worker-handshake.ts +121 -0
  241. package/src/client-ids.ts +49 -0
  242. package/src/clock.ts +68 -10
  243. package/src/console-logger.ts +39 -0
  244. package/src/data/data-protocol-methods.ts +14 -4
  245. package/src/data/data-server-protocol.ts +198 -48
  246. package/src/data/events.ts +150 -33
  247. package/src/data/requests.ts +82 -11
  248. package/src/debouncer.ts +11 -11
  249. package/src/errors.ts +453 -65
  250. package/src/format-log-arg.ts +176 -0
  251. package/src/glsp-edits-settled-actions.ts +62 -0
  252. package/src/glsp-request-model-args.ts +16 -0
  253. package/src/glsp-save-model-actions.ts +64 -0
  254. package/src/index.ts +11 -0
  255. package/src/latency-collector.ts +10 -3
  256. package/src/logger.ts +44 -8
  257. package/src/messages/index.ts +11 -2
  258. package/src/messages/primitives.ts +129 -5
  259. package/src/model-server.ts +64 -19
  260. package/src/model-service/base-version.ts +75 -0
  261. package/src/model-service/index.ts +4 -5
  262. package/src/model-service/reference-candidate.ts +5 -3
  263. package/src/node/index.ts +14 -0
  264. package/src/node/process-memory.ts +299 -0
  265. package/src/patch-merge.ts +230 -45
  266. package/src/pending-work-tracker.ts +47 -0
  267. package/src/profile-session.ts +31 -11
  268. package/src/profiling.ts +15 -2
  269. package/src/project.ts +4 -1
  270. package/src/random-uuid.ts +21 -0
  271. package/src/reconcile-write.ts +131 -0
  272. package/src/rpc/README.md +6 -6
  273. package/src/rpc/bind-rpc-methods.ts +18 -8
  274. package/src/rpc/create-rpc-proxy.ts +6 -1
  275. package/src/rpc/index.ts +1 -0
  276. package/src/rpc/send-by-method-name.ts +140 -0
  277. package/src/save-text-document.ts +39 -0
  278. package/src/testing/data-doubles.ts +141 -19
  279. package/src/testing/fake-clock.ts +76 -48
  280. package/src/testing/index.ts +4 -3
  281. package/src/testing/node/duplex-connection.ts +3 -2
  282. package/src/testing/node/index.ts +2 -2
  283. package/src/testing/node/message-port-pair.ts +40 -0
  284. package/src/testing/transfer-node-builder.ts +107 -0
  285. package/src/testing/wait-for.ts +61 -13
  286. package/src/tracer.ts +5 -9
  287. package/src/transfer-document.ts +116 -34
  288. package/src/transfer-element.ts +4 -4
  289. package/src/types.ts +30 -0
  290. package/src/util.ts +33 -6
  291. package/lib/model-service/args.d.ts +0 -64
  292. package/lib/model-service/args.d.ts.map +0 -1
  293. package/lib/model-service/args.js.map +0 -1
  294. package/src/model-service/args.ts +0 -67
@@ -7,123 +7,482 @@
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 { defineMessage, describeError, resolve } from '../messages/primitives';
13
- import { type RpcProxy, createRpcProxy } from '../rpc';
14
- import type { TransferDocument } from '../transfer-document';
10
+ import { type Disposable, Emitter, type Event } from 'vscode-jsonrpc';
11
+ import { UNKNOWN_CLIENT_ID } from '../client-ids';
12
+ import { type Clock, SystemClock, TIMED_OUT } from '../clock';
13
+ import type {
14
+ DataServerProtocol,
15
+ DiagnosticOf,
16
+ TransferDocumentDeletedEvent,
17
+ TransferDocumentDirtyChangedEvent,
18
+ TransferDocumentUpdatedEvent
19
+ } from '../data';
20
+ import { isConflictError, SessionClosedError } from '../errors';
21
+ import type { Logger } from '../logger';
22
+ import { type BaseVersion, isModelVersion, type ModelVersion, type TextVersion, UNRECORDED_VERSION } from '../model-service/base-version';
23
+ import { type ResolvedMessage, defineMessage, describeError, resolve } from '../messages/primitives';
24
+ import { NoopLogger } from '../noop-logger';
25
+ import { PendingWorkTracker } from '../pending-work-tracker';
26
+ import { randomUuid } from '../random-uuid';
27
+ import type { MaybePromise } from '../util';
28
+ import type { RpcProxy } from '../rpc';
29
+ import type { TextState, TransferCreatedDocument, TransferDocument, TransferSavedDocument } from '../transfer-document';
15
30
  import type { TransferElement } from '../transfer-element';
16
- import type { DataPort } from './data-port';
17
31
 
18
32
  /**
19
- * The transport never opened. A complete sentence rather than a fragment: a
20
- * fragment is nested inside a sentence the framework does not own, so no
21
- * translator controls the whole and the composition cannot be made to read
22
- * correctly in every language.
33
+ * A session could not re-open a document it had open after its connection
34
+ * dropped, and forgot it; or could not write it again for another reason than
35
+ * a conflict, and keeps its unsaved edits for the next restore.
23
36
  */
24
- export const DATA_SERVER_CONNECT_FAILED = defineMessage(
25
- 'hydranium/protocol/data-server-connect-failed',
26
- 'Could not connect to the data server: {detail}'
37
+ export const DATA_SESSION_RESTORE_FAILED = defineMessage(
38
+ 'hydranium/protocol/data-session-restore-failed',
39
+ 'Could not restore {uri} after reconnecting to the data server: {detail}'
27
40
  );
28
41
 
29
- export const DATA_SERVER_NOT_READY = defineMessage(
30
- 'hydranium/protocol/data-server-not-ready',
31
- 'The data server did not become ready: {detail}'
42
+ /** A write or open of `{uri}` that the data server answered without a model. */
43
+ export const DATA_SESSION_ANSWER_WITHOUT_MODEL = defineMessage(
44
+ 'hydranium/protocol/data-session-answer-without-model',
45
+ 'The data server answered a write of {uri} without a model; the session counts that answer as older than every version.'
32
46
  );
33
47
 
34
- /** Options for {@link DataSession}. */
35
- export interface DataSessionOptions {
48
+ /**
49
+ * A session re-opened documents after its connection dropped and cannot put
50
+ * back what it wrote to them since their last save: another client changed
51
+ * them, even while the session was still connected; the session could not
52
+ * tell the text its writes started from, or lost another document written with
53
+ * them; or the write it sent again conflicted. The session's unsaved edits may
54
+ * be gone, and it no longer holds them.
55
+ */
56
+ export const DATA_SESSION_UNSAVED_LOST = defineMessage(
57
+ 'hydranium/protocol/data-session-unsaved-lost',
58
+ 'Unsaved changes to {uris} may have been lost when the connection to the data server dropped.'
59
+ );
60
+
61
+ /**
62
+ * What one of `TServer`'s document methods takes, minus the `clientId` a
63
+ * {@link DataSession} stamps itself.
64
+ *
65
+ * Read off the SERVER's signature, not off the framework's own arg type: an
66
+ * adopter server widens these, and a wrapper declared against the narrow
67
+ * shape rejects the extra field on a fresh object literal, so that call
68
+ * cannot go through a session at all.
69
+ */
70
+ export type DataSessionArgs<TMethod extends (args: never) => unknown> = Omit<Parameters<TMethod>[0], 'clientId'>;
71
+
72
+ /**
73
+ * Open a document through a session; the session supplies `clientId`. Only the
74
+ * URI and the open's options, read off the server's signature: the server
75
+ * ignores the `languageId`, `version` and `text` seeds of `OpenModelArgs`, and
76
+ * a field an adopter adds never reaches the server session's open, so
77
+ * accepting either would let a caller believe it took effect.
78
+ */
79
+ export type DataSessionOpenArgs<
80
+ TTransfer extends TransferElement,
81
+ TServer extends DataServerProtocol<TTransfer, DiagnosticOf<TServer>> = DataServerProtocol<TTransfer>
82
+ > = Pick<Parameters<TServer['openModelDocument']>[0], 'uri' | ('options' & keyof Parameters<TServer['openModelDocument']>[0])>;
83
+
84
+ /**
85
+ * The options an open through a session passes to `TServer`, `undefined` when
86
+ * it passed none; only `undefined` for a server whose open takes none.
87
+ */
88
+ export type DataSessionOpenOptions<
89
+ TTransfer extends TransferElement,
90
+ TServer extends DataServerProtocol<TTransfer, DiagnosticOf<TServer>> = DataServerProtocol<TTransfer>
91
+ > = DataSessionOpenArgs<TTransfer, TServer>['options' & keyof DataSessionOpenArgs<TTransfer, TServer>] | undefined;
92
+
93
+ /** Create a document through a session; the session supplies `clientId`. */
94
+ export type DataSessionCreateArgs<
95
+ TTransfer extends TransferElement,
96
+ TServer extends DataServerProtocol<TTransfer, DiagnosticOf<TServer>> = DataServerProtocol<TTransfer>
97
+ > = DataSessionArgs<TServer['createModelDocument']>;
98
+
99
+ /** Close a document through a session; the session supplies `clientId`. */
100
+ export type DataSessionCloseArgs<
101
+ TTransfer extends TransferElement,
102
+ TServer extends DataServerProtocol<TTransfer, DiagnosticOf<TServer>> = DataServerProtocol<TTransfer>
103
+ > = DataSessionArgs<TServer['closeModelDocument']>;
104
+
105
+ /** Update a document through a session; the session supplies `clientId`. */
106
+ export type DataSessionUpdateArgs<
107
+ TTransfer extends TransferElement,
108
+ TServer extends DataServerProtocol<TTransfer, DiagnosticOf<TServer>> = DataServerProtocol<TTransfer>
109
+ > = DataSessionArgs<TServer['updateModelDocument']>;
110
+
111
+ /** Update several documents at once through a session; the session supplies `clientId`. */
112
+ export type DataSessionUpdatesArgs<
113
+ TTransfer extends TransferElement,
114
+ TServer extends DataServerProtocol<TTransfer, DiagnosticOf<TServer>> = DataServerProtocol<TTransfer>
115
+ > = DataSessionArgs<TServer['updateModelDocuments']>;
116
+
117
+ /** Persist a document through a session; the session supplies `clientId`. */
118
+ export type DataSessionSaveArgs<
119
+ TTransfer extends TransferElement,
120
+ TServer extends DataServerProtocol<TTransfer, DiagnosticOf<TServer>> = DataServerProtocol<TTransfer>
121
+ > = DataSessionArgs<TServer['saveModelDocument']>;
122
+
123
+ /** Persist the text the server holds through a session; the session supplies `clientId`. */
124
+ export type DataSessionPersistArgs<
125
+ TTransfer extends TransferElement,
126
+ TServer extends DataServerProtocol<TTransfer, DiagnosticOf<TServer>> = DataServerProtocol<TTransfer>
127
+ > = DataSessionArgs<TServer['persistModelDocument']>;
128
+
129
+ /** Delete a document through a session; the session supplies `clientId`. */
130
+ export type DataSessionDeleteArgs<
131
+ TTransfer extends TransferElement,
132
+ TServer extends DataServerProtocol<TTransfer, DiagnosticOf<TServer>> = DataServerProtocol<TTransfer>
133
+ > = DataSessionArgs<TServer['deleteModelDocument']>;
134
+
135
+ /** The document a session hands back, carrying its server's diagnostic shape. */
136
+ export type DataSessionDocument<
137
+ TTransfer extends TransferElement,
138
+ TServer extends DataServerProtocol<TTransfer, DiagnosticOf<TServer>> = DataServerProtocol<TTransfer>
139
+ > = TransferDocument<TTransfer, DiagnosticOf<TServer>>;
140
+
141
+ /**
142
+ * What a {@link DataSession} keeps of a URI it wrote since the URI's last save,
143
+ * to write it again after a reconnect that lost it.
144
+ */
145
+ export interface DataSessionUnsavedWrite<
146
+ TTransfer extends TransferElement,
147
+ TServer extends DataServerProtocol<TTransfer, DiagnosticOf<TServer>> = DataServerProtocol<TTransfer>
148
+ > {
36
149
  /**
37
- * Wire namespace the server is addressed under. Defaults to the
38
- * framework's {@link DATA_SERVER_WIRE_PREFIX}, which is what an unmodified
39
- * `DataServer` binds. Override only alongside the server's own
40
- * `methodNamespace` option — a mismatch turns every request into
41
- * "Unhandled method" rather than failing at wire-up.
150
+ * The `text.hash` of the text the first of these writes was based on.
151
+ * `undefined` when the session could not tell, for a write based on
152
+ * `'any'` or on a version it could not read back, and such a write is
153
+ * never sent again: the session cannot tell another client's text from the
154
+ * text it wrote over.
42
155
  */
43
- readonly methodNamespace?: string;
156
+ readonly baseHash: string | undefined;
157
+ /**
158
+ * The model version the last of these writes was answered with, which
159
+ * orders its answers, and the `text.hash` of that answer.
160
+ */
161
+ readonly answer: { readonly version: ModelVersion; readonly hash?: string };
162
+ /**
163
+ * The call that made the last write, and for an `updateDocuments` call this
164
+ * URI's index in it. Records whose `updates` is the same object were
165
+ * written together and are sent again together, so a restore never applies
166
+ * part of a set.
167
+ */
168
+ readonly call:
169
+ | { readonly update: DataSessionUpdateArgs<TTransfer, TServer> }
170
+ | { readonly updates: DataSessionUpdatesArgs<TTransfer, TServer>; readonly index: number };
44
171
  }
45
172
 
46
- /** One connection generation: its connection, its proxy, and its readiness. */
47
- interface Generation<TTransfer extends TransferElement> {
48
- readonly connection: Promise<MessageConnection>;
49
- readonly server: RpcProxy<DataServerProtocol<TTransfer>>;
50
- /** Set on first use; the shared readiness gate for this generation. */
51
- ready?: Promise<void>;
173
+ /**
174
+ * One open of a URI by a {@link DataSession}, from the answer to its open,
175
+ * create or re-open until a close or a deletion ends it. A call records its
176
+ * answer only while the open it was sent under is still the URI's: checking
177
+ * that the URI is open accepts an answer from before a close or deletion
178
+ * once the URI is open again.
179
+ */
180
+ export interface DataSessionOpen<
181
+ TTransfer extends TransferElement,
182
+ TServer extends DataServerProtocol<TTransfer, DiagnosticOf<TServer>> = DataServerProtocol<TTransfer>
183
+ > {
184
+ /** The URI the open's answer named, which the server keys its notifications by. */
185
+ readonly serverUri: string;
186
+ /**
187
+ * The options the server opened under, which a re-open after a reconnect
188
+ * passes again: those of the earliest open of the URI under way when the
189
+ * first answered, since the server keeps the open that arrives first.
190
+ */
191
+ readonly options: DataSessionOpenOptions<TTransfer, TServer>;
192
+ /** Whether a deletion ended the open, which an open still watching sends again; a close does not. */
193
+ deleted: boolean;
52
194
  }
53
195
 
54
196
  /**
55
- * The host-invariant half of talking to the data head: everything above
56
- * {@link DataPort} that would otherwise be re-derived by every host
57
- * adapter.
197
+ * One open or create of a URI by a {@link DataSession}, from its call until it
198
+ * settles. A close of the URI while it is under way marks it: it then records
199
+ * nothing and is not sent again, so the close stands. Without the mark, a
200
+ * deletion during its watch has it sent again after the close.
201
+ */
202
+ export interface DataSessionOpening<
203
+ TTransfer extends TransferElement,
204
+ TServer extends DataServerProtocol<TTransfer, DiagnosticOf<TServer>> = DataServerProtocol<TTransfer>
205
+ > {
206
+ /** Whether a close of the URI came while this open was under way. */
207
+ closed: boolean;
208
+ /** The options the open was sent with; none for a create. */
209
+ readonly options: DataSessionOpenOptions<TTransfer, TServer>;
210
+ }
211
+
212
+ /** Where `write` stands in the `updateDocuments` call it was last written by; `0` for a single update. */
213
+ function indexOf(write: DataSessionUnsavedWrite<TransferElement, DataServerProtocol<TransferElement>>): number {
214
+ return 'index' in write.call ? write.call.index : 0;
215
+ }
216
+
217
+ /** The call `write` was last written by, which a restore writes again as one set. */
218
+ function setOf(write: DataSessionUnsavedWrite<TransferElement, DataServerProtocol<TransferElement>>): object {
219
+ return 'update' in write.call ? write.call.update : write.call.updates;
220
+ }
221
+
222
+ /**
223
+ * What a {@link DataSession} needs from the connection that minted it.
58
224
  *
59
- * Three jobs, and deliberately no fourth:
225
+ * Narrower than the connection itself so the dependency points one way:
226
+ * `DataConnection` constructs sessions, and nothing here imports it back.
227
+ */
228
+ export interface DataSessionHost<TTransfer extends TransferElement, TServer extends DataServerProtocol<TTransfer, DiagnosticOf<TServer>>> {
229
+ /** The connected, READY proxy of the current connection; a new object after each reconnect. */
230
+ connected(): Promise<RpcProxy<TServer>>;
231
+ /** Surface a failure no caller is waiting on, such as restoring a document after a reconnect. */
232
+ reportError?(error: unknown, reported: ResolvedMessage): void;
233
+ /**
234
+ * Tell the connection's client the dirty state a restore read, unless it
235
+ * is what the client was last told of the URI since the URI's last open.
236
+ */
237
+ restoreDirty?(event: TransferDocumentDirtyChangedEvent): void;
238
+ /**
239
+ * Tell the connection's client of a document a restore found gone, whose
240
+ * deletion reached no one while the connection was down, as the server
241
+ * tells it of a deletion over a live connection. Without it, the restore
242
+ * reports the unsaved text such a document took with it as lost.
243
+ */
244
+ restoreDeletion?(event: TransferDocumentDeletedEvent): void;
245
+ /**
246
+ * Forget what the client was told of `uri`'s dirty state: an open just
247
+ * made answered its caller afresh, and the client heard none of it, or a
248
+ * close leaves nothing to restore. Forgetting a URI another session still
249
+ * has open costs at most one repeat of a state the client already has.
250
+ */
251
+ forgetDirty?(uri: string): void;
252
+ /**
253
+ * Fires with each flip of a document's dirty state the server sends. A
254
+ * session drops the unsaved write it keeps of a document that turns
255
+ * clean; without this event it keeps it, and a restore after another
256
+ * client's save of the document can report the write lost.
257
+ */
258
+ readonly onDidChangeDirty?: Event<TransferDocumentDirtyChangedEvent>;
259
+ /**
260
+ * Fires with each update event the server sends. A session drops the
261
+ * unsaved write it keeps of a document another client wrote over; without
262
+ * this event it keeps it, and a restore reports the write lost.
263
+ */
264
+ readonly onDidUpdateDocument?: Event<TransferDocumentUpdatedEvent<TTransfer, DiagnosticOf<TServer>>>;
265
+ /**
266
+ * Fires with each deletion the server sends. A session forgets a document
267
+ * whose file was deleted; without this event it keeps it as open until a
268
+ * restore finds it gone.
269
+ */
270
+ readonly onDidDeleteDocument?: Event<TransferDocumentDeletedEvent>;
271
+ /** Where the session logs the documents it forgets as gone. */
272
+ readonly logger?: Logger;
273
+ }
274
+
275
+ /**
276
+ * Builds the session `DataConnection.createSession` hands out, for an adopter
277
+ * that extends {@link DataSession}. The connection has minted `clientId` and
278
+ * checked it by then.
279
+ */
280
+ export type DataSessionFactory<TTransfer extends TransferElement, TServer extends DataServerProtocol<TTransfer, DiagnosticOf<TServer>>> = (
281
+ clientId: string,
282
+ host: DataSessionHost<TTransfer, TServer>,
283
+ label: string
284
+ ) => DataSession<TTransfer, TServer>;
285
+
286
+ /**
287
+ * One participant on a data connection: a properties panel, a tree, a form
288
+ * editor. The client side of a server client session, registered over the
289
+ * wire under {@link clientId}.
290
+ *
291
+ * The session writes only what it has open: the server refuses its update or
292
+ * save of a document it has not opened with a `DocumentNotOpenError` code.
293
+ * Every call waits for the registration, so the first can be issued at once.
294
+ *
295
+ * Every document operation stamps {@link clientId} itself. A caller that
296
+ * passed its own could pass another participant's, and the server would
297
+ * attribute the write and close the document accordingly.
60
298
  *
61
- * 1. **Build the typed proxy** over the port's connection, with the framework's
62
- * wire prefix and its drift-proof client-method allowlist.
63
- * 2. **Own the readiness gate** — `waitForReady` once per connection, shared
64
- * across concurrent callers. A socket client can connect before the
65
- * workspace walk finishes, and an early request is then answered correctly
66
- * from an empty registry, which reads as a broken project tier rather than
67
- * as a race.
68
- * 3. **Own the reconnect policy**, by dropping its connection generation when
69
- * the port disposes and building a fresh one on the next request.
299
+ * {@link closeDocument}, {@link deleteDocument} and {@link dispose} first wait,
300
+ * up to {@link settleBeforeCloseMs}, for this session's calls still in flight
301
+ * on the URI, or on any URI for `dispose`: a save sent just before its close
302
+ * would otherwise reach the server after it, and fail as not open. An open or
303
+ * create of a URI called while a close or delete of it is under way is sent
304
+ * once that has answered, so the server takes them in the order they were
305
+ * called.
70
306
  *
71
- * It does **not** wrap the protocol methods; callers reach them through
72
- * {@link connected}. The one exception is {@link openDocument}, which exists
73
- * because the open/watch *order* is silently wrong the other way round — see
74
- * its own doc.
307
+ * After the connection drops, the session registers again under the same id,
308
+ * re-opens and re-watches what it had open, tells the client of their dirty
309
+ * state where it changed, and reports the documents whose unsaved edits did
310
+ * not survive; see {@link restore}. The connection does this at
311
+ * once for a session with documents open, and again once any later connection
312
+ * is ready, so a reconnect that failed is not left to the session's own next
313
+ * call; any session's next call does it too.
75
314
  *
76
- * Generic over the transfer root so this file names no grammar. An adopter
77
- * binds the concrete root (or the union of them, for a multi-grammar head) at
78
- * its own edge.
315
+ * Generic over the transfer root so this file names no grammar.
316
+ *
317
+ * `TServer` is bound to a server answering with ITS OWN diagnostic shape, read
318
+ * back off the parameter being bound. Simplifying that to
319
+ * `DataServerProtocol<TTransfer>` compiles and costs the wrappers their
320
+ * return type: every call through `TServer` would resolve against that looser
321
+ * bound, so an adopter's diagnostics would come back as the framework's and
322
+ * the document would have to be cast on the way out.
79
323
  */
80
- export class DataSession<TTransfer extends TransferElement> {
81
- protected readonly methodNamespace: string;
82
- /** The current generation, or `undefined` before the first request / after a teardown. */
83
- protected generation?: Generation<TTransfer>;
324
+ export class DataSession<
325
+ TTransfer extends TransferElement,
326
+ TServer extends DataServerProtocol<TTransfer, DiagnosticOf<TServer>> = DataServerProtocol<TTransfer>
327
+ > implements Disposable {
328
+ /**
329
+ * How long {@link closeDocument}, {@link deleteDocument} and {@link dispose}
330
+ * wait for this session's calls in flight before going on anyway. Long,
331
+ * because a close sent while a save is still writing fails that save. It
332
+ * need not outlast the server's language-client settle after the write,
333
+ * which a close does not fail.
334
+ */
335
+ protected readonly settleBeforeCloseMs: number = 10_000;
336
+ /**
337
+ * How long {@link whenWritesSettled} waits before going on anyway: well past
338
+ * the server's bound on the language-client settle it runs before answering
339
+ * an update. The update itself has no bound, so a server slower than that is
340
+ * taken as lost.
341
+ */
342
+ protected readonly settleWritesMs: number = 30_000;
343
+ /**
344
+ * The clock {@link settleBeforeCloseMs} runs on. {@link DataSessionHost}
345
+ * carries no {@link Clock}, so a subclass replaces this field as it
346
+ * replaces the bound.
347
+ */
348
+ protected readonly clock: Clock = new SystemClock();
349
+ /** URIs this session has open, re-opened after a reconnect. */
350
+ protected readonly openUris = new Set<string>();
351
+ /**
352
+ * Per URI in {@link openUris}, or whose open answered and whose watch is
353
+ * still under way, the open it is under. A repeat open keeps it, as the
354
+ * server keeps its earlier open.
355
+ */
356
+ protected readonly opens = new Map<string, DataSessionOpen<TTransfer, TServer>>();
357
+ /**
358
+ * Per URI, the opens of it this session has under way. Such a URI counts
359
+ * as open for {@link withOpenDocument}, which would otherwise close it
360
+ * under the open that is still being made.
361
+ */
362
+ protected readonly openings = new Map<string, Set<DataSessionOpening<TTransfer, TServer>>>();
363
+ /**
364
+ * Per URI, the closes and deletes of it this session has under way, which
365
+ * an open or create called meanwhile waits for; see {@link trackEnding}.
366
+ */
367
+ protected readonly endings = new Map<string, Promise<unknown>>();
368
+ /** Per URI written since its last save, what {@link restore} needs to write it again. */
369
+ protected readonly unsavedWrites = new Map<string, DataSessionUnsavedWrite<TTransfer, TServer>>();
370
+ /**
371
+ * Per URI this session has open, the text of the last document one of its
372
+ * own calls was answered with, which spares the read a first unsaved write
373
+ * otherwise makes for its base; see {@link baseHashOf}.
374
+ */
375
+ protected readonly lastAnswers = new Map<string, TextState>();
376
+ /**
377
+ * Per URI this session has open, the text version its last save or persist
378
+ * of it wrote, as its answer's `persisted` says; see {@link recordWrite}.
379
+ * Not the answer's model version, which can carry a write that landed
380
+ * after the text was taken. Only those set it: an open answers at the
381
+ * version of a write still in flight as well, and that write is not saved.
382
+ */
383
+ protected readonly savedVersions = new Map<string, TextVersion>();
384
+ /**
385
+ * URIs this session created whose whole text is still its own and unsaved,
386
+ * even with no write recorded: no save, clean flip, other client's write or
387
+ * reported loss has come since the create, its answer included; see
388
+ * {@link forgetGoneDocument}.
389
+ */
390
+ protected readonly createdUris = new Set<string>();
391
+ /** Per URI, this session's calls still in flight on it, which a close or delete waits for. */
392
+ protected readonly inFlight = new Map<string, PendingWorkTracker>();
393
+ /** This session's saves, persists and deletes still in flight, which a host's exit waits for; see {@link hasSavesInFlight}. */
394
+ protected readonly savesInFlight = new PendingWorkTracker();
395
+ /** This session's updates still in flight, which a page's unload guard and save account for; see {@link hasWritesInFlight}. */
396
+ protected readonly writesInFlight = new PendingWorkTracker();
397
+ protected readonly disposeEmitter = new Emitter<void>();
398
+ /**
399
+ * Fires once when the session ends, by {@link dispose} or {@link detach}, as
400
+ * soon as it rejects further calls and before any close is sent. For a
401
+ * session its connection created, the connection's listener runs first, so
402
+ * the id is free again on that connection by the time any other listener
403
+ * runs; the server still holds it until the close arrives, and refuses a new
404
+ * session under it until then.
405
+ *
406
+ * A listener subscribed once the session has ended is never called, so a
407
+ * late subscriber checks {@link isDisposed} first.
408
+ */
409
+ readonly onDidDispose: Event<void> = this.disposeEmitter.event;
410
+ /**
411
+ * Sent with every registration, so the server lets this session register
412
+ * its id again while the dropped connection's session is still live there:
413
+ * a server that has not yet noticed the drop would otherwise refuse the id
414
+ * as a duplicate until it does.
415
+ */
416
+ protected readonly resumeToken: string = randomUuid();
417
+ /** The proxy the session is registered on; another one means the connection was replaced. */
418
+ protected registeredOn?: RpcProxy<TServer>;
419
+ /** The registration on {@link registeredOn}, which {@link connected} awaits. Replaced when the proxy changes. */
420
+ protected registration?: Promise<void>;
421
+ /** Set by {@link dispose} or {@link detach}, whichever comes first, after which {@link assertLive} throws. */
84
422
  protected disposed = false;
85
- protected readonly portDisposeListener: { dispose(): void };
423
+ /**
424
+ * Disposed through {@link detach} rather than {@link dispose}, so nothing may
425
+ * be sent. Folding it into {@link disposed} would send the session's close
426
+ * over a connection that is going away.
427
+ */
428
+ protected detached = false;
429
+ /**
430
+ * Write sets, keyed as a restore groups them, that lost a document to
431
+ * another client's deletion. A restore cannot write such a set again
432
+ * whole, so it writes none of it. Weak, so a set goes once no write
433
+ * record holds it.
434
+ */
435
+ protected readonly brokenSets = new WeakSet<object>();
436
+ /** The subscription to the host's `onDidChangeDirty`, disposed with the session. */
437
+ protected readonly dirtySubscription?: Disposable;
438
+ /** The subscription to the host's `onDidUpdateDocument`, disposed with the session. */
439
+ protected readonly updateSubscription?: Disposable;
440
+ /** The subscription to the host's `onDidDeleteDocument`, disposed with the session. */
441
+ protected readonly deletionSubscription?: Disposable;
442
+ /** The host's logger, or one that logs nothing. */
443
+ protected readonly logger: Logger;
86
444
 
87
445
  constructor(
88
- protected readonly port: DataPort,
89
- protected readonly client: DataClientProtocol<TTransfer>,
90
- options: DataSessionOptions = {}
446
+ readonly clientId: string,
447
+ protected readonly host: DataSessionHost<TTransfer, TServer>,
448
+ readonly label: string
91
449
  ) {
92
- this.methodNamespace = options.methodNamespace ?? DATA_SERVER_WIRE_PREFIX;
93
- this.portDisposeListener = this.port.onDispose(() => this.dropGeneration());
94
- }
95
-
96
- /** The identity every request is made under — the port's, not a second one. */
97
- get clientId(): string {
98
- return this.port.clientId;
450
+ this.logger = host.logger ?? new NoopLogger();
451
+ this.dirtySubscription = host.onDidChangeDirty?.(event => this.forgetSavedWrite(event));
452
+ this.updateSubscription = host.onDidUpdateDocument?.(event => this.forgetSupersededWrite(event));
453
+ this.deletionSubscription = host.onDidDeleteDocument?.(event => this.forgetDeletedDocument(event));
99
454
  }
100
455
 
101
456
  /**
102
- * The connected, READY server proxy.
103
- *
104
- * Returns the proxy rather than `void` on purpose. A reconnect replaces the
105
- * proxy, so a caller that cached one from an earlier call would go on
106
- * addressing a dead connection with no error — handing it back per call
107
- * makes the stale reference unrepresentable.
108
- *
109
- * Concurrent callers share one readiness promise, so `waitForReady` is
110
- * awaited once per generation and not once per caller.
457
+ * The connected, READY server proxy once this session is registered on it,
458
+ * for protocol methods this session does not wrap. The proxy stamps
459
+ * nothing: pass this session's {@link clientId} to any method that carries
460
+ * one.
111
461
  */
112
- async connected(): Promise<RpcProxy<DataServerProtocol<TTransfer>>> {
113
- if (this.disposed) {
114
- throw new Error('DataSession is disposed');
462
+ async connected(): Promise<RpcProxy<TServer>> {
463
+ // `async` so a disposed session REJECTS rather than throwing
464
+ // synchronously: the connection's own `connected` rejects, and a caller
465
+ // reaching for `.catch` on one of them would not catch the other.
466
+ this.assertLive();
467
+ const server = await this.host.connected();
468
+ // Again after the wait: a session disposed meanwhile must not register,
469
+ // since its dispose found nothing registered to end.
470
+ this.assertLive();
471
+ if (this.registeredOn !== server) {
472
+ const reconnected = this.registeredOn !== undefined;
473
+ this.registeredOn = server;
474
+ this.registration = this.register(server, reconnected);
115
475
  }
116
- const generation = this.currentGeneration();
117
- if (!generation.ready) {
118
- generation.ready = this.awaitReady(generation);
119
- }
120
- await generation.ready;
121
- return generation.server;
476
+ await this.registration;
477
+ // And after the registration: a call waiting on it has not reached the
478
+ // wire, and sent now it would land after the session's close.
479
+ this.assertLive();
480
+ return server;
122
481
  }
123
482
 
124
483
  /**
125
- * Open `uri` for editing and start watching it, in that order, returning
126
- * the opened snapshot.
484
+ * Open `args.uri` for editing and start watching it, in that order,
485
+ * returning the opened snapshot.
127
486
  *
128
487
  * **The order is the whole reason this method exists.**
129
488
  * `watchModelDocument` baselines its dedup fingerprint from the *current*
@@ -131,32 +490,384 @@ export class DataSession<TTransfer extends TransferElement> {
131
490
  * baseline, and the first phase event after the open arrives as a spurious
132
491
  * `'changed'` — which a widget that resets its in-memory root to the server
133
492
  * view misreads as a concurrent third-party write, losing whatever the user
134
- * had typed. Nothing about the wrong order fails loudly, so it is encoded
135
- * here rather than documented and re-derived.
493
+ * had typed.
136
494
  *
137
- * Note that the returned snapshot's empty `diagnostics` does not mean
138
- * valid: `open` settles at the integrity landmark, not at validation.
495
+ * Note that the returned snapshot's model usually has no `diagnostics`:
496
+ * `open` settles at the integrity landmark, not at validation.
139
497
  * Validity arrives asynchronously on `onDocumentUpdated`, or synchronously
140
498
  * from `getModelDocument({ includeDiagnostics: true })`.
141
499
  */
142
- async openDocument(uri: string): Promise<TransferDocument<TTransfer>> {
143
- const server = await this.connected();
144
- const document = await server.openModelDocument({ uri, clientId: this.clientId });
145
- await server.watchModelDocument({ uri, clientId: this.clientId });
500
+ openDocument(args: DataSessionOpenArgs<TTransfer, TServer>): Promise<DataSessionDocument<TTransfer, TServer>> {
501
+ return this.trackOpen(args.uri, args.options, opening =>
502
+ this.openAndWatch(
503
+ args.uri,
504
+ opening,
505
+ () => undefined,
506
+ server => server.openModelDocument({ ...args, clientId: this.clientId })
507
+ )
508
+ );
509
+ }
510
+
511
+ /**
512
+ * Create a document that exists nowhere yet, open and watched for this
513
+ * session; it reaches disk with the first {@link saveDocument}. The server
514
+ * refuses a URI that exists on disk or that any client has open. The answer
515
+ * names the version the create made in `created`, which a write of what
516
+ * this session created is based on: the answered model can already be
517
+ * another client's write or an integrity repair.
518
+ */
519
+ createDocument(args: DataSessionCreateArgs<TTransfer, TServer>): Promise<TransferCreatedDocument<TTransfer, DiagnosticOf<TServer>>> {
520
+ return this.trackOpen(args.uri, undefined, opening =>
521
+ this.openAndWatch(
522
+ args.uri,
523
+ opening,
524
+ document => document.created.version,
525
+ server => server.createModelDocument({ ...args, clientId: this.clientId })
526
+ )
527
+ );
528
+ }
529
+
530
+ /**
531
+ * Send `open` and watch what it answered, again for as long as a deletion
532
+ * heard while the watch is under way closes that open: sent after the
533
+ * deletion, the open fails as an open of a gone file does, or opens the
534
+ * file that is back. `created` reads the version the create made off the
535
+ * answered document, or none for an open; see {@link watchOpened} for the
536
+ * mark it puts in {@link createdUris}.
537
+ *
538
+ * An `opening` a close marked answers with the document, recording nothing
539
+ * and sending nothing again; one it marked before the open answered is
540
+ * undone, since the server may have taken the close first. A failed watch
541
+ * is undone too: the caller sees a failed open, and so would never close it.
542
+ */
543
+ protected async openAndWatch<TDocument extends DataSessionDocument<TTransfer, TServer>>(
544
+ uri: string,
545
+ opening: DataSessionOpening<TTransfer, TServer>,
546
+ created: (document: TDocument) => ModelVersion | undefined,
547
+ open: (server: RpcProxy<TServer>) => Promise<TDocument>
548
+ ): Promise<TDocument> {
549
+ for (;;) {
550
+ const server = await this.connected();
551
+ const document = await open(server);
552
+ if (opening.closed) {
553
+ await this.undoOpen(server, uri, opening);
554
+ return document;
555
+ }
556
+ let watched: TDocument | undefined;
557
+ try {
558
+ watched = await this.watchOpened(server, uri, document, created(document));
559
+ } catch (error: unknown) {
560
+ await this.undoOpen(server, uri, opening);
561
+ throw error;
562
+ }
563
+ if (watched || opening.closed) {
564
+ return watched ?? document;
565
+ }
566
+ }
567
+ }
568
+
569
+ /**
570
+ * Watch a document this session just opened, and record it as open.
571
+ * Answers `undefined`, recording nothing, when a deletion heard while the
572
+ * watch is under way has ended the open already, and the document,
573
+ * recording nothing, when a close has. A failed watch rejects with the open
574
+ * still recorded, for its caller to undo, see {@link undoOpen}.
575
+ *
576
+ * A document created at `createdVersion` is marked in {@link createdUris}
577
+ * while its text is still at that version: a version past it is another's,
578
+ * a write or a repair, as a changed event would have said. Marked before the
579
+ * watch, so an event heard while it is under way clears the mark for good,
580
+ * and checked again against the text the watch answered, which an event
581
+ * sent before the watch was in place moved on unheard. The restore's
582
+ * re-open is the one other point the session learns of the text without
583
+ * hearing the events between, and checks the mark the same way. An answer
584
+ * without text leaves the mark as it is, at every one of the three.
585
+ */
586
+ protected async watchOpened<TDocument extends DataSessionDocument<TTransfer, TServer>>(
587
+ server: RpcProxy<TServer>,
588
+ uri: string,
589
+ document: TDocument,
590
+ createdVersion?: ModelVersion
591
+ ): Promise<TDocument | undefined> {
592
+ // Recorded before the watch, so a deletion heard while it is under way
593
+ // finds this open, which the server made before the deletion.
594
+ // Under the options of the earliest open still under way, which the
595
+ // server took first; one that failed is gone from `openings` by now,
596
+ // as the connection handles each answer in a task of its own.
597
+ const open = this.opens.get(uri) ?? {
598
+ serverUri: document.uri,
599
+ deleted: false,
600
+ options: [...(this.openings.get(uri) ?? [])].find(opening => !opening.closed)?.options
601
+ };
602
+ this.opens.set(uri, open);
603
+ if (createdVersion !== undefined && (document.text === undefined || document.text.version === createdVersion)) {
604
+ this.createdUris.add(uri);
605
+ }
606
+ const watched = await server.watchModelDocument({ uri, clientId: this.clientId });
607
+ if (createdVersion !== undefined && watched.text !== undefined && watched.text.version !== createdVersion) {
608
+ this.createdUris.delete(uri);
609
+ }
610
+ if (this.opens.get(uri) !== open) {
611
+ // Sent again, it ends as an open sent after the deletion would; a
612
+ // close is the caller's later call, and stands.
613
+ return open.deleted ? undefined : document;
614
+ }
615
+ this.openUris.add(uri);
616
+ this.recordText(uri, document);
617
+ // Keyed as the server keys its notifications, which may not be how the
618
+ // caller spelled the URI.
619
+ this.host.forgetDirty?.(document.uri);
146
620
  return document;
147
621
  }
148
622
 
149
623
  /**
150
- * Close `uri`. The server unwatches implicitly, so this is the dual of
151
- * {@link openDocument} and needs no separate unwatch.
624
+ * Close `args.uri`, once this session's calls on it have settled or
625
+ * {@link settleBeforeCloseMs} has passed. The server unwatches implicitly,
626
+ * so this is the dual of {@link openDocument} and needs no separate unwatch.
627
+ */
628
+ async closeDocument(args: DataSessionCloseArgs<TTransfer, TServer>): Promise<void> {
629
+ this.assertLive();
630
+ // An open called after this close waits for it instead, see `trackOpen`.
631
+ const underWay = [...(this.openings.get(args.uri) ?? [])];
632
+ await this.trackEnding(args.uri, async () => {
633
+ await this.settle([this.inFlight.get(args.uri)]);
634
+ // Forgotten before the close is sent, so a reconnect in between does
635
+ // not re-open a document the caller has closed. Every open of it that
636
+ // was under way when the close was called is marked, so it neither
637
+ // records it again nor is sent again.
638
+ underWay.forEach(opening => {
639
+ opening.closed = true;
640
+ });
641
+ this.forgetDocument(args.uri);
642
+ const server = await this.connected();
643
+ await server.closeModelDocument({ ...args, clientId: this.clientId });
644
+ });
645
+ }
646
+
647
+ /**
648
+ * Close `uri` again after `opening` failed or was closed while under way,
649
+ * and drop what it recorded, unless the session still relies on the open,
650
+ * see {@link hasOpen}: the server holds one open per session and URI, so
651
+ * the close would end that one too.
652
+ */
653
+ protected async undoOpen(server: RpcProxy<TServer>, uri: string, opening: DataSessionOpening<TTransfer, TServer>): Promise<void> {
654
+ if (this.hasOpen(uri, opening)) {
655
+ return;
656
+ }
657
+ this.opens.delete(uri);
658
+ this.createdUris.delete(uri);
659
+ await server.closeModelDocument({ uri, clientId: this.clientId }).catch(() => undefined);
660
+ }
661
+
662
+ /** Drop everything this session keeps of `uri`, which it no longer has open. */
663
+ protected forgetDocument(uri: string): void {
664
+ const serverUri = this.opens.get(uri)?.serverUri ?? uri;
665
+ this.openUris.delete(uri);
666
+ this.opens.delete(uri);
667
+ this.unsavedWrites.delete(uri);
668
+ this.lastAnswers.delete(uri);
669
+ this.savedVersions.delete(uri);
670
+ this.createdUris.delete(uri);
671
+ this.host.forgetDirty?.(serverUri);
672
+ }
673
+
674
+ /**
675
+ * Whether this session has `uri` open, or has an open of it under way that
676
+ * no close has marked, other than `except`. A marked open records nothing,
677
+ * so nothing can rely on it.
152
678
  */
153
- async closeDocument(uri: string): Promise<void> {
154
- const server = await this.connected();
155
- await server.closeModelDocument({ uri, clientId: this.clientId });
679
+ protected hasOpen(uri: string, except?: DataSessionOpening<TTransfer, TServer>): boolean {
680
+ return this.openUris.has(uri) || [...(this.openings.get(uri) ?? [])].some(opening => opening !== except && !opening.closed);
156
681
  }
157
682
 
158
683
  /**
159
- * Whether `event.sourceClientId` identifies this session's own write.
684
+ * Open `args.uri`, run `fn` with the opened snapshot, and close it once
685
+ * `fn` settles, whether it returned or threw. A URI this session already
686
+ * had open, or is still opening through another call, stays open: the close
687
+ * undoes only the open this call made.
688
+ */
689
+ async withOpenDocument<T>(
690
+ args: DataSessionOpenArgs<TTransfer, TServer>,
691
+ fn: (document: DataSessionDocument<TTransfer, TServer>) => MaybePromise<T>
692
+ ): Promise<T> {
693
+ // Asked once the closes and deletes of the URI under way have answered:
694
+ // before, the session still counts as open a document they are ending.
695
+ for (let ending = this.endings.get(args.uri); ending; ending = this.endings.get(args.uri)) {
696
+ await ending;
697
+ }
698
+ const alreadyOpen = this.hasOpen(args.uri);
699
+ const document = await this.openDocument(args);
700
+ try {
701
+ return await fn(document);
702
+ } finally {
703
+ if (!alreadyOpen && !this.disposed) {
704
+ await this.closeDocument({ uri: args.uri } as DataSessionCloseArgs<TTransfer, TServer>);
705
+ }
706
+ }
707
+ }
708
+
709
+ /** Write `args.model` back as this session. The session must have `args.uri` open. */
710
+ updateDocument(args: DataSessionUpdateArgs<TTransfer, TServer>): Promise<DataSessionDocument<TTransfer, TServer>> {
711
+ return this.trackWrite([args.uri], async () => {
712
+ const server = await this.connected();
713
+ const update = { ...args };
714
+ const baseHash = await this.baseHashOf(server, args.uri, args.baseVersion);
715
+ const open = this.opens.get(args.uri);
716
+ const document = await server.updateModelDocument({ ...args, clientId: this.clientId });
717
+ this.recordWrite(args.uri, open, document, baseHash, { update });
718
+ return document;
719
+ });
720
+ }
721
+
722
+ /**
723
+ * Write several documents this session has open, all or none: the server
724
+ * refuses the whole set, before any text applies, when one is stale or not
725
+ * open. Resolves to the documents in the order given.
726
+ */
727
+ updateDocuments(args: DataSessionUpdatesArgs<TTransfer, TServer>): Promise<DataSessionDocument<TTransfer, TServer>[]> {
728
+ return this.trackWrite(
729
+ args.updates.map(update => update.uri),
730
+ async () => {
731
+ // One copy for the whole call: the copy's identity is what ties its
732
+ // records together.
733
+ const updates = { ...args, updates: args.updates.map(update => ({ ...update })) };
734
+ const server = await this.connected();
735
+ const baseHashes = await Promise.all(args.updates.map(update => this.baseHashOf(server, update.uri, update.baseVersion)));
736
+ const opens = args.updates.map(update => this.opens.get(update.uri));
737
+ const documents = await server.updateModelDocuments({ ...args, clientId: this.clientId });
738
+ args.updates.forEach((update, index) =>
739
+ this.recordWrite(update.uri, opens[index], documents[index], baseHashes[index], { updates, index })
740
+ );
741
+ return documents;
742
+ }
743
+ );
744
+ }
745
+
746
+ /** Persist `args.model` to disk as this session. The session must have `args.uri` open. */
747
+ saveDocument(args: DataSessionSaveArgs<TTransfer, TServer>): Promise<TransferSavedDocument<TTransfer, DiagnosticOf<TServer>>> {
748
+ return this.trackSave(args.uri, server => server.saveModelDocument({ ...args, clientId: this.clientId }));
749
+ }
750
+
751
+ /**
752
+ * Persist the text the server holds for `args.uri` as this session, with no
753
+ * model of its own. The session must have `args.uri` open.
754
+ */
755
+ persistDocument(args: DataSessionPersistArgs<TTransfer, TServer>): Promise<TransferSavedDocument<TTransfer, DiagnosticOf<TServer>>> {
756
+ return this.trackSave(args.uri, server => server.persistModelDocument({ ...args, clientId: this.clientId }));
757
+ }
758
+
759
+ /**
760
+ * Delete `args.uri` as this session, at once: its file, then the document.
761
+ * The session must have `args.uri` open. Sent once this session's calls in
762
+ * flight on the URI have settled, as {@link closeDocument} is, and counted
763
+ * in {@link hasSavesInFlight} until it answers.
764
+ *
765
+ * The session forgets the document once the delete has succeeded: on
766
+ * hearing its own deletion, which the server sends before it answers, or
767
+ * on the answer, for a client that hears no deletions. A refused delete
768
+ * leaves the document open, as the server does.
769
+ */
770
+ deleteDocument(args: DataSessionDeleteArgs<TTransfer, TServer>): Promise<void> {
771
+ const deleting = this.trackEnding(args.uri, () =>
772
+ this.track([args.uri], async () => {
773
+ this.assertLive();
774
+ await this.settle([this.inFlight.get(args.uri)]);
775
+ const server = await this.connected();
776
+ const open = this.opens.get(args.uri);
777
+ await server.deleteModelDocument({ ...args, clientId: this.clientId });
778
+ // Still the open it was sent under: the deletion was not heard.
779
+ if (open && this.opens.get(args.uri) === open) {
780
+ open.deleted = true;
781
+ this.logger.withUri(args.uri).debug('Forgot the document: this session deleted it');
782
+ this.forgetDocument(args.uri);
783
+ }
784
+ })
785
+ );
786
+ return this.savesInFlight.track(deleting);
787
+ }
788
+
789
+ /** Run a save or persist of `uri` and record what it answered as saved. */
790
+ protected trackSave(
791
+ uri: string,
792
+ send: (server: RpcProxy<TServer>) => Promise<TransferSavedDocument<TTransfer, DiagnosticOf<TServer>>>
793
+ ): Promise<TransferSavedDocument<TTransfer, DiagnosticOf<TServer>>> {
794
+ const saving = this.track([uri], async () => {
795
+ const server = await this.connected();
796
+ const open = this.opens.get(uri);
797
+ const document = await send(server);
798
+ // Sent under no open, or under one a close or deletion has ended
799
+ // since: recorded, it would outlive that open.
800
+ if (!open || this.opens.get(uri) !== open) {
801
+ return document;
802
+ }
803
+ // Kept only when its last answer is newer than the text written. Kept
804
+ // whenever it changed while the save ran, a record the save covered
805
+ // survives, and a restore then reports it lost.
806
+ const unsaved = this.unsavedWrites.get(uri);
807
+ if (unsaved && unsaved.answer.version <= document.persisted.version) {
808
+ this.unsavedWrites.delete(uri);
809
+ }
810
+ this.recordText(uri, document);
811
+ this.createdUris.delete(uri);
812
+ // The higher of two saves' answers, which may arrive out of order.
813
+ const saved = this.savedVersions.get(uri);
814
+ if (saved === undefined || document.persisted.version > saved) {
815
+ this.savedVersions.set(uri, document.persisted.version);
816
+ }
817
+ return document;
818
+ });
819
+ return this.savesInFlight.track(saving);
820
+ }
821
+
822
+ /** Whether the session has ended, by {@link dispose} or {@link detach}. */
823
+ get isDisposed(): boolean {
824
+ return this.disposed;
825
+ }
826
+
827
+ /**
828
+ * Whether a save, persist or delete of this session has not answered yet.
829
+ * Synchronous, for a host whose exit veto must decide within the tick, such
830
+ * as Theia's `onWillStop`.
831
+ */
832
+ get hasSavesInFlight(): boolean {
833
+ return !this.savesInFlight.isIdle;
834
+ }
835
+
836
+ /**
837
+ * Resolves once the saves in flight now have answered, or
838
+ * {@link settleBeforeCloseMs} has passed. Never rejects: a failed save has
839
+ * answered too.
840
+ */
841
+ whenSavesSettled(): Promise<void> {
842
+ return this.settle([this.savesInFlight]);
843
+ }
844
+
845
+ /**
846
+ * Whether an update of this session, one a restore sends again included,
847
+ * has not answered yet. The server answers once an editor on the language
848
+ * client holds the text, so a page that reads unsaved work from its editor
849
+ * guards a reload on this too. Synchronous, for an unload guard that must
850
+ * decide within the tick.
851
+ */
852
+ get hasWritesInFlight(): boolean {
853
+ return !this.writesInFlight.isIdle;
854
+ }
855
+
856
+ /**
857
+ * Resolves to `true` once the updates in flight now have answered, so a
858
+ * save of the editor's documents started after it includes them, or to
859
+ * `false` once {@link settleWritesMs} has passed first. An update sent while
860
+ * it waits is not waited for. Never rejects.
861
+ */
862
+ async whenWritesSettled(): Promise<boolean> {
863
+ if (this.writesInFlight.isIdle) {
864
+ return true;
865
+ }
866
+ return (await this.clock.raceTimer(this.writesInFlight.whenSettled(), this.settleWritesMs)) !== TIMED_OUT;
867
+ }
868
+
869
+ /**
870
+ * Whether `sourceClientId` identifies this session's own write.
160
871
  *
161
872
  * Every watcher needs this and the check is one comparison, so getting it
162
873
  * wrong is cheap to do and expensive to find: an unfiltered echo looks
@@ -166,63 +877,691 @@ export class DataSession<TTransfer extends TransferElement> {
166
877
  return sourceClientId === this.clientId;
167
878
  }
168
879
 
169
- /** Tear down the current connection and stop tracking the port. Idempotent. */
880
+ /**
881
+ * End the session: detach it from the connection at once, and once its
882
+ * calls in flight have settled or {@link settleBeforeCloseMs} has passed,
883
+ * end it on the server, which closes everything it has open. Idempotent,
884
+ * and leaves the connection usable by its other sessions.
885
+ *
886
+ * Every later call rejects, and so does a call made earlier in the same
887
+ * tick, which has not reached the wire yet and is never sent. The server
888
+ * close is not awaited, because a `Disposable` cannot be; a close that fails
889
+ * leaves the session to the server's connection-close cleanup.
890
+ */
170
891
  dispose(): void {
171
892
  if (this.disposed) {
172
893
  return;
173
894
  }
174
895
  this.disposed = true;
175
- this.portDisposeListener.dispose();
176
- this.dropGeneration();
896
+ this.fireDispose();
897
+ const settled = this.settle([...this.inFlight.values()]);
898
+ void (async () => {
899
+ await settled;
900
+ await this.registration;
901
+ // The proxy the session registered on, never a fresh connection: a
902
+ // connection that dropped already ended the session on the server.
903
+ if (!this.detached && this.registeredOn) {
904
+ await this.registeredOn.closeSession({ clientId: this.clientId });
905
+ }
906
+ })().catch(() => undefined);
177
907
  }
178
908
 
179
- /** The live generation, building one if there is none. */
180
- protected currentGeneration(): Generation<TTransfer> {
181
- if (this.generation) {
182
- return this.generation;
909
+ /**
910
+ * Come off the connection because it is going away.
911
+ *
912
+ * Sends nothing, unlike {@link dispose}: the server ends every session on a
913
+ * connection it sees close, and the close would travel over the very
914
+ * connection being disposed.
915
+ *
916
+ * Public because the connection calls it; anyone else ends a session with
917
+ * {@link dispose}. It fires {@link onDidDispose} only if the session has not
918
+ * already ended, and after {@link dispose} it still cancels the close that
919
+ * dispose has not sent yet.
920
+ */
921
+ detach(): void {
922
+ this.detached = true;
923
+ this.openUris.clear();
924
+ this.opens.clear();
925
+ this.unsavedWrites.clear();
926
+ this.lastAnswers.clear();
927
+ this.savedVersions.clear();
928
+ this.createdUris.clear();
929
+ if (!this.disposed) {
930
+ this.disposed = true;
931
+ this.fireDispose();
932
+ }
933
+ }
934
+
935
+ /**
936
+ * Dispose {@link dirtySubscription}, {@link updateSubscription} and
937
+ * {@link deletionSubscription}, fire {@link onDidDispose} and dispose its
938
+ * emitter, so a second call fires nothing.
939
+ */
940
+ protected fireDispose(): void {
941
+ this.dirtySubscription?.dispose();
942
+ this.updateSubscription?.dispose();
943
+ this.deletionSubscription?.dispose();
944
+ this.disposeEmitter.fire(undefined);
945
+ this.disposeEmitter.dispose();
946
+ }
947
+
948
+ /**
949
+ * Register again and restore now, after the connection dropped, instead of
950
+ * on the next call. A no-op for a session with nothing open, which the next
951
+ * call restores anyway, and for one already registered on the current
952
+ * connection. A failure is retried on the connection's next ready
953
+ * generation; a call before then meets it again.
954
+ */
955
+ reconnect(): void {
956
+ if (!this.disposed && this.openUris.size > 0) {
957
+ this.connected().catch(() => undefined);
958
+ }
959
+ }
960
+
961
+ /**
962
+ * Drop the record in {@link unsavedWrites} of a document this session has
963
+ * open once the server says it turned clean, and its mark in
964
+ * {@link createdUris}: it holds no unsaved text then, and a record kept
965
+ * would have a restore report the write lost once another client's save
966
+ * changed the file.
967
+ *
968
+ * The server sends a flip only for a document someone watches, so a
969
+ * document the session writes without watching it keeps its record, and
970
+ * can still be reported lost that way.
971
+ */
972
+ protected forgetSavedWrite(event: TransferDocumentDirtyChangedEvent): void {
973
+ if (event.text?.dirty) {
974
+ return;
975
+ }
976
+ // The flip names the server's key, which is not always the caller's
977
+ // spelling that the records are kept under.
978
+ for (const [uri, open] of this.opens) {
979
+ if (open.serverUri === event.uri) {
980
+ this.unsavedWrites.delete(uri);
981
+ this.createdUris.delete(uri);
982
+ }
983
+ }
984
+ }
985
+
986
+ /**
987
+ * Drop the record in {@link unsavedWrites} of a document another client
988
+ * wrote over while the connection held: its write replaced the session's,
989
+ * so a restore has nothing of the session's to put back, and a record kept
990
+ * would have it report the write lost to the reconnect. A write superseded
991
+ * before its answer needs nothing: the answer names the other client's
992
+ * text, which the record then holds.
993
+ *
994
+ * Only a `'changed'` event from another client counts, and only where the
995
+ * document no longer holds the write: the session's own echo, and an
996
+ * integrity repair already in the write's answer, replaced nothing, and a
997
+ * `'rebuilt'` event carries no new text. Like {@link forgetSavedWrite}, it
998
+ * depends on the server sending the event, which it does only for a
999
+ * document someone watches.
1000
+ *
1001
+ * The mark in {@link createdUris} goes on any such event: the unsaved text
1002
+ * is then the other client's, and a record still kept reports the
1003
+ * session's own.
1004
+ */
1005
+ protected forgetSupersededWrite(event: TransferDocumentUpdatedEvent<TTransfer, DiagnosticOf<TServer>>): void {
1006
+ if (event.reason !== 'changed' || this.isOwnEcho(event.sourceClientId)) {
1007
+ return;
1008
+ }
1009
+ for (const [uri, open] of this.opens) {
1010
+ if (open.serverUri !== event.document.uri) {
1011
+ continue;
1012
+ }
1013
+ this.createdUris.delete(uri);
1014
+ const write = this.unsavedWrites.get(uri);
1015
+ if (write && this.restoreOutcome(write, event.document) !== 'kept') {
1016
+ this.unsavedWrites.delete(uri);
1017
+ }
1018
+ }
1019
+ }
1020
+
1021
+ /**
1022
+ * Forget a document whose file was deleted, which closed this session's
1023
+ * open. At once rather than after the calls in flight settle, which would
1024
+ * let a restore re-open the file that is gone. Unwatched rather than
1025
+ * closed: the server keeps the watch, and a close could end a re-open of a
1026
+ * re-created file still in flight. Unsaved writes are logged, not
1027
+ * reported: the client hears the deletion too. A document this session
1028
+ * created and never saved, deleted by no session, is reported as well: a
1029
+ * drop released it. An unsaved write breaks the set it was written with,
1030
+ * see {@link brokenSets}.
1031
+ *
1032
+ * This session's own deletion is neither unwatched nor logged as dropping
1033
+ * unsaved text: its delete released the watch, and its caller chose to
1034
+ * drop the text.
1035
+ */
1036
+ protected forgetDeletedDocument(event: TransferDocumentDeletedEvent): void {
1037
+ for (const [uri, open] of this.opens) {
1038
+ if (open.serverUri !== event.uri) {
1039
+ continue;
1040
+ }
1041
+ open.deleted = true;
1042
+ if (this.isOwnEcho(event.sourceClientId)) {
1043
+ this.logger.withUri(uri).debug('Forgot the document: this session deleted it');
1044
+ this.forgetDocument(uri);
1045
+ continue;
1046
+ }
1047
+ const write = this.unsavedWrites.get(uri);
1048
+ if (write) {
1049
+ this.brokenSets.add(setOf(write));
1050
+ }
1051
+ // Never saved, so no file a watcher could see removed: a deletion
1052
+ // naming no session is the release of the text a drop left behind.
1053
+ const released = this.createdUris.has(uri) && event.sourceClientId === UNKNOWN_CLIENT_ID;
1054
+ this.forgetGoneDocument(uri);
1055
+ if (released) {
1056
+ const reported = resolve(DATA_SESSION_UNSAVED_LOST, { uris: uri });
1057
+ this.host.reportError?.(new Error(reported.text), reported);
1058
+ }
1059
+ this.connected()
1060
+ .then(server => server.unwatchModelDocument({ uri, clientId: this.clientId }))
1061
+ .catch(() => undefined);
1062
+ }
1063
+ }
1064
+
1065
+ /**
1066
+ * {@link forgetDocument} a document that is gone, logging any unsaved text
1067
+ * it drops, written or created; returns whether it dropped some.
1068
+ */
1069
+ protected forgetGoneDocument(uri: string): boolean {
1070
+ const unsaved = this.unsavedWrites.has(uri) || this.createdUris.has(uri);
1071
+ if (unsaved) {
1072
+ this.logger.withUri(uri).warn('Dropped unsaved text: the document is gone');
1073
+ } else {
1074
+ this.logger.withUri(uri).debug('Forgot the document: it is gone');
1075
+ }
1076
+ this.forgetDocument(uri);
1077
+ return unsaved;
1078
+ }
1079
+
1080
+ /**
1081
+ * Register on `server`, and after a reconnect restore what the ended session
1082
+ * had. Calls issued meanwhile wait for this.
1083
+ */
1084
+ protected async register(server: RpcProxy<TServer>, reconnected: boolean): Promise<void> {
1085
+ await server.createSession({ clientId: this.clientId, label: this.label, resumeToken: this.resumeToken });
1086
+ if (reconnected) {
1087
+ await this.restore(server);
1088
+ }
1089
+ }
1090
+
1091
+ /**
1092
+ * Re-open, each under the options its {@link DataSessionOpen} holds, and
1093
+ * re-watch every document the session had open, write again what it wrote
1094
+ * since their last save where the re-open lost it, and tell the host which
1095
+ * of them lost it for good.
1096
+ *
1097
+ * Decided per document by the re-opened document's `text.hash`,
1098
+ * in {@link restoreOutcome}. Versions cannot decide a write: a revert moves
1099
+ * the version on and a restarted server numbers afresh, so the version the
1100
+ * last write was answered with never matches where a write is needed, and
1101
+ * any other version may be another client's edit, which a write would
1102
+ * overwrite.
1103
+ *
1104
+ * Only what the drop cost is reported: a write another client wrote over
1105
+ * while the connection held has no record left by then, see
1106
+ * {@link forgetSupersededWrite}.
1107
+ *
1108
+ * A write is sent again based on the re-opened version, as an ordinary
1109
+ * write, so an edit arriving in between conflicts, and a conflict is not
1110
+ * retried. Documents last written by one {@link updateDocuments} are sent
1111
+ * again by one, and only when every one of them may be; a document that
1112
+ * could not be re-opened, or that another client deleted, blocks its set.
1113
+ *
1114
+ * No caller is waiting, so the outcomes go through the host: one report
1115
+ * naming every document whose unsaved text is gone, whose record is then
1116
+ * dropped, and one per document that could not be re-opened or written
1117
+ * again for another reason than a conflict. A document that could not be
1118
+ * re-opened is forgotten; a failed write keeps its record, for the next
1119
+ * restore to decide again. A document closed while the restore runs, or
1120
+ * whose file is deleted then, is neither restored nor reported. One gone
1121
+ * while the connection was down, which the server reads back without a
1122
+ * model, is forgotten, and its deletion goes to the host as the deletion
1123
+ * no event brought; unsaved text it took with it is logged, as for a
1124
+ * deletion heard live, and reported as well for a document the session
1125
+ * created and never saved, which the drop released. A host that cannot
1126
+ * tell the client has the unsaved text of either reported. Once the session
1127
+ * is disposed, its caller has ended it, and the restore returns at its
1128
+ * next await: nothing more goes to the server or the host.
1129
+ *
1130
+ * Each document's dirty state goes to the host too, read once the watch is
1131
+ * in place and any write is sent: a flip while the connection was down, or
1132
+ * between the re-open and the watch, reached no one, and the re-open's own
1133
+ * answer misses the second. Read before the write, it would tell the client
1134
+ * a document is clean that the write is about to make dirty again.
1135
+ */
1136
+ protected async restore(server: RpcProxy<TServer>): Promise<void> {
1137
+ const writes = [...this.unsavedWrites];
1138
+ // No write sent before the drop answers any more, and a restarted
1139
+ // server numbers afresh, below the versions saved before it.
1140
+ this.savedVersions.clear();
1141
+ const reopened = new Map<string, DataSessionDocument<TTransfer, TServer>>();
1142
+ const lost: string[] = [];
1143
+ for (const uri of [...this.openUris]) {
1144
+ // Closed, or its file deleted, while the restore ran.
1145
+ if (!this.openUris.has(uri)) {
1146
+ continue;
1147
+ }
1148
+ try {
1149
+ const options = this.opens.get(uri)?.options;
1150
+ const document = await server.openModelDocument({ uri, clientId: this.clientId, options });
1151
+ if (this.disposed) {
1152
+ return;
1153
+ }
1154
+ if (!this.openUris.has(uri)) {
1155
+ // Forgotten while it re-opened. A close of the caller's would
1156
+ // follow, but a deletion sends none.
1157
+ await server.closeModelDocument({ uri, clientId: this.clientId }).catch(() => undefined);
1158
+ continue;
1159
+ }
1160
+ // Recorded before the watch, so a deletion heard while it is under
1161
+ // way finds the re-open under the URI it answered with, which a
1162
+ // restarted server may key differently.
1163
+ this.opens.set(uri, { serverUri: document.uri, deleted: false, options });
1164
+ await server.watchModelDocument({ uri, clientId: this.clientId }).catch(async (error: unknown) => {
1165
+ // Closed, or the server holds the re-open until the session
1166
+ // ends; no other call relies on it while the restore runs.
1167
+ await server.closeModelDocument({ uri, clientId: this.clientId }).catch(() => undefined);
1168
+ throw error;
1169
+ });
1170
+ if (this.disposed) {
1171
+ return;
1172
+ }
1173
+ if (this.openUris.has(uri)) {
1174
+ // Text other than this session last saw was written while the
1175
+ // connection was down, by an event it never heard.
1176
+ const known = this.lastAnswers.get(uri);
1177
+ if (this.createdUris.has(uri) && document.text !== undefined && known !== undefined && document.text.hash !== known.hash) {
1178
+ this.createdUris.delete(uri);
1179
+ }
1180
+ this.recordText(uri, document);
1181
+ }
1182
+ reopened.set(uri, document);
1183
+ } catch (error: unknown) {
1184
+ // Gone while the connection was down, which no deletion told the
1185
+ // session of: the server answers a read of it without a model.
1186
+ const read = await server.getModelDocument({ uri }).catch(() => undefined);
1187
+ if (this.disposed) {
1188
+ return;
1189
+ }
1190
+ // Forgotten meanwhile, so nothing is lost.
1191
+ if (!this.openUris.has(uri)) {
1192
+ continue;
1193
+ }
1194
+ if (read && !read.model) {
1195
+ const write = this.unsavedWrites.get(uri);
1196
+ // Named as the client last heard it, by the open's answer.
1197
+ const serverUri = this.opens.get(uri)?.serverUri ?? uri;
1198
+ // Never saved, so the drop released it and no one deleted it.
1199
+ const created = this.createdUris.has(uri);
1200
+ const unsaved = this.forgetGoneDocument(uri);
1201
+ // Kept for `reapply`, where it blocks its set as a document
1202
+ // that could not be re-opened does, and goes.
1203
+ if (write) {
1204
+ this.unsavedWrites.set(uri, write);
1205
+ }
1206
+ if (!this.host.restoreDeletion) {
1207
+ // No client hears of the deletion, so the loss is reported.
1208
+ if (unsaved) {
1209
+ lost.push(uri);
1210
+ }
1211
+ continue;
1212
+ }
1213
+ // The client hears of the deletion, so unsaved text is logged,
1214
+ // as for one heard live; the drop's release is reported too.
1215
+ if (created) {
1216
+ lost.push(uri);
1217
+ }
1218
+ try {
1219
+ this.host.restoreDeletion({ uri: serverUri, sourceClientId: UNKNOWN_CLIENT_ID });
1220
+ } catch {
1221
+ // The client's listener failed, not the restore.
1222
+ }
1223
+ continue;
1224
+ }
1225
+ // Its record goes with its set's, in `reapply`, which it blocks.
1226
+ this.openUris.delete(uri);
1227
+ this.opens.delete(uri);
1228
+ this.lastAnswers.delete(uri);
1229
+ this.savedVersions.delete(uri);
1230
+ this.createdUris.delete(uri);
1231
+ this.host.reportError?.(error, resolve(DATA_SESSION_RESTORE_FAILED, { uri, detail: describeError(error) }));
1232
+ }
1233
+ }
1234
+ const sets = new Map<object, [string, DataSessionUnsavedWrite<TTransfer, TServer>][]>();
1235
+ for (const [uri, write] of writes) {
1236
+ const set = setOf(write);
1237
+ sets.set(set, [...(sets.get(set) ?? []), [uri, write]]);
1238
+ }
1239
+ for (const members of sets.values()) {
1240
+ lost.push(...(await this.reapply(server, members, reopened)));
1241
+ if (this.disposed) {
1242
+ return;
1243
+ }
1244
+ }
1245
+ for (const uri of reopened.keys()) {
1246
+ if (!this.openUris.has(uri)) {
1247
+ continue;
1248
+ }
1249
+ // A failed read, or one without text, leaves the client's dirty
1250
+ // state as it was; the document is restored all the same.
1251
+ const current = await server.getModelDocument({ uri }).catch(() => undefined);
1252
+ if (this.disposed) {
1253
+ return;
1254
+ }
1255
+ // Again after the read: one closed or deleted meanwhile has no
1256
+ // state to tell.
1257
+ if (current?.text !== undefined && this.openUris.has(uri)) {
1258
+ // A created document reads clean only once a save gave it a
1259
+ // baseline, so its text is no longer unsaved. A write record
1260
+ // stays: a reverted document reads clean too, its write unsent.
1261
+ if (!current.text.dirty) {
1262
+ this.createdUris.delete(uri);
1263
+ }
1264
+ try {
1265
+ this.host.restoreDirty?.({ uri: current.uri, text: current.text });
1266
+ } catch {
1267
+ // The client's listener failed, not the restore: the server
1268
+ // has the document open and watched, so it stays restored.
1269
+ }
1270
+ }
1271
+ }
1272
+ if (lost.length > 0) {
1273
+ const reported = resolve(DATA_SESSION_UNSAVED_LOST, { uris: lost.join(', ') });
1274
+ this.host.reportError?.(new Error(reported.text), reported);
183
1275
  }
184
- const connection = this.port.connect();
185
- // Rejection is reported here rather than left to float: an unhandled
186
- // rejection on a connection promise is the failure mode that reads as
187
- // "the model is empty" instead of "the transport never opened".
188
- connection.catch((error: unknown) =>
189
- this.port.reportError(error, resolve(DATA_SERVER_CONNECT_FAILED, { detail: describeError(error) }))
190
- );
191
- const server = createRpcProxy<DataServerProtocol<TTransfer>, DataClientProtocol<TTransfer>>(connection, {
192
- methodNamespace: this.methodNamespace,
193
- localTarget: this.client,
194
- localMethods: DATA_CLIENT_PROTOCOL_METHODS
195
- });
196
- this.generation = { connection, server };
197
- return this.generation;
198
1276
  }
199
1277
 
200
- /** Await the connection and the server's startup gate for one generation. */
201
- protected async awaitReady(generation: Generation<TTransfer>): Promise<void> {
1278
+ /**
1279
+ * Whether the re-opened `document` still holds the session's unsaved
1280
+ * `write` (`'kept'`), holds the text the write started from, so the write
1281
+ * can be sent again (`'resend'`), or holds something else (`'lost'`).
1282
+ *
1283
+ * A document without `text` comes from a server that sends none, and
1284
+ * counts as kept only at the version the write was answered with. One
1285
+ * without a model has no version to send the write again on.
1286
+ */
1287
+ protected restoreOutcome(
1288
+ write: DataSessionUnsavedWrite<TTransfer, TServer>,
1289
+ document: DataSessionDocument<TTransfer, TServer>
1290
+ ): 'kept' | 'resend' | 'lost' {
1291
+ if (document.text === undefined) {
1292
+ return document.model?.version === write.answer.version ? 'kept' : 'lost';
1293
+ }
1294
+ if (document.text.hash === write.answer.hash) {
1295
+ return 'kept';
1296
+ }
1297
+ return document.model && write.baseHash !== undefined && document.text.hash === write.baseHash ? 'resend' : 'lost';
1298
+ }
1299
+
1300
+ /**
1301
+ * Write again, in one call and based on their `reopened` versions, the
1302
+ * `members` of one write call that the re-open lost, all or none. Returns
1303
+ * the URIs whose unsaved text is gone, and drops their records, and the
1304
+ * record of a member that could not be re-opened.
1305
+ *
1306
+ * A member whose record is no longer the one the restore started with was
1307
+ * closed, saved or disposed meanwhile, and is left out: writing it would
1308
+ * put back text its caller discarded. A set in {@link brokenSets} is
1309
+ * not written again.
1310
+ */
1311
+ protected async reapply(
1312
+ server: RpcProxy<TServer>,
1313
+ members: readonly [string, DataSessionUnsavedWrite<TTransfer, TServer>][],
1314
+ reopened: ReadonlyMap<string, DataSessionDocument<TTransfer, TServer>>
1315
+ ): Promise<string[]> {
1316
+ const current = (uri: string, write: DataSessionUnsavedWrite<TTransfer, TServer>): boolean =>
1317
+ !this.disposed && this.unsavedWrites.get(uri) === write;
1318
+ const outcomes = members
1319
+ .filter(([uri, write]) => current(uri, write))
1320
+ .map(([uri, write]) => {
1321
+ const document = reopened.get(uri);
1322
+ return { uri, write, document, outcome: document ? this.restoreOutcome(write, document) : 'failed' };
1323
+ });
1324
+ // A restarted server numbers afresh: the answers to later writes follow
1325
+ // on from the re-opened version, not from the one the record holds.
1326
+ for (const { uri, write, document, outcome } of outcomes) {
1327
+ if (outcome === 'kept' && document) {
1328
+ this.unsavedWrites.set(uri, { ...write, answer: this.answerOf(uri, document) });
1329
+ }
1330
+ }
1331
+ // A document that could not be re-opened is forgotten, and was reported
1332
+ // as such; one closed, saved or deleted while a write ran lost nothing.
1333
+ const lose = (): string[] => {
1334
+ const gone = outcomes.filter(member => member.outcome !== 'kept' && current(member.uri, member.write));
1335
+ gone.forEach(member => {
1336
+ this.unsavedWrites.delete(member.uri);
1337
+ this.createdUris.delete(member.uri);
1338
+ });
1339
+ return gone.filter(member => member.outcome === 'lost' || member.outcome === 'resend').map(member => member.uri);
1340
+ };
1341
+ if (this.brokenSets.has(setOf(members[0][1])) || outcomes.some(member => member.outcome === 'lost' || member.outcome === 'failed')) {
1342
+ return lose();
1343
+ }
1344
+ // In the order of the call's updates, which is the order of its answers.
1345
+ const resend = outcomes
1346
+ .flatMap(({ uri, write, document, outcome }) =>
1347
+ outcome === 'resend' && document?.model ? [{ uri, write, baseVersion: document.model.version }] : []
1348
+ )
1349
+ .sort((left, right) => indexOf(left.write) - indexOf(right.write));
1350
+ if (resend.length === 0) {
1351
+ return [];
1352
+ }
1353
+ const opens = resend.map(member => this.opens.get(member.uri));
1354
+ let documents: DataSessionDocument<TTransfer, TServer>[];
202
1355
  try {
203
- await generation.connection;
204
- await generation.server.waitForReady();
1356
+ const { call } = resend[0].write;
1357
+ if ('update' in call) {
1358
+ documents = [
1359
+ await this.writesInFlight.track(
1360
+ server.updateModelDocument({ ...call.update, baseVersion: resend[0].baseVersion, clientId: this.clientId })
1361
+ )
1362
+ ];
1363
+ } else {
1364
+ const baseVersion = new Map(resend.map(member => [indexOf(member.write), member.baseVersion]));
1365
+ documents = await this.writesInFlight.track(
1366
+ server.updateModelDocuments({
1367
+ ...call.updates,
1368
+ clientId: this.clientId,
1369
+ updates: call.updates.updates.flatMap((update, index) => {
1370
+ const version = baseVersion.get(index);
1371
+ return version === undefined ? [] : [{ ...update, baseVersion: version }];
1372
+ })
1373
+ })
1374
+ );
1375
+ }
205
1376
  } catch (error: unknown) {
206
- // Drop the generation so the next request retries rather than
207
- // re-awaiting a settled rejection forever.
208
- if (this.generation === generation) {
209
- this.generation = undefined;
1377
+ if (isConflictError(error)) {
1378
+ return lose();
1379
+ }
1380
+ for (const { uri, write, baseVersion } of resend) {
1381
+ // Closed, saved or deleted while the write ran: nothing to restore.
1382
+ if (!current(uri, write)) {
1383
+ continue;
1384
+ }
1385
+ this.host.reportError?.(error, resolve(DATA_SESSION_RESTORE_FAILED, { uri, detail: describeError(error) }));
1386
+ // Kept for the next restore, and numbered from the re-opened
1387
+ // version, as the kept records are: a record numbered by a server
1388
+ // that has since restarted would have later answers ignored.
1389
+ this.unsavedWrites.set(uri, { ...write, answer: { ...write.answer, version: baseVersion } });
1390
+ }
1391
+ return [];
1392
+ }
1393
+ resend.forEach((member, index) => {
1394
+ if (current(member.uri, member.write)) {
1395
+ // Recorded afresh, since the answer of a restarted server may be
1396
+ // numbered below the one it replaces.
1397
+ this.unsavedWrites.delete(member.uri);
1398
+ this.recordWrite(member.uri, opens[index], documents[index], member.write.baseHash, member.write.call);
1399
+ }
1400
+ });
1401
+ return [];
1402
+ }
1403
+
1404
+ /**
1405
+ * The text hash of the version `baseVersion` names for `uri`, for a write that
1406
+ * starts the URI's record in {@link unsavedWrites}; `undefined` for any
1407
+ * other write, whose record keeps the base it has.
1408
+ *
1409
+ * Taken from {@link lastAnswers} when that is at the version, otherwise
1410
+ * read, and kept only when the read answers that version: a server's text
1411
+ * changes only with its version, so the text at a version is the text the
1412
+ * write, once it passes the gate, was applied to.
1413
+ */
1414
+ protected async baseHashOf(server: RpcProxy<TServer>, uri: string, baseVersion: BaseVersion): Promise<string | undefined> {
1415
+ if (this.unsavedWrites.has(uri) || !isModelVersion(baseVersion)) {
1416
+ return undefined;
1417
+ }
1418
+ const known = this.lastAnswers.get(uri);
1419
+ if (known?.version === baseVersion) {
1420
+ return known.hash;
1421
+ }
1422
+ const read = await server.getModelDocument({ uri }).catch(() => undefined);
1423
+ return read?.text?.version === baseVersion ? read.text.hash : undefined;
1424
+ }
1425
+
1426
+ /**
1427
+ * Record `document` as the answer to a write of `uri` sent under `open`,
1428
+ * keeping the base of the URI's record if it has one. An answer sent under
1429
+ * no open, or under one that has ended, is ignored. So is one numbered below
1430
+ * the record's: two writes of `uri` in flight at once may answer out of
1431
+ * order, and the record holds the one applied last.
1432
+ *
1433
+ * So is one numbered at or below the URI's entry in {@link savedVersions}.
1434
+ * The save came after that write was applied, so the save persisted its
1435
+ * text or a later write replaced it, and its answer carries the text as it
1436
+ * was when sent, which a restore would report as lost.
1437
+ */
1438
+ protected recordWrite(
1439
+ uri: string,
1440
+ open: DataSessionOpen<TTransfer, TServer> | undefined,
1441
+ document: DataSessionDocument<TTransfer, TServer>,
1442
+ baseHash: string | undefined,
1443
+ call: DataSessionUnsavedWrite<TTransfer, TServer>['call']
1444
+ ): void {
1445
+ // Recorded, it would outlive that open.
1446
+ if (!open || this.opens.get(uri) !== open) {
1447
+ return;
1448
+ }
1449
+ const answer = this.answerOf(uri, document);
1450
+ const kept = this.unsavedWrites.get(uri);
1451
+ if (kept && answer.version < kept.answer.version) {
1452
+ return;
1453
+ }
1454
+ const saved = this.savedVersions.get(uri);
1455
+ if (saved !== undefined && answer.version <= saved) {
1456
+ return;
1457
+ }
1458
+ this.unsavedWrites.set(uri, { baseHash: kept ? kept.baseHash : baseHash, answer, call });
1459
+ this.recordText(uri, document);
1460
+ }
1461
+
1462
+ /**
1463
+ * What {@link DataSessionUnsavedWrite.answer} keeps of `document`. Every write
1464
+ * and open answers with a model; one without is reported and counted older
1465
+ * than every version, so it never replaces a real answer.
1466
+ */
1467
+ protected answerOf(
1468
+ uri: string,
1469
+ document: DataSessionDocument<TTransfer, TServer>
1470
+ ): DataSessionUnsavedWrite<TTransfer, TServer>['answer'] {
1471
+ if (!document.model) {
1472
+ const reported = resolve(DATA_SESSION_ANSWER_WITHOUT_MODEL, { uri });
1473
+ this.host.reportError?.(new Error(reported.text), reported);
1474
+ return { version: UNRECORDED_VERSION, hash: document.text?.hash };
1475
+ }
1476
+ return { version: document.model.version, hash: document.text?.hash };
1477
+ }
1478
+
1479
+ /** Keep `document`'s text in {@link lastAnswers}, or forget it for a server that sends none. */
1480
+ protected recordText(uri: string, document: DataSessionDocument<TTransfer, TServer>): void {
1481
+ if (document.text) {
1482
+ this.lastAnswers.set(uri, document.text);
1483
+ } else {
1484
+ this.lastAnswers.delete(uri);
1485
+ }
1486
+ }
1487
+
1488
+ /** Run `call`, counted as in flight on each of `uris` until it settles. */
1489
+ protected track<T>(uris: readonly string[], call: () => Promise<T>): Promise<T> {
1490
+ const running = call();
1491
+ for (const uri of uris) {
1492
+ let tracker = this.inFlight.get(uri);
1493
+ if (tracker === undefined) {
1494
+ tracker = new PendingWorkTracker();
1495
+ this.inFlight.set(uri, tracker);
210
1496
  }
211
- this.port.reportError(error, resolve(DATA_SERVER_NOT_READY, { detail: describeError(error) }));
212
- throw error;
1497
+ tracker.track(running);
213
1498
  }
1499
+ return running;
1500
+ }
1501
+
1502
+ /** {@link track} an update of `uris`, counted in {@link writesInFlight} too. */
1503
+ protected trackWrite<T>(uris: readonly string[], call: () => Promise<T>): Promise<T> {
1504
+ return this.writesInFlight.track(this.track(uris, call));
1505
+ }
1506
+
1507
+ /**
1508
+ * {@link track} an open of `uri`, kept in {@link openings} until it settles,
1509
+ * and sent once the closes and deletes of `uri` called before it have
1510
+ * answered.
1511
+ */
1512
+ protected trackOpen<T>(
1513
+ uri: string,
1514
+ options: DataSessionOpenOptions<TTransfer, TServer>,
1515
+ call: (opening: DataSessionOpening<TTransfer, TServer>) => Promise<T>
1516
+ ): Promise<T> {
1517
+ const opening: DataSessionOpening<TTransfer, TServer> = { closed: false, options };
1518
+ const openings = this.openings.get(uri) ?? new Set<DataSessionOpening<TTransfer, TServer>>();
1519
+ this.openings.set(uri, openings.add(opening));
1520
+ const done = (): void => {
1521
+ openings.delete(opening);
1522
+ if (openings.size === 0 && this.openings.get(uri) === openings) {
1523
+ this.openings.delete(uri);
1524
+ }
1525
+ };
1526
+ const ending = this.endings.get(uri);
1527
+ const running = this.track([uri], () => (ending ? ending.then(() => call(opening)) : call(opening)));
1528
+ running.then(done, done);
1529
+ return running;
214
1530
  }
215
1531
 
216
1532
  /**
217
- * Discard the current generation, disposing its connection if it opened.
218
- * The next {@link connected} builds a fresh one.
1533
+ * Run `end`, a close or delete of `uri`, kept in {@link endings} until it
1534
+ * and every earlier one of `uri` have settled.
219
1535
  */
220
- protected dropGeneration(): void {
221
- const generation = this.generation;
222
- this.generation = undefined;
223
- if (!generation) {
1536
+ protected trackEnding(uri: string, end: () => Promise<void>): Promise<void> {
1537
+ const ending = end();
1538
+ const settled = Promise.allSettled([this.endings.get(uri), ending]);
1539
+ this.endings.set(uri, settled);
1540
+ void settled.then(() => {
1541
+ if (this.endings.get(uri) === settled) {
1542
+ this.endings.delete(uri);
1543
+ }
1544
+ });
1545
+ return ending;
1546
+ }
1547
+
1548
+ /** Wait until the work `trackers` hold now has settled, or {@link settleBeforeCloseMs} has passed. */
1549
+ protected async settle(trackers: Iterable<PendingWorkTracker | undefined>): Promise<void> {
1550
+ const pending = [...trackers].filter((tracker): tracker is PendingWorkTracker => tracker !== undefined && !tracker.isIdle);
1551
+ if (pending.length === 0) {
224
1552
  return;
225
1553
  }
226
- generation.connection.then(connection => connection.dispose()).catch(() => undefined);
1554
+ await this.clock.raceTimer(Promise.all(pending.map(tracker => tracker.whenSettled())), this.settleBeforeCloseMs);
1555
+ }
1556
+
1557
+ /**
1558
+ * Throw a `SessionClosedError` once the session has ended. {@link connected}
1559
+ * runs it again after each of its waits, since a session disposed during
1560
+ * one would otherwise register or send after the close.
1561
+ */
1562
+ protected assertLive(): void {
1563
+ if (this.disposed) {
1564
+ throw new SessionClosedError(this.clientId);
1565
+ }
227
1566
  }
228
1567
  }