@hydranium/protocol 1.0.0-next.23 → 1.0.0-next.230

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