Something went wrong. Try again.
Private notes, end to end encrypted, on atproto. wholebit.studio/stones
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177import type { NoteCodec } from './crypto'import { sameText, unpin, type LocalNote, type NoteContent } from './model'import { ChangesUnavailableError, type Remote, type RemoteChange } from './remote'import type { NoteStore } from './store'
export interface SyncResult { pulled: number pushed: number conflicts: number undecryptable: number}
function conflictTitle(title: string): string { return title ? `${title} (conflict copy)` : 'Conflict copy'}
const RECONCILE_EVERY_MS = 24 * 60 * 60 * 1000
export class SyncEngine { private result: SyncResult = { pulled: 0, pushed: 0, conflicts: 0, undecryptable: 0 } private reportedPulled = 0
constructor( private readonly remote: Remote, private readonly store: NoteStore, public codec: NoteCodec, private readonly now: () => number = Date.now, private readonly onProgress: () => void = () => {}, ) {}
async sync(): Promise<SyncResult> { this.result = { pulled: 0, pushed: 0, conflicts: 0, undecryptable: 0 } this.reportedPulled = 0 const encoding = this.codec.keyId ?? 'plain' if ((await this.store.getMeta('encoding')) !== encoding) { await this.reconcile(true) await this.store.setMeta('encoding', encoding) } else { await this.pull() } await this.push() return this.result }
private decode(id: string, record: unknown): NoteContent | null { try { return this.codec.decode(id, record) } catch { return null } }
private progress(): void { if (this.result.pulled === this.reportedPulled) return this.reportedPulled = this.result.pulled this.onProgress() }
private async pull(): Promise<void> { const since = await this.store.getMeta('head') const reconciledAt = Number((await this.store.getMeta('reconciledAt')) ?? 0) if (!since || this.now() - reconciledAt > RECONCILE_EVERY_MS) return this.reconcile()
let cursor: string | undefined let head: string | undefined do { let page try { page = await this.remote.changes(since, cursor) } catch (err) { if (err instanceof ChangesUnavailableError) return this.reconcile() throw err } await this.store.batch(async () => { for (const change of page.changes) await this.applyChange(change) }) this.progress() head = page.head ?? head cursor = page.cursor } while (cursor) if (head) await this.store.setMeta('head', head) }
private async applyChange(change: RemoteChange): Promise<void> { if (change.version === null) return this.applyRemote(change.id, null, null) if (change.record === undefined || this.store.get(change.id)?.version === change.version) return const content = this.decode(change.id, change.record) if (content) await this.applyRemote(change.id, change.version, content) else this.result.undecryptable++ }
private async reconcile(reencode = false): Promise<void> { const seen = new Set<string>() let head: string | undefined let cursor: string | undefined do { const page = await this.remote.list(cursor) head ??= page.head await this.store.batch(async () => { for (const remoteRecord of page.records) { seen.add(remoteRecord.id) const local = this.store.get(remoteRecord.id) const known = local?.version === remoteRecord.version ? local : undefined if (known && !reencode) continue const content = this.decode(remoteRecord.id, remoteRecord.record) // A record that does not decode is lost for all devices. A local copy replaces it, even an older one. if (content && !known) await this.applyRemote(remoteRecord.id, remoteRecord.version, content) else if (!content && local && !local.dirty) await this.store.put({ ...local, dirty: true }) else if (!content && !local) this.result.undecryptable++ } }) this.progress() cursor = page.cursor } while (cursor)
await this.store.batch(async () => { for (const note of this.store.all()) { if (note.version !== null && !seen.has(note.id)) await this.applyRemote(note.id, null, null) } }) if (head) await this.store.setMeta('head', head) await this.store.setMeta('reconciledAt', String(this.now())) }
private async applyRemote(id: string, version: string | null, remote: NoteContent | null): Promise<void> { const local = this.store.get(id)
if (version === null || remote === null) { if (!local) return if (local.dirty && !local.deleted) return this.store.put({ ...local, version: null }) this.result.pulled++ return this.store.remove(id) }
this.result.pulled++ const clean: LocalNote = { id, content: remote, version, dirty: false, deleted: false } if (!local || local.deleted) return this.store.put(clean) // Edits only increase modifiedAt, so an older remote copy replaced a newer one. Upload the newer one again. if (!local.dirty && local.content.modifiedAt > remote.modifiedAt) return this.store.put({ ...local, version, dirty: true }) if (!local.dirty) return this.store.put(clean)
const localWins = local.content.modifiedAt > remote.modifiedAt if (sameText(local.content, remote)) { return this.store.put(localWins ? { ...local, version } : clean) }
this.result.conflicts++ const loser = localWins ? remote : local.content await this.store.put(localWins ? { ...local, version } : clean) await this.store.put({ id: this.codec.newId(), content: { ...loser, ...unpin(loser), title: conflictTitle(loser.title) }, version: null, dirty: true, deleted: false, }) }
private async push(): Promise<void> { for (const note of this.store.all().filter((candidate) => candidate.dirty)) { if (note.deleted) { if (note.version !== null) await this.remote.delete(note.id) if (this.store.get(note.id)?.deleted) await this.store.remove(note.id) this.result.pushed++ continue }
const { version } = await this.remote.put(note.id, this.codec.encode(note.id, note.content)) this.result.pushed++ const current = this.store.get(note.id) if (!current) continue const unchanged = !current.deleted && current.content.modifiedAt === note.content.modifiedAt await this.store.put({ ...current, version, dirty: !unchanged }) } }}