Skip to content

Commit 858e76b

Browse files
committed
Add initial timestamp doc and example for restoring clock state
1 parent 94d9217 commit 858e76b

File tree

2 files changed

+26
-1
lines changed

2 files changed

+26
-1
lines changed

README.md

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -98,6 +98,10 @@ Creates a new Hybrid Logical Clock instance.
9898
- `getWallClockTime?: () => number` — Function to get current time (default:
9999
`Date.now()`).
100100
- `maxDrift?: number` — Maximum allowed drift in ms (default: 5 minutes).
101+
- `initialTimestamp?: HLCTimestamp | string` — (Optional) The initial timestamp
102+
to start the clock from. Useful for restoring state or resuming from a
103+
persisted timestamp. If a string is provided, it must be a valid HLC timestamp
104+
string.
101105

102106
**Returns:** `HLCInstance` object:
103107

@@ -187,6 +191,27 @@ const tsB = hlcB.receive(tsA);
187191
// Now, tsB > tsA and reflects the causal relationship
188192
```
189193

194+
## Example: Restoring a Clock
195+
196+
You can restore a clock's state by passing the last timestamp to
197+
`initialTimestamp` when creating a new HLC instance. This is useful for resuming
198+
from a persisted state.
199+
200+
```ts
201+
const hlc = createHLC({ nodeId: "node-1", getWallClockTime: () => 1000 });
202+
const t1 = hlc.send();
203+
// t1.toString() === "1970-01-01T00:00:01.000Z|00000001|node-1"
204+
205+
// Restore the clock from the last timestamp
206+
const restoredHLC = createHLC({
207+
nodeId: "node-1",
208+
getWallClockTime: () => 1000,
209+
initialTimestamp: t1,
210+
});
211+
const t2 = restoredHLC.send();
212+
// t2.toString() === "1970-01-01T00:00:01.000Z|00000002|node-1"
213+
```
214+
190215
## Error Handling
191216

192217
- If the drift between local and remote timestamps exceeds `maxDrift`, an error

tests/core.test.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -178,7 +178,7 @@ Deno.test("can restore a clock by passing last timestamp", () => {
178178
expect(t2.toString()).toBe("1970-01-01T00:00:01.000Z|00000002|node-1");
179179
});
180180

181-
Deno.test("restpore should not restore nodeId ", () => {
181+
Deno.test("restore should not restore nodeId ", () => {
182182
const hlc = createHLC({ nodeId: "node-1", getWallClockTime: () => 1000 });
183183
const t1 = hlc.send();
184184
expect(t1.toString()).toBe("1970-01-01T00:00:01.000Z|00000001|node-1");

0 commit comments

Comments
 (0)