-
Notifications
You must be signed in to change notification settings - Fork 49
feat: persistent history for SDS #2741
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Draft
danisharora099
wants to merge
7
commits into
master
Choose a base branch
from
feat/persistent_history
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
7aa290d
feat: persistent history for SDS
danisharora099 b88e3f1
refactor: simplify localHistory initialization by removing intermedia…
danisharora099 93c351f
feat(history): introduce `ILocalHistory` interface and refactor `Pers…
danisharora099 3c5ebe4
refactor: rename `storageKey` to `storageKeyPrefix` and update storag…
danisharora099 2947541
refactor: rename persistence methods from `persist`/`restore` to `sav…
danisharora099 af8ee45
refactor: Remove silent error suppression for persistent history stor…
danisharora099 92dd0ba
feat: remove `storageKeyPrefix` and `getDefaultHistoryStorage`, simpl…
danisharora099 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
62 changes: 62 additions & 0 deletions
62
packages/sds/src/message_channel/persistent_history.spec.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,62 @@ | ||
| import { expect } from "chai"; | ||
|
|
||
| import { ContentMessage } from "./message.js"; | ||
| import { HistoryStorage, PersistentHistory } from "./persistent_history.js"; | ||
|
|
||
| class MemoryStorage implements HistoryStorage { | ||
| private readonly store = new Map<string, string>(); | ||
|
|
||
| public getItem(key: string): string | null { | ||
| return this.store.get(key) ?? null; | ||
| } | ||
|
|
||
| public setItem(key: string, value: string): void { | ||
| this.store.set(key, value); | ||
| } | ||
|
|
||
| public removeItem(key: string): void { | ||
| this.store.delete(key); | ||
| } | ||
| } | ||
|
|
||
| const channelId = "channel-1"; | ||
|
|
||
| const createMessage = (id: string, timestamp: number): ContentMessage => { | ||
| return new ContentMessage( | ||
| id, | ||
| channelId, | ||
| "sender", | ||
| [], | ||
| BigInt(timestamp), | ||
| undefined, | ||
| new Uint8Array([timestamp]), | ||
| undefined | ||
| ); | ||
| }; | ||
|
|
||
| describe("PersistentHistory", () => { | ||
| it("persists and restores messages", () => { | ||
| const storage = new MemoryStorage(); | ||
| const history = new PersistentHistory({ channelId, storage }); | ||
|
|
||
| history.push(createMessage("msg-1", 1)); | ||
| history.push(createMessage("msg-2", 2)); | ||
|
|
||
| const restored = new PersistentHistory({ channelId, storage }); | ||
|
|
||
| expect(restored.length).to.equal(2); | ||
| expect(restored.slice(0).map((msg) => msg.messageId)).to.deep.equal([ | ||
| "msg-1", | ||
| "msg-2" | ||
| ]); | ||
| }); | ||
|
|
||
| it("behaves like memory history when storage is unavailable", () => { | ||
| const history = new PersistentHistory({ channelId, storage: undefined }); | ||
|
|
||
| history.push(createMessage("msg-3", 3)); | ||
|
|
||
| expect(history.length).to.equal(1); | ||
| expect(history.slice(0)[0].messageId).to.equal("msg-3"); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,196 @@ | ||
| import { bytesToHex, hexToBytes } from "@noble/hashes/utils"; | ||
|
|
||
| import { ILocalHistory, MemLocalHistory } from "./mem_local_history.js"; | ||
| import { ChannelId, ContentMessage, HistoryEntry } from "./message.js"; | ||
|
|
||
| export interface HistoryStorage { | ||
| getItem(key: string): string | null; | ||
| setItem(key: string, value: string): void; | ||
| removeItem(key: string): void; | ||
| } | ||
|
|
||
| export interface PersistentHistoryOptions { | ||
danisharora099 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| channelId: ChannelId; | ||
| storage?: HistoryStorage; | ||
| } | ||
|
|
||
| type StoredHistoryEntry = { | ||
| messageId: string; | ||
| retrievalHint?: string; | ||
| }; | ||
|
|
||
| type StoredContentMessage = { | ||
| messageId: string; | ||
| channelId: string; | ||
| senderId: string; | ||
| lamportTimestamp: string; | ||
| causalHistory: StoredHistoryEntry[]; | ||
| bloomFilter?: string; | ||
| content: string; | ||
| retrievalHint?: string; | ||
| }; | ||
|
|
||
| const HISTORY_STORAGE_PREFIX = "waku:sds:history:"; | ||
danisharora099 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| /** | ||
| * Persists the SDS local history in a browser/localStorage compatible backend. | ||
| * | ||
| * If no storage backend is available, this behaves like {@link MemLocalHistory}. | ||
| */ | ||
| export class PersistentHistory implements ILocalHistory { | ||
| private readonly storage?: HistoryStorage; | ||
| private readonly storageKey: string; | ||
| private readonly memory: MemLocalHistory; | ||
|
|
||
| public constructor(options: PersistentHistoryOptions) { | ||
| this.memory = new MemLocalHistory(); | ||
| this.storage = options.storage || localStorage; | ||
| this.storageKey = `${HISTORY_STORAGE_PREFIX}${options.channelId}`; | ||
| this.load(); | ||
| } | ||
|
|
||
| public get length(): number { | ||
| return this.memory.length; | ||
| } | ||
|
|
||
| public push(...items: ContentMessage[]): number { | ||
| const length = this.memory.push(...items); | ||
| this.save(); | ||
| return length; | ||
| } | ||
|
|
||
| public some( | ||
| predicate: ( | ||
| value: ContentMessage, | ||
| index: number, | ||
| array: ContentMessage[] | ||
| ) => unknown, | ||
| thisArg?: any | ||
| ): boolean { | ||
| return this.memory.some(predicate, thisArg); | ||
| } | ||
|
|
||
| public slice(start?: number, end?: number): ContentMessage[] { | ||
| return this.memory.slice(start, end); | ||
| } | ||
|
|
||
| public find( | ||
| predicate: ( | ||
| value: ContentMessage, | ||
| index: number, | ||
| obj: ContentMessage[] | ||
| ) => unknown, | ||
| thisArg?: any | ||
| ): ContentMessage | undefined { | ||
| return this.memory.find(predicate, thisArg); | ||
| } | ||
|
|
||
| public findIndex( | ||
| predicate: ( | ||
| value: ContentMessage, | ||
| index: number, | ||
| obj: ContentMessage[] | ||
| ) => unknown, | ||
| thisArg?: any | ||
| ): number { | ||
| return this.memory.findIndex(predicate, thisArg); | ||
| } | ||
|
|
||
| private save(): void { | ||
| if (!this.storage) { | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Hum, does it make sense for it to be constructed without storage?
Collaborator
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. we want the class to behave like |
||
| return; | ||
| } | ||
|
|
||
| const payload = JSON.stringify( | ||
| this.memory.slice(0).map(serializeContentMessage) | ||
| ); | ||
| this.storage.setItem(this.storageKey, payload); | ||
| } | ||
|
|
||
| private load(): void { | ||
| if (!this.storage) { | ||
| return; | ||
| } | ||
|
|
||
| try { | ||
| const raw = this.storage.getItem(this.storageKey); | ||
| if (!raw) { | ||
| return; | ||
| } | ||
|
|
||
| const stored = JSON.parse(raw) as StoredContentMessage[]; | ||
| const messages = stored | ||
| .map(deserializeContentMessage) | ||
| .filter((message): message is ContentMessage => Boolean(message)); | ||
| if (messages.length) { | ||
| this.memory.push(...messages); | ||
| } | ||
| } catch { | ||
| this.storage.removeItem(this.storageKey); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| const serializeHistoryEntry = (entry: HistoryEntry): StoredHistoryEntry => ({ | ||
| messageId: entry.messageId, | ||
| retrievalHint: entry.retrievalHint | ||
| ? bytesToHex(entry.retrievalHint) | ||
| : undefined | ||
| }); | ||
|
|
||
| const deserializeHistoryEntry = (entry: StoredHistoryEntry): HistoryEntry => ({ | ||
| messageId: entry.messageId, | ||
| retrievalHint: entry.retrievalHint | ||
| ? hexToBytes(entry.retrievalHint) | ||
| : undefined | ||
| }); | ||
|
|
||
| const serializeContentMessage = ( | ||
| message: ContentMessage | ||
| ): StoredContentMessage => ({ | ||
| messageId: message.messageId, | ||
| channelId: message.channelId, | ||
| senderId: message.senderId, | ||
| lamportTimestamp: message.lamportTimestamp.toString(), | ||
| causalHistory: message.causalHistory.map(serializeHistoryEntry), | ||
| bloomFilter: toHex(message.bloomFilter), | ||
| content: bytesToHex(new Uint8Array(message.content)), | ||
| retrievalHint: toHex(message.retrievalHint) | ||
| }); | ||
|
|
||
| const deserializeContentMessage = ( | ||
| record: StoredContentMessage | ||
| ): ContentMessage | undefined => { | ||
| try { | ||
| const content = hexToBytes(record.content); | ||
| return new ContentMessage( | ||
| record.messageId, | ||
| record.channelId, | ||
| record.senderId, | ||
| record.causalHistory.map(deserializeHistoryEntry), | ||
| BigInt(record.lamportTimestamp), | ||
| fromHex(record.bloomFilter), | ||
| content, | ||
| [], | ||
| fromHex(record.retrievalHint) | ||
| ); | ||
| } catch { | ||
| return undefined; | ||
| } | ||
| }; | ||
|
|
||
| const toHex = ( | ||
| data?: Uint8Array | Uint8Array<ArrayBufferLike> | ||
| ): string | undefined => { | ||
| if (!data || data.length === 0) { | ||
| return undefined; | ||
| } | ||
| return bytesToHex(data instanceof Uint8Array ? data : new Uint8Array(data)); | ||
| }; | ||
|
|
||
| const fromHex = (value?: string): Uint8Array | undefined => { | ||
| if (!value) { | ||
| return undefined; | ||
| } | ||
| return hexToBytes(value); | ||
| }; | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.