@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,1048 @@
1
+ // State: a TypeScript device's shared collections, kept in step over its
2
+ // Client's connections, and its Remotes to the Nodes whose owned
3
+ // collections it follows (spec/state.md, sections 2 and 3.2).
4
+ import { create, toBinary } from "@bufbuild/protobuf";
5
+ import { FIRST_EXTENSION_SERVICE, LAST_EXTENSION_SERVICE } from "../conn.js";
6
+ import { SharedEntrySchema, SyncBatchSchema, } from "../gen/keywire/state/v1/state_pb.js";
7
+ import { Forbidden, Indeterminate, InvalidExchange, NotReady, StateFull, Stopped, } from "./errors.js";
8
+ import { bounded, frameBoundOf, sharedLimits, stateLimits, varintLen, } from "./limits.js";
9
+ import { Remote } from "./remote.js";
10
+ import { BATCH_ENTRIES, BATCH_FILL, BUCKETS, compareBytes, compareNames, Index, utf8Len, validEntry, validName, } from "./shared.js";
11
+ import { memoryStore } from "./store.js";
12
+ import { CODE_INVALID, CODE_NOT_READY, CODE_REFUSED, Conv, closedForm, VERSION, VersionError, } from "./wire.js";
13
+ export const DEFAULT_SERVICE = 16;
14
+ const MIB = 1 << 20;
15
+ const GIB = 1 << 30;
16
+ const rowOf = (e, version) => ({
17
+ id: e.id,
18
+ version,
19
+ data: e.value.slice(),
20
+ deleted: e.deleted,
21
+ stamp: { timeMs: e.timeMs, counter: e.counter, writer: e.writer.slice() },
22
+ });
23
+ // allowed reports whether role rs lets this device hold d's replica as
24
+ // validated at generation g: an owner (admitted) since no later than g.
25
+ function allowed(d, rs, g) {
26
+ if (d.participants === "owners")
27
+ return rs.role === "owner" && rs.ownerSince !== 0 && rs.ownerSince <= g;
28
+ return rs.role !== "none" && rs.admittedSince !== 0 && rs.admittedSince <= g;
29
+ }
30
+ function settings(opts) {
31
+ const limits = stateLimits(opts.limits);
32
+ const service = opts.service ?? DEFAULT_SERVICE;
33
+ if (!Number.isInteger(service) ||
34
+ service < FIRST_EXTENSION_SERVICE ||
35
+ service > LAST_EXTENSION_SERVICE)
36
+ throw new RangeError(`keywire: state service must be ${FIRST_EXTENSION_SERVICE} to ${LAST_EXTENSION_SERVICE}`);
37
+ const b = (v, d, lo, hi, name) => bounded(v, d, lo, hi, name);
38
+ const maxWriting = b(opts.maxWriting, 2, 1, 1024, "maxWriting");
39
+ return {
40
+ service,
41
+ limits,
42
+ frameBound: 0,
43
+ closed: closedForm(limits),
44
+ nowMs: opts.nowMs ?? Date.now,
45
+ debounceMs: b(opts.debounceMs, 500, 1, 3_600_000, "debounceMs"),
46
+ intervalMs: b(opts.intervalMs, 600_000, 1000, 7 * 86_400_000, "intervalMs"),
47
+ syncTimeoutMs: b(opts.syncTimeoutMs, 10_000, 1000, 600_000, "syncTimeoutMs"),
48
+ requestTimeoutMs: b(opts.requestTimeoutMs, 10_000, 1000, 300_000, "requestTimeoutMs"),
49
+ maxPendingCommands: b(opts.maxPendingCommands, 256, 1, 65536, "maxPendingCommands"),
50
+ maxPendingBytes: b(opts.maxPendingBytes, 16 * MIB, 1024, GIB, "maxPendingBytes"),
51
+ maxRemotes: b(opts.maxRemotes, 64, 1, 1024, "maxRemotes"),
52
+ maxMirrors: b(opts.maxMirrors, 64, 1, 1024, "maxMirrors"),
53
+ maxLogs: b(opts.maxLogs, 64, 1, 1024, "maxLogs"),
54
+ mirrorRows: b(opts.mirrorRows, 65536, 1, 1 << 24, "mirrorRows"),
55
+ mirrorBytes: b(opts.mirrorBytes, 64 * MIB, 1024, GIB, "mirrorBytes"),
56
+ maxQuerying: b(opts.maxQuerying, 4, 1, 1024, "maxQuerying"),
57
+ maxWaitingQueries: b(opts.maxWaitingQueries, 256, 0, 65536, "maxWaitingQueries"),
58
+ maxReading: b(opts.maxReading, 2, 1, 1024, "maxReading"),
59
+ maxWaitingReads: b(opts.maxWaitingReads, 256, 0, 65536, "maxWaitingReads"),
60
+ maxWriting,
61
+ maxWaitingWrites: b(opts.maxWaitingWrites, 256, 0, 65536, "maxWaitingWrites"),
62
+ maxWaitingUpdates: b(opts.maxWaitingUpdates, 256, 0, 65536, "maxWaitingUpdates"),
63
+ connectWaitMs: b(opts.connectWaitMs, 30_000, 0, 600_000, "connectWaitMs"),
64
+ };
65
+ }
66
+ function declare(specs, l) {
67
+ if (!Array.isArray(specs))
68
+ throw new TypeError("keywire: state collections is an array");
69
+ if (specs.length > l.maxCollections)
70
+ throw new RangeError(`keywire: at most ${l.maxCollections} shared collections`);
71
+ const out = [];
72
+ const names = new Set();
73
+ for (const c of specs) {
74
+ if (!validName(c?.name, l.maxName))
75
+ throw new RangeError(`keywire: a collection name is 1 to ${l.maxName} bytes of UTF-8 with no control character`);
76
+ if (names.has(c.name))
77
+ throw new RangeError(`keywire: collection ${c.name} declared twice`);
78
+ names.add(c.name);
79
+ const participants = c.participants ?? "owners";
80
+ if (participants !== "owners" && participants !== "admitted")
81
+ throw new RangeError("keywire: participants are owners or admitted");
82
+ if (c.allow !== undefined && typeof c.allow !== "function")
83
+ throw new TypeError("keywire: allow is a function");
84
+ out.push({
85
+ name: c.name,
86
+ participants,
87
+ limits: sharedLimits(c.limits, l),
88
+ allow: c.allow,
89
+ compress: c.compress === true,
90
+ });
91
+ }
92
+ return out.sort((a, b) => compareNames(a.name, b.name));
93
+ }
94
+ // frameBound is the largest message a State under limits with collections
95
+ // sends or takes (spec/state.md, 5.4).
96
+ export function frameBound(limits, collections) {
97
+ return frameBoundOf(limits, declare(collections, limits).map((d) => d.limits));
98
+ }
99
+ // State is this device's shared collections and Remotes. Pass extension()
100
+ // to the Client, as one of its extensions, then await ready().
101
+ export class State {
102
+ settings;
103
+ #store;
104
+ #names;
105
+ #colls = new Map();
106
+ // #seq numbers the changes this State has held since it opened.
107
+ #seq = 0n;
108
+ #queue = Promise.resolve();
109
+ #waitingUpdates = 0;
110
+ #roleChain = Promise.resolve();
111
+ #extension;
112
+ #attached = false;
113
+ #self;
114
+ #feed;
115
+ #unfeed;
116
+ #ready = false;
117
+ #readyP = Promise.withResolvers();
118
+ #stopped;
119
+ #closing;
120
+ #links = new Map();
121
+ #push;
122
+ #nodes = new Map();
123
+ #remotes = new Set();
124
+ // #syncCompress is set when a collection is declared compressed.
125
+ #syncCompress;
126
+ constructor(s, store, decls) {
127
+ this.settings = s;
128
+ this.#store = store;
129
+ this.#names = decls.map((d) => d.name);
130
+ this.#syncCompress = decls.some((d) => d.compress);
131
+ for (const d of decls)
132
+ this.#colls.set(d.name, {
133
+ decl: d,
134
+ index: undefined,
135
+ open: false,
136
+ err: new NotReady(),
137
+ gen: 0,
138
+ synced: false,
139
+ held: true,
140
+ watchers: new Set(),
141
+ });
142
+ // ready() rejects only for those who wait on it.
143
+ this.#readyP.promise.catch(() => { });
144
+ }
145
+ // open checks opts and makes the State; shared collections stay closed
146
+ // until its extension is attached and their first open completes.
147
+ static async open(opts) {
148
+ if (typeof opts !== "object" || opts === null)
149
+ throw new TypeError("keywire: State.open takes options");
150
+ const s = settings(opts);
151
+ const decls = declare(opts.collections, s.limits);
152
+ s.frameBound = frameBoundOf(s.limits, decls.map((d) => d.limits));
153
+ if (opts.nowMs !== undefined && typeof opts.nowMs !== "function")
154
+ throw new TypeError("keywire: nowMs is a function");
155
+ return new State(s, opts.store ?? memoryStore(), decls);
156
+ }
157
+ // extension is what the Client runs this State's service through: pass
158
+ // it as one of the Client's extensions, one Client only.
159
+ extension() {
160
+ this.#extension ??= {
161
+ service: this.settings.service,
162
+ attach: (a) => this.#attach(a),
163
+ serve: (link, stream) => void this.#serve(link, stream),
164
+ connected: (link) => this.#connected(link),
165
+ ended: (link) => this.#ended(link),
166
+ };
167
+ return this.#extension;
168
+ }
169
+ // ready resolves once the first open of the shared collections completes,
170
+ // or rejects with Stopped if the State stops or closes first.
171
+ ready() {
172
+ return this.#readyP.promise;
173
+ }
174
+ // update runs fn on the replica: its writes are staged, kept with one
175
+ // store write, then applied and told to watchers. fn is synchronous. If
176
+ // the write fails, nothing is applied.
177
+ update(fn) {
178
+ if (this.#stopped)
179
+ return Promise.reject(new Stopped(this.#stopped));
180
+ // One runs and at most maxWaitingUpdates wait behind it.
181
+ if (this.#waitingUpdates > this.settings.maxWaitingUpdates)
182
+ return Promise.reject(new StateFull("too many updates are waiting"));
183
+ this.#waitingUpdates++;
184
+ return this.#serial(async () => {
185
+ this.#check();
186
+ const tx = new StateTx(this, this.#self);
187
+ let r;
188
+ try {
189
+ r = fn(tx);
190
+ }
191
+ finally {
192
+ // A tx kept past fn changes nothing: what is written is fixed here.
193
+ tx.end();
194
+ }
195
+ if (r instanceof Promise || (typeof r === "object" && r !== null && "then" in r))
196
+ throw new TypeError("keywire: an update's function is synchronous");
197
+ const changes = tx.changes();
198
+ if (changes.length === 0)
199
+ return;
200
+ for (const [name, st] of tx.staged) {
201
+ const c = this.#colls.get(name);
202
+ if (!c.open || c.index !== st.index)
203
+ throw c.err;
204
+ }
205
+ await this.#write(changes);
206
+ this.#publish(tx.staged);
207
+ }).finally(() => {
208
+ this.#waitingUpdates--;
209
+ });
210
+ }
211
+ // get is id's row of collection, unless it has none or it is deleted.
212
+ get(collection, id) {
213
+ const c = this.#openColl(collection);
214
+ const e = c.index.get(id);
215
+ if (!e || e.deleted)
216
+ return undefined;
217
+ return rowOf(e, c.index.version(id));
218
+ }
219
+ // rows are collection's rows, in order of their ids' bytes.
220
+ rows(collection) {
221
+ const x = this.#openColl(collection).index;
222
+ return x
223
+ .entries()
224
+ .filter((e) => !e.deleted)
225
+ .map((e) => rowOf(e, x.version(e.id)))[Symbol.iterator]();
226
+ }
227
+ // watch calls onChange after every change of collection, local or
228
+ // synced, and when it is told synced; what onChange throws is ignored.
229
+ watch(collection, onChange) {
230
+ const c = this.#coll(collection);
231
+ c.watchers.add(onChange);
232
+ return () => c.watchers.delete(onChange);
233
+ }
234
+ // synced reports whether collection has completed an exchange with an
235
+ // owner since it opened, or this device is one.
236
+ synced(collection) {
237
+ const c = this.#coll(collection);
238
+ return c.open && c.synced;
239
+ }
240
+ // node is the open Remote for the Node whose static key is key, made if
241
+ // there is none.
242
+ node(key) {
243
+ this.#check();
244
+ if (!(key instanceof Uint8Array) || key.length !== 32)
245
+ throw new RangeError("keywire: a Node's key is 32 bytes");
246
+ const k = hexKey(key);
247
+ const have = this.#nodes.get(k);
248
+ if (have)
249
+ return have;
250
+ const r = this.#newRemote(key.slice(), undefined, undefined);
251
+ this.#nodes.set(k, r);
252
+ for (const link of this.#links.keys())
253
+ if (compareBytes(link.peer, key) === 0)
254
+ r.linked(link);
255
+ return r;
256
+ }
257
+ // guest is a new Remote on the links connect makes, as a guest of a Node:
258
+ // it dials and backs off itself, and closes itself once the share ended.
259
+ guest(connect, opts = {}) {
260
+ this.#check();
261
+ if (typeof connect !== "function")
262
+ throw new TypeError("keywire: connect is a function");
263
+ return this.#newRemote(undefined, connect, opts);
264
+ }
265
+ // close waits for updates in flight, closes every Remote, then the store.
266
+ close() {
267
+ this.#closing ??= (async () => {
268
+ this.#stop(new Stopped("the state closed"));
269
+ await this.#queue.catch(() => { });
270
+ await this.#store.close();
271
+ })();
272
+ return this.#closing;
273
+ }
274
+ #newRemote(key, connect, opts) {
275
+ if (this.#remotes.size >= this.settings.maxRemotes)
276
+ throw new StateFull(`at most ${this.settings.maxRemotes} Remotes are open`);
277
+ const r = new Remote(this, key, connect, opts);
278
+ this.#remotes.add(r);
279
+ return r;
280
+ }
281
+ // removed frees a closed Remote's slot.
282
+ removed(r) {
283
+ this.#remotes.delete(r);
284
+ if (r.key) {
285
+ const k = hexKey(r.key);
286
+ if (this.#nodes.get(k) === r)
287
+ this.#nodes.delete(k);
288
+ }
289
+ }
290
+ get stopped() {
291
+ return this.#stopped;
292
+ }
293
+ #check() {
294
+ if (this.#stopped)
295
+ throw new Stopped(this.#stopped);
296
+ }
297
+ #coll(collection) {
298
+ const c = this.#colls.get(collection);
299
+ if (!c)
300
+ throw new RangeError(`keywire: no shared collection ${collection} is declared`);
301
+ return c;
302
+ }
303
+ #openColl(collection) {
304
+ const c = this.#coll(collection);
305
+ this.#check();
306
+ if (!c.open)
307
+ throw c.err;
308
+ return c;
309
+ }
310
+ // stagedOf is a stage over collection's replica, for a Tx.
311
+ stagedOf(collection) {
312
+ const c = this.#openColl(collection);
313
+ return { staged: c.index.stage(), decl: c.decl, nowMs: this.settings.nowMs() };
314
+ }
315
+ // #serial runs fn after every update, merge and discard before it.
316
+ #serial(fn) {
317
+ const run = this.#queue.then(fn);
318
+ this.#queue = run.catch(() => { });
319
+ return run;
320
+ }
321
+ async #write(changes) {
322
+ try {
323
+ await this.#store.write(changes);
324
+ }
325
+ catch (e) {
326
+ if (e instanceof Indeterminate)
327
+ this.#stop(e);
328
+ throw e;
329
+ }
330
+ }
331
+ // #publish applies committed stages to their collections, unless one was
332
+ // closed meanwhile, and tells watchers.
333
+ #publish(staged) {
334
+ let shared = false;
335
+ for (const [name, st] of staged) {
336
+ const c = this.#colls.get(name);
337
+ if (!c.open || c.index !== st.index)
338
+ continue;
339
+ const changes = { upserted: [], removed: [] };
340
+ for (const e of st.changed()) {
341
+ const was = st.index.get(e.id);
342
+ if (e.deleted) {
343
+ if (was && !was.deleted)
344
+ changes.removed.push(e.id);
345
+ }
346
+ else
347
+ changes.upserted.push(rowOf(e, 0n));
348
+ }
349
+ st.commit(() => ++this.#seq);
350
+ for (const r of changes.upserted)
351
+ r.version = st.index.version(r.id);
352
+ this.#tell(c, changes);
353
+ shared = true;
354
+ }
355
+ if (shared)
356
+ this.#schedulePush();
357
+ }
358
+ #tell(c, changes) {
359
+ for (const w of [...c.watchers]) {
360
+ try {
361
+ w(changes);
362
+ }
363
+ catch {
364
+ // A watcher's throw is its own.
365
+ }
366
+ }
367
+ }
368
+ // #close closes c at once: reads and writes fail with err, and its
369
+ // watchers learn its rows are gone.
370
+ #close(c, err) {
371
+ const removed = c.open
372
+ ? c
373
+ .index.entries()
374
+ .filter((e) => !e.deleted)
375
+ .map((e) => e.id)
376
+ : [];
377
+ c.open = false;
378
+ c.err = err;
379
+ c.index = undefined;
380
+ c.synced = false;
381
+ if (removed.length > 0)
382
+ this.#tell(c, { upserted: [], removed });
383
+ }
384
+ #stop(err) {
385
+ if (this.#stopped)
386
+ return;
387
+ this.#stopped = err;
388
+ this.#unfeed?.();
389
+ const stopped = err instanceof Stopped ? err : new Stopped(err);
390
+ for (const c of this.#colls.values())
391
+ this.#close(c, stopped);
392
+ clearTimeout(this.#push);
393
+ for (const [link, s] of this.#links) {
394
+ this.#links.delete(link);
395
+ s.closed = true;
396
+ clearInterval(s.interval);
397
+ for (const st of s.active)
398
+ st.reset(CODE_REFUSED);
399
+ }
400
+ for (const r of [...this.#remotes])
401
+ r.close();
402
+ this.#readyP.reject(stopped);
403
+ }
404
+ #attach(a) {
405
+ if (this.#attached)
406
+ throw new Error("keywire: a State attaches to one Client, once");
407
+ this.#check();
408
+ if (!a?.role)
409
+ throw new Error("keywire: a State needs a role feed");
410
+ this.#attached = true;
411
+ this.#self = a.self.slice();
412
+ this.#feed = a.role;
413
+ this.#unfeed = a.role.onChange(() => this.#roleChanged());
414
+ this.#roleChain = this.#roleChain
415
+ .then(() => this.#openShared())
416
+ .then(() => {
417
+ this.#ready = true;
418
+ this.#readyP.resolve();
419
+ // Exchanges refused before now are opened again.
420
+ for (const [link, s] of this.#links)
421
+ void this.#sync(link, s);
422
+ })
423
+ .catch((e) => this.#stop(e instanceof Error ? e : new Error(String(e))));
424
+ }
425
+ // #roleChanged closes at once every open collection the role no longer
426
+ // allows, then discards it and opens those it now allows; a failed
427
+ // discard stops the State (spec/state.md, 2.6).
428
+ #roleChanged() {
429
+ const feed = this.#feed;
430
+ const rs = feed.state();
431
+ if (rs.closed) {
432
+ this.#stop(new Stopped("the role feed ended"));
433
+ return;
434
+ }
435
+ if (this.#stopped)
436
+ return;
437
+ const lost = [];
438
+ for (const c of this.#colls.values()) {
439
+ if (!c.open)
440
+ continue;
441
+ if (allowed(c.decl, rs, c.gen)) {
442
+ c.gen = rs.generation;
443
+ continue;
444
+ }
445
+ this.#close(c, new Forbidden(`this device may not hold ${c.decl.name}`));
446
+ lost.push(c);
447
+ }
448
+ if (lost.length > 0)
449
+ for (const s of this.#links.values())
450
+ for (const st of s.active)
451
+ st.reset(CODE_REFUSED);
452
+ this.#roleChain = this.#roleChain
453
+ .then(async () => {
454
+ if (lost.length > 0) {
455
+ await this.#serial(() => this.#write(lost.map((c) => ({ collection: c.decl.name, discard: true }))));
456
+ for (const c of lost)
457
+ c.held = false;
458
+ }
459
+ await this.#openShared();
460
+ for (const [link, s] of this.#links)
461
+ void this.#sync(link, s);
462
+ })
463
+ .catch((e) => this.#stop(e instanceof Error ? e : new Error(String(e))));
464
+ }
465
+ // #openShared opens every closed collection the role allows, having
466
+ // discarded every one it forbids: it notes the feed's generation, loads
467
+ // while they stay closed, and opens them only if the generation is still
468
+ // that one, else starts again.
469
+ async #openShared() {
470
+ const feed = this.#feed;
471
+ // outdated are collections whose load a role loss outdated: what the
472
+ // store holds of them is discarded, even if the role allows them again.
473
+ const outdated = new Set();
474
+ for (;;) {
475
+ const rs = feed.state();
476
+ if (rs.closed)
477
+ throw new Stopped("the role feed ended");
478
+ this.#check();
479
+ const g = rs.generation;
480
+ const discard = [];
481
+ const load = [];
482
+ for (const c of this.#colls.values()) {
483
+ if (c.open)
484
+ continue;
485
+ if (allowed(c.decl, rs, g))
486
+ load.push(c);
487
+ else
488
+ discard.push(c);
489
+ }
490
+ const held = [...new Set([...discard, ...outdated])].filter((c) => c.held);
491
+ outdated.clear();
492
+ if (held.length > 0) {
493
+ await this.#serial(() => this.#write(held.map((c) => ({ collection: c.decl.name, discard: true }))));
494
+ for (const c of held)
495
+ c.held = false;
496
+ }
497
+ for (const c of discard)
498
+ c.err = new Forbidden(`this device may not hold ${c.decl.name}`);
499
+ const loaded = new Map();
500
+ for (const c of load)
501
+ loaded.set(c, await this.#load(c.decl));
502
+ const again = await this.#serial(async () => {
503
+ this.#check();
504
+ const now = feed.state();
505
+ if (now.closed)
506
+ throw new Stopped("the role feed ended");
507
+ if (now.generation !== g) {
508
+ for (const c of loaded.keys())
509
+ if (!allowed(c.decl, now, g))
510
+ outdated.add(c);
511
+ return true;
512
+ }
513
+ for (const [c, x] of loaded) {
514
+ c.index = x;
515
+ c.open = true;
516
+ c.held = true;
517
+ c.gen = g;
518
+ c.synced = rs.role === "owner";
519
+ const upserted = x
520
+ .entries()
521
+ .filter((e) => !e.deleted)
522
+ .map((e) => rowOf(e, x.version(e.id)));
523
+ this.#tell(c, { upserted, removed: [] });
524
+ }
525
+ return false;
526
+ });
527
+ if (!again)
528
+ return;
529
+ }
530
+ }
531
+ // #load reads d's rows from the store into an index, refusing them past
532
+ // the collection's limits before holding more.
533
+ async #load(d) {
534
+ const l = d.limits;
535
+ const rows = await this.#store.load(d.name, l.maxEntries, l.maxBytes);
536
+ const x = new Index(d.name);
537
+ let bytes = 0;
538
+ for (const r of rows) {
539
+ const e = {
540
+ id: r.id,
541
+ value: r.data,
542
+ deleted: r.deleted,
543
+ timeMs: r.stamp.timeMs,
544
+ counter: r.stamp.counter,
545
+ writer: r.stamp.writer,
546
+ };
547
+ if (!validEntry(e, l) || x.get(e.id))
548
+ throw new Error(`keywire: the store holds a row of ${d.name} its limits refuse`);
549
+ bytes += utf8Len(e.id) + e.value.length;
550
+ if (x.length + 1 > l.maxEntries || bytes > l.maxBytes)
551
+ throw new StateFull(`the store holds more of ${d.name} than its limits allow`);
552
+ x.set(e, ++this.#seq);
553
+ }
554
+ return x;
555
+ }
556
+ // Sync.
557
+ #connected(link) {
558
+ if (this.#stopped)
559
+ return;
560
+ const s = {
561
+ active: new Set(),
562
+ outgoing: undefined,
563
+ requested: false,
564
+ closed: false,
565
+ interval: undefined,
566
+ };
567
+ this.#links.set(link, s);
568
+ s.interval = setInterval(() => {
569
+ const roles = link.roles();
570
+ if (roles?.local === "owner" && roles.remote === "owner")
571
+ void this.#sync(link, s);
572
+ }, this.settings.intervalMs);
573
+ if (this.#ready && link.dialer)
574
+ void this.#sync(link, s);
575
+ this.#nodes.get(hexKey(link.peer))?.linked(link);
576
+ }
577
+ #ended(link) {
578
+ const s = this.#links.get(link);
579
+ this.#nodes.get(hexKey(link.peer))?.unlinked(link);
580
+ if (!s)
581
+ return;
582
+ this.#links.delete(link);
583
+ s.closed = true;
584
+ clearInterval(s.interval);
585
+ for (const st of s.active)
586
+ st.reset(CODE_REFUSED);
587
+ }
588
+ // links are the current links to the device with key, latest last.
589
+ links(key) {
590
+ return [...this.#links.keys()].filter((l) => compareBytes(l.peer, key) === 0);
591
+ }
592
+ #schedulePush() {
593
+ if (this.#stopped)
594
+ return;
595
+ clearTimeout(this.#push);
596
+ this.#push = setTimeout(() => {
597
+ for (const [link, s] of this.#links)
598
+ void this.#sync(link, s);
599
+ }, this.settings.debounceMs);
600
+ }
601
+ // #sync runs one more exchange this device opens on link, after any in
602
+ // progress; asks that come meanwhile fold into one.
603
+ #sync(link, s) {
604
+ if (s.closed || !this.#ready)
605
+ return Promise.resolve();
606
+ s.requested = true;
607
+ s.outgoing ??= (async () => {
608
+ while (s.requested && !s.closed) {
609
+ s.requested = false;
610
+ if (s.active.size >= this.settings.limits.syncsPerConn)
611
+ continue;
612
+ if (this.#syncable(link).length === 0)
613
+ continue;
614
+ let stream;
615
+ try {
616
+ // The exchange asks for compression if a collection is declared
617
+ // compressed; only its batches are, the rest goes plain.
618
+ stream = link.openStream({ compress: this.#syncCompress });
619
+ }
620
+ catch {
621
+ continue;
622
+ }
623
+ stream.setWriteCompression(false);
624
+ await this.#run(link, s, stream, undefined);
625
+ }
626
+ })().finally(() => {
627
+ s.outgoing = undefined;
628
+ });
629
+ return s.outgoing;
630
+ }
631
+ async #run(link, s, stream, open) {
632
+ s.active.add(stream);
633
+ const timeout = setTimeout(() => stream.reset(CODE_REFUSED), this.settings.syncTimeoutMs);
634
+ try {
635
+ const conv = open?.conv ?? new Conv(stream, this.settings.frameBound, this.settings.closed);
636
+ await this.#exchange(conv, link, open?.summary);
637
+ }
638
+ catch {
639
+ stream.reset(CODE_INVALID);
640
+ }
641
+ finally {
642
+ clearTimeout(timeout);
643
+ s.active.delete(stream);
644
+ }
645
+ }
646
+ async #serve(link, stream) {
647
+ if (this.#stopped) {
648
+ stream.reset(CODE_REFUSED);
649
+ return;
650
+ }
651
+ // Nothing is compressed unless a declaration asks for it, whatever
652
+ // the opener asked.
653
+ stream.setWriteCompression(false);
654
+ const conv = new Conv(stream, this.settings.frameBound, this.settings.closed);
655
+ const timer = setTimeout(() => stream.reset(CODE_INVALID), this.settings.requestTimeoutMs);
656
+ let env;
657
+ try {
658
+ env = await conv.recv();
659
+ }
660
+ catch (e) {
661
+ clearTimeout(timer);
662
+ // A first message of another version is answered whatever its body:
663
+ // its version comes first (spec/state.md, 5.1).
664
+ const v = e instanceof VersionError ? e.env.version : conv.lastVersion;
665
+ if (v !== undefined && v !== 0 && v !== VERSION) {
666
+ try {
667
+ await conv.send({
668
+ case: "failure",
669
+ value: {
670
+ code: "version",
671
+ message: `this State speaks version ${VERSION}`,
672
+ supported: [VERSION],
673
+ },
674
+ });
675
+ await stream.closeWrite();
676
+ }
677
+ catch {
678
+ stream.reset(CODE_INVALID);
679
+ }
680
+ return;
681
+ }
682
+ stream.reset(CODE_INVALID);
683
+ return;
684
+ }
685
+ clearTimeout(timer);
686
+ if (!env) {
687
+ stream.reset(CODE_INVALID);
688
+ return;
689
+ }
690
+ if (env.body.case === "syncOpen") {
691
+ if (!this.#ready) {
692
+ stream.reset(CODE_NOT_READY);
693
+ return;
694
+ }
695
+ const s = this.#links.get(link);
696
+ if (!s || s.closed || s.active.size >= this.settings.limits.syncsPerConn) {
697
+ stream.reset(CODE_REFUSED);
698
+ return;
699
+ }
700
+ await this.#run(link, s, stream, { conv, summary: env.body.value });
701
+ return;
702
+ }
703
+ // A TypeScript State serves no owned collection.
704
+ try {
705
+ await conv.send({
706
+ case: "failure",
707
+ value: { code: "forbidden", message: "this device serves no owned requests" },
708
+ });
709
+ await stream.closeWrite();
710
+ }
711
+ catch {
712
+ stream.reset(CODE_INVALID);
713
+ }
714
+ }
715
+ // #syncable are the shared collections, ascending, open and syncing with
716
+ // link's peer now.
717
+ #syncable(link) {
718
+ const roles = link.roles();
719
+ if (!roles || this.#stopped)
720
+ return [];
721
+ return this.#names.filter((n) => {
722
+ const c = this.#colls.get(n);
723
+ return c.open && mayShare(c.decl, roles.local, roles.remote);
724
+ });
725
+ }
726
+ #stillShares(link, name) {
727
+ const roles = link.roles();
728
+ const c = this.#colls.get(name);
729
+ return !this.#stopped && !!roles && c.open && mayShare(c.decl, roles.local, roles.remote);
730
+ }
731
+ // #exchange runs one anti-entropy exchange on conv: as its opener if open
732
+ // is undefined, else answering open (spec/state.md, 5.3).
733
+ async #exchange(conv, link, open) {
734
+ let colls;
735
+ let remote;
736
+ if (!open) {
737
+ const mine = this.#syncable(link);
738
+ await this.#purgeLapsed(mine);
739
+ await conv.send({ case: "syncOpen", value: this.#summary(mine) });
740
+ const env = await conv.recv();
741
+ if (env?.body.case !== "syncSummary")
742
+ throw new InvalidExchange("no sync summary");
743
+ [remote, colls] = this.#readSummary(env.body.value);
744
+ const named = new Set(mine);
745
+ if (colls.some((c) => !named.has(c)))
746
+ throw new InvalidExchange("an unnamed collection");
747
+ }
748
+ else {
749
+ const [theirs, names] = this.#readSummary(open);
750
+ const mine = new Set(this.#syncable(link));
751
+ colls = names.filter((n) => mine.has(n));
752
+ remote = theirs;
753
+ await this.#purgeLapsed(colls);
754
+ await conv.send({ case: "syncSummary", value: this.#summary(colls) });
755
+ }
756
+ const fail = (e) => {
757
+ conv.stream.reset(CODE_INVALID);
758
+ throw e;
759
+ };
760
+ const sending = (async () => {
761
+ await this.#sendEntries(conv, link, colls, remote);
762
+ await conv.stream.closeWrite();
763
+ })().catch(fail);
764
+ const receiving = this.#receiveEntries(conv, link, colls).catch(fail);
765
+ sending.catch(() => { });
766
+ receiving.catch(() => { });
767
+ await Promise.all([sending, receiving]);
768
+ if (link.roles()?.remote === "owner")
769
+ this.#markSynced(colls);
770
+ }
771
+ #readSummary(m) {
772
+ const out = new Map();
773
+ const names = [];
774
+ for (const cd of m.collections) {
775
+ const name = cd.collection;
776
+ if (!validName(name, this.settings.limits.maxName) ||
777
+ (names.length > 0 && compareNames(names.at(-1), name) >= 0) ||
778
+ cd.buckets.length !== BUCKETS ||
779
+ cd.buckets.some((b) => b.length !== 32))
780
+ throw new InvalidExchange("a malformed sync summary");
781
+ out.set(name, cd.buckets);
782
+ names.push(name);
783
+ }
784
+ return [out, names];
785
+ }
786
+ #summary(collections) {
787
+ return {
788
+ collections: collections.map((name) => {
789
+ const c = this.#colls.get(name);
790
+ const buckets = c.open
791
+ ? c.index.digests()
792
+ : Array.from({ length: BUCKETS }, () => new Uint8Array(32));
793
+ return { collection: name, buckets };
794
+ }),
795
+ };
796
+ }
797
+ // #sendEntries sends the entries of every bucket of collections whose
798
+ // digest differs from remote's, collection by collection.
799
+ async #sendEntries(conv, link, collections, remote) {
800
+ for (const name of collections) {
801
+ if (!this.#stillShares(link, name))
802
+ throw new InvalidExchange("no longer shared");
803
+ const compress = this.#colls.get(name).decl.compress;
804
+ let entries = this.#colls.get(name).index.differing(remote.get(name));
805
+ while (entries.length > 0) {
806
+ const batch = [];
807
+ let size = 1 + varintLen(utf8Len(name)) + utf8Len(name);
808
+ for (const e of entries.slice(0, BATCH_ENTRIES)) {
809
+ const m = toWire(e);
810
+ const n = toBinary(SharedEntrySchema, m).length;
811
+ const field = 1 + varintLen(n) + n;
812
+ if (batch.length > 0 && size + field > BATCH_FILL)
813
+ break;
814
+ batch.push(m);
815
+ size += field;
816
+ }
817
+ if (!this.#stillShares(link, name))
818
+ throw new InvalidExchange("no longer shared");
819
+ // A write's compression is fixed as it is called: this batch alone
820
+ // is compressed as its collection declares.
821
+ conv.stream.setWriteCompression(compress);
822
+ const sent = conv.send({ case: "syncBatch", value: { collection: name, entries: batch } });
823
+ conv.stream.setWriteCompression(false);
824
+ await sent;
825
+ entries = entries.slice(batch.length);
826
+ }
827
+ }
828
+ }
829
+ // #receiveEntries reads the peer's batches until it closes its side,
830
+ // merging each as it comes.
831
+ async #receiveEntries(conv, link, collections) {
832
+ const ins = new Set(collections);
833
+ let current = "";
834
+ let last = "";
835
+ let count = 0;
836
+ let size = 0;
837
+ const wire = { maxID: this.settings.limits.maxName, maxValue: this.settings.limits.maxValue };
838
+ for (;;) {
839
+ const env = await conv.recv();
840
+ if (env === null)
841
+ return;
842
+ if (env.body.case !== "syncBatch" || env.body.value.entries.length === 0)
843
+ throw new InvalidExchange("not a sync batch");
844
+ const batch = env.body.value;
845
+ const name = batch.collection;
846
+ if (!ins.has(name) || compareNames(name, current) < 0)
847
+ throw new InvalidExchange("a batch out of order");
848
+ if (name !== current) {
849
+ current = name;
850
+ last = "";
851
+ count = 0;
852
+ size = 0;
853
+ }
854
+ if (batch.entries.length > 1 &&
855
+ conv.lastSize > BATCH_FILL &&
856
+ toBinary(SyncBatchSchema, create(SyncBatchSchema, batch)).length > BATCH_FILL)
857
+ throw new InvalidExchange("a batch past 64 KiB");
858
+ const d = this.#colls.get(name).decl;
859
+ const entries = [];
860
+ for (const w of batch.entries) {
861
+ if (w.timeMs > BigInt(Number.MAX_SAFE_INTEGER))
862
+ throw new InvalidExchange("a time past 2^53-1");
863
+ const e = {
864
+ id: w.id,
865
+ value: w.value,
866
+ deleted: w.deleted,
867
+ timeMs: Number(w.timeMs),
868
+ counter: w.counter,
869
+ writer: w.writer,
870
+ };
871
+ // An entry of a shape no device takes breaks the protocol; one past
872
+ // only this device's limits is left at merging.
873
+ if (!validEntry(e, wire) || (last !== "" && compareNames(e.id, last) <= 0))
874
+ throw new InvalidExchange("an invalid entry");
875
+ last = e.id;
876
+ count++;
877
+ size += utf8Len(e.id) + e.value.length;
878
+ if (count > d.limits.maxEntries || size > d.limits.maxBytes)
879
+ throw new InvalidExchange("entries past the collection's limits");
880
+ entries.push(e);
881
+ }
882
+ await this.#merge(link, d, entries);
883
+ }
884
+ }
885
+ // #merge takes entries link's peer sent into collection d, in one store
886
+ // write. Both ends' roles are checked once its turn comes, so a batch
887
+ // that waited behind other writes is judged by the roles current then.
888
+ #merge(link, d, entries) {
889
+ if (entries.length === 0)
890
+ return Promise.resolve();
891
+ return this.#serial(async () => {
892
+ this.#check();
893
+ const c = this.#colls.get(d.name);
894
+ if (!c.open)
895
+ throw c.err;
896
+ if (!this.#stillShares(link, d.name))
897
+ throw new InvalidExchange("no longer shared");
898
+ if (link.roles()?.remote !== "owner") {
899
+ // A member gives only its own writes, as allow permits.
900
+ const peer = link.peer;
901
+ entries = entries.filter((e) => compareBytes(e.writer, peer) === 0 && (!d.allow || d.allow(peer, e.id)));
902
+ if (entries.length === 0)
903
+ return;
904
+ }
905
+ const st = c.index.stage();
906
+ const now = this.settings.nowMs();
907
+ for (const e of entries)
908
+ st.merge(e, now, d.limits, true);
909
+ const changed = st.changed();
910
+ if (changed.length === 0)
911
+ return;
912
+ await this.#write(changed.map((e) => ({ collection: d.name, put: storedOf(e) })));
913
+ this.#publish(new Map([[d.name, st]]));
914
+ });
915
+ }
916
+ // #purgeLapsed purges the deletions of collections older than retention.
917
+ #purgeLapsed(collections) {
918
+ return this.#serial(async () => {
919
+ const now = this.settings.nowMs();
920
+ const lapsed = [];
921
+ for (const name of collections) {
922
+ const c = this.#colls.get(name);
923
+ if (!c.open)
924
+ continue;
925
+ const ids = c.index.lapsed(now, c.decl.limits);
926
+ if (ids.length > 0)
927
+ lapsed.push([c, ids]);
928
+ }
929
+ if (lapsed.length === 0)
930
+ return;
931
+ const index = new Map(lapsed.map(([c]) => [c, c.index]));
932
+ await this.#write(lapsed.flatMap(([c, ids]) => ids.map((id) => ({ collection: c.decl.name, purge: id }))));
933
+ for (const [c, ids] of lapsed)
934
+ if (c.open && c.index === index.get(c))
935
+ for (const id of ids)
936
+ c.index.remove(id);
937
+ });
938
+ }
939
+ #markSynced(collections) {
940
+ for (const name of collections) {
941
+ const c = this.#colls.get(name);
942
+ if (c.open && !c.synced) {
943
+ c.synced = true;
944
+ this.#tell(c, { upserted: [], removed: [] });
945
+ }
946
+ }
947
+ }
948
+ }
949
+ function mayShare(d, local, remote) {
950
+ if (d.participants === "owners")
951
+ return local === "owner" && remote === "owner";
952
+ return true;
953
+ }
954
+ export const hexKey = (k) => Array.from(k, (b) => b.toString(16).padStart(2, "0")).join("");
955
+ function toWire(e) {
956
+ return create(SharedEntrySchema, {
957
+ id: e.id,
958
+ value: e.value,
959
+ deleted: e.deleted,
960
+ timeMs: BigInt(e.timeMs),
961
+ counter: e.counter,
962
+ writer: e.writer,
963
+ });
964
+ }
965
+ const storedOf = (e) => ({
966
+ id: e.id,
967
+ data: e.value,
968
+ deleted: e.deleted,
969
+ stamp: { timeMs: e.timeMs, counter: e.counter, writer: e.writer },
970
+ });
971
+ // StateTx stages an update's writes.
972
+ class StateTx {
973
+ state;
974
+ self;
975
+ staged = new Map();
976
+ #decls = new Map();
977
+ #rows = 0;
978
+ #bytes = 0;
979
+ #now = 0;
980
+ #ended = false;
981
+ constructor(state, self) {
982
+ this.state = state;
983
+ this.self = self;
984
+ }
985
+ end() {
986
+ this.#ended = true;
987
+ }
988
+ #stage(collection) {
989
+ if (this.#ended)
990
+ throw new Error("keywire: a Tx is used only inside its update");
991
+ let st = this.staged.get(collection);
992
+ if (!st) {
993
+ const s = this.state.stagedOf(collection);
994
+ st = s.staged;
995
+ this.#now = s.nowMs;
996
+ this.staged.set(collection, st);
997
+ this.#decls.set(collection, s.decl);
998
+ }
999
+ return [st, this.#decls.get(collection)];
1000
+ }
1001
+ get(collection, id) {
1002
+ const [st] = this.#stage(collection);
1003
+ const e = st.get(id);
1004
+ return e && !e.deleted ? e.value.slice() : undefined;
1005
+ }
1006
+ put(collection, id, data) {
1007
+ if (!(data instanceof Uint8Array))
1008
+ throw new TypeError("keywire: a row's data is a Uint8Array");
1009
+ this.#write(collection, id, data, false);
1010
+ }
1011
+ delete(collection, id) {
1012
+ this.#write(collection, id, new Uint8Array(0), true);
1013
+ }
1014
+ #write(collection, id, data, deleted) {
1015
+ const [st, d] = this.#stage(collection);
1016
+ const l = d.limits;
1017
+ if (!validName(id, l.maxID) || data.length > l.maxValue)
1018
+ throw new RangeError(`keywire: an id of ${collection} is 1 to ${l.maxID} bytes of UTF-8 with no control character, and a value at most ${l.maxValue} bytes`);
1019
+ const self = this.self;
1020
+ if (!self)
1021
+ throw new NotReady();
1022
+ if (d.allow && !d.allow(self.slice(), id))
1023
+ throw new Forbidden(`allow refuses this device ${id} of ${collection}`);
1024
+ const cur = st.get(id);
1025
+ if (deleted && (!cur || cur.deleted))
1026
+ return;
1027
+ const rows = this.#rows + 1;
1028
+ const bytes = this.#bytes + utf8Len(id) + data.length;
1029
+ if (rows > this.state.settings.limits.txRows || bytes > this.state.settings.limits.txBytes)
1030
+ throw new StateFull("an update's writes are past txRows or txBytes");
1031
+ const { timeMs, counter } = st.next(this.#now);
1032
+ const out = st.merge({ id, value: data, deleted, timeMs, counter, writer: self }, this.#now, l, false);
1033
+ if (out === "full")
1034
+ throw new StateFull(`${collection} holds at most ${l.maxEntries} rows and ${l.maxBytes} bytes`);
1035
+ if (out !== "applied")
1036
+ throw new Error(`keywire: the write to ${collection} was not taken`);
1037
+ this.#rows = rows;
1038
+ this.#bytes = bytes;
1039
+ }
1040
+ changes() {
1041
+ const out = [];
1042
+ for (const [name, st] of this.staged)
1043
+ for (const e of st.changed())
1044
+ out.push({ collection: name, put: storedOf(e) });
1045
+ return out;
1046
+ }
1047
+ }
1048
+ //# sourceMappingURL=state.js.map