@hydranium/protocol 1.0.0-next.27 → 1.0.0-next.271

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