@hydranium/protocol 1.0.0-next.19 → 1.0.0-next.192

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 (205) hide show
  1. package/README.md +35 -1
  2. package/lib/abstract-logger.d.ts.map +1 -1
  3. package/lib/abstract-logger.js.map +1 -1
  4. package/lib/client/data-connection.d.ts +157 -0
  5. package/lib/client/data-connection.d.ts.map +1 -0
  6. package/lib/client/data-connection.js +236 -0
  7. package/lib/client/data-connection.js.map +1 -0
  8. package/lib/client/data-events.d.ts +13 -1
  9. package/lib/client/data-events.d.ts.map +1 -1
  10. package/lib/client/data-events.js +21 -0
  11. package/lib/client/data-events.js.map +1 -1
  12. package/lib/client/data-port.d.ts +24 -22
  13. package/lib/client/data-port.d.ts.map +1 -1
  14. package/lib/client/data-session.d.ts +461 -81
  15. package/lib/client/data-session.d.ts.map +1 -1
  16. package/lib/client/data-session.js +725 -108
  17. package/lib/client/data-session.js.map +1 -1
  18. package/lib/client/index.d.ts +14 -9
  19. package/lib/client/index.d.ts.map +1 -1
  20. package/lib/client/index.js +14 -9
  21. package/lib/client/index.js.map +1 -1
  22. package/lib/client/message-relay.d.ts +9 -3
  23. package/lib/client/message-relay.d.ts.map +1 -1
  24. package/lib/client/message-relay.js +11 -5
  25. package/lib/client/message-relay.js.map +1 -1
  26. package/lib/client/post-message-transport.d.ts +64 -3
  27. package/lib/client/post-message-transport.d.ts.map +1 -1
  28. package/lib/client/post-message-transport.js +175 -1
  29. package/lib/client/post-message-transport.js.map +1 -1
  30. package/lib/client/rpc-connection.d.ts +149 -0
  31. package/lib/client/rpc-connection.d.ts.map +1 -0
  32. package/lib/client/rpc-connection.js +202 -0
  33. package/lib/client/rpc-connection.js.map +1 -0
  34. package/lib/client-ids.d.ts +45 -0
  35. package/lib/client-ids.d.ts.map +1 -0
  36. package/lib/client-ids.js +48 -0
  37. package/lib/client-ids.js.map +1 -0
  38. package/lib/clock.d.ts +38 -0
  39. package/lib/clock.d.ts.map +1 -1
  40. package/lib/clock.js +36 -1
  41. package/lib/clock.js.map +1 -1
  42. package/lib/data/data-protocol-methods.d.ts +4 -4
  43. package/lib/data/data-protocol-methods.d.ts.map +1 -1
  44. package/lib/data/data-protocol-methods.js +11 -1
  45. package/lib/data/data-protocol-methods.js.map +1 -1
  46. package/lib/data/data-server-protocol.d.ts +117 -36
  47. package/lib/data/data-server-protocol.d.ts.map +1 -1
  48. package/lib/data/events.d.ts +110 -15
  49. package/lib/data/events.d.ts.map +1 -1
  50. package/lib/data/requests.d.ts +67 -11
  51. package/lib/data/requests.d.ts.map +1 -1
  52. package/lib/debouncer.d.ts.map +1 -1
  53. package/lib/debouncer.js.map +1 -1
  54. package/lib/errors.d.ts +181 -29
  55. package/lib/errors.d.ts.map +1 -1
  56. package/lib/errors.js +261 -29
  57. package/lib/errors.js.map +1 -1
  58. package/lib/glsp-save-model-actions.d.ts +50 -0
  59. package/lib/glsp-save-model-actions.d.ts.map +1 -0
  60. package/lib/glsp-save-model-actions.js +28 -0
  61. package/lib/glsp-save-model-actions.js.map +1 -0
  62. package/lib/index.d.ts +4 -0
  63. package/lib/index.d.ts.map +1 -1
  64. package/lib/index.js +7 -0
  65. package/lib/index.js.map +1 -1
  66. package/lib/latency-collector.d.ts +8 -4
  67. package/lib/latency-collector.d.ts.map +1 -1
  68. package/lib/latency-collector.js.map +1 -1
  69. package/lib/logger.d.ts +22 -1
  70. package/lib/logger.d.ts.map +1 -1
  71. package/lib/logger.js +31 -3
  72. package/lib/logger.js.map +1 -1
  73. package/lib/messages/index.d.ts +29 -0
  74. package/lib/messages/index.d.ts.map +1 -0
  75. package/lib/messages/index.js +59 -0
  76. package/lib/messages/index.js.map +1 -0
  77. package/lib/messages/primitives.d.ts +188 -0
  78. package/lib/messages/primitives.d.ts.map +1 -0
  79. package/lib/messages/primitives.js +161 -0
  80. package/lib/messages/primitives.js.map +1 -0
  81. package/lib/model-server.d.ts +60 -13
  82. package/lib/model-server.d.ts.map +1 -1
  83. package/lib/model-server.js +4 -2
  84. package/lib/model-server.js.map +1 -1
  85. package/lib/model-service/base-version.d.ts +64 -0
  86. package/lib/model-service/base-version.d.ts.map +1 -0
  87. package/lib/model-service/base-version.js +43 -0
  88. package/lib/model-service/base-version.js.map +1 -0
  89. package/lib/model-service/index.d.ts +1 -1
  90. package/lib/model-service/index.d.ts.map +1 -1
  91. package/lib/model-service/index.js +4 -5
  92. package/lib/model-service/index.js.map +1 -1
  93. package/lib/model-service/reference-candidate.d.ts +5 -3
  94. package/lib/model-service/reference-candidate.d.ts.map +1 -1
  95. package/lib/noop-logger.d.ts.map +1 -1
  96. package/lib/noop-logger.js.map +1 -1
  97. package/lib/observable-value.js.map +1 -1
  98. package/lib/patch-merge.d.ts +35 -32
  99. package/lib/patch-merge.d.ts.map +1 -1
  100. package/lib/patch-merge.js +67 -23
  101. package/lib/patch-merge.js.map +1 -1
  102. package/lib/profile-session.d.ts +8 -4
  103. package/lib/profile-session.d.ts.map +1 -1
  104. package/lib/profile-session.js.map +1 -1
  105. package/lib/reconcile-write.d.ts +65 -0
  106. package/lib/reconcile-write.d.ts.map +1 -0
  107. package/lib/reconcile-write.js +67 -0
  108. package/lib/reconcile-write.js.map +1 -0
  109. package/lib/rpc/bind-rpc-methods.d.ts +29 -3
  110. package/lib/rpc/bind-rpc-methods.d.ts.map +1 -1
  111. package/lib/rpc/bind-rpc-methods.js +22 -3
  112. package/lib/rpc/bind-rpc-methods.js.map +1 -1
  113. package/lib/rpc/create-rpc-proxy.d.ts +10 -0
  114. package/lib/rpc/create-rpc-proxy.d.ts.map +1 -1
  115. package/lib/rpc/create-rpc-proxy.js +12 -2
  116. package/lib/rpc/create-rpc-proxy.js.map +1 -1
  117. package/lib/rpc/wire-prefix.js.map +1 -1
  118. package/lib/testing/catalogue-audit.d.ts +80 -0
  119. package/lib/testing/catalogue-audit.d.ts.map +1 -0
  120. package/lib/testing/catalogue-audit.js +94 -0
  121. package/lib/testing/catalogue-audit.js.map +1 -0
  122. package/lib/testing/data-doubles.d.ts +13 -12
  123. package/lib/testing/data-doubles.d.ts.map +1 -1
  124. package/lib/testing/data-doubles.js +19 -5
  125. package/lib/testing/data-doubles.js.map +1 -1
  126. package/lib/testing/fake-clock.d.ts +9 -1
  127. package/lib/testing/fake-clock.d.ts.map +1 -1
  128. package/lib/testing/fake-clock.js +54 -45
  129. package/lib/testing/fake-clock.js.map +1 -1
  130. package/lib/testing/index.d.ts +1 -0
  131. package/lib/testing/index.d.ts.map +1 -1
  132. package/lib/testing/index.js +5 -2
  133. package/lib/testing/index.js.map +1 -1
  134. package/lib/testing/node/duplex-connection.js.map +1 -1
  135. package/lib/testing/node/duplex-stream.js.map +1 -1
  136. package/lib/testing/node/index.d.ts +1 -0
  137. package/lib/testing/node/index.d.ts.map +1 -1
  138. package/lib/testing/node/index.js +2 -2
  139. package/lib/testing/node/index.js.map +1 -1
  140. package/lib/testing/node/message-port-pair.d.ts +25 -0
  141. package/lib/testing/node/message-port-pair.d.ts.map +1 -0
  142. package/lib/testing/node/message-port-pair.js +26 -0
  143. package/lib/testing/node/message-port-pair.js.map +1 -0
  144. package/lib/testing/wait-for.js.map +1 -1
  145. package/lib/tracer.d.ts.map +1 -1
  146. package/lib/tracer.js.map +1 -1
  147. package/lib/transfer-diagnostic.d.ts +33 -0
  148. package/lib/transfer-diagnostic.d.ts.map +1 -1
  149. package/lib/transfer-diagnostic.js +23 -0
  150. package/lib/transfer-diagnostic.js.map +1 -1
  151. package/lib/transfer-document.d.ts +59 -32
  152. package/lib/transfer-document.d.ts.map +1 -1
  153. package/lib/transfer-document.js +17 -9
  154. package/lib/transfer-document.js.map +1 -1
  155. package/lib/uri.d.ts.map +1 -1
  156. package/lib/uri.js.map +1 -1
  157. package/lib/util.d.ts +8 -0
  158. package/lib/util.d.ts.map +1 -1
  159. package/lib/util.js +32 -0
  160. package/lib/util.js.map +1 -1
  161. package/package.json +27 -18
  162. package/src/client/data-connection.ts +314 -0
  163. package/src/client/data-events.ts +33 -1
  164. package/src/client/data-port.ts +25 -23
  165. package/src/client/data-session.ts +922 -126
  166. package/src/client/index.ts +14 -9
  167. package/src/client/message-relay.ts +29 -7
  168. package/src/client/post-message-transport.ts +219 -4
  169. package/src/client/rpc-connection.ts +268 -0
  170. package/src/client-ids.ts +49 -0
  171. package/src/clock.ts +56 -0
  172. package/src/data/data-protocol-methods.ts +12 -4
  173. package/src/data/data-server-protocol.ts +140 -36
  174. package/src/data/events.ts +116 -15
  175. package/src/data/requests.ts +71 -11
  176. package/src/errors.ts +311 -36
  177. package/src/glsp-save-model-actions.ts +59 -0
  178. package/src/index.ts +7 -0
  179. package/src/latency-collector.ts +8 -3
  180. package/src/logger.ts +28 -2
  181. package/src/messages/index.ts +36 -0
  182. package/src/messages/primitives.ts +271 -0
  183. package/src/model-server.ts +63 -18
  184. package/src/model-service/base-version.ts +72 -0
  185. package/src/model-service/index.ts +4 -5
  186. package/src/model-service/reference-candidate.ts +5 -3
  187. package/src/patch-merge.ts +97 -42
  188. package/src/profile-session.ts +9 -4
  189. package/src/reconcile-write.ts +124 -0
  190. package/src/rpc/bind-rpc-methods.ts +49 -4
  191. package/src/rpc/create-rpc-proxy.ts +20 -2
  192. package/src/testing/catalogue-audit.ts +111 -0
  193. package/src/testing/data-doubles.ts +42 -17
  194. package/src/testing/fake-clock.ts +62 -47
  195. package/src/testing/index.ts +5 -2
  196. package/src/testing/node/index.ts +2 -2
  197. package/src/testing/node/message-port-pair.ts +40 -0
  198. package/src/transfer-diagnostic.ts +40 -0
  199. package/src/transfer-document.ts +74 -34
  200. package/src/util.ts +33 -0
  201. package/lib/model-service/args.d.ts +0 -64
  202. package/lib/model-service/args.d.ts.map +0 -1
  203. package/lib/model-service/args.js +0 -11
  204. package/lib/model-service/args.js.map +0 -1
  205. package/src/model-service/args.ts +0 -67
@@ -8,78 +8,184 @@
8
8
  * SPDX-License-Identifier: MIT
9
9
  ********************************************************************************/
10
10
  Object.defineProperty(exports, "__esModule", { value: true });
11
- exports.DataSession = void 0;
12
- const data_1 = require("../data");
13
- const rpc_1 = require("../rpc");
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");
16
+ const primitives_1 = require("../messages/primitives");
14
17
  /**
15
- * The host-invariant half of talking to the data head: everything above
16
- * {@link DataPort} that would otherwise be re-derived by every host
17
- * adapter.
18
+ * A session could not re-open a document it had open after its connection
19
+ * dropped, and forgot it; or could not write it again for another reason than
20
+ * a conflict, and keeps its unsaved edits for the next restore.
21
+ */
22
+ 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}');
23
+ /** A write or open of `{uri}` that the data server answered without a model. */
24
+ 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.');
25
+ /**
26
+ * A session re-opened documents after its connection dropped and cannot put
27
+ * back what it wrote to them since their last save: another client changed
28
+ * them, even while the session was still connected; the session could not
29
+ * tell the text its writes started from, or lost another document written with
30
+ * them; or the write it sent again conflicted. The session's unsaved edits may
31
+ * be gone, and it no longer holds them.
32
+ */
33
+ 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.');
34
+ /** Where `write` stands in the `updateDocuments` call it was last written by; `0` for a single update. */
35
+ function indexOf(write) {
36
+ return 'index' in write.call ? write.call.index : 0;
37
+ }
38
+ /**
39
+ * One participant on a data connection: a properties panel, a tree, a form
40
+ * editor. The client side of a server client session, registered over the
41
+ * wire under {@link clientId}.
42
+ *
43
+ * The session writes only what it has open: the server refuses its update or
44
+ * save of a document it has not opened with a `DocumentNotOpenError` code.
45
+ * Every call waits for the registration, so the first can be issued at once.
18
46
  *
19
- * Three jobs, and deliberately no fourth:
47
+ * Every document operation stamps {@link clientId} itself. A caller that
48
+ * passed its own could pass another participant's, and the server would
49
+ * attribute the write and close the document accordingly.
20
50
  *
21
- * 1. **Build the typed proxy** over the port's connection, with the framework's
22
- * wire prefix and its drift-proof client-method allowlist.
23
- * 2. **Own the readiness gate** — `waitForReady` once per connection, shared
24
- * across concurrent callers. A socket client can connect before the
25
- * workspace walk finishes, and an early request is then answered correctly
26
- * from an empty registry, which reads as a broken project tier rather than
27
- * as a race.
28
- * 3. **Own the reconnect policy**, by dropping its connection generation when
29
- * the port disposes and building a fresh one on the next request.
51
+ * {@link closeDocument} and {@link dispose} first wait, up to
52
+ * {@link settleBeforeCloseMs}, for this session's calls still in flight on the
53
+ * URI, or on any URI for `dispose`: a save sent just before its close would
54
+ * otherwise reach the server after it, and fail as not open.
30
55
  *
31
- * It does **not** wrap the protocol methods; callers reach them through
32
- * {@link connected}. The one exception is {@link openDocument}, which exists
33
- * because the open/watch *order* is silently wrong the other way round — see
34
- * its own doc.
56
+ * After the connection drops, the session registers again under the same id,
57
+ * re-opens and re-watches what it had open, tells the client of their dirty
58
+ * state where it changed, and reports the documents whose unsaved edits did
59
+ * not survive; see {@link restore}. The connection does this at
60
+ * once for a session with documents open, and any session's next call does it
61
+ * too.
35
62
  *
36
- * Generic over the transfer root so this file names no grammar. An adopter
37
- * binds the concrete root (or the union of them, for a multi-grammar head) at
38
- * its own edge.
63
+ * Generic over the transfer root so this file names no grammar.
64
+ *
65
+ * `TServer` is bound to a server answering with ITS OWN diagnostic shape, read
66
+ * back off the parameter being bound. Simplifying that to
67
+ * `DataServerProtocol<TTransfer>` compiles and costs the wrappers their
68
+ * return type: every call through `TServer` would resolve against that looser
69
+ * bound, so an adopter's diagnostics would come back as the framework's and
70
+ * the document would have to be cast on the way out.
39
71
  */
40
72
  class DataSession {
41
- port;
42
- client;
43
- methodNamespace;
44
- /** The current generation, or `undefined` before the first request / after a teardown. */
45
- generation;
73
+ clientId;
74
+ host;
75
+ label;
76
+ /**
77
+ * How long {@link closeDocument} and {@link dispose} wait for this session's
78
+ * calls in flight before closing anyway. Long, because the wait only runs
79
+ * out when a call hangs, and a close sent while a save is still running
80
+ * fails that save.
81
+ */
82
+ settleBeforeCloseMs = 10_000;
83
+ /**
84
+ * The clock {@link settleBeforeCloseMs} runs on. {@link DataSessionHost}
85
+ * carries no {@link Clock}, so a subclass replaces this field as it
86
+ * replaces the bound.
87
+ */
88
+ clock = new clock_1.SystemClock();
89
+ /** URIs this session has open, re-opened after a reconnect. */
90
+ openUris = new Set();
91
+ /**
92
+ * Per URI in {@link openUris}, the URI the server's last answer to its open
93
+ * or re-open named. The server keys its notifications by it, and so does
94
+ * the host's record of what its client was told.
95
+ */
96
+ serverUris = new Map();
97
+ /**
98
+ * Per URI, how many opens of it this session has under way. Such a URI
99
+ * counts as open for {@link withOpenDocument}, which would otherwise close
100
+ * it under the open that is still being made.
101
+ */
102
+ openingUris = new Map();
103
+ /** Per URI written since its last save, what {@link restore} needs to write it again. */
104
+ unsavedWrites = new Map();
105
+ /**
106
+ * Per URI this session has open, the text of the last document one of its
107
+ * own calls was answered with, which spares the read a first unsaved write
108
+ * otherwise makes for its base; see {@link baseHashOf}.
109
+ */
110
+ lastAnswers = new Map();
111
+ /**
112
+ * Per URI this session has open, the model version its last save of it was
113
+ * answered with; see {@link recordWrite}. Only a save sets it: an open
114
+ * answers at the version of a write still in flight as well, and that
115
+ * write is not saved.
116
+ */
117
+ savedVersions = new Map();
118
+ /** Per URI, this session's calls still in flight on it, which a close waits for. */
119
+ inFlight = new Map();
120
+ /** This session's saves still in flight, which a host's exit waits for; see {@link hasSavesInFlight}. */
121
+ savesInFlight = new Set();
122
+ disposeEmitter = new vscode_jsonrpc_1.Emitter();
123
+ /**
124
+ * Fires once when the session ends, by {@link dispose} or {@link detach}, as
125
+ * soon as it rejects further calls and before any close is sent. For a
126
+ * session its connection created, the connection's listener runs first, so
127
+ * the id is free again on that connection by the time any other listener
128
+ * runs; the server still holds it until the close arrives, and refuses a new
129
+ * session under it until then.
130
+ *
131
+ * A listener subscribed once the session has ended is never called, so a
132
+ * late subscriber checks {@link isDisposed} first.
133
+ */
134
+ onDidDispose = this.disposeEmitter.event;
135
+ /**
136
+ * Sent with every registration, so the server lets this session register
137
+ * its id again while the dropped connection's session is still live there:
138
+ * a server that has not yet noticed the drop would otherwise refuse the id
139
+ * as a duplicate until it does.
140
+ */
141
+ resumeToken = globalThis.crypto.randomUUID();
142
+ /** The proxy the session is registered on; another one means the connection was replaced. */
143
+ registeredOn;
144
+ registration;
46
145
  disposed = false;
47
- portDisposeListener;
48
- constructor(port, client, options = {}) {
49
- this.port = port;
50
- this.client = client;
51
- this.methodNamespace = options.methodNamespace ?? data_1.DATA_SERVER_WIRE_PREFIX;
52
- this.portDisposeListener = this.port.onDispose(() => this.dropGeneration());
53
- }
54
- /** The identity every request is made under — the port's, not a second one. */
55
- get clientId() {
56
- return this.port.clientId;
146
+ /**
147
+ * Disposed through {@link detach} rather than {@link dispose}, so nothing may
148
+ * be sent. Folding it into {@link disposed} would send the session's close
149
+ * over a connection that is going away.
150
+ */
151
+ detached = false;
152
+ /** The subscription to the host's `onDidChangeDirty`, disposed with the session. */
153
+ dirtySubscription;
154
+ /** The subscription to the host's `onDidUpdateDocument`, disposed with the session. */
155
+ updateSubscription;
156
+ constructor(clientId, host, label) {
157
+ this.clientId = clientId;
158
+ this.host = host;
159
+ this.label = label;
160
+ this.dirtySubscription = host.onDidChangeDirty?.(event => this.forgetSavedWrite(event));
161
+ this.updateSubscription = host.onDidUpdateDocument?.(event => this.forgetSupersededWrite(event));
57
162
  }
58
163
  /**
59
- * The connected, READY server proxy.
60
- *
61
- * Returns the proxy rather than `void` on purpose. A reconnect replaces the
62
- * proxy, so a caller that cached one from an earlier call would go on
63
- * addressing a dead connection with no error — handing it back per call
64
- * makes the stale reference unrepresentable.
65
- *
66
- * Concurrent callers share one readiness promise, so `waitForReady` is
67
- * awaited once per generation and not once per caller.
164
+ * The connected, READY server proxy once this session is registered on it,
165
+ * for protocol methods this session does not wrap. The proxy stamps
166
+ * nothing: pass this session's {@link clientId} to any method that carries
167
+ * one.
68
168
  */
69
169
  async connected() {
70
- if (this.disposed) {
71
- throw new Error('DataSession is disposed');
72
- }
73
- const generation = this.currentGeneration();
74
- if (!generation.ready) {
75
- generation.ready = this.awaitReady(generation);
170
+ // `async` so a disposed session REJECTS rather than throwing
171
+ // synchronously: the connection's own `connected` rejects, and a caller
172
+ // reaching for `.catch` on one of them would not catch the other.
173
+ this.assertLive();
174
+ const server = await this.host.connected();
175
+ // Again after the wait: a session disposed meanwhile must not register,
176
+ // since its dispose found nothing registered to end.
177
+ this.assertLive();
178
+ if (this.registeredOn !== server) {
179
+ const reconnected = this.registeredOn !== undefined;
180
+ this.registeredOn = server;
181
+ this.registration = this.register(server, reconnected);
76
182
  }
77
- await generation.ready;
78
- return generation.server;
183
+ await this.registration;
184
+ return server;
79
185
  }
80
186
  /**
81
- * Open `uri` for editing and start watching it, in that order, returning
82
- * the opened snapshot.
187
+ * Open `args.uri` for editing and start watching it, in that order,
188
+ * returning the opened snapshot.
83
189
  *
84
190
  * **The order is the whole reason this method exists.**
85
191
  * `watchModelDocument` baselines its dedup fingerprint from the *current*
@@ -87,30 +193,165 @@ class DataSession {
87
193
  * baseline, and the first phase event after the open arrives as a spurious
88
194
  * `'changed'` — which a widget that resets its in-memory root to the server
89
195
  * view misreads as a concurrent third-party write, losing whatever the user
90
- * had typed. Nothing about the wrong order fails loudly, so it is encoded
91
- * here rather than documented and re-derived.
196
+ * had typed.
92
197
  *
93
- * Note that the returned snapshot's empty `diagnostics` does not mean
94
- * valid: `open` settles at the integrity landmark, not at validation.
198
+ * Note that the returned snapshot's model usually has no `diagnostics`:
199
+ * `open` settles at the integrity landmark, not at validation.
95
200
  * Validity arrives asynchronously on `onDocumentUpdated`, or synchronously
96
201
  * from `getModelDocument({ includeDiagnostics: true })`.
97
202
  */
98
- async openDocument(uri) {
99
- const server = await this.connected();
100
- const document = await server.openModelDocument({ uri, clientId: this.clientId });
101
- await server.watchModelDocument({ uri, clientId: this.clientId });
203
+ openDocument(args) {
204
+ return this.trackOpen(args.uri, async () => {
205
+ const server = await this.connected();
206
+ return this.watchOpened(server, args.uri, await server.openModelDocument({ ...args, clientId: this.clientId }));
207
+ });
208
+ }
209
+ /**
210
+ * Create a document that exists nowhere yet, open and watched for this
211
+ * session; it reaches disk with the first {@link saveDocument}. The server
212
+ * refuses a URI that exists on disk or that any client has open.
213
+ */
214
+ createDocument(args) {
215
+ return this.trackOpen(args.uri, async () => {
216
+ const server = await this.connected();
217
+ return this.watchOpened(server, args.uri, await server.createModelDocument({ ...args, clientId: this.clientId }));
218
+ });
219
+ }
220
+ /**
221
+ * Watch a document this session just opened, and record it as open. A
222
+ * failed watch closes it again: the caller sees a failed open and so would
223
+ * never close it.
224
+ */
225
+ async watchOpened(server, uri, document) {
226
+ try {
227
+ await server.watchModelDocument({ uri, clientId: this.clientId });
228
+ }
229
+ catch (error) {
230
+ await server.closeModelDocument({ uri, clientId: this.clientId }).catch(() => undefined);
231
+ throw error;
232
+ }
233
+ this.openUris.add(uri);
234
+ this.serverUris.set(uri, document.uri);
235
+ this.recordText(uri, document);
236
+ // Keyed as the server keys its notifications, which may not be how the
237
+ // caller spelled the URI.
238
+ this.host.forgetDirty?.(document.uri);
102
239
  return document;
103
240
  }
104
241
  /**
105
- * Close `uri`. The server unwatches implicitly, so this is the dual of
106
- * {@link openDocument} and needs no separate unwatch.
242
+ * Close `args.uri`, once this session's calls on it have settled or
243
+ * {@link settleBeforeCloseMs} has passed. The server unwatches implicitly,
244
+ * so this is the dual of {@link openDocument} and needs no separate unwatch.
107
245
  */
108
- async closeDocument(uri) {
246
+ async closeDocument(args) {
247
+ this.assertLive();
248
+ await this.settle(this.inFlight.get(args.uri));
249
+ // Forgotten before the close is sent, so a reconnect in between does not
250
+ // re-open a document the caller has closed; after the wait, so an open
251
+ // of it that was still in flight does not record it again.
252
+ const serverUri = this.serverUris.get(args.uri) ?? args.uri;
253
+ this.openUris.delete(args.uri);
254
+ this.serverUris.delete(args.uri);
255
+ this.unsavedWrites.delete(args.uri);
256
+ this.lastAnswers.delete(args.uri);
257
+ this.savedVersions.delete(args.uri);
258
+ this.host.forgetDirty?.(serverUri);
109
259
  const server = await this.connected();
110
- await server.closeModelDocument({ uri, clientId: this.clientId });
260
+ await server.closeModelDocument({ ...args, clientId: this.clientId });
261
+ }
262
+ /**
263
+ * Open `args.uri`, run `fn` with the opened snapshot, and close it once
264
+ * `fn` settles, whether it returned or threw. A URI this session already
265
+ * had open, or is still opening through another call, stays open: the close
266
+ * undoes only the open this call made.
267
+ */
268
+ async withOpenDocument(args, fn) {
269
+ const alreadyOpen = this.openUris.has(args.uri) || this.openingUris.has(args.uri);
270
+ const document = await this.openDocument(args);
271
+ try {
272
+ return await fn(document);
273
+ }
274
+ finally {
275
+ if (!alreadyOpen && !this.disposed) {
276
+ await this.closeDocument({ uri: args.uri });
277
+ }
278
+ }
279
+ }
280
+ /** Write `args.model` back as this session. The session must have `args.uri` open. */
281
+ updateDocument(args) {
282
+ return this.track([args.uri], async () => {
283
+ const server = await this.connected();
284
+ const update = { ...args };
285
+ const baseHash = await this.baseHashOf(server, args.uri, args.baseVersion);
286
+ const document = await server.updateModelDocument({ ...args, clientId: this.clientId });
287
+ this.recordWrite(args.uri, document, baseHash, { update });
288
+ return document;
289
+ });
111
290
  }
112
291
  /**
113
- * Whether `event.sourceClientId` identifies this session's own write.
292
+ * Write several documents this session has open, all or none: the server
293
+ * refuses the whole set, before any text applies, when one is stale or not
294
+ * open. Resolves to the documents in the order given.
295
+ */
296
+ updateDocuments(args) {
297
+ return this.track(args.updates.map(update => update.uri), async () => {
298
+ // One copy for the whole call: the copy's identity is what ties its
299
+ // records together.
300
+ const updates = { ...args, updates: args.updates.map(update => ({ ...update })) };
301
+ const server = await this.connected();
302
+ const baseHashes = await Promise.all(args.updates.map(update => this.baseHashOf(server, update.uri, update.baseVersion)));
303
+ const documents = await server.updateModelDocuments({ ...args, clientId: this.clientId });
304
+ args.updates.forEach((update, index) => this.recordWrite(update.uri, documents[index], baseHashes[index], { updates, index }));
305
+ return documents;
306
+ });
307
+ }
308
+ /** Persist `args.model` to disk as this session. The session must have `args.uri` open. */
309
+ saveDocument(args) {
310
+ const saving = this.track([args.uri], async () => {
311
+ const server = await this.connected();
312
+ const unsaved = this.unsavedWrites.get(args.uri);
313
+ const document = await server.saveModelDocument({ ...args, clientId: this.clientId });
314
+ // A write that answered while the save ran made a record the save
315
+ // may not have persisted, which a restore still needs.
316
+ if (this.unsavedWrites.get(args.uri) === unsaved) {
317
+ this.unsavedWrites.delete(args.uri);
318
+ }
319
+ const answer = this.answerOf(args.uri, document);
320
+ this.recordText(args.uri, document);
321
+ // The higher of two saves' answers, which may arrive out of order.
322
+ const saved = this.savedVersions.get(args.uri);
323
+ if (saved === undefined || answer.version > saved) {
324
+ this.savedVersions.set(args.uri, answer.version);
325
+ }
326
+ return document;
327
+ });
328
+ this.savesInFlight.add(saving);
329
+ const done = () => this.savesInFlight.delete(saving);
330
+ saving.then(done, done);
331
+ return saving;
332
+ }
333
+ /** Whether the session has ended, by {@link dispose} or {@link detach}. */
334
+ get isDisposed() {
335
+ return this.disposed;
336
+ }
337
+ /**
338
+ * Whether a save of this session has not answered yet. Synchronous, for a
339
+ * host whose exit veto must decide within the tick, such as Theia's
340
+ * `onWillStop`.
341
+ */
342
+ get hasSavesInFlight() {
343
+ return this.savesInFlight.size > 0;
344
+ }
345
+ /**
346
+ * Resolves once the saves in flight now have answered, or
347
+ * {@link settleBeforeCloseMs} has passed. Never rejects: a failed save has
348
+ * answered too.
349
+ */
350
+ whenSavesSettled() {
351
+ return this.settle(this.savesInFlight);
352
+ }
353
+ /**
354
+ * Whether `sourceClientId` identifies this session's own write.
114
355
  *
115
356
  * Every watcher needs this and the check is one comparison, so getting it
116
357
  * wrong is cheap to do and expensive to find: an unfiltered echo looks
@@ -119,60 +360,436 @@ class DataSession {
119
360
  isOwnEcho(sourceClientId) {
120
361
  return sourceClientId === this.clientId;
121
362
  }
122
- /** Tear down the current connection and stop tracking the port. Idempotent. */
363
+ /**
364
+ * End the session: detach it from the connection at once, and once its
365
+ * calls in flight have settled or {@link settleBeforeCloseMs} has passed,
366
+ * end it on the server, which closes everything it has open. Idempotent,
367
+ * and leaves the connection usable by its other sessions.
368
+ *
369
+ * Every later call rejects, and so does a call made earlier in the same
370
+ * tick, which has not reached the wire yet and is never sent. The server
371
+ * close is not awaited, because a `Disposable` cannot be; a close that fails
372
+ * leaves the session to the server's connection-close cleanup.
373
+ */
123
374
  dispose() {
124
375
  if (this.disposed) {
125
376
  return;
126
377
  }
127
378
  this.disposed = true;
128
- this.portDisposeListener.dispose();
129
- this.dropGeneration();
130
- }
131
- /** The live generation, building one if there is none. */
132
- currentGeneration() {
133
- if (this.generation) {
134
- return this.generation;
135
- }
136
- const connection = this.port.connect();
137
- // Rejection is reported here rather than left to float: an unhandled
138
- // rejection on a connection promise is the failure mode that reads as
139
- // "the model is empty" instead of "the transport never opened".
140
- connection.catch((error) => this.port.reportError(error, 'connecting to the data server'));
141
- const server = (0, rpc_1.createRpcProxy)(connection, {
142
- methodNamespace: this.methodNamespace,
143
- localTarget: this.client,
144
- localMethods: data_1.DATA_CLIENT_PROTOCOL_METHODS
145
- });
146
- this.generation = { connection, server };
147
- return this.generation;
379
+ this.fireDispose();
380
+ const pending = [...this.inFlight.values()].flatMap(calls => [...calls]);
381
+ void (async () => {
382
+ await this.settle(pending);
383
+ await this.registration;
384
+ // The proxy the session registered on, never a fresh connection: a
385
+ // connection that dropped already ended the session on the server.
386
+ if (!this.detached && this.registeredOn) {
387
+ await this.registeredOn.closeSession({ clientId: this.clientId });
388
+ }
389
+ })().catch(() => undefined);
148
390
  }
149
- /** Await the connection and the server's startup gate for one generation. */
150
- async awaitReady(generation) {
391
+ /**
392
+ * Come off the connection because it is going away.
393
+ *
394
+ * Sends nothing, unlike {@link dispose}: the server ends every session on a
395
+ * connection it sees close, and the close would travel over the very
396
+ * connection being disposed.
397
+ *
398
+ * Public because the connection calls it; anyone else ends a session with
399
+ * {@link dispose}. It fires {@link onDidDispose} only if the session has not
400
+ * already ended, and after {@link dispose} it still cancels the close that
401
+ * dispose has not sent yet.
402
+ */
403
+ detach() {
404
+ this.detached = true;
405
+ this.openUris.clear();
406
+ this.serverUris.clear();
407
+ this.unsavedWrites.clear();
408
+ this.lastAnswers.clear();
409
+ this.savedVersions.clear();
410
+ if (!this.disposed) {
411
+ this.disposed = true;
412
+ this.fireDispose();
413
+ }
414
+ }
415
+ /**
416
+ * Dispose {@link dirtySubscription} and {@link updateSubscription}, fire
417
+ * {@link onDidDispose} and dispose its emitter, so a second call fires
418
+ * nothing.
419
+ */
420
+ fireDispose() {
421
+ this.dirtySubscription?.dispose();
422
+ this.updateSubscription?.dispose();
423
+ this.disposeEmitter.fire(undefined);
424
+ this.disposeEmitter.dispose();
425
+ }
426
+ /**
427
+ * Register again and restore now, after the connection dropped, instead of
428
+ * on the next call. A no-op for a session with nothing open, which the next
429
+ * call restores anyway. A failure is left to that next call, which meets it
430
+ * again.
431
+ */
432
+ reconnect() {
433
+ if (!this.disposed && this.openUris.size > 0) {
434
+ this.connected().catch(() => undefined);
435
+ }
436
+ }
437
+ /**
438
+ * Drop the record in {@link unsavedWrites} of a document this session has
439
+ * open once the server says it turned clean: it holds no unsaved text
440
+ * then, and a record kept would have a restore report the write lost once
441
+ * another client's save changed the file.
442
+ *
443
+ * The server sends a flip only for a document someone watches, so a
444
+ * document the session writes without watching it keeps its record, and
445
+ * can still be reported lost that way.
446
+ */
447
+ forgetSavedWrite(event) {
448
+ if (event.text?.dirty) {
449
+ return;
450
+ }
451
+ // The flip names the server's key, which is not always the caller's
452
+ // spelling that the records are kept under.
453
+ for (const [uri, serverUri] of this.serverUris) {
454
+ if (serverUri === event.uri) {
455
+ this.unsavedWrites.delete(uri);
456
+ }
457
+ }
458
+ }
459
+ /**
460
+ * Drop the record in {@link unsavedWrites} of a document another client
461
+ * wrote over while the connection held: its write replaced the session's,
462
+ * so a restore has nothing of the session's to put back, and a record kept
463
+ * would have it report the write lost to the reconnect. A write superseded
464
+ * before its answer needs nothing: the answer names the other client's
465
+ * text, which the record then holds.
466
+ *
467
+ * Only a `'changed'` event from another client counts, and only where the
468
+ * document no longer holds the write: the session's own echo, and an
469
+ * integrity repair already in the write's answer, replaced nothing, and a
470
+ * `'rebuilt'` event carries no new text. Like {@link forgetSavedWrite}, it
471
+ * depends on the server sending the event, which it does only for a
472
+ * document someone watches.
473
+ */
474
+ forgetSupersededWrite(event) {
475
+ if (event.reason !== 'changed' || this.isOwnEcho(event.sourceClientId)) {
476
+ return;
477
+ }
478
+ for (const [uri, serverUri] of this.serverUris) {
479
+ const write = this.unsavedWrites.get(uri);
480
+ if (serverUri === event.document.uri && write && this.restoreOutcome(write, event.document) !== 'kept') {
481
+ this.unsavedWrites.delete(uri);
482
+ }
483
+ }
484
+ }
485
+ /**
486
+ * Register on `server`, and after a reconnect restore what the ended session
487
+ * had. Calls issued meanwhile wait for this.
488
+ */
489
+ async register(server, reconnected) {
490
+ await server.createSession({ clientId: this.clientId, label: this.label, resumeToken: this.resumeToken });
491
+ if (reconnected) {
492
+ await this.restore(server);
493
+ }
494
+ }
495
+ /**
496
+ * Re-open and re-watch every document the session had open, write again
497
+ * what it wrote since their last save where the re-open lost it, and tell
498
+ * the host which of them lost it for good.
499
+ *
500
+ * Decided per document by the re-opened document's `text.hash`,
501
+ * in {@link restoreOutcome}. Versions cannot decide a write: a revert moves
502
+ * the version on and a restarted server numbers afresh, so the version the
503
+ * last write was answered with never matches where a write is needed, and
504
+ * any other version may be another client's edit, which a write would
505
+ * overwrite.
506
+ *
507
+ * Only what the drop cost is reported: a write another client wrote over
508
+ * while the connection held has no record left by then, see
509
+ * {@link forgetSupersededWrite}.
510
+ *
511
+ * A write is sent again based on the re-opened version, as an ordinary
512
+ * write, so an edit arriving in between conflicts, and a conflict is not
513
+ * retried. Documents last written by one {@link updateDocuments} are sent
514
+ * again by one, and only when every one of them may be; a document that
515
+ * could not be re-opened blocks its set.
516
+ *
517
+ * No caller is waiting, so the outcomes go through the host: one report
518
+ * naming every document whose unsaved text is gone, whose record is then
519
+ * dropped, and one per document that could not be re-opened or written
520
+ * again for another reason than a conflict. A document that could not be
521
+ * re-opened is forgotten; a failed write keeps its record, for the next
522
+ * restore to decide again.
523
+ *
524
+ * Each document's dirty state goes to the host too, read once the watch is
525
+ * in place and any write is sent: a flip while the connection was down, or
526
+ * between the re-open and the watch, reached no one, and the re-open's own
527
+ * answer misses the second. Read before the write, it would tell the client
528
+ * a document is clean that the write is about to make dirty again.
529
+ */
530
+ async restore(server) {
531
+ const writes = [...this.unsavedWrites];
532
+ // No write sent before the drop answers any more, and a restarted
533
+ // server numbers afresh, below the versions saved before it.
534
+ this.savedVersions.clear();
535
+ const reopened = new Map();
536
+ for (const uri of [...this.openUris]) {
537
+ try {
538
+ const document = await server.openModelDocument({ uri, clientId: this.clientId });
539
+ await server.watchModelDocument({ uri, clientId: this.clientId });
540
+ if (this.openUris.has(uri)) {
541
+ this.serverUris.set(uri, document.uri);
542
+ this.recordText(uri, document);
543
+ }
544
+ reopened.set(uri, document);
545
+ }
546
+ catch (error) {
547
+ // Its record goes with its set's, in `reapply`, which it blocks.
548
+ this.openUris.delete(uri);
549
+ this.serverUris.delete(uri);
550
+ this.lastAnswers.delete(uri);
551
+ this.savedVersions.delete(uri);
552
+ this.host.reportError?.(error, (0, primitives_1.resolve)(exports.DATA_SESSION_RESTORE_FAILED, { uri, detail: (0, primitives_1.describeError)(error) }));
553
+ }
554
+ }
555
+ const sets = new Map();
556
+ for (const [uri, write] of writes) {
557
+ const call = 'update' in write.call ? write.call.update : write.call.updates;
558
+ sets.set(call, [...(sets.get(call) ?? []), [uri, write]]);
559
+ }
560
+ const lost = [];
561
+ for (const members of sets.values()) {
562
+ lost.push(...(await this.reapply(server, members, reopened)));
563
+ }
564
+ for (const uri of reopened.keys()) {
565
+ if (!this.openUris.has(uri)) {
566
+ continue;
567
+ }
568
+ // A failed read, or one without text, leaves the client's dirty
569
+ // state as it was; the document is restored all the same.
570
+ const current = await server.getModelDocument({ uri }).catch(() => undefined);
571
+ if (current?.text !== undefined) {
572
+ try {
573
+ this.host.restoreDirty?.({ uri: current.uri, text: current.text });
574
+ }
575
+ catch {
576
+ // The client's listener failed, not the restore: the server
577
+ // has the document open and watched, so it stays restored.
578
+ }
579
+ }
580
+ }
581
+ if (lost.length > 0) {
582
+ const reported = (0, primitives_1.resolve)(exports.DATA_SESSION_UNSAVED_LOST, { uris: lost.join(', ') });
583
+ this.host.reportError?.(new Error(reported.text), reported);
584
+ }
585
+ }
586
+ /**
587
+ * Whether the re-opened `document` still holds the session's unsaved
588
+ * `write` (`'kept'`), holds the text the write started from, so the write
589
+ * can be sent again (`'resend'`), or holds something else (`'lost'`).
590
+ *
591
+ * A document without `text` comes from a server that sends none, and
592
+ * counts as kept only at the version the write was answered with. One
593
+ * without a model has no version to send the write again on.
594
+ */
595
+ restoreOutcome(write, document) {
596
+ if (document.text === undefined) {
597
+ return document.model?.version === write.answer.version ? 'kept' : 'lost';
598
+ }
599
+ if (document.text.hash === write.answer.hash) {
600
+ return 'kept';
601
+ }
602
+ return document.model && write.baseHash !== undefined && document.text.hash === write.baseHash ? 'resend' : 'lost';
603
+ }
604
+ /**
605
+ * Write again, in one call and based on their `reopened` versions, the
606
+ * `members` of one write call that the re-open lost, all or none. Returns
607
+ * the URIs whose unsaved text is gone, and drops their records, and the
608
+ * record of a member that could not be re-opened.
609
+ *
610
+ * A member whose record is no longer the one the restore started with was
611
+ * closed, saved or disposed meanwhile, and is left out: writing it would
612
+ * put back text its caller discarded.
613
+ */
614
+ async reapply(server, members, reopened) {
615
+ const current = (uri, write) => !this.disposed && this.unsavedWrites.get(uri) === write;
616
+ const outcomes = members
617
+ .filter(([uri, write]) => current(uri, write))
618
+ .map(([uri, write]) => {
619
+ const document = reopened.get(uri);
620
+ return { uri, write, document, outcome: document ? this.restoreOutcome(write, document) : 'failed' };
621
+ });
622
+ // A restarted server numbers afresh: the answers to later writes follow
623
+ // on from the re-opened version, not from the one the record holds.
624
+ for (const { uri, write, document, outcome } of outcomes) {
625
+ if (outcome === 'kept' && document) {
626
+ this.unsavedWrites.set(uri, { ...write, answer: this.answerOf(uri, document) });
627
+ }
628
+ }
629
+ // A document that could not be re-opened is forgotten, and was reported
630
+ // as such.
631
+ const lose = () => {
632
+ outcomes.filter(member => member.outcome !== 'kept').forEach(member => this.unsavedWrites.delete(member.uri));
633
+ return outcomes.filter(member => member.outcome === 'lost' || member.outcome === 'resend').map(member => member.uri);
634
+ };
635
+ if (outcomes.some(member => member.outcome === 'lost' || member.outcome === 'failed')) {
636
+ return lose();
637
+ }
638
+ // In the order of the call's updates, which is the order of its answers.
639
+ const resend = outcomes
640
+ .flatMap(({ uri, write, document, outcome }) => outcome === 'resend' && document?.model ? [{ uri, write, baseVersion: document.model.version }] : [])
641
+ .sort((left, right) => indexOf(left.write) - indexOf(right.write));
642
+ if (resend.length === 0) {
643
+ return [];
644
+ }
645
+ let documents;
151
646
  try {
152
- await generation.connection;
153
- await generation.server.waitForReady();
647
+ const { call } = resend[0].write;
648
+ if ('update' in call) {
649
+ documents = [await server.updateModelDocument({ ...call.update, baseVersion: resend[0].baseVersion, clientId: this.clientId })];
650
+ }
651
+ else {
652
+ const baseVersion = new Map(resend.map(member => [indexOf(member.write), member.baseVersion]));
653
+ documents = await server.updateModelDocuments({
654
+ ...call.updates,
655
+ clientId: this.clientId,
656
+ updates: call.updates.updates.flatMap((update, index) => {
657
+ const version = baseVersion.get(index);
658
+ return version === undefined ? [] : [{ ...update, baseVersion: version }];
659
+ })
660
+ });
661
+ }
154
662
  }
155
663
  catch (error) {
156
- // Drop the generation so the next request retries rather than
157
- // re-awaiting a settled rejection forever.
158
- if (this.generation === generation) {
159
- this.generation = undefined;
664
+ if ((0, errors_1.isConflictError)(error)) {
665
+ return lose();
160
666
  }
161
- this.port.reportError(error, 'waiting for the data server to become ready');
162
- throw error;
667
+ for (const { uri, write, baseVersion } of resend) {
668
+ this.host.reportError?.(error, (0, primitives_1.resolve)(exports.DATA_SESSION_RESTORE_FAILED, { uri, detail: (0, primitives_1.describeError)(error) }));
669
+ // Kept for the next restore, and numbered from the re-opened
670
+ // version, as the kept records are: a record numbered by a server
671
+ // that has since restarted would have later answers ignored.
672
+ if (current(uri, write)) {
673
+ this.unsavedWrites.set(uri, { ...write, answer: { ...write.answer, version: baseVersion } });
674
+ }
675
+ }
676
+ return [];
677
+ }
678
+ resend.forEach((member, index) => {
679
+ if (current(member.uri, member.write)) {
680
+ // Recorded afresh, since the answer of a restarted server may be
681
+ // numbered below the one it replaces.
682
+ this.unsavedWrites.delete(member.uri);
683
+ this.recordWrite(member.uri, documents[index], member.write.baseHash, member.write.call);
684
+ }
685
+ });
686
+ return [];
687
+ }
688
+ /**
689
+ * The text hash of the version `baseVersion` names for `uri`, for a write that
690
+ * starts the URI's record in {@link unsavedWrites}; `undefined` for any
691
+ * other write, whose record keeps the base it has.
692
+ *
693
+ * Taken from {@link lastAnswers} when that is at the version, otherwise
694
+ * read, and kept only when the read answers that version: a server's text
695
+ * changes only with its version, so the text at a version is the text the
696
+ * write, once it passes the gate, was applied to.
697
+ */
698
+ async baseHashOf(server, uri, baseVersion) {
699
+ if (this.unsavedWrites.has(uri) || !(0, base_version_1.isModelVersion)(baseVersion)) {
700
+ return undefined;
701
+ }
702
+ const known = this.lastAnswers.get(uri);
703
+ if (known?.version === baseVersion) {
704
+ return known.hash;
163
705
  }
706
+ const read = await server.getModelDocument({ uri }).catch(() => undefined);
707
+ return read?.text?.version === baseVersion ? read.text.hash : undefined;
164
708
  }
165
709
  /**
166
- * Discard the current generation, disposing its connection if it opened.
167
- * The next {@link connected} builds a fresh one.
710
+ * Record `document` as the answer to a write of `uri`, keeping the base of
711
+ * the URI's record if it has one. An answer numbered below the record's is
712
+ * ignored: two writes of `uri` in flight at once may answer out of order,
713
+ * and the record holds the one applied last.
714
+ *
715
+ * So is one numbered at or below the URI's entry in {@link savedVersions}.
716
+ * The save came after that write was applied, so the save persisted its
717
+ * text or a later write replaced it, and its answer carries the text as it
718
+ * was when sent, which a restore would report as lost.
168
719
  */
169
- dropGeneration() {
170
- const generation = this.generation;
171
- this.generation = undefined;
172
- if (!generation) {
720
+ recordWrite(uri, document, baseHash, call) {
721
+ const answer = this.answerOf(uri, document);
722
+ const kept = this.unsavedWrites.get(uri);
723
+ if (kept && answer.version < kept.answer.version) {
724
+ return;
725
+ }
726
+ const saved = this.savedVersions.get(uri);
727
+ if (saved !== undefined && answer.version <= saved) {
173
728
  return;
174
729
  }
175
- generation.connection.then(connection => connection.dispose()).catch(() => undefined);
730
+ this.unsavedWrites.set(uri, { baseHash: kept ? kept.baseHash : baseHash, answer, call });
731
+ this.recordText(uri, document);
732
+ }
733
+ /**
734
+ * What {@link DataSessionUnsavedWrite.answer} keeps of `document`. Every write
735
+ * and open answers with a model; one without is reported and counted older
736
+ * than every version, so it never replaces a real answer.
737
+ */
738
+ answerOf(uri, document) {
739
+ if (!document.model) {
740
+ const reported = (0, primitives_1.resolve)(exports.DATA_SESSION_ANSWER_WITHOUT_MODEL, { uri });
741
+ this.host.reportError?.(new Error(reported.text), reported);
742
+ return { version: base_version_1.UNRECORDED_VERSION, hash: document.text?.hash };
743
+ }
744
+ return { version: document.model.version, hash: document.text?.hash };
745
+ }
746
+ /** Keep `document`'s text in {@link lastAnswers}, or forget it for a server that sends none. */
747
+ recordText(uri, document) {
748
+ if (document.text) {
749
+ this.lastAnswers.set(uri, document.text);
750
+ }
751
+ else {
752
+ this.lastAnswers.delete(uri);
753
+ }
754
+ }
755
+ /** Run `call`, counted as in flight on each of `uris` until it settles. */
756
+ track(uris, call) {
757
+ const running = call();
758
+ for (const uri of uris) {
759
+ this.inFlight.set(uri, (this.inFlight.get(uri) ?? new Set()).add(running));
760
+ }
761
+ const done = () => uris.forEach(uri => this.inFlight.get(uri)?.delete(running));
762
+ running.then(done, done);
763
+ return running;
764
+ }
765
+ /** {@link track} an open of `uri`, counted in {@link openingUris} until it settles. */
766
+ trackOpen(uri, call) {
767
+ this.openingUris.set(uri, (this.openingUris.get(uri) ?? 0) + 1);
768
+ const done = () => {
769
+ const remaining = (this.openingUris.get(uri) ?? 1) - 1;
770
+ if (remaining > 0) {
771
+ this.openingUris.set(uri, remaining);
772
+ }
773
+ else {
774
+ this.openingUris.delete(uri);
775
+ }
776
+ };
777
+ const running = this.track([uri], call);
778
+ running.then(done, done);
779
+ return running;
780
+ }
781
+ /** Wait until `calls` have settled, or {@link settleBeforeCloseMs} has passed. */
782
+ async settle(calls) {
783
+ const pending = [...(calls ?? [])];
784
+ if (pending.length === 0) {
785
+ return;
786
+ }
787
+ await this.clock.raceTimer(Promise.allSettled(pending), this.settleBeforeCloseMs);
788
+ }
789
+ assertLive() {
790
+ if (this.disposed) {
791
+ throw new errors_1.SessionClosedError(this.clientId);
792
+ }
176
793
  }
177
794
  }
178
795
  exports.DataSession = DataSession;