@evolu/common 5.4.7 → 6.0.0

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 (242) hide show
  1. package/README.md +30 -34
  2. package/dist/src/Array.d.ts +17 -0
  3. package/dist/src/Array.d.ts.map +1 -0
  4. package/dist/src/Array.js +12 -0
  5. package/dist/src/Assert.d.ts +68 -0
  6. package/dist/src/Assert.d.ts.map +1 -0
  7. package/dist/src/Assert.js +77 -0
  8. package/dist/src/BigInt.d.ts +20 -0
  9. package/dist/src/BigInt.d.ts.map +1 -0
  10. package/dist/src/BigInt.js +18 -0
  11. package/dist/src/Buffer.d.ts +92 -0
  12. package/dist/src/Buffer.d.ts.map +1 -0
  13. package/dist/src/Buffer.js +62 -0
  14. package/dist/src/Callbacks.d.ts +20 -0
  15. package/dist/src/Callbacks.d.ts.map +1 -0
  16. package/dist/src/Callbacks.js +18 -0
  17. package/dist/src/Console.d.ts +78 -0
  18. package/dist/src/Console.d.ts.map +1 -0
  19. package/dist/src/Console.js +103 -0
  20. package/dist/src/Crypto.d.ts +72 -39
  21. package/dist/src/Crypto.d.ts.map +1 -1
  22. package/dist/src/Crypto.js +89 -54
  23. package/dist/src/Eq.d.ts +97 -0
  24. package/dist/src/Eq.d.ts.map +1 -0
  25. package/dist/src/Eq.js +167 -0
  26. package/dist/src/Error.d.ts +14 -10
  27. package/dist/src/Error.d.ts.map +1 -1
  28. package/dist/src/Error.js +43 -11
  29. package/dist/src/Evolu/Config.d.ts +69 -0
  30. package/dist/src/Evolu/Config.d.ts.map +1 -0
  31. package/dist/src/Evolu/Config.js +9 -0
  32. package/dist/src/Evolu/Db.d.ts +126 -0
  33. package/dist/src/Evolu/Db.d.ts.map +1 -0
  34. package/dist/src/Evolu/Db.js +774 -0
  35. package/dist/src/Evolu/Diff.d.ts +43 -0
  36. package/dist/src/Evolu/Diff.d.ts.map +1 -0
  37. package/dist/src/Evolu/Diff.js +95 -0
  38. package/dist/src/Evolu/Evolu.d.ts +334 -0
  39. package/dist/src/Evolu/Evolu.d.ts.map +1 -0
  40. package/dist/src/Evolu/Evolu.js +434 -0
  41. package/dist/src/Evolu/Internal.d.ts +26 -0
  42. package/dist/src/Evolu/Internal.d.ts.map +1 -0
  43. package/dist/src/Evolu/Internal.js +25 -0
  44. package/dist/src/Evolu/Kysely.d.ts +6 -0
  45. package/dist/src/Evolu/Kysely.d.ts.map +1 -0
  46. package/dist/src/Evolu/Kysely.js +21 -0
  47. package/dist/src/Evolu/Owner.d.ts +155 -0
  48. package/dist/src/Evolu/Owner.d.ts.map +1 -0
  49. package/dist/src/Evolu/Owner.js +126 -0
  50. package/dist/src/Evolu/Platform.d.ts +23 -0
  51. package/dist/src/Evolu/Platform.d.ts.map +1 -0
  52. package/dist/src/Evolu/Platform.js +1 -0
  53. package/dist/src/Evolu/Protocol.d.ts +401 -0
  54. package/dist/src/Evolu/Protocol.d.ts.map +1 -0
  55. package/dist/src/Evolu/Protocol.js +1151 -0
  56. package/dist/src/Evolu/Public.d.ts +18 -0
  57. package/dist/src/Evolu/Public.d.ts.map +1 -0
  58. package/dist/src/Evolu/Public.js +11 -0
  59. package/dist/src/Evolu/PublicKysely.d.ts +148 -0
  60. package/dist/src/Evolu/PublicKysely.d.ts.map +1 -0
  61. package/dist/src/Evolu/PublicKysely.js +185 -0
  62. package/dist/src/Evolu/Query.d.ts +63 -0
  63. package/dist/src/Evolu/Query.d.ts.map +1 -0
  64. package/dist/src/Evolu/Query.js +61 -0
  65. package/dist/src/Evolu/Relay.d.ts +13 -0
  66. package/dist/src/Evolu/Relay.d.ts.map +1 -0
  67. package/dist/src/Evolu/Relay.js +109 -0
  68. package/dist/src/Evolu/Schema.d.ts +201 -0
  69. package/dist/src/Evolu/Schema.d.ts.map +1 -0
  70. package/dist/src/Evolu/Schema.js +150 -0
  71. package/dist/src/Evolu/Storage.d.ts +49 -0
  72. package/dist/src/Evolu/Storage.d.ts.map +1 -0
  73. package/dist/src/Evolu/Storage.js +1111 -0
  74. package/dist/src/Evolu/Sync.d.ts +59 -0
  75. package/dist/src/Evolu/Sync.d.ts.map +1 -0
  76. package/dist/src/Evolu/Sync.js +29 -0
  77. package/dist/src/Evolu/Timestamp.d.ts +106 -0
  78. package/dist/src/Evolu/Timestamp.d.ts.map +1 -0
  79. package/dist/src/Evolu/Timestamp.js +179 -0
  80. package/dist/src/Function.d.ts +54 -0
  81. package/dist/src/Function.d.ts.map +1 -0
  82. package/dist/src/Function.js +38 -0
  83. package/dist/src/ManyToManyMap.d.ts +26 -0
  84. package/dist/src/ManyToManyMap.d.ts.map +1 -0
  85. package/dist/src/ManyToManyMap.js +92 -0
  86. package/dist/src/NanoId.d.ts +27 -0
  87. package/dist/src/NanoId.d.ts.map +1 -0
  88. package/dist/src/NanoId.js +6 -0
  89. package/dist/src/Number.d.ts +42 -0
  90. package/dist/src/Number.d.ts.map +1 -0
  91. package/dist/src/Number.js +55 -0
  92. package/dist/src/Object.d.ts +35 -0
  93. package/dist/src/Object.d.ts.map +1 -0
  94. package/dist/src/Object.js +36 -0
  95. package/dist/src/Order.d.ts +90 -0
  96. package/dist/src/Order.d.ts.map +1 -0
  97. package/dist/src/Order.js +85 -0
  98. package/dist/src/Promise.d.ts +180 -0
  99. package/dist/src/Promise.d.ts.map +1 -0
  100. package/dist/src/Promise.js +176 -0
  101. package/dist/src/Random.d.ts +52 -0
  102. package/dist/src/Random.d.ts.map +1 -0
  103. package/dist/src/Random.js +29 -0
  104. package/dist/src/Ref.d.ts +40 -0
  105. package/dist/src/Ref.d.ts.map +1 -0
  106. package/dist/src/Ref.js +13 -0
  107. package/dist/src/Result.d.ts +421 -0
  108. package/dist/src/Result.d.ts.map +1 -0
  109. package/dist/src/Result.js +357 -0
  110. package/dist/src/Skiplist.d.ts +23 -0
  111. package/dist/src/Skiplist.d.ts.map +1 -0
  112. package/dist/src/Skiplist.js +58 -0
  113. package/dist/src/Sqlite.d.ts +116 -52
  114. package/dist/src/Sqlite.d.ts.map +1 -1
  115. package/dist/src/Sqlite.js +183 -67
  116. package/dist/src/Store.d.ts +45 -8
  117. package/dist/src/Store.d.ts.map +1 -1
  118. package/dist/src/Store.js +33 -17
  119. package/dist/src/String.d.ts +2 -0
  120. package/dist/src/String.d.ts.map +1 -0
  121. package/dist/src/String.js +14 -0
  122. package/dist/src/Time.d.ts +20 -0
  123. package/dist/src/Time.d.ts.map +1 -0
  124. package/dist/src/Time.js +25 -0
  125. package/dist/src/Type.d.ts +1937 -0
  126. package/dist/src/Type.d.ts.map +1 -0
  127. package/dist/src/Type.js +2002 -0
  128. package/dist/src/Types.d.ts +188 -0
  129. package/dist/src/Types.d.ts.map +1 -0
  130. package/dist/src/Types.js +6 -0
  131. package/dist/src/WebSocket.d.ts +112 -0
  132. package/dist/src/WebSocket.d.ts.map +1 -0
  133. package/dist/src/WebSocket.js +139 -0
  134. package/dist/src/Worker.d.ts +44 -0
  135. package/dist/src/Worker.d.ts.map +1 -0
  136. package/dist/src/Worker.js +66 -0
  137. package/dist/src/index.d.ts +24 -11
  138. package/dist/src/index.d.ts.map +1 -1
  139. package/dist/src/index.js +24 -11
  140. package/package.json +29 -38
  141. package/src/Array.ts +39 -0
  142. package/src/Assert.ts +116 -0
  143. package/src/BigInt.ts +29 -0
  144. package/src/Buffer.ts +175 -0
  145. package/src/Callbacks.ts +43 -0
  146. package/src/Console.ts +159 -0
  147. package/src/Crypto.ts +169 -115
  148. package/src/Eq.ts +204 -0
  149. package/src/Error.ts +57 -20
  150. package/src/Evolu/Config.ts +83 -0
  151. package/src/Evolu/Db.ts +1275 -0
  152. package/src/Evolu/Diff.ts +142 -0
  153. package/src/Evolu/Evolu.ts +947 -0
  154. package/src/Evolu/Internal.ts +26 -0
  155. package/src/Evolu/Kysely.ts +38 -0
  156. package/src/Evolu/Owner.ts +296 -0
  157. package/src/Evolu/Platform.ts +27 -0
  158. package/src/Evolu/Protocol.ts +1857 -0
  159. package/src/Evolu/Public.ts +43 -0
  160. package/src/Evolu/PublicKysely.ts +240 -0
  161. package/src/Evolu/Query.ts +167 -0
  162. package/src/Evolu/Relay.ts +142 -0
  163. package/src/Evolu/Schema.ts +417 -0
  164. package/src/Evolu/Storage.ts +1281 -0
  165. package/src/Evolu/Sync.ts +105 -0
  166. package/src/Evolu/Timestamp.ts +311 -0
  167. package/src/Function.ts +58 -0
  168. package/src/ManyToManyMap.ts +140 -0
  169. package/src/NanoId.ts +39 -0
  170. package/src/Number.ts +90 -0
  171. package/src/Object.ts +64 -0
  172. package/src/Order.ts +113 -0
  173. package/src/Promise.ts +295 -0
  174. package/src/Random.ts +68 -0
  175. package/src/Ref.ts +63 -0
  176. package/src/Result.ts +453 -0
  177. package/src/Skiplist.ts +102 -0
  178. package/src/Sqlite.ts +366 -153
  179. package/src/Store.ts +79 -36
  180. package/src/String.ts +10 -0
  181. package/src/Time.ts +36 -0
  182. package/src/Type.ts +3978 -0
  183. package/src/Types.ts +209 -0
  184. package/src/WebSocket.ts +273 -0
  185. package/src/Worker.ts +129 -0
  186. package/src/index.ts +24 -11
  187. package/dist/src/Config.d.ts +0 -56
  188. package/dist/src/Config.d.ts.map +0 -1
  189. package/dist/src/Config.js +0 -39
  190. package/dist/src/Crdt.d.ts +0 -89
  191. package/dist/src/Crdt.d.ts.map +0 -1
  192. package/dist/src/Crdt.js +0 -181
  193. package/dist/src/Db.d.ts +0 -107
  194. package/dist/src/Db.d.ts.map +0 -1
  195. package/dist/src/Db.js +0 -443
  196. package/dist/src/Diff.d.ts +0 -27
  197. package/dist/src/Diff.d.ts.map +0 -1
  198. package/dist/src/Diff.js +0 -84
  199. package/dist/src/Evolu.d.ts +0 -426
  200. package/dist/src/Evolu.d.ts.map +0 -1
  201. package/dist/src/Evolu.js +0 -333
  202. package/dist/src/Model.d.ts +0 -141
  203. package/dist/src/Model.d.ts.map +0 -1
  204. package/dist/src/Model.js +0 -125
  205. package/dist/src/Murmurhash.d.ts +0 -2
  206. package/dist/src/Murmurhash.d.ts.map +0 -1
  207. package/dist/src/Murmurhash.js +0 -60
  208. package/dist/src/Owner.d.ts +0 -33
  209. package/dist/src/Owner.d.ts.map +0 -1
  210. package/dist/src/Owner.js +0 -26
  211. package/dist/src/Platform.d.ts +0 -37
  212. package/dist/src/Platform.d.ts.map +0 -1
  213. package/dist/src/Platform.js +0 -11
  214. package/dist/src/Protobuf.d.ts +0 -81
  215. package/dist/src/Protobuf.d.ts.map +0 -1
  216. package/dist/src/Protobuf.js +0 -92
  217. package/dist/src/Public.d.ts +0 -13
  218. package/dist/src/Public.d.ts.map +0 -1
  219. package/dist/src/Public.js +0 -6
  220. package/dist/src/Socket.d.ts +0 -8
  221. package/dist/src/Socket.d.ts.map +0 -1
  222. package/dist/src/Socket.js +0 -51
  223. package/dist/src/Sql.d.ts +0 -12
  224. package/dist/src/Sql.d.ts.map +0 -1
  225. package/dist/src/Sql.js +0 -30
  226. package/dist/src/Sync.d.ts +0 -70
  227. package/dist/src/Sync.d.ts.map +0 -1
  228. package/dist/src/Sync.js +0 -127
  229. package/src/Config.ts +0 -119
  230. package/src/Crdt.ts +0 -361
  231. package/src/Db.ts +0 -955
  232. package/src/Diff.ts +0 -114
  233. package/src/Evolu.ts +0 -1016
  234. package/src/Model.ts +0 -233
  235. package/src/Murmurhash.ts +0 -70
  236. package/src/Owner.ts +0 -69
  237. package/src/Platform.ts +0 -47
  238. package/src/Protobuf.ts +0 -155
  239. package/src/Public.ts +0 -12
  240. package/src/Socket.ts +0 -83
  241. package/src/Sql.ts +0 -41
  242. package/src/Sync.ts +0 -315
package/src/Config.ts DELETED
@@ -1,119 +0,0 @@
1
- import * as Context from "effect/Context";
2
- import * as Layer from "effect/Layer";
3
- import * as LogLevel from "effect/LogLevel";
4
- import * as Logger from "effect/Logger";
5
- import * as ManagedRuntime from "effect/ManagedRuntime";
6
- import * as Match from "effect/Match";
7
-
8
- export interface Config {
9
- /**
10
- * URL to reload browser tabs after {@link Owner} reset or restore.
11
- *
12
- * The default value is `/`.
13
- */
14
- reloadUrl: string;
15
-
16
- /**
17
- * URL for Evolu sync and backup server.
18
- *
19
- * The default value is `https://evolu.world`.
20
- */
21
- syncUrl: string;
22
-
23
- /**
24
- * Evolu is multitenant - it can run more instances concurrently. Every Evolu
25
- * instance has to have its own unique name. Database files are separated and
26
- * invisible to each other.
27
- *
28
- * The default value is: `Evolu`.
29
- */
30
- name: string;
31
-
32
- /**
33
- * Maximum physical clock drift allowed in ms.
34
- *
35
- * The default value is 5 * 60 * 1000 (5 minutes).
36
- */
37
- maxDrift: number;
38
-
39
- /**
40
- * Setting the minimum log level. The default value is `none`.
41
- *
42
- * For development, use `trace` to log all events and `debug` to log only
43
- * events with values. For production, use `warning`.
44
- */
45
- minimumLogLevel: "none" | "trace" | "debug" | "warning";
46
-
47
- /**
48
- * Enables websocket connection
49
- *
50
- * If set to true runs a websocket connection on the sync url
51
- */
52
- enableWebsocketConnection?: true;
53
-
54
- /**
55
- * Allows to reuse websocket connections for multiple database setup
56
- *
57
- * Works INSTEAD of enableWebsocket and if set overrides enableWebsocket this
58
- * attaches the database to a connection produced by a call back from another
59
- * database that has enableWebsocketConnection
60
- */
61
- externalWebsocketConnection?: WebSocket;
62
- }
63
-
64
- export const Config = Context.GenericTag<Config>("Config");
65
-
66
- export const defaultConfig: Config = {
67
- reloadUrl: "/",
68
- syncUrl: "https://evolu.world",
69
- name: "Evolu",
70
- maxDrift: 5 * 60 * 1000,
71
- minimumLogLevel: "none",
72
- };
73
-
74
- /** https://effect.website/docs/guides/runtime */
75
- export const createRuntime = (
76
- partialConfig?: Partial<Config>,
77
- ): ManagedRuntime.ManagedRuntime<Config, never> => {
78
- const config = { ...defaultConfig, ...partialConfig };
79
- const ConfigLive = Layer.succeed(Config, config);
80
-
81
- const minimumLogLevel = Match.value(config.minimumLogLevel).pipe(
82
- Match.when("debug", () => LogLevel.Debug),
83
- Match.when("none", () => LogLevel.None),
84
- Match.when("trace", () => LogLevel.Trace),
85
- Match.when("warning", () => LogLevel.Warning),
86
- Match.exhaustive,
87
- );
88
-
89
- const evoluLayer =
90
- config.minimumLogLevel === "none"
91
- ? ConfigLive
92
- : Layer.mergeAll(
93
- ConfigLive,
94
- Logger.minimumLogLevel(minimumLogLevel),
95
- Logger.replace(Logger.defaultLogger, makeEvoluLogger(config.name)),
96
- );
97
-
98
- return ManagedRuntime.make(evoluLayer);
99
- };
100
-
101
- // TODO: Spans and Effect native variadic log args.
102
- const makeEvoluLogger = (name: string) =>
103
- Logger.make(({ logLevel, message, date }) => {
104
- const fn =
105
- logLevel._tag === "Warning"
106
- ? "warn"
107
- : logLevel._tag === "Error"
108
- ? "error"
109
- : "log";
110
-
111
- const hours = date.getHours().toString().padStart(2, "0");
112
- const minutes = date.getMinutes().toString().padStart(2, "0");
113
- const seconds = date.getSeconds().toString().padStart(2, "0");
114
- const milliseconds = date.getMilliseconds().toString().padStart(3, "0");
115
- const formattedDate = `${hours}:${minutes}:${seconds}:${milliseconds}`;
116
-
117
- const messages: unknown[] = Array.isArray(message) ? message : [message];
118
- globalThis.console[fn](`${formattedDate} [${name}]`, ...messages);
119
- });
package/src/Crdt.ts DELETED
@@ -1,361 +0,0 @@
1
- import * as S from "@effect/schema/Schema";
2
- import * as Arr from "effect/Array";
3
- import * as Brand from "effect/Brand";
4
- import * as Context from "effect/Context";
5
- import * as Effect from "effect/Effect";
6
- import * as Either from "effect/Either";
7
- import { pipe } from "effect/Function";
8
- import * as Layer from "effect/Layer";
9
- import * as Number from "effect/Number";
10
- import * as Option from "effect/Option";
11
- import * as String from "effect/String";
12
- import { Config } from "./Config.js";
13
- import { NanoIdGenerator, NodeId } from "./Crypto.js";
14
- import { murmurhash } from "./Murmurhash.js";
15
-
16
- // https://sergeiturukin.com/2017/06/26/hybrid-logical-clocks.html
17
- // https://muratbuffalo.blogspot.com/2014/07/hybrid-logical-clocks.html
18
- // https://jaredforsyth.com/posts/hybrid-logical-clocks/
19
- // https://github.com/clintharris/crdt-example-app_annotated/blob/master/shared/timestamp.js
20
-
21
- export interface Timestamp {
22
- readonly node: NodeId;
23
- readonly millis: Millis;
24
- readonly counter: Counter;
25
- }
26
-
27
- export const AllowedTimeRange = {
28
- greaterThan: 860934419999,
29
- lessThan: 2582803260000,
30
- };
31
-
32
- /**
33
- * Millis represents a time that is valid for usage with the Merkle tree. It
34
- * must be between Apr 13, 1997, and Nov 05, 2051, to ensure MinutesBase3 length
35
- * equals 16. We can find diff for two Merkle trees only within this range. If
36
- * the device clock is out of range, Evolu will not store data until it's
37
- * fixed.
38
- */
39
- export const Millis = S.Number.pipe(
40
- S.greaterThan(AllowedTimeRange.greaterThan),
41
- S.lessThan(AllowedTimeRange.lessThan),
42
- S.brand("Millis"),
43
- );
44
-
45
- export type Millis = typeof Millis.Type;
46
-
47
- export const initialMillis = S.decodeSync(Millis)(
48
- AllowedTimeRange.greaterThan + 1,
49
- );
50
-
51
- export const Counter = S.Number.pipe(S.between(0, 65535), S.brand("Counter"));
52
- export type Counter = typeof Counter.Type;
53
-
54
- const initialCounter = S.decodeSync(Counter)(0);
55
-
56
- export type TimestampHash = number & Brand.Brand<"TimestampHash">;
57
-
58
- export type TimestampString = string & Brand.Brand<"TimestampString">;
59
-
60
- export const timestampToString = (t: Timestamp): TimestampString =>
61
- [
62
- new Date(t.millis).toISOString(),
63
- t.counter.toString(16).toUpperCase().padStart(4, "0"),
64
- t.node,
65
- ].join("-") as TimestampString;
66
-
67
- export const unsafeTimestampFromString = (s: TimestampString): Timestamp => {
68
- const a = s.split("-");
69
- return {
70
- millis: Date.parse(a.slice(0, 3).join("-")).valueOf() as Millis,
71
- counter: parseInt(a[3], 16) as Counter,
72
- node: a[4] as NodeId,
73
- };
74
- };
75
-
76
- export const timestampToHash = (t: Timestamp): TimestampHash =>
77
- murmurhash(timestampToString(t)) as TimestampHash;
78
-
79
- const syncNodeId = S.decodeSync(NodeId)("0000000000000000");
80
-
81
- export const makeSyncTimestamp = (
82
- millis: Millis = initialMillis,
83
- ): Timestamp => ({
84
- millis,
85
- counter: initialCounter,
86
- node: syncNodeId,
87
- });
88
-
89
- export const makeInitialTimestamp = NanoIdGenerator.pipe(
90
- Effect.flatMap(({ nodeId }) => nodeId),
91
- Effect.map(
92
- (node): Timestamp => ({
93
- millis: initialMillis,
94
- counter: initialCounter,
95
- node,
96
- }),
97
- ),
98
- );
99
-
100
- export class Time extends Context.Tag("Time")<
101
- Time,
102
- {
103
- readonly now: Effect.Effect<Millis, TimestampTimeOutOfRangeError>;
104
- }
105
- >() {
106
- static Live = Layer.succeed(Time, {
107
- now: Effect.suspend(() => S.decode(Millis)(Date.now())).pipe(
108
- Effect.catchTag("ParseError", () =>
109
- Effect.fail<TimestampTimeOutOfRangeError>({
110
- _tag: "TimestampTimeOutOfRangeError",
111
- }),
112
- ),
113
- ),
114
- });
115
- }
116
-
117
- /**
118
- * The TimestampError type represents all Timestamp-related errors. If such an
119
- * error happens, the device clock is skewed and should be set to the current
120
- * time.
121
- */
122
- export type TimestampError =
123
- | TimestampDriftError
124
- | TimestampCounterOverflowError
125
- | TimestampDuplicateNodeError
126
- | TimestampTimeOutOfRangeError;
127
-
128
- export interface TimestampDriftError {
129
- readonly _tag: "TimestampDriftError";
130
- readonly next: Millis;
131
- readonly now: Millis;
132
- }
133
-
134
- export interface TimestampCounterOverflowError {
135
- readonly _tag: "TimestampCounterOverflowError";
136
- }
137
-
138
- export interface TimestampDuplicateNodeError {
139
- readonly _tag: "TimestampDuplicateNodeError";
140
- readonly node: NodeId;
141
- }
142
-
143
- export interface TimestampTimeOutOfRangeError {
144
- readonly _tag: "TimestampTimeOutOfRangeError";
145
- }
146
-
147
- const getNextMillis = (millis: ReadonlyArray<Millis>) =>
148
- Effect.gen(function* () {
149
- const time = yield* Time;
150
- const config = yield* Config;
151
-
152
- const now = yield* time.now;
153
- const next = Math.max(now, ...millis) as Millis;
154
-
155
- if (next - now > config.maxDrift)
156
- yield* Effect.fail<TimestampDriftError>({
157
- _tag: "TimestampDriftError",
158
- now,
159
- next,
160
- });
161
-
162
- return next;
163
- });
164
-
165
- const incrementCounter = (counter: Counter) =>
166
- pipe(
167
- Number.increment(counter),
168
- S.decodeEither(Counter),
169
- Either.mapLeft(
170
- (): TimestampCounterOverflowError => ({
171
- _tag: "TimestampCounterOverflowError",
172
- }),
173
- ),
174
- );
175
-
176
- const counterMin = S.decodeSync(Counter)(0);
177
-
178
- export const sendTimestamp = (
179
- timestamp: Timestamp,
180
- ): Effect.Effect<
181
- Timestamp,
182
- | TimestampDriftError
183
- | TimestampCounterOverflowError
184
- | TimestampTimeOutOfRangeError,
185
- Time | Config
186
- > =>
187
- Effect.gen(function* () {
188
- const millis = yield* getNextMillis([timestamp.millis]);
189
- const counter =
190
- millis === timestamp.millis
191
- ? yield* incrementCounter(timestamp.counter)
192
- : counterMin;
193
- return { ...timestamp, millis, counter };
194
- });
195
-
196
- export const receiveTimestamp = ({
197
- local,
198
- remote,
199
- }: {
200
- readonly local: Timestamp;
201
- readonly remote: Timestamp;
202
- }): Effect.Effect<
203
- Timestamp,
204
- | TimestampDriftError
205
- | TimestampCounterOverflowError
206
- | TimestampDuplicateNodeError
207
- | TimestampTimeOutOfRangeError,
208
- Time | Config
209
- > =>
210
- Effect.gen(function* (_) {
211
- if (local.node === remote.node)
212
- yield* Effect.fail<TimestampDuplicateNodeError>({
213
- _tag: "TimestampDuplicateNodeError",
214
- node: local.node,
215
- });
216
-
217
- const millis = yield* getNextMillis([local.millis, remote.millis]);
218
- const counter = yield* millis === local.millis && millis === remote.millis
219
- ? incrementCounter(Math.max(local.counter, remote.counter) as Counter)
220
- : millis === local.millis
221
- ? incrementCounter(local.counter)
222
- : millis === remote.millis
223
- ? incrementCounter(remote.counter)
224
- : Either.right(counterMin);
225
-
226
- return { ...local, millis, counter };
227
- });
228
-
229
- /**
230
- * It's actually not Merkle Tree but a Merkleized prefix tree, aka Merkle Trie.
231
- * https://decomposition.al/blog/2019/05/31/how-i-learned-about-merklix-trees-without-having-to-become-a-cryptocurrency-enthusiast
232
- */
233
- export interface MerkleTree {
234
- readonly hash?: TimestampHash;
235
- readonly "0"?: MerkleTree;
236
- readonly "1"?: MerkleTree;
237
- readonly "2"?: MerkleTree;
238
- }
239
-
240
- export type MerkleTreeString = string & Brand.Brand<"MerkleTreeString">;
241
-
242
- export const initialMerkleTree = Object.create(null) as MerkleTree;
243
-
244
- type MerkleTreeKey = keyof Omit<MerkleTree, "hash">;
245
-
246
- type MerkleTreePath = ReadonlyArray<MerkleTreeKey>;
247
-
248
- export const millisToMerkleTreePath = (millis: Millis): MerkleTreePath =>
249
- Math.floor(millis / 1000 / 60)
250
- .toString(3)
251
- .split("") as MerkleTreePath;
252
-
253
- const merkleTreePathToMillis = (path: MerkleTreePath) =>
254
- path.length === 0
255
- ? initialMillis
256
- : // 16 is the length of the base 3 value of the current time in minutes.
257
- // Ensure it's padded to create the full value.
258
- ((parseInt(path.join("").padEnd(16, "0"), 3) * 1000 * 60) as Millis);
259
-
260
- const xorTimestampHashes = (a: TimestampHash | undefined, b: TimestampHash) =>
261
- ((a || 0) ^ b) as TimestampHash;
262
-
263
- const insertKey = (
264
- tree: MerkleTree,
265
- path: MerkleTreePath,
266
- hash: TimestampHash,
267
- ): MerkleTree => {
268
- if (path.length === 0) return tree;
269
- const key = path[0];
270
- const child = tree[key] || {};
271
- return {
272
- ...tree,
273
- [key]: {
274
- ...child,
275
- ...insertKey(child, path.slice(1), hash),
276
- hash: xorTimestampHashes(child.hash, hash),
277
- },
278
- };
279
- };
280
-
281
- export const insertIntoMerkleTree = (
282
- tree: MerkleTree,
283
- timestamp: Timestamp,
284
- ): MerkleTree => {
285
- const path = millisToMerkleTreePath(timestamp.millis);
286
- const hash = timestampToHash(timestamp);
287
- return insertKey(
288
- { ...tree, hash: xorTimestampHashes(tree.hash, hash) },
289
- path,
290
- hash,
291
- );
292
- };
293
-
294
- const sortedMerkleTreeKeys: ReadonlyArray<MerkleTreeKey> = ["0", "1", "2"];
295
-
296
- const getSortedMerkleTreeKeys = (tree: MerkleTree) =>
297
- sortedMerkleTreeKeys.filter((key) => key in tree);
298
-
299
- export const diffMerkleTrees = (
300
- tree1: MerkleTree,
301
- tree2: MerkleTree,
302
- ): Option.Option<Millis> => {
303
- if (tree1.hash === tree2.hash) return Option.none();
304
- let node1 = tree1;
305
- let node2 = tree2;
306
- let diffPath: MerkleTreePath = [];
307
-
308
- // This loop will eventually stop when it traverses down to find
309
- // where the hashes differ, or otherwise when there are no leaves
310
- // left (this shouldn't happen, if that's the case the hash check at
311
- // the top of this function should pass)
312
- // eslint-disable-next-line no-constant-condition
313
- while (1) {
314
- const keys = Arr.dedupeWith(
315
- getSortedMerkleTreeKeys(node1).concat(getSortedMerkleTreeKeys(node2)),
316
- String.Equivalence,
317
- );
318
- let diffKey: MerkleTreeKey | null = null;
319
-
320
- // Traverse down the trie through keys that are different. We
321
- // traverse down the keys in order. Stop in two cases: either one
322
- // of the nodes doesn't have the key or a different key isn't
323
- // found. For the former case, we have to do that because pruning is
324
- // lossy. We don't know if we've pruned off a changed key, so we
325
- // can't traverse down anymore. For the latter case, it means two
326
- // things: either we've hit the bottom of the tree, or the changed
327
- // key has been pruned off. In the latter case, we have a "partial"
328
- // key and will fill the rest with 0s. If multiple older
329
- // messages were added into one trie, we might likely
330
- // generate a time that only encompasses *some* of those
331
- // messages. Pruning is lossy, and we traverse down the left-most
332
- // changed time that we know of, because of pruning, it might take
333
- // multiple passes to sync up a trie.
334
- for (let i = 0; i < keys.length; i++) {
335
- const key = keys[i];
336
- const next1 = node1[key];
337
- const next2 = node2[key];
338
- if (!next1 || !next2) break;
339
- if (next1.hash !== next2.hash) {
340
- diffKey = key;
341
- break;
342
- }
343
- }
344
-
345
- if (!diffKey) {
346
- return Option.some(merkleTreePathToMillis(diffPath));
347
- }
348
-
349
- diffPath = [...diffPath, diffKey];
350
- node1 = node1[diffKey] || initialMerkleTree;
351
- node2 = node2[diffKey] || initialMerkleTree;
352
- }
353
-
354
- return Option.none();
355
- };
356
-
357
- export const merkleTreeToString = (m: MerkleTree): MerkleTreeString =>
358
- JSON.stringify(m) as MerkleTreeString;
359
-
360
- export const unsafeMerkleTreeFromString = (m: MerkleTreeString): MerkleTree =>
361
- JSON.parse(m) as MerkleTree;