@hydranium/protocol 1.0.0-next.30 → 1.0.0-next.301

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