@hydranium/protocol 1.0.0-next.39 → 1.0.0-next.390

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