@hydranium/protocol 1.0.0-next.27 → 1.0.0-next.271

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