@hydranium/protocol 1.0.0-next.29 → 1.0.0-next.299

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