@hydranium/protocol 1.0.0-next.36 → 1.0.0-next.360

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