P2-04: coalesce facade autosaves

This commit is contained in:
2026-08-02 05:21:31 -04:00
parent 5f0d9a8d0e
commit feb2eb8be6
5 changed files with 51 additions and 6 deletions

View File

@@ -35,6 +35,35 @@ export class PersistenceWriteQueue {
}
}
export class ProjectAutosaveScheduler {
private timer: ReturnType<typeof setTimeout> | null = null
private pending: DocumentSnapshot | null = null
private flushPromise: Promise<ProjectSaveResult | null> | null = null
constructor(private readonly save: (document: DocumentSnapshot) => Promise<ProjectSaveResult>, private readonly idleMs = 800) {}
schedule(document: DocumentSnapshot) {
this.pending = cloneDocument(document)
if (this.timer) clearTimeout(this.timer)
this.timer = setTimeout(() => { this.timer = null; void this.flush() }, this.idleMs)
}
flush() {
if (this.flushPromise) return this.flushPromise
const document = this.pending
this.pending = null
if (!document) return Promise.resolve(null)
this.flushPromise = this.save(document).finally(() => { this.flushPromise = null; if (this.pending) void this.flush() })
return this.flushPromise
}
cancel() {
if (this.timer) clearTimeout(this.timer)
this.timer = null
this.pending = null
}
}
export class SqliteProjectPersistence implements ProjectPersistenceClient {
private readonly worker: Worker | null
private nextRequestId = 0