@hydranium/protocol 1.0.0-next.28 → 1.0.0-next.280

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