@hydranium/protocol 1.0.0-next.34 → 1.0.0-next.340

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