@bowl42/keywire 0.0.0-stage → 0.3.1

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 (384) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +118 -2
  3. package/dist/app.d.ts +2 -0
  4. package/dist/app.js +13 -0
  5. package/dist/app.js.map +1 -0
  6. package/dist/bytes.d.ts +1 -0
  7. package/dist/bytes.js +7 -0
  8. package/dist/bytes.js.map +1 -0
  9. package/dist/client.d.ts +66 -0
  10. package/dist/client.js +846 -0
  11. package/dist/client.js.map +1 -0
  12. package/dist/compress/block.d.ts +51 -0
  13. package/dist/compress/block.js +667 -0
  14. package/dist/compress/block.js.map +1 -0
  15. package/dist/compress/deflate.d.ts +7 -0
  16. package/dist/compress/deflate.js +603 -0
  17. package/dist/compress/deflate.js.map +1 -0
  18. package/dist/compress/index.d.ts +6 -0
  19. package/dist/compress/index.js +13 -0
  20. package/dist/compress/index.js.map +1 -0
  21. package/dist/compress/inflate.d.ts +21 -0
  22. package/dist/compress/inflate.js +380 -0
  23. package/dist/compress/inflate.js.map +1 -0
  24. package/dist/compress/wasm.d.ts +50 -0
  25. package/dist/compress/wasm.js +192 -0
  26. package/dist/compress/wasm.js.map +1 -0
  27. package/dist/compress/zlib-wasm.d.ts +15 -0
  28. package/dist/compress/zlib-wasm.js +18 -0
  29. package/dist/compress/zlib-wasm.js.map +1 -0
  30. package/dist/conn.d.ts +126 -0
  31. package/dist/conn.js +685 -0
  32. package/dist/conn.js.map +1 -0
  33. package/dist/dial/index.d.ts +3 -0
  34. package/dist/dial/index.js +10 -0
  35. package/dist/dial/index.js.map +1 -0
  36. package/dist/discovery/index.d.ts +16 -0
  37. package/dist/discovery/index.js +173 -0
  38. package/dist/discovery/index.js.map +1 -0
  39. package/dist/discovery/reach.d.ts +4 -0
  40. package/dist/discovery/reach.js +36 -0
  41. package/dist/discovery/reach.js.map +1 -0
  42. package/dist/domain.d.ts +3 -0
  43. package/dist/domain.js +12 -0
  44. package/dist/domain.js.map +1 -0
  45. package/dist/errors.d.ts +7 -0
  46. package/dist/errors.js +49 -0
  47. package/dist/errors.js.map +1 -0
  48. package/dist/extension.d.ts +53 -0
  49. package/dist/extension.js +158 -0
  50. package/dist/extension.js.map +1 -0
  51. package/dist/forward.d.ts +11 -0
  52. package/dist/forward.js +125 -0
  53. package/dist/forward.js.map +1 -0
  54. package/dist/framed-stream.d.ts +14 -0
  55. package/dist/framed-stream.js +113 -0
  56. package/dist/framed-stream.js.map +1 -0
  57. package/dist/gen/keywire/discovery/v1/discovery_pb.d.ts +105 -0
  58. package/dist/gen/keywire/discovery/v1/discovery_pb.js +57 -0
  59. package/dist/gen/keywire/discovery/v1/discovery_pb.js.map +1 -0
  60. package/dist/gen/keywire/state/v1/state_pb.d.ts +988 -0
  61. package/dist/gen/keywire/state/v1/state_pb.js +184 -0
  62. package/dist/gen/keywire/state/v1/state_pb.js.map +1 -0
  63. package/dist/gen/keywire/v1/forward_pb.d.ts +53 -0
  64. package/dist/gen/keywire/v1/forward_pb.js +58 -0
  65. package/dist/gen/keywire/v1/forward_pb.js.map +1 -0
  66. package/dist/gen/keywire/v1/guest_pb.d.ts +322 -0
  67. package/dist/gen/keywire/v1/guest_pb.js +100 -0
  68. package/dist/gen/keywire/v1/guest_pb.js.map +1 -0
  69. package/dist/gen/keywire/v1/pair_pb.d.ts +106 -0
  70. package/dist/gen/keywire/v1/pair_pb.js +45 -0
  71. package/dist/gen/keywire/v1/pair_pb.js.map +1 -0
  72. package/dist/gen/keywire/v1/relay_pb.d.ts +116 -0
  73. package/dist/gen/keywire/v1/relay_pb.js +20 -0
  74. package/dist/gen/keywire/v1/relay_pb.js.map +1 -0
  75. package/dist/gen/keywire/v1/roster_pb.d.ts +213 -0
  76. package/dist/gen/keywire/v1/roster_pb.js +77 -0
  77. package/dist/gen/keywire/v1/roster_pb.js.map +1 -0
  78. package/dist/gen/keywire/v1/sync_pb.d.ts +68 -0
  79. package/dist/gen/keywire/v1/sync_pb.js +24 -0
  80. package/dist/gen/keywire/v1/sync_pb.js.map +1 -0
  81. package/dist/guest/equal-bytes.d.ts +1 -0
  82. package/dist/guest/equal-bytes.js +10 -0
  83. package/dist/guest/equal-bytes.js.map +1 -0
  84. package/dist/guest/hello.d.ts +4 -0
  85. package/dist/guest/hello.js +42 -0
  86. package/dist/guest/hello.js.map +1 -0
  87. package/dist/guest/invite-frame.d.ts +8 -0
  88. package/dist/guest/invite-frame.js +44 -0
  89. package/dist/guest/invite-frame.js.map +1 -0
  90. package/dist/guest/invite.d.ts +17 -0
  91. package/dist/guest/invite.js +86 -0
  92. package/dist/guest/invite.js.map +1 -0
  93. package/dist/guest/relay-hello.d.ts +2 -0
  94. package/dist/guest/relay-hello.js +38 -0
  95. package/dist/guest/relay-hello.js.map +1 -0
  96. package/dist/guest/revocations.d.ts +12 -0
  97. package/dist/guest/revocations.js +134 -0
  98. package/dist/guest/revocations.js.map +1 -0
  99. package/dist/guest/roster.d.ts +2 -0
  100. package/dist/guest/roster.js +14 -0
  101. package/dist/guest/roster.js.map +1 -0
  102. package/dist/guest/token-payload.d.ts +2 -0
  103. package/dist/guest/token-payload.js +71 -0
  104. package/dist/guest/token-payload.js.map +1 -0
  105. package/dist/guest-conn.d.ts +20 -0
  106. package/dist/guest-conn.js +99 -0
  107. package/dist/guest-conn.js.map +1 -0
  108. package/dist/guest-relay.d.ts +7 -0
  109. package/dist/guest-relay.js +45 -0
  110. package/dist/guest-relay.js.map +1 -0
  111. package/dist/guest.d.ts +20 -0
  112. package/dist/guest.js +99 -0
  113. package/dist/guest.js.map +1 -0
  114. package/dist/index.d.ts +31 -0
  115. package/dist/index.js +28 -0
  116. package/dist/index.js.map +1 -0
  117. package/dist/msg-path.d.ts +9 -0
  118. package/dist/msg-path.js +2 -0
  119. package/dist/msg-path.js.map +1 -0
  120. package/dist/mux/byte-queue.d.ts +9 -0
  121. package/dist/mux/byte-queue.js +62 -0
  122. package/dist/mux/byte-queue.js.map +1 -0
  123. package/dist/mux/codec.d.ts +30 -0
  124. package/dist/mux/codec.js +23 -0
  125. package/dist/mux/codec.js.map +1 -0
  126. package/dist/mux/errors.d.ts +23 -0
  127. package/dist/mux/errors.js +47 -0
  128. package/dist/mux/errors.js.map +1 -0
  129. package/dist/mux/frame.d.ts +44 -0
  130. package/dist/mux/frame.js +161 -0
  131. package/dist/mux/frame.js.map +1 -0
  132. package/dist/mux/nexttask.d.ts +1 -0
  133. package/dist/mux/nexttask.js +19 -0
  134. package/dist/mux/nexttask.js.map +1 -0
  135. package/dist/mux/session.d.ts +69 -0
  136. package/dist/mux/session.js +586 -0
  137. package/dist/mux/session.js.map +1 -0
  138. package/dist/mux/signal.d.ts +5 -0
  139. package/dist/mux/signal.js +14 -0
  140. package/dist/mux/signal.js.map +1 -0
  141. package/dist/mux/stream.d.ts +34 -0
  142. package/dist/mux/stream.js +620 -0
  143. package/dist/mux/stream.js.map +1 -0
  144. package/dist/nodekit/device.d.ts +40 -0
  145. package/dist/nodekit/device.js +188 -0
  146. package/dist/nodekit/device.js.map +1 -0
  147. package/dist/nodekit/index.d.ts +5 -0
  148. package/dist/nodekit/index.js +8 -0
  149. package/dist/nodekit/index.js.map +1 -0
  150. package/dist/nodekit/indexeddb.d.ts +2 -0
  151. package/dist/nodekit/indexeddb.js +114 -0
  152. package/dist/nodekit/indexeddb.js.map +1 -0
  153. package/dist/nodekit/pair-device.d.ts +27 -0
  154. package/dist/nodekit/pair-device.js +44 -0
  155. package/dist/nodekit/pair-device.js.map +1 -0
  156. package/dist/nodekit/sealed-signer.d.ts +22 -0
  157. package/dist/nodekit/sealed-signer.js +74 -0
  158. package/dist/nodekit/sealed-signer.js.map +1 -0
  159. package/dist/nodekit/store.d.ts +22 -0
  160. package/dist/nodekit/store.js +21 -0
  161. package/dist/nodekit/store.js.map +1 -0
  162. package/dist/noise/backend.d.ts +25 -0
  163. package/dist/noise/backend.js +2 -0
  164. package/dist/noise/backend.js.map +1 -0
  165. package/dist/noise/backends.d.ts +4 -0
  166. package/dist/noise/backends.js +19 -0
  167. package/dist/noise/backends.js.map +1 -0
  168. package/dist/noise/cipher.d.ts +18 -0
  169. package/dist/noise/cipher.js +69 -0
  170. package/dist/noise/cipher.js.map +1 -0
  171. package/dist/noise/crypto.d.ts +11 -0
  172. package/dist/noise/crypto.js +47 -0
  173. package/dist/noise/crypto.js.map +1 -0
  174. package/dist/noise/handshake.d.ts +28 -0
  175. package/dist/noise/handshake.js +183 -0
  176. package/dist/noise/handshake.js.map +1 -0
  177. package/dist/noise/import.d.ts +2 -0
  178. package/dist/noise/import.js +16 -0
  179. package/dist/noise/import.js.map +1 -0
  180. package/dist/noise/noble.d.ts +2 -0
  181. package/dist/noise/noble.js +51 -0
  182. package/dist/noise/noble.js.map +1 -0
  183. package/dist/noise/pair-code.d.ts +2 -0
  184. package/dist/noise/pair-code.js +11 -0
  185. package/dist/noise/pair-code.js.map +1 -0
  186. package/dist/noise/pkcs8.d.ts +3 -0
  187. package/dist/noise/pkcs8.js +18 -0
  188. package/dist/noise/pkcs8.js.map +1 -0
  189. package/dist/noise/sealed.d.ts +21 -0
  190. package/dist/noise/sealed.js +40 -0
  191. package/dist/noise/sealed.js.map +1 -0
  192. package/dist/noise/symmetric.d.ts +17 -0
  193. package/dist/noise/symmetric.js +56 -0
  194. package/dist/noise/symmetric.js.map +1 -0
  195. package/dist/noise/webcrypto.d.ts +3 -0
  196. package/dist/noise/webcrypto.js +98 -0
  197. package/dist/noise/webcrypto.js.map +1 -0
  198. package/dist/pair-relay.d.ts +4 -0
  199. package/dist/pair-relay.js +46 -0
  200. package/dist/pair-relay.js.map +1 -0
  201. package/dist/pair.d.ts +7 -0
  202. package/dist/pair.js +50 -0
  203. package/dist/pair.js.map +1 -0
  204. package/dist/paths/link.d.ts +33 -0
  205. package/dist/paths/link.js +132 -0
  206. package/dist/paths/link.js.map +1 -0
  207. package/dist/paths/node-paths.d.ts +10 -0
  208. package/dist/paths/node-paths.js +41 -0
  209. package/dist/paths/node-paths.js.map +1 -0
  210. package/dist/paths/path.d.ts +11 -0
  211. package/dist/paths/path.js +25 -0
  212. package/dist/paths/path.js.map +1 -0
  213. package/dist/paths/race.d.ts +18 -0
  214. package/dist/paths/race.js +157 -0
  215. package/dist/paths/race.js.map +1 -0
  216. package/dist/paths/relay-sessions.d.ts +11 -0
  217. package/dist/paths/relay-sessions.js +93 -0
  218. package/dist/paths/relay-sessions.js.map +1 -0
  219. package/dist/paths/upgrades.d.ts +12 -0
  220. package/dist/paths/upgrades.js +58 -0
  221. package/dist/paths/upgrades.js.map +1 -0
  222. package/dist/relay-server/admission.d.ts +24 -0
  223. package/dist/relay-server/admission.js +140 -0
  224. package/dist/relay-server/admission.js.map +1 -0
  225. package/dist/relay-server/config.d.ts +28 -0
  226. package/dist/relay-server/config.js +47 -0
  227. package/dist/relay-server/config.js.map +1 -0
  228. package/dist/relay-server/discovery/addr.d.ts +18 -0
  229. package/dist/relay-server/discovery/addr.js +211 -0
  230. package/dist/relay-server/discovery/addr.js.map +1 -0
  231. package/dist/relay-server/discovery/directory.d.ts +42 -0
  232. package/dist/relay-server/discovery/directory.js +101 -0
  233. package/dist/relay-server/discovery/directory.js.map +1 -0
  234. package/dist/relay-server/discovery/http.d.ts +10 -0
  235. package/dist/relay-server/discovery/http.js +172 -0
  236. package/dist/relay-server/discovery/http.js.map +1 -0
  237. package/dist/relay-server/discovery/index.d.ts +6 -0
  238. package/dist/relay-server/discovery/index.js +15 -0
  239. package/dist/relay-server/discovery/index.js.map +1 -0
  240. package/dist/relay-server/discovery/listing.d.ts +24 -0
  241. package/dist/relay-server/discovery/listing.js +115 -0
  242. package/dist/relay-server/discovery/listing.js.map +1 -0
  243. package/dist/relay-server/discovery/options.d.ts +39 -0
  244. package/dist/relay-server/discovery/options.js +97 -0
  245. package/dist/relay-server/discovery/options.js.map +1 -0
  246. package/dist/relay-server/discovery/service.d.ts +21 -0
  247. package/dist/relay-server/discovery/service.js +409 -0
  248. package/dist/relay-server/discovery/service.js.map +1 -0
  249. package/dist/relay-server/forward.d.ts +3 -0
  250. package/dist/relay-server/forward.js +97 -0
  251. package/dist/relay-server/forward.js.map +1 -0
  252. package/dist/relay-server/handshake.d.ts +10 -0
  253. package/dist/relay-server/handshake.js +36 -0
  254. package/dist/relay-server/handshake.js.map +1 -0
  255. package/dist/relay-server/index.d.ts +6 -0
  256. package/dist/relay-server/index.js +10 -0
  257. package/dist/relay-server/index.js.map +1 -0
  258. package/dist/relay-server/relay.d.ts +25 -0
  259. package/dist/relay-server/relay.js +392 -0
  260. package/dist/relay-server/relay.js.map +1 -0
  261. package/dist/relay-server/service-read.d.ts +4 -0
  262. package/dist/relay-server/service-read.js +16 -0
  263. package/dist/relay-server/service-read.js.map +1 -0
  264. package/dist/relay-server/service.d.ts +25 -0
  265. package/dist/relay-server/service.js +8 -0
  266. package/dist/relay-server/service.js.map +1 -0
  267. package/dist/relay-server/session.d.ts +60 -0
  268. package/dist/relay-server/session.js +35 -0
  269. package/dist/relay-server/session.js.map +1 -0
  270. package/dist/relay-server/url.d.ts +1 -0
  271. package/dist/relay-server/url.js +8 -0
  272. package/dist/relay-server/url.js.map +1 -0
  273. package/dist/relay-url.d.ts +2 -0
  274. package/dist/relay-url.js +11 -0
  275. package/dist/relay-url.js.map +1 -0
  276. package/dist/relay.d.ts +5 -0
  277. package/dist/relay.js +60 -0
  278. package/dist/relay.js.map +1 -0
  279. package/dist/roster/admission.d.ts +17 -0
  280. package/dist/roster/admission.js +85 -0
  281. package/dist/roster/admission.js.map +1 -0
  282. package/dist/roster/credentials.d.ts +5 -0
  283. package/dist/roster/credentials.js +72 -0
  284. package/dist/roster/credentials.js.map +1 -0
  285. package/dist/roster/digest.d.ts +3 -0
  286. package/dist/roster/digest.js +23 -0
  287. package/dist/roster/digest.js.map +1 -0
  288. package/dist/roster/envelope.d.ts +11 -0
  289. package/dist/roster/envelope.js +35 -0
  290. package/dist/roster/envelope.js.map +1 -0
  291. package/dist/roster/errors.d.ts +6 -0
  292. package/dist/roster/errors.js +11 -0
  293. package/dist/roster/errors.js.map +1 -0
  294. package/dist/roster/limits.d.ts +25 -0
  295. package/dist/roster/limits.js +26 -0
  296. package/dist/roster/limits.js.map +1 -0
  297. package/dist/roster/merge.d.ts +10 -0
  298. package/dist/roster/merge.js +101 -0
  299. package/dist/roster/merge.js.map +1 -0
  300. package/dist/roster/name.d.ts +1 -0
  301. package/dist/roster/name.js +7 -0
  302. package/dist/roster/name.js.map +1 -0
  303. package/dist/roster/order.d.ts +5 -0
  304. package/dist/roster/order.js +22 -0
  305. package/dist/roster/order.js.map +1 -0
  306. package/dist/roster/ownership.d.ts +9 -0
  307. package/dist/roster/ownership.js +42 -0
  308. package/dist/roster/ownership.js.map +1 -0
  309. package/dist/roster/retain.d.ts +2 -0
  310. package/dist/roster/retain.js +55 -0
  311. package/dist/roster/retain.js.map +1 -0
  312. package/dist/roster/revocations.d.ts +5 -0
  313. package/dist/roster/revocations.js +37 -0
  314. package/dist/roster/revocations.js.map +1 -0
  315. package/dist/roster/scan.d.ts +16 -0
  316. package/dist/roster/scan.js +194 -0
  317. package/dist/roster/scan.js.map +1 -0
  318. package/dist/roster/state.d.ts +34 -0
  319. package/dist/roster/state.js +204 -0
  320. package/dist/roster/state.js.map +1 -0
  321. package/dist/roster/statement.d.ts +38 -0
  322. package/dist/roster/statement.js +176 -0
  323. package/dist/roster/statement.js.map +1 -0
  324. package/dist/roster/types.d.ts +35 -0
  325. package/dist/roster/types.js +2 -0
  326. package/dist/roster/types.js.map +1 -0
  327. package/dist/roster/verify.d.ts +3 -0
  328. package/dist/roster/verify.js +63 -0
  329. package/dist/roster/verify.js.map +1 -0
  330. package/dist/roster-sync/apply.d.ts +2 -0
  331. package/dist/roster-sync/apply.js +23 -0
  332. package/dist/roster-sync/apply.js.map +1 -0
  333. package/dist/roster-sync/exchange.d.ts +3 -0
  334. package/dist/roster-sync/exchange.js +25 -0
  335. package/dist/roster-sync/exchange.js.map +1 -0
  336. package/dist/roster-sync/frame.d.ts +17 -0
  337. package/dist/roster-sync/frame.js +66 -0
  338. package/dist/roster-sync/frame.js.map +1 -0
  339. package/dist/roster-sync/records.d.ts +8 -0
  340. package/dist/roster-sync/records.js +78 -0
  341. package/dist/roster-sync/records.js.map +1 -0
  342. package/dist/roster-sync/sync.d.ts +12 -0
  343. package/dist/roster-sync/sync.js +69 -0
  344. package/dist/roster-sync/sync.js.map +1 -0
  345. package/dist/rtc.d.ts +15 -0
  346. package/dist/rtc.js +275 -0
  347. package/dist/rtc.js.map +1 -0
  348. package/dist/state/errors.d.ts +30 -0
  349. package/dist/state/errors.js +72 -0
  350. package/dist/state/errors.js.map +1 -0
  351. package/dist/state/index.d.ts +6 -0
  352. package/dist/state/index.js +11 -0
  353. package/dist/state/index.js.map +1 -0
  354. package/dist/state/limits.d.ts +34 -0
  355. package/dist/state/limits.js +115 -0
  356. package/dist/state/limits.js.map +1 -0
  357. package/dist/state/remote.d.ts +217 -0
  358. package/dist/state/remote.js +1934 -0
  359. package/dist/state/remote.js.map +1 -0
  360. package/dist/state/shared.d.ts +56 -0
  361. package/dist/state/shared.js +300 -0
  362. package/dist/state/shared.js.map +1 -0
  363. package/dist/state/state.d.ts +118 -0
  364. package/dist/state/state.js +1048 -0
  365. package/dist/state/state.js.map +1 -0
  366. package/dist/state/store.d.ts +31 -0
  367. package/dist/state/store.js +375 -0
  368. package/dist/state/store.js.map +1 -0
  369. package/dist/state/wire.d.ts +43 -0
  370. package/dist/state/wire.js +179 -0
  371. package/dist/state/wire.js.map +1 -0
  372. package/dist/strict-proto.d.ts +10 -0
  373. package/dist/strict-proto.js +167 -0
  374. package/dist/strict-proto.js.map +1 -0
  375. package/dist/token.d.ts +18 -0
  376. package/dist/token.js +60 -0
  377. package/dist/token.js.map +1 -0
  378. package/dist/urls.d.ts +7 -0
  379. package/dist/urls.js +117 -0
  380. package/dist/urls.js.map +1 -0
  381. package/dist/ws.d.ts +19 -0
  382. package/dist/ws.js +143 -0
  383. package/dist/ws.js.map +1 -0
  384. package/package.json +72 -3
@@ -0,0 +1,1934 @@
1
+ import { KeywireError } from "../errors.js";
2
+ import { Failure, InvalidExchange, StateFull, Stopped, TooManyPending, Uncertain, } from "./errors.js";
3
+ import { compareBytes, utf8Len, validName } from "./shared.js";
4
+ import { CODE_INVALID, Conv, MAX_VARIANT, rejection, VersionError } from "./wire.js";
5
+ // RETRY_MS is how long a request that failed waits to start again on the
6
+ // same link.
7
+ const RETRY_MS = 1000;
8
+ const CODE_CANCEL = 0;
9
+ // MAX_REMOTE_WATCHERS bounds the watch calls in effect on one Remote.
10
+ const MAX_REMOTE_WATCHERS = 64;
11
+ // COMPRESSIBLE are the requests whose answers the Node may compress, as
12
+ // its declarations say (spec/state.md, 5.5): their streams ask for
13
+ // compression, which takes effect only where the connection can.
14
+ const COMPRESSIBLE = new Set([
15
+ "subscribe",
16
+ "subscribeLog",
17
+ "readLog",
18
+ "readBlob",
19
+ "query",
20
+ "openChannel",
21
+ ]);
22
+ // openFor opens a stream on link for a request of body: asking for
23
+ // compression where its answers may be compressed, and with this side's
24
+ // writes (the request, channel messages) always plain.
25
+ function openFor(link, body) {
26
+ const st = link.open({ compress: COMPRESSIBLE.has(body?.case ?? "") });
27
+ st.setWriteCompression(false);
28
+ return st;
29
+ }
30
+ const sameBytes = (a, b) => !!a && !!b && compareBytes(a, b) === 0;
31
+ function failureOf(env) {
32
+ if (env.body.case !== "failure")
33
+ return undefined;
34
+ const { code, message } = rejection(env.body.value.code, env.body.value.message);
35
+ return new Failure(code, message);
36
+ }
37
+ // request opens a stream on link, sends body, and reads the first answer:
38
+ // a Failure becomes one.
39
+ async function request(link, s, body, opened) {
40
+ const stream = openFor(link, body);
41
+ opened?.(stream);
42
+ const conv = new Conv(stream, s.frameBound, s.closed);
43
+ try {
44
+ await conv.send(body);
45
+ let first;
46
+ try {
47
+ first = await conv.recv();
48
+ }
49
+ catch (e) {
50
+ // A Node of another version answers in its own: its Failure says
51
+ // which versions it speaks (spec/state.md, 5.1).
52
+ const f = e instanceof VersionError && e.env.version !== 0 ? e.env.body : undefined;
53
+ if (f?.case === "failure" && f.value.code === "version") {
54
+ const { code, message } = rejection(f.value.code, f.value.message);
55
+ throw new Failure(code, message, [...f.value.supported]);
56
+ }
57
+ throw e;
58
+ }
59
+ if (first === null)
60
+ throw new InvalidExchange("no answer");
61
+ const f = failureOf(first);
62
+ if (f)
63
+ throw f;
64
+ return { conv, first };
65
+ }
66
+ catch (e) {
67
+ stream.reset(CODE_CANCEL);
68
+ throw e;
69
+ }
70
+ }
71
+ // once asks body and returns the answer, ending the stream.
72
+ async function once(link, s, body, opened) {
73
+ const { conv, first } = await request(link, s, body, opened);
74
+ conv.stream.reset(CODE_CANCEL);
75
+ return first;
76
+ }
77
+ const num = (b) => b > BigInt(Number.MAX_SAFE_INTEGER) ? Number.MAX_SAFE_INTEGER : Number(b);
78
+ async function askInfo(link, s) {
79
+ const env = await once(link, s, { case: "info", value: {} });
80
+ if (env.body.case !== "infoResult")
81
+ throw new InvalidExchange("not an info answer");
82
+ const m = env.body.value;
83
+ if (m.outcomeEpoch.length !== 16 || m.versions.length === 0)
84
+ throw new InvalidExchange("a malformed info answer");
85
+ if (m.frameBound > BigInt(s.frameBound))
86
+ throw new InvalidExchange(`the Node's frame bound ${m.frameBound} exceeds this device's ${s.frameBound}`);
87
+ return {
88
+ version: m.versions[0],
89
+ frameBound: Number(m.frameBound),
90
+ outcomeEpoch: m.outcomeEpoch,
91
+ outcomeAgeMs: num(m.outcomeAgeMs),
92
+ maxOutcomes: num(m.maxOutcomes),
93
+ maxName: num(m.maxName),
94
+ maxValue: num(m.maxValue),
95
+ maxPayload: num(m.maxPayload),
96
+ pageEntries: num(m.pageEntries),
97
+ pageBytes: num(m.pageBytes),
98
+ maxQueryArgs: num(m.maxQueryArgs),
99
+ maxQueryResult: num(m.maxQueryResult),
100
+ maxChannelMessage: num(m.maxChannelMessage),
101
+ chunkSize: num(m.chunkSize),
102
+ maxBlob: num(m.maxBlob),
103
+ };
104
+ }
105
+ // Remote is one Node as this device follows it: its mirrors, log
106
+ // subscriptions and outbox restart on every new link to it.
107
+ export class Remote {
108
+ #host;
109
+ #s;
110
+ // key is the Node's static key, for a Remote from node().
111
+ key;
112
+ #connect;
113
+ #backoff;
114
+ #onError;
115
+ #watchers = new Set();
116
+ #told = "waiting";
117
+ #error;
118
+ #closed = false;
119
+ #link;
120
+ #pending;
121
+ #info;
122
+ #ext = new Map();
123
+ #guest;
124
+ #wake;
125
+ // delay is a guest Remote's next wait after a failed attempt.
126
+ #delay = 0;
127
+ #subs = new Set();
128
+ #mirrors = 0;
129
+ #logs = 0;
130
+ outbox;
131
+ #queries;
132
+ #reads;
133
+ #writes;
134
+ #waiters = new Set();
135
+ // blobs are the blob reads and writes in progress, ended by close.
136
+ #blobs = new Set();
137
+ #channelsWaiting = 0;
138
+ constructor(host, key, connect, opts = {}) {
139
+ this.#host = host;
140
+ this.#s = host.settings;
141
+ this.key = key;
142
+ this.#connect = connect;
143
+ const { backoff, onError } = opts;
144
+ if (onError !== undefined && typeof onError !== "function")
145
+ throw new TypeError("keywire: onError is a function");
146
+ this.#onError = onError;
147
+ const minMs = backoff?.minMs ?? 250;
148
+ const maxMs = backoff?.maxMs ?? 30_000;
149
+ if (!Number.isSafeInteger(minMs) || !Number.isSafeInteger(maxMs) || minMs < 1 || maxMs < minMs)
150
+ throw new RangeError("keywire: a backoff is 1 ms or more, its most no less than its least");
151
+ this.#backoff = { minMs, maxMs };
152
+ this.outbox = new Outbox(this.#s, () => this.#current());
153
+ this.#queries = new Queue(this.#s.maxQuerying, this.#s.maxWaitingQueries, this);
154
+ this.#reads = new Queue(this.#s.maxReading, this.#s.maxWaitingReads, this);
155
+ this.#writes = new Queue(this.#s.maxWriting, this.#s.maxWaitingWrites, this);
156
+ if (connect)
157
+ void this.#dial();
158
+ }
159
+ get state() {
160
+ if (this.#closed)
161
+ return "closed";
162
+ return this.#link ? "connected" : "waiting";
163
+ }
164
+ // error is why the Remote closed itself, as the end of a guest's share;
165
+ // while open, a Failure "version" from a Node of another version, with
166
+ // the versions it speaks, until a link's Info succeeds; else undefined.
167
+ get error() {
168
+ return this.#error;
169
+ }
170
+ // versionFailure is the Failure a Node of another version answered, while
171
+ // it stands.
172
+ versionFailure() {
173
+ const e = this.#error;
174
+ return !this.#closed && e instanceof Failure && e.code === "version" ? e : undefined;
175
+ }
176
+ // watch calls f with the state now and after each change, until the
177
+ // returned function is called; "closed" is the last call. At most 64
178
+ // watch a Remote at once; what f throws is dropped.
179
+ watch(f) {
180
+ if (typeof f !== "function")
181
+ throw new TypeError("keywire: f is a function");
182
+ if (this.#watchers.size >= MAX_REMOTE_WATCHERS)
183
+ throw new RangeError("keywire: too many watchers of a Remote");
184
+ this.#watchers.add(f);
185
+ this.#call(f, this.state);
186
+ return () => {
187
+ this.#watchers.delete(f);
188
+ };
189
+ }
190
+ // watchPending calls f with copies of the pending commands now and after
191
+ // each change to the outbox, as Outbox.watch: a command is first sent
192
+ // only once what f returned for its epoch settled. At most 16 at once.
193
+ watchPending(f) {
194
+ return this.outbox.watch(f);
195
+ }
196
+ // wake has a guest Remote waiting out its backoff try to connect now,
197
+ // from its least wait again; on any other Remote it does nothing.
198
+ wake() {
199
+ this.#delay = this.#backoff.minMs;
200
+ this.#wake?.();
201
+ }
202
+ #call(f, state) {
203
+ try {
204
+ f(state);
205
+ }
206
+ catch {
207
+ // A watcher's failure is its own.
208
+ }
209
+ }
210
+ // #changed tells the watchers of a change of state, or with again of one
211
+ // of error.
212
+ #changed(again = false) {
213
+ const now = this.state;
214
+ if (now === this.#told && !again)
215
+ return;
216
+ this.#told = now;
217
+ for (const f of [...this.#watchers]) {
218
+ // A watcher changed the state again: that round told the rest.
219
+ if (this.#told !== now)
220
+ return;
221
+ this.#call(f, now);
222
+ }
223
+ if (now === "closed")
224
+ this.#watchers.clear();
225
+ }
226
+ // info is what the Node told of itself on the current link.
227
+ info() {
228
+ return this.#info && { ...this.#info, outcomeEpoch: this.#info.outcomeEpoch.slice() };
229
+ }
230
+ #current() {
231
+ return this.#link && this.#info ? { link: this.#link, info: this.#info } : undefined;
232
+ }
233
+ // linked is told of a link the State's extension runs on to this Node.
234
+ linked(ext) {
235
+ if (this.#closed)
236
+ return;
237
+ const link = { peer: ext.peer, open: (o) => ext.openStream(o) };
238
+ this.#ext.set(ext, link);
239
+ this.#adopt(link);
240
+ }
241
+ unlinked(ext) {
242
+ const link = this.#ext.get(ext);
243
+ this.#ext.delete(ext);
244
+ if (!link)
245
+ return;
246
+ this.#drop(link);
247
+ // Another link still up takes over.
248
+ const next = [...this.#ext.values()].at(-1);
249
+ if (next && !this.#link && !this.#pending)
250
+ this.#adopt(next);
251
+ }
252
+ #drop(link) {
253
+ if (this.#pending === link)
254
+ this.#pending = undefined;
255
+ if (this.#link === link) {
256
+ this.#link = undefined;
257
+ this.#info = undefined;
258
+ this.#changed();
259
+ }
260
+ }
261
+ // #adopt asks the Node of itself on link, then makes it the current one.
262
+ #adopt(link) {
263
+ this.#pending = link;
264
+ void (async () => {
265
+ let delay = this.#backoff.minMs;
266
+ for (;;) {
267
+ if (this.#closed || this.#pending !== link)
268
+ return;
269
+ try {
270
+ const info = await askInfo(link, this.#s);
271
+ if (this.#closed || this.#pending !== link)
272
+ return;
273
+ this.#pending = undefined;
274
+ this.#link = link;
275
+ this.#info = info;
276
+ if (this.versionFailure())
277
+ this.#error = undefined;
278
+ break;
279
+ }
280
+ catch (e) {
281
+ if (e instanceof InvalidExchange && /frame bound/.test(e.message)) {
282
+ // A Node this device cannot follow: it stays waiting.
283
+ if (this.#pending === link)
284
+ this.#pending = undefined;
285
+ return;
286
+ }
287
+ if (e instanceof Failure && e.code === "version") {
288
+ // A Node of another version: told, and tried again on the
289
+ // backoff, as it may be updated meanwhile; never closed for it.
290
+ this.#error = e;
291
+ this.#changed(true);
292
+ for (const w of [...this.#waiters])
293
+ w(undefined);
294
+ if (this.#connect) {
295
+ try {
296
+ this.#onError?.(e);
297
+ }
298
+ catch {
299
+ // The hook's failure is its own.
300
+ }
301
+ // A guest dials again, on its backoff.
302
+ if (this.#pending === link)
303
+ this.#pending = undefined;
304
+ this.#guest?.close();
305
+ return;
306
+ }
307
+ await this.#sleep(delay);
308
+ delay = Math.min(delay * 2, this.#backoff.maxMs);
309
+ continue;
310
+ }
311
+ await sleep(RETRY_MS);
312
+ }
313
+ }
314
+ for (const s of this.#subs)
315
+ s.start(link);
316
+ this.outbox.start(link, this.#info);
317
+ for (const w of [...this.#waiters])
318
+ w(link);
319
+ // Last: a watcher may close the Remote, or the link may be lost, as
320
+ // it is told.
321
+ this.#changed();
322
+ })();
323
+ }
324
+ async #dial() {
325
+ this.#delay = this.#backoff.minMs;
326
+ while (!this.#closed) {
327
+ let conn;
328
+ try {
329
+ conn = await this.#connect();
330
+ }
331
+ catch (e) {
332
+ if (this.#closed)
333
+ return;
334
+ try {
335
+ this.#onError?.(e);
336
+ }
337
+ catch {
338
+ // The hook's failure is its own.
339
+ }
340
+ if (this.#closed)
341
+ return;
342
+ if (e instanceof KeywireError && e.code === "share-ended") {
343
+ // No attempt can mend it: the share is gone.
344
+ this.#error = e;
345
+ this.close();
346
+ return;
347
+ }
348
+ const delay = this.#delay;
349
+ this.#delay = Math.min(delay * 2, this.#backoff.maxMs);
350
+ await this.#sleep(delay);
351
+ continue;
352
+ }
353
+ if (this.#closed) {
354
+ conn.close();
355
+ return;
356
+ }
357
+ this.#guest = conn;
358
+ const service = this.#s.service;
359
+ const link = { peer: conn.peer, open: (o) => conn.openExtensionStream(service, o) };
360
+ this.#adopt(link);
361
+ await conn.closed;
362
+ this.#drop(link);
363
+ this.#guest = undefined;
364
+ if (this.#closed)
365
+ return;
366
+ if (this.versionFailure()) {
367
+ // The Node answered in another version: back off, as from a
368
+ // failed attempt.
369
+ const delay = this.#delay;
370
+ this.#delay = Math.min(delay * 2, this.#backoff.maxMs);
371
+ await this.#sleep(delay);
372
+ continue;
373
+ }
374
+ this.#delay = this.#backoff.minMs;
375
+ await this.#sleep(this.#delay);
376
+ }
377
+ }
378
+ // #sleep waits about ms, jittered so that guests do not reconnect in step.
379
+ #sleep(ms) {
380
+ return new Promise((resolve) => {
381
+ const done = () => {
382
+ clearTimeout(t);
383
+ this.#wake = undefined;
384
+ resolve();
385
+ };
386
+ const t = setTimeout(done, ms * (0.5 + Math.random() / 2));
387
+ this.#wake = done;
388
+ });
389
+ }
390
+ // nextLink resolves with the current link, or the next within
391
+ // connectWaitMs, or undefined.
392
+ nextLink() {
393
+ const now = this.#current();
394
+ if (now || this.#closed || this.versionFailure())
395
+ return Promise.resolve(now);
396
+ return new Promise((resolve) => {
397
+ const done = (l) => {
398
+ clearTimeout(timer);
399
+ this.#waiters.delete(done);
400
+ resolve(l && this.#current());
401
+ };
402
+ const timer = setTimeout(() => done(undefined), this.#s.connectWaitMs);
403
+ this.#waiters.add(done);
404
+ });
405
+ }
406
+ linkIs(link) {
407
+ return this.#link === link;
408
+ }
409
+ #check() {
410
+ if (this.#closed)
411
+ throw new Stopped("the Remote is closed");
412
+ if (this.#host.stopped)
413
+ throw new Stopped(this.#host.stopped);
414
+ }
415
+ // mirror mirrors collection, starting from copy if given.
416
+ mirror(collection, onChange, copy) {
417
+ this.#check();
418
+ if (!validName(collection, this.#s.limits.maxName))
419
+ throw new RangeError("keywire: a collection name is a name (spec/state.md, 2.1)");
420
+ if (this.#mirrors >= this.#s.maxMirrors)
421
+ throw new StateFull(`at most ${this.#s.maxMirrors} mirrors per Remote`);
422
+ const m = new Mirror(this, this.#s, collection, onChange, copy);
423
+ this.#mirrors++;
424
+ return this.#add(m);
425
+ }
426
+ // log follows log, from its start or as opts says.
427
+ log(name, handler, opts = {}) {
428
+ this.#check();
429
+ if (!validName(name, this.#s.limits.maxName))
430
+ throw new RangeError("keywire: a log name is a name (spec/state.md, 2.1)");
431
+ if (this.#logs >= this.#s.maxLogs)
432
+ throw new StateFull(`at most ${this.#s.maxLogs} log subscriptions per Remote`);
433
+ const l = new LogSubscription(this, this.#s, name, handler, opts);
434
+ this.#logs++;
435
+ return this.#add(l);
436
+ }
437
+ #add(s) {
438
+ this.#subs.add(s);
439
+ if (this.#link)
440
+ s.start(this.#link);
441
+ return s;
442
+ }
443
+ // remove forgets a closed subscription.
444
+ remove(s) {
445
+ if (!this.#subs.delete(s))
446
+ return;
447
+ if (s instanceof Mirror)
448
+ this.#mirrors--;
449
+ else
450
+ this.#logs--;
451
+ }
452
+ // readLog reads, once, up to limit entries of log just before before,
453
+ // under epoch, in log order: fewer when the log starts later. The Node
454
+ // sends them in pages, the latest first. It fails with Failure "stale"
455
+ // once the log has moved to another epoch, and while there is no link.
456
+ async readLog(log, epoch, before, limit) {
457
+ this.#check();
458
+ if (!Number.isSafeInteger(limit) || limit < 1 || limit > this.#s.limits.pageEntries)
459
+ throw new RangeError(`keywire: a log read takes 1 to ${this.#s.limits.pageEntries} entries`);
460
+ const c = this.#current();
461
+ if (!c)
462
+ throw new Failure("unreachable", "not connected to the Node");
463
+ return readLog(c.link, this.#s, log, epoch.slice(), before, limit);
464
+ }
465
+ // readBlob reads blob name, verified chunk by chunk (spec/state.md,
466
+ // 2.9): it resolves once the Node's head and hash list are verified, with
467
+ // the stream of the blob's chunks. A lost link is asked again on the next,
468
+ // from the first chunk not yet queued; reads are a few at a time
469
+ // (maxReading), each holding its slot until its stream ends.
470
+ readBlob(name, opts = {}) {
471
+ try {
472
+ this.#check();
473
+ }
474
+ catch (e) {
475
+ return Promise.reject(e);
476
+ }
477
+ const l = this.#s.limits;
478
+ const variant = opts.variant ?? new Uint8Array(0);
479
+ if (!(variant instanceof Uint8Array) || variant.length > MAX_VARIANT)
480
+ return Promise.reject(new RangeError(`keywire: a blob variant is at most ${MAX_VARIANT} bytes`));
481
+ const maxSize = opts.maxSize ?? l.maxBlob;
482
+ if (!Number.isSafeInteger(maxSize) || maxSize < 1 || maxSize > l.maxBlob)
483
+ return Promise.reject(new RangeError(`keywire: a blob read takes 1 to ${l.maxBlob} bytes`));
484
+ let from = 0;
485
+ let digest;
486
+ if (opts.from !== undefined) {
487
+ from = opts.from.offset;
488
+ if (!Number.isSafeInteger(from) ||
489
+ from < 0 ||
490
+ !(opts.from.digest instanceof Uint8Array) ||
491
+ opts.from.digest.length !== 32)
492
+ return Promise.reject(new RangeError("keywire: a blob read resumes from an offset of a blob of 32-byte digest"));
493
+ digest = opts.from.digest.slice();
494
+ }
495
+ const r = new BlobReader(this.#s, name, variant.slice(), from, digest, maxSize);
496
+ this.#blobs.add(r);
497
+ this.#reads
498
+ .ask((link) => r.attempt(link))
499
+ .then(() => { }, (e) => r.fail(e))
500
+ .finally(() => this.#blobs.delete(r));
501
+ return r.head;
502
+ }
503
+ // writeBlob gives the Node a blob under prefix and resolves with its name
504
+ // for it. source is kept, not copied: a Blob (a File too) is read with
505
+ // slice, a BlobStreamSource opened when its bytes are needed. Once it has
506
+ // one of maxWriting slots, the source is hashed once; then each attempt
507
+ // sends only what the sink does not hold, again while the Node is busy
508
+ // or once a link is lost. A source that changed fails "changed".
509
+ writeBlob(prefix, source) {
510
+ try {
511
+ this.#check();
512
+ }
513
+ catch (e) {
514
+ return Promise.reject(e);
515
+ }
516
+ let size;
517
+ if (isBlob(source))
518
+ size = source.size;
519
+ else if (source &&
520
+ typeof source.open === "function" &&
521
+ Number.isSafeInteger(source.size) &&
522
+ source.size >= 0)
523
+ size = source.size;
524
+ else
525
+ return Promise.reject(new TypeError("keywire: a blob is a Blob, or a source of a size and an open"));
526
+ if (size > this.#s.limits.maxBlob)
527
+ return Promise.reject(new Failure("too_large", "the blob is larger than maxBlob"));
528
+ const w = new BlobWriter(this.#s, prefix, source, size);
529
+ this.#blobs.add(w);
530
+ return this.#writes.ask((link) => w.attempt(link)).finally(() => this.#blobs.delete(w));
531
+ }
532
+ // query asks the Node the query name of args and resolves with its
533
+ // answer. args is copied as it is accepted; a query only reads, so it is
534
+ // asked again while the Node is busy or once a link is lost, and with no
535
+ // link waits connectWaitMs for one.
536
+ query(name, args) {
537
+ try {
538
+ this.#check();
539
+ }
540
+ catch (e) {
541
+ return Promise.reject(e);
542
+ }
543
+ if (args.length > this.#s.limits.maxQueryArgs)
544
+ return Promise.reject(new RangeError(`keywire: query args are at most ${this.#s.limits.maxQueryArgs} bytes`));
545
+ const copy = args.slice();
546
+ return this.#queries.ask(async (link) => {
547
+ const env = await once(link, this.#s, { case: "query", value: { name, args: copy } });
548
+ if (env.body.case !== "queryResult" ||
549
+ env.body.value.data.length > this.#s.limits.maxQueryResult)
550
+ throw new InvalidExchange("not a query answer");
551
+ return env.body.value.data;
552
+ });
553
+ }
554
+ // outcome reads back the outcome of this device's command id without
555
+ // sending its payload. It only reads, so it is asked again like a query;
556
+ // the outbox does not use it. Within the outcome window a resend under
557
+ // the same id remains the way to settle a command.
558
+ outcome(id) {
559
+ try {
560
+ this.#check();
561
+ }
562
+ catch (e) {
563
+ return Promise.reject(e);
564
+ }
565
+ if (id.length !== 16)
566
+ return Promise.reject(new RangeError("keywire: a command id is 16 bytes"));
567
+ const copy = id.slice();
568
+ return this.#queries.ask(async (link) => {
569
+ const env = await once(link, this.#s, { case: "readOutcome", value: { id: copy } });
570
+ if (env.body.case !== "outcomeResult")
571
+ throw new InvalidExchange("not an outcome result");
572
+ const r = env.body.value;
573
+ if (r.outcomeEpoch.length !== 16)
574
+ throw new InvalidExchange("an outcome epoch is 16 bytes");
575
+ const o = r.outcome;
576
+ if (o.case === "pending" || o.case === "unknown") {
577
+ if (r.digest.length !== 0)
578
+ throw new InvalidExchange("a digest with no outcome");
579
+ return { state: o.case, epoch: r.outcomeEpoch };
580
+ }
581
+ if (r.digest.length !== 32)
582
+ throw new InvalidExchange("a command digest is 32 bytes");
583
+ if (o.case === "accepted")
584
+ return { state: "accepted", epoch: r.outcomeEpoch, digest: r.digest };
585
+ if (o.case === "rejected")
586
+ return {
587
+ state: "rejected",
588
+ epoch: r.outcomeEpoch,
589
+ digest: r.digest,
590
+ ...rejection(o.value.code, o.value.message),
591
+ };
592
+ throw new InvalidExchange("an outcome result with no outcome");
593
+ });
594
+ }
595
+ // openChannel opens channel name with payload on the link there is, or
596
+ // the next. The channel ends with that link.
597
+ async openChannel(name, payload) {
598
+ this.#check();
599
+ if (payload.length > this.#s.limits.maxPayload)
600
+ throw new RangeError(`keywire: a channel payload is at most ${this.#s.limits.maxPayload} bytes`);
601
+ if (this.#channelsWaiting >= this.#s.maxWaitingQueries && !this.#current())
602
+ throw new Failure("busy", "too many channels are waiting for a link");
603
+ this.#channelsWaiting++;
604
+ let c;
605
+ try {
606
+ c = await this.nextLink();
607
+ }
608
+ finally {
609
+ this.#channelsWaiting--;
610
+ }
611
+ if (!c)
612
+ throw new Failure("unreachable", "not connected to the Node");
613
+ return openChannel(c.link, this.#s, name, payload.slice());
614
+ }
615
+ // command resolves with the Node's answer, however many links that takes,
616
+ // or rejects with Uncertain (spec/state.md, 2.4). payload is copied.
617
+ command(name, payload = new Uint8Array(0), opts = {}) {
618
+ try {
619
+ this.#check();
620
+ }
621
+ catch (e) {
622
+ return Promise.reject(e);
623
+ }
624
+ return this.outbox.submit(name, payload, opts.signal, undefined);
625
+ }
626
+ // resume submits again a command kept from before a restart, under its
627
+ // id and its age, checked like a new one.
628
+ resume(p, opts = {}) {
629
+ try {
630
+ this.#check();
631
+ }
632
+ catch (e) {
633
+ return Promise.reject(e);
634
+ }
635
+ return this.outbox.submit(p.name, p.payload, opts.signal, p);
636
+ }
637
+ // pendingCommands are copies of every command not yet answered.
638
+ pendingCommands() {
639
+ return this.outbox.pending();
640
+ }
641
+ // withdraw stops sending the command under id, which then rejects; one
642
+ // already on its way may still reach the Node.
643
+ withdraw(id) {
644
+ this.outbox.withdraw(id);
645
+ }
646
+ // close ends the Remote's mirrors, logs and outbox, and frees its slot.
647
+ close() {
648
+ if (this.#closed)
649
+ return;
650
+ this.#closed = true;
651
+ for (const s of [...this.#subs])
652
+ s.close();
653
+ const stopped = new Stopped("the Remote is closed");
654
+ for (const b of [...this.#blobs])
655
+ b.stop(stopped);
656
+ this.#blobs.clear();
657
+ this.outbox.close();
658
+ for (const w of [...this.#waiters])
659
+ w(undefined);
660
+ this.#link = undefined;
661
+ this.#pending = undefined;
662
+ this.#info = undefined;
663
+ this.#guest?.close();
664
+ this.#wake?.();
665
+ this.#host.removed(this);
666
+ this.#changed();
667
+ }
668
+ get closed() {
669
+ return this.#closed;
670
+ }
671
+ }
672
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
673
+ // Subscription is a request that lasts until closed: it restarts on every
674
+ // link, resuming from what it has already received.
675
+ export class Subscription {
676
+ #remote;
677
+ s;
678
+ #stream;
679
+ #closed = false;
680
+ #error;
681
+ #retry;
682
+ constructor(remote, s) {
683
+ this.#remote = remote;
684
+ this.s = s;
685
+ }
686
+ // error is set once the Node refuses the subscription, or it failed past
687
+ // its limits; it then stops.
688
+ get error() {
689
+ return this.#error;
690
+ }
691
+ linkedTo(_link) { }
692
+ start(link) {
693
+ if (this.#closed || this.#error || this.#stream)
694
+ return;
695
+ this.linkedTo(link);
696
+ let st;
697
+ try {
698
+ st = openFor(link, this.request());
699
+ }
700
+ catch {
701
+ this.#again(link);
702
+ return;
703
+ }
704
+ this.#stream = st;
705
+ void this.#pump(link, st);
706
+ }
707
+ fail(e) {
708
+ this.#error = e;
709
+ this.#stream?.reset(CODE_CANCEL);
710
+ }
711
+ close() {
712
+ if (this.#closed)
713
+ return;
714
+ this.#closed = true;
715
+ clearTimeout(this.#retry);
716
+ this.#stream?.reset(CODE_CANCEL);
717
+ this.#remote.remove(this);
718
+ }
719
+ async #pump(link, st) {
720
+ const conv = new Conv(st, this.s.frameBound, this.s.closed);
721
+ try {
722
+ await conv.send(this.request());
723
+ for (let env = await conv.recv(); env; env = await conv.recv()) {
724
+ const f = failureOf(env);
725
+ if (f) {
726
+ this.#error = f;
727
+ return;
728
+ }
729
+ this.apply(env, link);
730
+ if (this.#error)
731
+ return;
732
+ }
733
+ }
734
+ catch (e) {
735
+ // A message breaking the protocol resets the stream; the link or the
736
+ // stream ended otherwise. Either way it resumes later.
737
+ if (e instanceof InvalidExchange)
738
+ st.reset(CODE_INVALID);
739
+ }
740
+ finally {
741
+ if (this.#stream === st)
742
+ this.#stream = undefined;
743
+ st.reset(CODE_CANCEL);
744
+ }
745
+ this.#again(link);
746
+ }
747
+ // #again starts again on link if it is still current; a new link starts
748
+ // every subscription anyway.
749
+ #again(link) {
750
+ if (this.#closed || this.#error)
751
+ return;
752
+ clearTimeout(this.#retry);
753
+ this.#retry = setTimeout(() => {
754
+ if (this.#remote.linkIs(link) && !this.#stream)
755
+ this.start(link);
756
+ }, RETRY_MS);
757
+ }
758
+ }
759
+ const rowBytes = (r) => utf8Len(r.id) + r.data.length;
760
+ function sameRow(a, b) {
761
+ return a.version === b.version && compareBytes(a.data, b.data) === 0;
762
+ }
763
+ // Mirror is a local copy of one owned collection, kept up to date while
764
+ // linked and kept as is while not; bounded by mirrorRows and mirrorBytes.
765
+ // One started from a copy is caught up as of that copy, and resumes from
766
+ // it.
767
+ export class Mirror extends Subscription {
768
+ collection;
769
+ #rows = new Map();
770
+ #bytes = 0;
771
+ #onChange;
772
+ #node;
773
+ #cursor;
774
+ // #stale, during a reset, are the ids held when it began that no row
775
+ // sent since has confirmed; the batch that ends the reset drops them.
776
+ // It only ever shrinks from the rows held, so it is bounded by them.
777
+ #stale;
778
+ /** @internal How many ids a reset in progress holds, for tests. */
779
+ static staleIds(m) {
780
+ return m.#stale?.size ?? 0;
781
+ }
782
+ #synced = false;
783
+ #live = false;
784
+ constructor(remote, s, collection, onChange, copy) {
785
+ super(remote, s);
786
+ this.collection = collection;
787
+ this.#onChange = onChange;
788
+ this.#node = remote.key;
789
+ if (copy)
790
+ this.#import(copy);
791
+ }
792
+ // #import checks copy whole before holding any of its rows.
793
+ #import(copy) {
794
+ const bad = (why) => new RangeError(`keywire: a mirror copy ${why}`);
795
+ if (!(copy.node instanceof Uint8Array) || copy.node.length !== 32)
796
+ throw bad("names its Node");
797
+ if (this.#node && !sameBytes(copy.node, this.#node))
798
+ throw bad("of another Node");
799
+ if (copy.collection !== this.collection)
800
+ throw bad("of another collection");
801
+ if (!(copy.epoch instanceof Uint8Array) || copy.epoch.length !== 16)
802
+ throw bad("has a 16-byte epoch");
803
+ if (typeof copy.seq !== "bigint" || copy.seq < 0n)
804
+ throw bad("has a sequence number");
805
+ if (!Array.isArray(copy.rows) || copy.rows.length > this.s.mirrorRows)
806
+ throw bad(`holds at most ${this.s.mirrorRows} rows`);
807
+ const ids = new Set();
808
+ let bytes = 0;
809
+ for (const r of copy.rows) {
810
+ if (!validName(r?.id, this.s.limits.maxName) ||
811
+ !(r.data instanceof Uint8Array) ||
812
+ r.data.length > this.s.limits.maxValue ||
813
+ r.deleted !== false ||
814
+ typeof r.version !== "bigint" ||
815
+ ids.has(r.id))
816
+ throw bad("holds only valid rows, one per id");
817
+ ids.add(r.id);
818
+ bytes += rowBytes(r);
819
+ }
820
+ if (bytes > this.s.mirrorBytes)
821
+ throw bad(`holds at most ${this.s.mirrorBytes} bytes`);
822
+ for (const r of copy.rows) {
823
+ // Copied: a small view keeps no large buffer of the caller's alive.
824
+ this.#rows.set(r.id, { id: r.id, version: r.version, data: r.data.slice(), deleted: false });
825
+ }
826
+ this.#bytes = bytes;
827
+ this.#node = copy.node.slice();
828
+ this.#cursor = { epoch: copy.epoch.slice(), seq: copy.seq };
829
+ this.#synced = true;
830
+ }
831
+ // live reports whether the Node has caught the mirror up since it
832
+ // started, rather than its rows being only those of a copy.
833
+ get live() {
834
+ return this.#live && this.synced;
835
+ }
836
+ // synced reports whether the mirror has caught up with the Node at least
837
+ // once and is not in the middle of a reset.
838
+ get synced() {
839
+ return this.#synced && !this.#stale;
840
+ }
841
+ get size() {
842
+ return this.#rows.size;
843
+ }
844
+ get(id) {
845
+ const r = this.#rows.get(id);
846
+ return r && { ...r, data: r.data.slice() };
847
+ }
848
+ rows() {
849
+ return [...this.#rows.values()].map((r) => ({ ...r, data: r.data.slice() }))[Symbol.iterator]();
850
+ }
851
+ // copy is the mirror as it stands, while caught up and outside a reset.
852
+ copy() {
853
+ if (!this.synced || !this.#cursor || !this.#node)
854
+ return undefined;
855
+ return {
856
+ node: this.#node.slice(),
857
+ collection: this.collection,
858
+ epoch: this.#cursor.epoch.slice(),
859
+ seq: this.#cursor.seq,
860
+ rows: [...this.#rows.values()].map((r) => ({ ...r, data: r.data.slice() })),
861
+ };
862
+ }
863
+ linkedTo(link) {
864
+ // A guest's Remote learns its Node at the first link: a copy of
865
+ // another Node's is dropped.
866
+ if (this.#node && !sameBytes(this.#node, link.peer)) {
867
+ const removed = [...this.#rows.keys()];
868
+ this.#rows.clear();
869
+ this.#bytes = 0;
870
+ this.#cursor = undefined;
871
+ this.#synced = false;
872
+ if (removed.length > 0)
873
+ this.#onChange?.({ upserted: [], removed });
874
+ }
875
+ this.#node = link.peer.slice();
876
+ }
877
+ request() {
878
+ return {
879
+ case: "subscribe",
880
+ value: { collection: this.collection, ...(this.#cursor && { cursor: this.#cursor }) },
881
+ };
882
+ }
883
+ apply(env) {
884
+ if (env.body.case !== "rows")
885
+ throw new InvalidExchange("not a row batch");
886
+ const b = env.body.value;
887
+ if (b.cursor?.epoch.length !== 16)
888
+ throw new InvalidExchange("a batch's cursor");
889
+ for (const r of b.rows)
890
+ if (!validName(r.id, this.s.limits.maxName) ||
891
+ r.data.length > this.s.limits.maxValue ||
892
+ (r.deleted && r.data.length > 0))
893
+ throw new InvalidExchange("an invalid row");
894
+ const stale = b.reset ? new Set(this.#rows.keys()) : this.#stale;
895
+ // Worked out before any of it is held: the batch fits whole or fails
896
+ // the mirror.
897
+ const next = new Map();
898
+ const confirmed = new Set();
899
+ let count = this.#rows.size;
900
+ let bytes = this.#bytes;
901
+ const held = (id) => (next.has(id) ? next.get(id) : this.#rows.get(id));
902
+ for (const r of b.rows) {
903
+ const wasStale = !!stale?.has(r.id) && !confirmed.has(r.id);
904
+ if (wasStale)
905
+ confirmed.add(r.id);
906
+ const old = held(r.id) ?? undefined;
907
+ if (r.deleted) {
908
+ if (old) {
909
+ next.set(r.id, null);
910
+ count--;
911
+ bytes -= rowBytes(old);
912
+ }
913
+ }
914
+ else if (!old || r.version > old.version || (wasStale && !sameRow(old, r))) {
915
+ // A reset makes what is held stale: its versions belong to the old
916
+ // epoch, so a row sent before the next synced batch replaces it.
917
+ next.set(r.id, { id: r.id, version: r.version, data: r.data, deleted: false });
918
+ if (!old)
919
+ count++;
920
+ bytes += rowBytes(r) - (old ? rowBytes(old) : 0);
921
+ }
922
+ }
923
+ if (count > this.s.mirrorRows || bytes > this.s.mirrorBytes) {
924
+ this.fail(new StateFull(`a mirror holds at most ${this.s.mirrorRows} rows and ${this.s.mirrorBytes} bytes`));
925
+ return;
926
+ }
927
+ const changes = { upserted: [], removed: [] };
928
+ const wasLive = this.live;
929
+ for (const id of confirmed)
930
+ stale.delete(id);
931
+ this.#stale = stale;
932
+ for (const [id, r] of next) {
933
+ if (r) {
934
+ this.#rows.set(id, r);
935
+ changes.upserted.push({ ...r, data: r.data.slice() });
936
+ }
937
+ else {
938
+ this.#rows.delete(id);
939
+ changes.removed.push(id);
940
+ }
941
+ }
942
+ this.#bytes = bytes;
943
+ if (b.synced) {
944
+ if (this.#stale) {
945
+ for (const id of this.#stale) {
946
+ const r = this.#rows.get(id);
947
+ if (r) {
948
+ this.#rows.delete(id);
949
+ this.#bytes -= rowBytes(r);
950
+ changes.removed.push(id);
951
+ }
952
+ }
953
+ this.#stale = undefined;
954
+ }
955
+ this.#synced = true;
956
+ this.#live = true;
957
+ }
958
+ this.#cursor = { epoch: b.cursor.epoch, seq: b.cursor.seq };
959
+ // Catching up is told even when it changed nothing, so that "none" can
960
+ // be told from "not yet known".
961
+ if (this.#onChange &&
962
+ (changes.upserted.length > 0 || changes.removed.length > 0 || this.live !== wasLive))
963
+ this.#onChange(changes);
964
+ }
965
+ }
966
+ function logBatch(env, s) {
967
+ if (env.body.case !== "log")
968
+ throw new InvalidExchange("not a log batch");
969
+ const m = env.body.value;
970
+ if (m.epoch.length !== 16 || m.entries.some((e) => e.length > s.limits.maxValue))
971
+ throw new InvalidExchange("a malformed log batch");
972
+ return m;
973
+ }
974
+ // LogSubscription follows an append-only log, resuming after the last
975
+ // entry received.
976
+ export class LogSubscription extends Subscription {
977
+ log;
978
+ #handler;
979
+ #tail;
980
+ #epoch = new Uint8Array(0);
981
+ #offset = 0n;
982
+ constructor(remote, s, log, handler, opts) {
983
+ super(remote, s);
984
+ this.log = log;
985
+ this.#handler = handler;
986
+ const tail = opts.tail ?? 0;
987
+ if (!Number.isSafeInteger(tail) || tail < 0)
988
+ throw new RangeError("keywire: tail is 0 or more");
989
+ this.#tail = BigInt(tail);
990
+ if (opts.from) {
991
+ if (opts.from.epoch.length !== 16 || opts.from.offset < 0n)
992
+ throw new RangeError("keywire: a log resumes from a 16-byte epoch and an offset");
993
+ this.#epoch = opts.from.epoch.slice();
994
+ this.#offset = opts.from.offset;
995
+ }
996
+ }
997
+ // offset is where the next entry goes.
998
+ get offset() {
999
+ return this.#offset;
1000
+ }
1001
+ request() {
1002
+ return {
1003
+ case: "subscribeLog",
1004
+ value: { log: this.log, epoch: this.#epoch, offset: this.#offset, tail: this.#tail },
1005
+ };
1006
+ }
1007
+ apply(env) {
1008
+ const b = logBatch(env, this.s);
1009
+ if (b.reset) {
1010
+ this.#epoch = b.epoch;
1011
+ this.#offset = b.offset;
1012
+ this.#handler.reset?.(b.offset, b.epoch.slice());
1013
+ }
1014
+ if (b.offset !== this.#offset)
1015
+ throw new InvalidExchange("a log batch out of order");
1016
+ if (b.entries.length === 0 && !b.synced)
1017
+ return;
1018
+ this.#handler.entries(b.offset, b.entries, b.synced);
1019
+ this.#offset += BigInt(b.entries.length);
1020
+ }
1021
+ }
1022
+ // readLog collects a log read's pages, each ending where the later one
1023
+ // began, until limit entries or the Node ends the stream.
1024
+ async function readLog(link, s, log, epoch, before, limit) {
1025
+ const { conv, first } = await request(link, s, {
1026
+ case: "readLog",
1027
+ value: { log, epoch, before, limit: BigInt(limit) },
1028
+ });
1029
+ try {
1030
+ const pages = [];
1031
+ let end = before;
1032
+ let total = 0;
1033
+ for (let env = first; env; env = await conv.recv()) {
1034
+ const f = failureOf(env);
1035
+ if (f)
1036
+ throw f;
1037
+ const b = logBatch(env, s);
1038
+ const n = b.entries.length;
1039
+ if (b.reset ||
1040
+ b.synced ||
1041
+ compareBytes(b.epoch, epoch) !== 0 ||
1042
+ b.offset + BigInt(n) !== end ||
1043
+ (n === 0 && env !== first) ||
1044
+ total + n > limit)
1045
+ throw new InvalidExchange("a log page out of order");
1046
+ if (n === 0)
1047
+ break;
1048
+ pages.push(b.entries);
1049
+ end = b.offset;
1050
+ total += n;
1051
+ if (total === limit || end === 0n)
1052
+ break;
1053
+ }
1054
+ return { epoch, offset: end, entries: pages.reverse().flat() };
1055
+ }
1056
+ finally {
1057
+ conv.stream.reset(CODE_CANCEL);
1058
+ }
1059
+ }
1060
+ // HASH_PAGE is the most hashes one BlobHashes message carries.
1061
+ const HASH_PAGE = 1024;
1062
+ const sha256 = async (b) => new Uint8Array(await crypto.subtle.digest("SHA-256", b));
1063
+ // chunksOf is how many chunks a blob of size bytes has. Sizes are bounded
1064
+ // by maxBlob (at most 2^40) before they reach it; anything but a safe
1065
+ // integer is refused rather than rounded.
1066
+ function chunksOf(size, chunk) {
1067
+ if (!Number.isSafeInteger(size) || size < 0)
1068
+ throw new RangeError(`keywire: a blob size of ${size} bytes`);
1069
+ return Math.floor(size / chunk) + (size % chunk === 0 ? 0 : 1);
1070
+ }
1071
+ // boundary reports whether at is a chunk boundary of a blob of size bytes.
1072
+ const boundary = (at, size, chunk) => at <= size && (at % chunk === 0 || at === size);
1073
+ // sent sends body on conv; if that fails, the Node may have refused the
1074
+ // blob and closed: its Failure, if it sent one, is the error.
1075
+ async function sent(conv, body) {
1076
+ try {
1077
+ await conv.send(body);
1078
+ }
1079
+ catch (e) {
1080
+ let env = null;
1081
+ try {
1082
+ env = await conv.recv();
1083
+ }
1084
+ catch {
1085
+ // No answer: the send's failure stands.
1086
+ }
1087
+ const f = env && failureOf(env);
1088
+ throw f ?? e;
1089
+ }
1090
+ }
1091
+ // BlobReader is one readBlob call: its attempts, each resuming where the
1092
+ // last chunk handed on ended, and the verified stream they fill.
1093
+ class BlobReader {
1094
+ s;
1095
+ name;
1096
+ variant;
1097
+ from;
1098
+ digest;
1099
+ maxSize;
1100
+ head;
1101
+ stream;
1102
+ #resolve;
1103
+ #reject;
1104
+ #controller;
1105
+ #headed = false;
1106
+ // ended: the consumer cancelled the stream, or the Remote closed; no
1107
+ // attempt goes on.
1108
+ #ended = false;
1109
+ #wake;
1110
+ #st;
1111
+ #size;
1112
+ // next is where the chunks handed on end.
1113
+ #next;
1114
+ constructor(s, name, variant, from, digest, maxSize) {
1115
+ this.s = s;
1116
+ this.name = name;
1117
+ this.variant = variant;
1118
+ this.from = from;
1119
+ this.digest = digest;
1120
+ this.maxSize = maxSize;
1121
+ this.#next = from;
1122
+ this.head = new Promise((resolve, reject) => {
1123
+ this.#resolve = resolve;
1124
+ this.#reject = reject;
1125
+ });
1126
+ // Pulled: the next chunk is read from the Node only once the queue
1127
+ // is empty, so a read holds at most the chunk queued and the one
1128
+ // being received.
1129
+ this.stream = new ReadableStream({
1130
+ start: (c) => {
1131
+ this.#controller = c;
1132
+ },
1133
+ pull: () => {
1134
+ this.#wake?.();
1135
+ },
1136
+ cancel: () => {
1137
+ this.#end();
1138
+ },
1139
+ }, { highWaterMark: 1 });
1140
+ }
1141
+ #end() {
1142
+ this.#ended = true;
1143
+ this.#st?.reset(CODE_CANCEL);
1144
+ this.#wake?.();
1145
+ }
1146
+ // stop ends the read with e as its Remote closes: a wait for demand is
1147
+ // woken, the stream reset, the head or the stream failed with e, and no
1148
+ // attempt follows.
1149
+ stop(e) {
1150
+ if (this.#ended)
1151
+ return;
1152
+ this.fail(e);
1153
+ this.#end();
1154
+ }
1155
+ #demand() {
1156
+ if (this.#ended || (this.#controller.desiredSize ?? 0) > 0)
1157
+ return Promise.resolve();
1158
+ return new Promise((resolve) => {
1159
+ this.#wake = () => {
1160
+ this.#wake = undefined;
1161
+ resolve();
1162
+ };
1163
+ });
1164
+ }
1165
+ // fail ends the call with e: the head's promise if it is still to come,
1166
+ // else the stream.
1167
+ fail(e) {
1168
+ if (this.#ended)
1169
+ return;
1170
+ if (!this.#headed)
1171
+ this.#reject(e);
1172
+ else
1173
+ this.#controller.error(e);
1174
+ }
1175
+ async attempt(link) {
1176
+ if (this.#ended)
1177
+ return;
1178
+ try {
1179
+ await this.#attempt(link);
1180
+ }
1181
+ catch (e) {
1182
+ if (this.#ended)
1183
+ return;
1184
+ throw e;
1185
+ }
1186
+ }
1187
+ async #attempt(link) {
1188
+ const s = this.s;
1189
+ const chunk = s.limits.chunkSize;
1190
+ const { conv, first } = await request(link, s, {
1191
+ case: "readBlob",
1192
+ value: {
1193
+ name: this.name,
1194
+ variant: this.variant,
1195
+ from: BigInt(this.#next),
1196
+ chunkSize: BigInt(chunk),
1197
+ // Whenever the digest is known it is sent, from 0 too: an
1198
+ // attempt after the head must not take another blob under it.
1199
+ digest: this.digest ?? new Uint8Array(0),
1200
+ },
1201
+ }, (st) => {
1202
+ this.#st = st;
1203
+ });
1204
+ try {
1205
+ if (first.body.case !== "blobHead")
1206
+ throw new InvalidExchange("not a blob head");
1207
+ const head = first.body.value;
1208
+ if (head.digest.length !== 32)
1209
+ throw new InvalidExchange("a blob digest not of 32 bytes");
1210
+ if (head.size > BigInt(this.maxSize))
1211
+ throw new Failure("too_large", `blob ${this.name} is larger than this read takes`);
1212
+ const size = Number(head.size);
1213
+ if ((this.digest && !sameBytes(head.digest, this.digest)) ||
1214
+ !boundary(this.#next, size, chunk))
1215
+ throw new InvalidExchange("a blob head not of the blob resumed");
1216
+ this.digest = head.digest.slice();
1217
+ this.#size = size;
1218
+ const n = chunksOf(size, chunk);
1219
+ const hashes = new Uint8Array(32 * n);
1220
+ const short = () => new Failure("short", `blob ${this.name} ended before its last chunk`);
1221
+ const next = async () => {
1222
+ const env = await conv.recv();
1223
+ if (env === null)
1224
+ throw short();
1225
+ const f = failureOf(env);
1226
+ if (f)
1227
+ throw f;
1228
+ return env;
1229
+ };
1230
+ for (let got = 0; got < n;) {
1231
+ const env = await next();
1232
+ if (env.body.case !== "blobHashes")
1233
+ throw new InvalidExchange("not a hash page");
1234
+ const page = env.body.value.hashes;
1235
+ const k = page.length / 32;
1236
+ if (page.length === 0 || page.length % 32 !== 0 || k > HASH_PAGE || k > n - got)
1237
+ throw new InvalidExchange("a hash page out of bounds");
1238
+ hashes.set(page, 32 * got);
1239
+ got += k;
1240
+ }
1241
+ if (!sameBytes(await sha256(hashes), this.digest))
1242
+ throw new Failure("digest", "the hash list is not the blob's digest");
1243
+ if (!this.#headed) {
1244
+ this.#headed = true;
1245
+ this.#resolve({ size, digest: this.digest.slice(), from: this.from, stream: this.stream });
1246
+ }
1247
+ for (let i = chunksOf(this.#next, chunk); i < n; i++) {
1248
+ await this.#demand();
1249
+ if (this.#ended)
1250
+ return;
1251
+ const want = Math.min(chunk, size - i * chunk);
1252
+ const out = new Uint8Array(want);
1253
+ for (let at = 0; at < want;) {
1254
+ const env = await next();
1255
+ if (env.body.case !== "blob")
1256
+ throw new InvalidExchange("not a blob page");
1257
+ const data = env.body.value.data;
1258
+ if (data.length === 0 || at + data.length > want)
1259
+ throw new InvalidExchange("a blob page across a chunk");
1260
+ out.set(data, at);
1261
+ at += data.length;
1262
+ }
1263
+ if (!sameBytes(await sha256(out), hashes.subarray(32 * i, 32 * i + 32))) {
1264
+ conv.stream.reset(CODE_INVALID);
1265
+ throw new Failure("corrupt", `chunk ${i} of blob ${this.name} is not its hash`);
1266
+ }
1267
+ if (this.#ended)
1268
+ return;
1269
+ this.#controller.enqueue(out);
1270
+ this.#next += want;
1271
+ }
1272
+ const end = await conv.recv();
1273
+ if (end !== null)
1274
+ throw failureOf(end) ?? new InvalidExchange("a message after the blob");
1275
+ if (this.#ended)
1276
+ return;
1277
+ this.#controller.close();
1278
+ }
1279
+ finally {
1280
+ conv.stream.reset(CODE_CANCEL);
1281
+ }
1282
+ }
1283
+ }
1284
+ function chunkSource(source, offset, chunkSize) {
1285
+ const changed = (why) => new Failure("changed", `the blob's source ${why}`);
1286
+ if (isBlob(source)) {
1287
+ let at = offset;
1288
+ return {
1289
+ async next(want) {
1290
+ let b;
1291
+ try {
1292
+ b = new Uint8Array(await source.slice(at, at + want).arrayBuffer());
1293
+ }
1294
+ catch (e) {
1295
+ throw changed(`could not be read: ${e}`);
1296
+ }
1297
+ if (b.length !== want)
1298
+ throw changed("ended early");
1299
+ at += want;
1300
+ return b;
1301
+ },
1302
+ close() { },
1303
+ };
1304
+ }
1305
+ let reader;
1306
+ try {
1307
+ reader = source.open(offset).getReader();
1308
+ }
1309
+ catch (e) {
1310
+ throw changed(`could not be opened: ${e}`);
1311
+ }
1312
+ let rest = new Uint8Array(0);
1313
+ return {
1314
+ async next(want) {
1315
+ const out = new Uint8Array(want);
1316
+ for (let at = 0; at < want;) {
1317
+ if (rest.length === 0) {
1318
+ let r;
1319
+ try {
1320
+ r = await reader.read();
1321
+ }
1322
+ catch (e) {
1323
+ throw changed(`could not be read: ${e}`);
1324
+ }
1325
+ if (r.done)
1326
+ throw changed("ended early");
1327
+ if (!(r.value instanceof Uint8Array))
1328
+ throw changed("gave something other than bytes");
1329
+ // A piece is at most one chunk, and is copied: what is held of it
1330
+ // beside the chunk being filled is bounded, whatever buffer the
1331
+ // source's view is of.
1332
+ if (r.value.length > chunkSize)
1333
+ throw new RangeError(`keywire: a blob source gave a piece of ${r.value.length} bytes, past chunkSize (${chunkSize})`);
1334
+ rest = new Uint8Array(r.value);
1335
+ }
1336
+ const n = Math.min(want - at, rest.length);
1337
+ out.set(rest.subarray(0, n), at);
1338
+ rest = n === rest.length ? new Uint8Array(0) : rest.subarray(n);
1339
+ at += n;
1340
+ }
1341
+ return out;
1342
+ },
1343
+ close() {
1344
+ rest = new Uint8Array(0);
1345
+ void reader.cancel().catch(() => { });
1346
+ },
1347
+ };
1348
+ }
1349
+ const isBlob = (x) => typeof Blob !== "undefined" && x instanceof Blob;
1350
+ // BlobWriter is one writeBlob call: its source hashed once, then its
1351
+ // attempts, each sending what the sink does not hold.
1352
+ class BlobWriter {
1353
+ s;
1354
+ prefix;
1355
+ source;
1356
+ size;
1357
+ #hashes;
1358
+ #digest;
1359
+ #stopped;
1360
+ #src;
1361
+ #st;
1362
+ constructor(s, prefix, source, size) {
1363
+ this.s = s;
1364
+ this.prefix = prefix;
1365
+ this.source = source;
1366
+ this.size = size;
1367
+ }
1368
+ // stop ends the write with e as its Remote closes: its source reader is
1369
+ // cancelled, its stream reset, and no attempt starts or goes on.
1370
+ stop(e) {
1371
+ if (this.#stopped)
1372
+ return;
1373
+ this.#stopped = e;
1374
+ this.#src?.close();
1375
+ this.#st?.reset(CODE_CANCEL);
1376
+ }
1377
+ #open(offset) {
1378
+ if (this.#stopped)
1379
+ throw this.#stopped;
1380
+ this.#src = chunkSource(this.source, offset, this.s.limits.chunkSize);
1381
+ return this.#src;
1382
+ }
1383
+ // #step awaits p, and fails with why the write stopped if it did meanwhile.
1384
+ async #step(p) {
1385
+ try {
1386
+ const v = await p;
1387
+ if (this.#stopped)
1388
+ throw this.#stopped;
1389
+ return v;
1390
+ }
1391
+ catch (e) {
1392
+ throw this.#stopped ?? e;
1393
+ }
1394
+ }
1395
+ async #hash() {
1396
+ const chunk = this.s.limits.chunkSize;
1397
+ const n = chunksOf(this.size, chunk);
1398
+ const hashes = new Uint8Array(32 * n);
1399
+ const src = this.#open(0);
1400
+ try {
1401
+ for (let i = 0; i < n; i++)
1402
+ hashes.set(await this.#step(sha256(await this.#step(src.next(Math.min(chunk, this.size - i * chunk))))), 32 * i);
1403
+ }
1404
+ finally {
1405
+ src.close();
1406
+ }
1407
+ this.#hashes = hashes;
1408
+ this.#digest = await sha256(hashes);
1409
+ }
1410
+ async attempt(link) {
1411
+ if (this.#stopped)
1412
+ throw this.#stopped;
1413
+ if (!this.#hashes)
1414
+ await this.#hash();
1415
+ if (this.#stopped)
1416
+ throw this.#stopped;
1417
+ const hashes = this.#hashes;
1418
+ const s = this.s;
1419
+ const chunk = s.limits.chunkSize;
1420
+ const n = chunksOf(this.size, chunk);
1421
+ const { conv, first } = await this.#step(request(link, s, {
1422
+ case: "writeBlob",
1423
+ value: {
1424
+ prefix: this.prefix,
1425
+ size: BigInt(this.size),
1426
+ chunkSize: BigInt(chunk),
1427
+ digest: this.#digest,
1428
+ },
1429
+ }, (st) => {
1430
+ this.#st = st;
1431
+ }));
1432
+ let src;
1433
+ try {
1434
+ if (first.body.case !== "blobReady")
1435
+ throw new InvalidExchange("not ready for a blob");
1436
+ const held = first.body.value.held;
1437
+ if (held > BigInt(this.size) || !boundary(Number(held), this.size, chunk))
1438
+ throw new InvalidExchange("a sink holding bytes off a chunk boundary");
1439
+ for (let i = 0; i < n; i += HASH_PAGE)
1440
+ await sent(conv, {
1441
+ case: "blobHashes",
1442
+ value: { hashes: hashes.subarray(32 * i, 32 * Math.min(n, i + HASH_PAGE)) },
1443
+ });
1444
+ const start = chunksOf(Number(held), chunk);
1445
+ if (start < n)
1446
+ src = this.#open(start * chunk);
1447
+ for (let i = start; i < n; i++) {
1448
+ const data = await this.#step(src.next(Math.min(chunk, this.size - i * chunk)));
1449
+ if (!sameBytes(await sha256(data), hashes.subarray(32 * i, 32 * i + 32)))
1450
+ throw new Failure("changed", `chunk ${i} of the blob changed since it was hashed`);
1451
+ for (let at = 0; at < data.length; at += s.limits.pageBytes)
1452
+ await sent(conv, {
1453
+ case: "blob",
1454
+ value: { data: data.subarray(at, at + s.limits.pageBytes) },
1455
+ });
1456
+ }
1457
+ await conv.stream.closeWrite();
1458
+ const env = await conv.recv();
1459
+ if (env === null)
1460
+ throw new InvalidExchange("no answer to a blob");
1461
+ const f = failureOf(env);
1462
+ if (f)
1463
+ throw f;
1464
+ if (env.body.case !== "blobWritten")
1465
+ throw new InvalidExchange("not an answer to a blob");
1466
+ return env.body.value.name;
1467
+ }
1468
+ finally {
1469
+ src?.close();
1470
+ conv.stream.reset(CODE_CANCEL);
1471
+ }
1472
+ }
1473
+ }
1474
+ async function openChannel(link, s, name, payload) {
1475
+ const { conv, first } = await request(link, s, { case: "openChannel", value: { name, payload } });
1476
+ if (first.body.case !== "channelOpened") {
1477
+ conv.stream.reset(CODE_CANCEL);
1478
+ throw new InvalidExchange(`channel ${name} not opened`);
1479
+ }
1480
+ return {
1481
+ send: async (data) => {
1482
+ if (data.length > s.limits.maxChannelMessage)
1483
+ throw new RangeError(`keywire: a channel message is at most ${s.limits.maxChannelMessage} bytes`);
1484
+ await conv.send({ case: "channelMessage", value: { data } });
1485
+ },
1486
+ recv: async () => {
1487
+ const env = await conv.recv();
1488
+ if (env === null)
1489
+ return null;
1490
+ const f = failureOf(env);
1491
+ if (f)
1492
+ throw f;
1493
+ if (env.body.case !== "channelMessage" ||
1494
+ env.body.value.data.length > s.limits.maxChannelMessage) {
1495
+ conv.stream.reset(CODE_INVALID);
1496
+ throw new InvalidExchange(`not a message of channel ${name}`);
1497
+ }
1498
+ return env.body.value.data;
1499
+ },
1500
+ close: () => conv.stream.closeWrite(),
1501
+ abandon: () => conv.stream.reset(CODE_CANCEL),
1502
+ };
1503
+ }
1504
+ // busyRetries are how long to wait before asking again a Node that answers
1505
+ // "busy": what a Queue asks is safe to ask again.
1506
+ const busyRetries = [100, 400, 1_600];
1507
+ // lostRetries is how many times a request is asked again on the next link
1508
+ // after the one it was asked on was lost.
1509
+ const lostRetries = 2;
1510
+ // Queue asks a Node at most limit requests at a time, keeping at most
1511
+ // maxWaiting more until one is answered.
1512
+ class Queue {
1513
+ limit;
1514
+ maxWaiting;
1515
+ remote;
1516
+ #waiting = [];
1517
+ #asking = 0;
1518
+ constructor(limit, maxWaiting, remote) {
1519
+ this.limit = limit;
1520
+ this.maxWaiting = maxWaiting;
1521
+ this.remote = remote;
1522
+ }
1523
+ async ask(send) {
1524
+ if (this.#asking >= this.limit) {
1525
+ if (this.#waiting.length >= this.maxWaiting)
1526
+ throw new Failure("busy", "too many requests are waiting to be asked");
1527
+ await new Promise((resolve) => this.#waiting.push(resolve));
1528
+ }
1529
+ else {
1530
+ this.#asking++;
1531
+ }
1532
+ try {
1533
+ let busy = 0;
1534
+ let lost = 0;
1535
+ for (;;) {
1536
+ if (this.remote.closed)
1537
+ throw new Stopped("the Remote is closed");
1538
+ const c = await this.remote.nextLink();
1539
+ if (!c)
1540
+ throw (this.remote.versionFailure() ?? new Failure("unreachable", "not connected to the Node"));
1541
+ try {
1542
+ return await send(c.link);
1543
+ }
1544
+ catch (e) {
1545
+ if (e instanceof Failure) {
1546
+ const delay = busyRetries[busy++];
1547
+ if (e.code !== "busy" || delay === undefined)
1548
+ throw e;
1549
+ await sleep(delay);
1550
+ continue;
1551
+ }
1552
+ // A broken exchange, a caller's mistake (as a blob source's
1553
+ // piece past chunkSize) or a closed Remote is not a lost link.
1554
+ if (e instanceof InvalidExchange ||
1555
+ e instanceof RangeError ||
1556
+ e instanceof TypeError ||
1557
+ e instanceof Stopped ||
1558
+ lost >= lostRetries)
1559
+ throw e;
1560
+ lost++;
1561
+ // The link failed under it: asked again on the next.
1562
+ if (this.remote.linkIs(c.link))
1563
+ await sleep(RETRY_MS);
1564
+ }
1565
+ }
1566
+ }
1567
+ finally {
1568
+ // The slot passes to the next waiting, or is given up.
1569
+ const next = this.#waiting.shift();
1570
+ if (next)
1571
+ next();
1572
+ else
1573
+ this.#asking--;
1574
+ }
1575
+ }
1576
+ }
1577
+ const MAX_TIMER = 0x7fffffff;
1578
+ // newCommandId is a fresh id for a command.
1579
+ export const newCommandId = () => crypto.getRandomValues(new Uint8Array(16));
1580
+ // MAX_PENDING_WATCHERS bounds the watchPending calls in effect on one
1581
+ // Remote.
1582
+ const MAX_PENDING_WATCHERS = 16;
1583
+ export class Outbox {
1584
+ s;
1585
+ current;
1586
+ #pending = [];
1587
+ #watchers = new Set();
1588
+ // version counts the changes told to the watchers.
1589
+ #version = 0;
1590
+ // watching counts the watchers in effect and those unwatched whose call
1591
+ // still runs, at most MAX_PENDING_WATCHERS.
1592
+ #watching = 0;
1593
+ #bytes = 0;
1594
+ #link;
1595
+ #info;
1596
+ constructor(s, current) {
1597
+ this.s = s;
1598
+ this.current = current;
1599
+ }
1600
+ get size() {
1601
+ return this.#pending.length;
1602
+ }
1603
+ submit(name, payload, signal, kept) {
1604
+ const l = this.s.limits;
1605
+ if (!validName(name, l.maxName))
1606
+ return Promise.reject(new RangeError("keywire: a command name is a name (spec/state.md, 2.1)"));
1607
+ if (!(payload instanceof Uint8Array) || payload.length > l.maxPayload)
1608
+ return Promise.reject(new RangeError(`keywire: a command payload is at most ${l.maxPayload} bytes`));
1609
+ if (kept) {
1610
+ if (!(kept.id instanceof Uint8Array) ||
1611
+ kept.id.length !== 16 ||
1612
+ !Number.isSafeInteger(kept.sinceMs) ||
1613
+ kept.sinceMs < 0 ||
1614
+ (kept.epoch !== undefined &&
1615
+ (!(kept.epoch instanceof Uint8Array) || kept.epoch.length !== 16)))
1616
+ return Promise.reject(new RangeError("keywire: not a pending command"));
1617
+ if (this.#pending.some((p) => sameBytes(p.id, kept.id)))
1618
+ return Promise.reject(new RangeError("keywire: that command is pending already"));
1619
+ }
1620
+ if (signal?.aborted)
1621
+ return Promise.reject(signal.reason);
1622
+ if (this.#pending.length >= this.s.maxPendingCommands ||
1623
+ this.#bytes + payload.length > this.s.maxPendingBytes)
1624
+ return Promise.reject(new TooManyPending());
1625
+ return new Promise((resolve, reject) => {
1626
+ const now = Date.now();
1627
+ const p = {
1628
+ id: kept ? kept.id.slice() : newCommandId(),
1629
+ name,
1630
+ // Copied: a small view keeps no large buffer of the caller's alive.
1631
+ payload: payload.slice(),
1632
+ sinceMs: kept ? kept.sinceMs : now,
1633
+ priorMs: kept ? Math.max(0, now - kept.sinceMs) : 0,
1634
+ startMono: performance.now(),
1635
+ epoch: kept?.epoch?.slice(),
1636
+ sent: kept?.epoch !== undefined,
1637
+ keptAt: 0,
1638
+ held: false,
1639
+ link: undefined,
1640
+ stream: undefined,
1641
+ timer: undefined,
1642
+ retry: undefined,
1643
+ resolve,
1644
+ reject,
1645
+ unabort: undefined,
1646
+ };
1647
+ this.#pending.push(p);
1648
+ this.#bytes += p.payload.length;
1649
+ if (signal) {
1650
+ const abort = () => {
1651
+ if (p.sent)
1652
+ this.#uncertain(p, "aborted after it was sent");
1653
+ else
1654
+ this.#settle(p, () => p.reject(signal.reason));
1655
+ };
1656
+ signal.addEventListener("abort", abort, { once: true });
1657
+ p.unabort = () => signal.removeEventListener("abort", abort);
1658
+ }
1659
+ // Told first, as every change is: a command resumed with its epoch
1660
+ // goes at once, already kept.
1661
+ this.#notify();
1662
+ const c = this.current();
1663
+ if (c)
1664
+ this.#launch(c.link, c.info, [p]);
1665
+ });
1666
+ }
1667
+ // watch calls f with copies of the pending commands now and after each
1668
+ // change: one submitted, one given the outcome epoch it is first sent
1669
+ // under, one settled or withdrawn. Calls to one f are one at a time, in
1670
+ // order: while one runs, the changes after it are told in one call,
1671
+ // with the commands as they are then. A command is first sent under an
1672
+ // epoch only once every f has settled a call that saw it with that
1673
+ // epoch, however it settled: a durable copy of it can exist before the
1674
+ // Node could run it.
1675
+ watch(f) {
1676
+ if (typeof f !== "function")
1677
+ throw new TypeError("keywire: f is a function");
1678
+ // A watcher unwatched while its call runs still counts until it ends.
1679
+ if (this.#watching >= MAX_PENDING_WATCHERS)
1680
+ throw new RangeError("keywire: too many watchers of an outbox");
1681
+ const w = { f, done: 0, dirty: true, running: false, gone: false };
1682
+ this.#watchers.add(w);
1683
+ this.#watching++;
1684
+ void this.#deliver(w);
1685
+ return () => {
1686
+ if (w.gone)
1687
+ return;
1688
+ w.gone = true;
1689
+ this.#watchers.delete(w);
1690
+ if (!w.running)
1691
+ this.#watching--;
1692
+ this.#flush();
1693
+ };
1694
+ }
1695
+ // #deliver tells w of the outbox until it has seen the last change; what
1696
+ // f throws or rejects with is dropped.
1697
+ async #deliver(w) {
1698
+ if (w.running)
1699
+ return;
1700
+ w.running = true;
1701
+ while (w.dirty && !w.gone) {
1702
+ w.dirty = false;
1703
+ const version = this.#version;
1704
+ try {
1705
+ await w.f(this.pending());
1706
+ }
1707
+ catch {
1708
+ // A watcher's failure is its own.
1709
+ }
1710
+ w.done = version;
1711
+ this.#flush();
1712
+ }
1713
+ w.running = false;
1714
+ if (w.gone)
1715
+ this.#watching--;
1716
+ }
1717
+ // #notify counts a change and has every watcher told of it; it returns
1718
+ // the change's number.
1719
+ #notify() {
1720
+ const version = ++this.#version;
1721
+ for (const w of this.#watchers) {
1722
+ w.dirty = true;
1723
+ void this.#deliver(w);
1724
+ }
1725
+ return version;
1726
+ }
1727
+ // #kept says every watcher has seen p with its epoch.
1728
+ #kept(p) {
1729
+ for (const w of this.#watchers)
1730
+ if (w.done < p.keptAt)
1731
+ return false;
1732
+ return true;
1733
+ }
1734
+ // #flush sends the commands held for their watchers that every watcher
1735
+ // has now seen, on the current link, checked against it again.
1736
+ #flush() {
1737
+ const c = this.current();
1738
+ if (!c)
1739
+ return;
1740
+ const ready = this.#pending.filter((p) => p.held && this.#kept(p));
1741
+ for (const p of ready)
1742
+ p.held = false;
1743
+ if (ready.length)
1744
+ this.#launch(c.link, c.info, ready);
1745
+ }
1746
+ // start sends every pending command on link, a new link to the Node.
1747
+ start(link, info) {
1748
+ this.#link = link;
1749
+ this.#info = info;
1750
+ this.#launch(link, info, this.#pending.filter((p) => p.link !== link));
1751
+ }
1752
+ // #launch sends ps on link. One given the Node's outcome epoch now is
1753
+ // held until every watcher has seen it with it, as is one still held:
1754
+ // whatever launches it, it goes only then.
1755
+ #launch(link, info, ps) {
1756
+ const fresh = [];
1757
+ const go = [];
1758
+ for (const p of ps) {
1759
+ const r = this.#stamp(info, p);
1760
+ if (r === "gone")
1761
+ continue;
1762
+ if (r === "fresh")
1763
+ fresh.push(p);
1764
+ else if (p.held || !this.#kept(p))
1765
+ p.held = true;
1766
+ else
1767
+ go.push(p);
1768
+ }
1769
+ if (fresh.length) {
1770
+ // Held before any watcher is told: one launching again from within
1771
+ // its call finds them held.
1772
+ for (const p of fresh) {
1773
+ p.keptAt = this.#version + 1;
1774
+ p.held = true;
1775
+ }
1776
+ this.#notify();
1777
+ for (const p of fresh) {
1778
+ if (!p.held || !this.#pending.includes(p) || !this.#kept(p))
1779
+ continue;
1780
+ p.held = false;
1781
+ go.push(p);
1782
+ }
1783
+ }
1784
+ for (const p of go)
1785
+ this.#go(link, info, p);
1786
+ }
1787
+ #age(p) {
1788
+ return p.priorMs + (performance.now() - p.startMono);
1789
+ }
1790
+ #window(info) {
1791
+ return info.outcomeAgeMs - Math.max(info.outcomeAgeMs / 100, 60_000);
1792
+ }
1793
+ // #stamp checks p against the Node's outcome epoch and window: "gone"
1794
+ // if that settled it, "fresh" if it now has the epoch it is first sent
1795
+ // under, "ok" if it had one. One never sent takes the Node's epoch
1796
+ // anew if it changed: no Node has seen it.
1797
+ #stamp(info, p) {
1798
+ if (p.epoch && !p.sent && !sameBytes(p.epoch, info.outcomeEpoch))
1799
+ p.epoch = undefined;
1800
+ if (p.epoch && !sameBytes(p.epoch, info.outcomeEpoch)) {
1801
+ this.#uncertain(p, "the Node's outcome epoch changed");
1802
+ return "gone";
1803
+ }
1804
+ if (p.epoch && this.#age(p) >= this.#window(info)) {
1805
+ this.#uncertain(p, "it is older than the Node keeps outcomes");
1806
+ return "gone";
1807
+ }
1808
+ if (p.epoch)
1809
+ return "ok";
1810
+ // The first send opens the Node's window for it: age counts from
1811
+ // here, however long it waited unsent.
1812
+ p.epoch = info.outcomeEpoch.slice();
1813
+ p.sinceMs = Date.now();
1814
+ p.priorMs = 0;
1815
+ p.startMono = performance.now();
1816
+ return "fresh";
1817
+ }
1818
+ #go(link, info, p) {
1819
+ this.#arm(p, info);
1820
+ // Arming may have settled it.
1821
+ if (!this.#pending.includes(p))
1822
+ return;
1823
+ void this.#send(link, p);
1824
+ }
1825
+ // #arm makes p uncertain once its age passes the window the Node vouches
1826
+ // for.
1827
+ #arm(p, info) {
1828
+ if (p.timer !== undefined)
1829
+ return;
1830
+ const window = this.#window(info);
1831
+ const tick = () => {
1832
+ const left = window - this.#age(p);
1833
+ if (left <= 0) {
1834
+ p.timer = undefined;
1835
+ this.#uncertain(p, "it is older than the Node keeps outcomes");
1836
+ return;
1837
+ }
1838
+ p.timer = setTimeout(tick, Math.min(left, MAX_TIMER));
1839
+ };
1840
+ tick();
1841
+ }
1842
+ async #send(link, p) {
1843
+ p.link = link;
1844
+ p.sent = true;
1845
+ try {
1846
+ const env = await once(link, this.s, { case: "command", value: { id: p.id, name: p.name, payload: p.payload } }, (st) => {
1847
+ p.stream = st;
1848
+ });
1849
+ if (env.body.case !== "commandResult")
1850
+ throw new InvalidExchange("not a command result");
1851
+ const o = env.body.value.outcome;
1852
+ if (o.case === "accepted")
1853
+ this.#settle(p, () => p.resolve({ accepted: true }));
1854
+ else if (o.case === "rejected") {
1855
+ const r = rejection(o.value.code, o.value.message);
1856
+ this.#settle(p, () => p.resolve({ accepted: false, ...r }));
1857
+ }
1858
+ else
1859
+ throw new InvalidExchange("a command result with no outcome");
1860
+ return;
1861
+ }
1862
+ catch (e) {
1863
+ // An answer that breaks the protocol may follow a run: the outcome
1864
+ // is unknown, and sending again would meet the same answer.
1865
+ if (e instanceof InvalidExchange) {
1866
+ this.#uncertain(p, `the Node's answer broke the protocol: ${e.message}`);
1867
+ return;
1868
+ }
1869
+ // The Node cannot tell whether it committed.
1870
+ if (e instanceof Failure && e.code === "indeterminate") {
1871
+ this.#uncertain(p, "the Node cannot tell whether it committed");
1872
+ return;
1873
+ }
1874
+ // A Failure is the Node's answer, but busy (not run, sent again):
1875
+ // internal recorded nothing, so the caller may submit it again.
1876
+ if (e instanceof Failure && e.code !== "busy") {
1877
+ this.#settle(p, () => p.reject(e));
1878
+ return;
1879
+ }
1880
+ // Unanswered, or not run: sent again.
1881
+ }
1882
+ if (p.link !== link)
1883
+ return;
1884
+ p.link = undefined;
1885
+ clearTimeout(p.retry);
1886
+ p.retry = setTimeout(() => {
1887
+ const c = this.current();
1888
+ if (this.#pending.includes(p) && !p.link && c?.link === link)
1889
+ this.#launch(link, c.info, [p]);
1890
+ }, RETRY_MS);
1891
+ }
1892
+ #uncertain(p, why) {
1893
+ this.#settle(p, () => p.reject(new Uncertain(p.id.slice(), why)));
1894
+ }
1895
+ #settle(p, fn) {
1896
+ const i = this.#pending.indexOf(p);
1897
+ if (i < 0)
1898
+ return;
1899
+ this.#pending.splice(i, 1);
1900
+ this.#bytes -= p.payload.length;
1901
+ p.stream?.reset(CODE_CANCEL);
1902
+ p.stream = undefined;
1903
+ clearTimeout(p.timer);
1904
+ clearTimeout(p.retry);
1905
+ p.unabort?.();
1906
+ fn();
1907
+ this.#notify();
1908
+ }
1909
+ // pending are copies of every pending command.
1910
+ pending() {
1911
+ return this.#pending.map((p) => ({
1912
+ id: p.id.slice(),
1913
+ name: p.name,
1914
+ payload: p.payload.slice(),
1915
+ sinceMs: p.sinceMs,
1916
+ ...(p.epoch && { epoch: p.epoch.slice() }),
1917
+ }));
1918
+ }
1919
+ withdraw(id) {
1920
+ for (const p of [...this.#pending])
1921
+ if (sameBytes(p.id, id))
1922
+ this.#settle(p, () => p.reject(new Error("keywire: the command was withdrawn")));
1923
+ }
1924
+ // close withdraws every command never sent and makes the rest uncertain.
1925
+ close() {
1926
+ for (const p of [...this.#pending]) {
1927
+ if (p.sent)
1928
+ this.#uncertain(p, "its Remote closed");
1929
+ else
1930
+ this.#settle(p, () => p.reject(new Stopped("the Remote closed before it was sent")));
1931
+ }
1932
+ }
1933
+ }
1934
+ //# sourceMappingURL=remote.js.map