@hydranium/protocol 1.0.0-next.28 → 1.0.0-next.281

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