// saver.mjs — autosave, commit and rebase (spec §6.5). Everything the // page writes goes through here, and every write is a POST from this // tab: nothing runs on the server. // // - Autosave fires 1.2s after typing stops, with the §6.4 structure // check, and only when the text differs from what was last stored. // It writes the person's draft, never the page. // - A tab's own draft: sessionStorage keeps the last draft version this // tab wrote (mapa-draft:), so a reload still knows it. Only an // own draft commits by itself (⌘S, two minutes idle, leaving inside // Mapa, closing the tab); an offered one commits only on Save. // - The reply's merge: a clean one is applied when nothing was typed // since the send, the table rebuilt against it, and the base moved by // the version-checked rebase POST; three tries at most, then the // commit's own merge settles it. A conflict is shown inline (the ui's // job, conflict.mjs) and only the person's choice commits it. // - Some states hold commits but never the text (review H1, M2): a // conflict open, a page deleted under the editor, the draft bar's // "Show the saved version". Typing still autosaves the draft, and a // closing tab still writes it, without commit=1. // - A commit is a reply carrying a revision; anything else (an emptied // day, a page deleted under the commit) commits nothing (review H2). // - A new scratch page's first autosave is its first commit, keyed by a // token the tab draws once (D12, build note 31). // // The editor, the network, storage, timers and the page around it are // all passed in, so the gates can drive it without a browser. import { cleanBody, goTrimSpace, Grammar } from './markup.mjs' export const AUTOSAVE_DELAY = 1200 export const IDLE_COMMIT = 2 * 60 * 1000 // keepaliveCap is under the browsers' 64KB keepalive limit, with room // for the other fields. export const KEEPALIVE_CAP = 60 * 1024 const RETRIES = 3 export function drawToken (random = () => Math.random()) { const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789' let token = '' for (let index = 0; index < 24; index++) token += alphabet[Math.floor(random() * alphabet.length)] return token } export class Saver { constructor (island, deps) { this.deps = deps this.drafts = island.drafts this.page = island.page ?? '' this.token = island.first ? (deps.token ?? drawToken)() : null this.base = island.draft ? island.draft.base : island.base this.version = island.draft ? island.draft.version : '0' this.own = Boolean(island.draft) && this.stored() === island.draft.version // closed is the version this tab's last page sent to be committed as // it went: a page loaded meanwhile (a reload) may still show it. this.closed = Boolean(island.draft) && this.stored('mapa-closing:') === island.draft.version this.offered = Boolean(island.draft) && !this.own // saved is the text the server holds for this tab: the draft's, or // the committed page's. this.saved = cleanBody(island.source) this.loadedVersion = this.version this.dirty = false this.inflight = null this.tries = new Map() this.conflict = null // gone: the page was deleted while this tab wrote. Its text goes on // being stored as the draft, which Today offers as a scratch page, // and nothing commits (review H1). this.gone = false // orphan: the page was deleted before this tab stored any draft on // it, so the store refuses the draft (404) and nothing typed is // stored. The bar offers it as a new scratch page; a close makes one // (review round 4, M-B). this.orphan = false // holding: commits are held (the draft bar's Show the saved version) // while the text is still stored (review M2). this.holding = false // resolving: Resolve's POST is out; the editor takes no typing until // its answer is applied (review M1). this.resolving = false this.stopped = false this.failures = 0 // unacked is the text of an autosave that never answered (offline, // or aborted by post's timeout): it may have landed all the same. this.unacked = null this.timers = { autosave: null, idle: null, retry: null } } get key () { return `mapa-draft:${this.drafts}` } stored (prefix = 'mapa-draft:') { try { return this.deps.storage?.get(prefix + this.drafts) ?? null } catch { return null } } remember () { try { this.deps.storage?.set(this.key, this.version) } catch {} } forget () { try { this.deps.storage?.remove(this.key) } catch {} } status (state) { this.deps.ui?.status?.(state) } later (name, fn, ms) { const timers = this.deps.timers ?? globalThis if (this.timers[name] !== null) timers.clearTimeout(this.timers[name]) this.timers[name] = timers.setTimeout(() => { this.timers[name] = null fn() }, ms) } cancel (name) { const timers = this.deps.timers ?? globalThis if (this.timers[name] !== null) timers.clearTimeout(this.timers[name]) this.timers[name] = null } // changed is the person typing: the draft becomes this tab's own. changed () { if (this.stopped) return this.dirty = true this.own = true this.offered = false this.cancel('idle') this.later('autosave', () => this.autosave(), this.deps.delay ?? AUTOSAVE_DELAY) } // unsaved is whether the tab holds text the server does not. unsaved () { return this.dirty || this.deps.editor.current() !== this.saved } // committable is whether there is a draft of this tab's to commit. committable () { return this.own && (this.unsaved() || this.version !== '0') } // mayCommit is whether the draft may commit by itself now: never with // a choice open, a page deleted, or commits held. mayCommit () { return !this.conflict && !this.gone && !this.holding } // hold keeps the draft from committing from now on, while what is // typed is still stored (the draft bar's Show the saved version). hold () { this.holding = true this.cancel('idle') } // autosave sends the text when it differs from what is stored (or // always, with force: to ask for the merge again). It resolves true // when the text is stored. autosave (force = false) { if (this.stopped || this.orphan) return Promise.resolve(false) if (this.inflight) return this.inflight.then(() => this.autosave(force)) this.cancel('autosave') const body = this.deps.editor.prepare() if (!force && body === this.saved) { this.dirty = false return Promise.resolve(true) } this.dirty = false this.status('saving') const send = this.token ? this.first(body) : this.send(body) this.inflight = send.finally(() => { this.inflight = null }) return this.inflight } async send (body) { let reply try { reply = await this.deps.post(this.drafts, { base: this.base, version: this.version, body }) } catch { this.unacked = body return this.offline() } if (reply.status === 409) { this.stale(reply.json) return false } this.unacked = null if (reply.status === 404) return this.orphaned() if (reply.status !== 200) return this.offline() this.failures = 0 this.stored_(body, reply.json) await this.behind(reply.json.merge, body) return true } // stored_ takes an autosave's answer for body. stored_ (body, reply) { this.version = reply.version this.saved = body this.own = true this.remember() this.status(this.gone ? 'draft' : 'saved') if (this.mayCommit()) this.later('idle', () => this.commit(), this.deps.idle ?? IDLE_COMMIT) } // offline keeps the text and tries again, then says it failed. offline () { this.dirty = true this.failures++ if (this.failures > RETRIES) { this.status('failed') return false } this.status('retrying') this.later('retry', () => this.autosave(), (this.deps.delay ?? AUTOSAVE_DELAY) * 2 ** this.failures) return false } // first is a new scratch page's autosave before it has an address: // the first one creates the page, any later one with the token is a // draft on it. An empty page creates nothing. async first (body) { if (goTrimSpace(body) === '') { this.status('idle') return true } let reply try { reply = await this.deps.post('/scratch', { first: this.token, version: this.version, body }) } catch { return this.offline() } if (reply.status === 422) { this.status('idle') return true } if (reply.status !== 200) return this.offline() this.failures = 0 const answer = reply.json this.token = null this.page = answer.page this.drafts = `/p/${answer.page}/draft` this.deps.replaceURL?.(answer.href) if (answer.version === undefined) { this.base = answer.revision this.saved = body this.status('saved') return true } if (answer.revision !== undefined) this.base = this.base === '0' ? answer.revision : this.base this.stored_(body, answer) await this.behind(answer.merge, body) return true } // behind takes the merge an autosave's reply carried, if any. A reply // without a conflict ends any choice on show, whatever it carries // (review M4): a clean merge not applied because of typing included. async behind (merge, sent) { if (this.conflict && !merge?.conflict) this.settled() if (!merge) return if (merge.gone) { this.lost() return } if (merge.noBase) { this.cancel('idle') this.deps.ui?.notice?.('noBase', { page: this.page }) return } if (merge.conflict) { this.cancel('idle') if (this.deps.editor.current() !== sent) { this.later('autosave', () => this.autosave(true), 0) return } // The same hunks for a newer version (an edit elsewhere) keep the // choice on show, and what the person has picked in it. if (this.conflict && sameHunks(this.conflict, merge)) { this.conflict = { ...this.conflict, version: this.version, sent } return } this.conflict = { against: merge.against, version: this.version, hunks: merge.hunks, sent } this.deps.ui?.conflict?.(this.conflict) return } await this.rebase(merge.against, merge.body, sent) } // orphaned is a 404 from the drafts route: the page was deleted, and // this tab has no draft on it for the store to keep. Nothing more is // sent there; the bar offers the text as a new scratch page. orphaned () { this.cancel('idle') this.cancel('retry') this.dirty = true this.gone = true this.status('orphan') if (!this.orphan) this.deps.ui?.notice?.('orphan', {}) this.orphan = true return false } // lost is the page deleted under the editor (review H1): the text is // kept as the draft, still autosaved, and nothing commits. The bar // offers Save as a scratch page or Discard. lost () { this.cancel('idle') this.status('draft') if (this.gone) return this.gone = true this.deps.ui?.notice?.('gone', { page: this.page, version: this.version }) } // rebase is §6.5's clean merge: apply M, rebuild, check, move the base. async rebase (against, merged, sent) { if (this.deps.editor.current() !== sent) { this.later('autosave', () => this.autosave(true), 0) return } const tries = this.tries.get(against) ?? 0 if (tries >= RETRIES) return const { ok } = this.deps.editor.apply(merged) if (!ok) { this.tries.set(against, tries + 1) return } const body = this.deps.editor.current() let reply try { reply = await this.deps.post(this.drafts, { base: this.base, version: this.version, body, rebase: against }) } catch { return } if (reply.status === 409) { this.stale(reply.json) return } if (reply.status !== 200) return this.base = against this.version = reply.json.version this.saved = body this.remember() } // stale is the 409 a newer draft from another tab answers: this tab // shows that draft, offered, and never overwrites it (build note 31). stale (reply) { this.cancel('idle') if (reply?.committed) { this.recover() return } if (this.landed(reply)) return this.deps.editor.apply(reply.body) this.version = reply.version this.saved = this.deps.editor.current() this.dirty = false this.own = false this.offered = true this.forget() this.deps.ui?.notice?.('newer', {}) this.status('saved') } // landed is a 409 whose newer draft is this tab's own autosave that // never answered but was stored (review round 4): the tab takes its // version and goes on, typing since included, instead of replacing // the typing with it. landed (reply) { const sent = this.unacked this.unacked = null if (sent === null || reply?.body !== cleanBody(sent)) return false this.version = reply.version this.saved = sent this.own = true this.remember() this.status('saved') if (this.deps.editor.current() !== this.saved) this.later('autosave', () => this.autosave(), 0) return true } // recover is a draft committed meanwhile: by this tab's own closing // request as it went (build note 38), or by another tab. Nothing stops // (review H1): what is typed from here is a new draft. When the page // now holds exactly what the draft held, it starts from that revision; // otherwise from the old base, and the server's merge keeps both // sides. An offered draft, which this tab never typed into, shows the // page as it now is. async recover () { const held = this.saved let fresh = null try { fresh = await this.deps.refetch?.() } catch {} const page = fresh && !fresh.draft ? fresh : null if (page && cleanBody(page.source) === held) this.base = page.base this.version = '0' this.forget() this.offered = false if (this.own) { this.dirty = true this.later('autosave', () => this.autosave(true), 0) return } if (page && this.deps.editor.current() === held) { this.deps.editor.apply(page.source) this.base = page.base this.saved = this.deps.editor.current() } this.deps.ui?.notice?.('committed', {}) } // flush stores what is typed; false when it could not be stored. async flush () { this.cancel('autosave') if (this.unsaved() || this.inflight) { const stored = await this.autosave() if (!stored || this.unsaved()) return false } return true } // commit commits the draft: the person's own, or any on Save // (explicit). It answers what happened, for leaving. async commit ({ explicit = false } = {}) { if (this.stopped || (!this.own && !explicit)) return 'none' if (this.orphan) return 'orphan' if (this.conflict) return 'conflict' this.cancel('idle') if (!(await this.flush())) { if (this.orphan) return 'orphan' return this.own && !this.stopped ? 'flush-failed' : 'stale' } // The flush's own reply may have opened a choice or found the page // deleted: then the text is stored, and nothing commits. if (this.conflict) return 'conflict' if (this.gone || this.holding) return this.gone ? 'gone' : 'held' if (this.version === '0') return 'none' const sent = this.saved let reply try { reply = await this.deps.post(`${this.drafts}/save`, { version: this.version }) } catch { return 'commit-failed' } if (reply.status === 409) { this.stale(reply.json) return 'stale' } if (reply.status !== 200) return 'commit-failed' return this.committed(reply.json, sent) } // committed takes a commit's answer. Only a reply carrying a revision // is a commit (review H2). async committed (answer, sent) { if (answer.empty) { // An emptied day: the server dropped the draft and wrote nothing. // The next text typed is a new draft. this.version = '0' this.forget() this.offered = false this.status('idle') this.deps.ui?.committed?.({}) return 'empty' } if (answer.gone) { this.lost() return 'gone' } if (!answer.saved) { if (/\/conflict$/u.test(answer.href ?? '')) { await this.autosave(true) return this.conflict ? 'conflict' : 'nobase' } // Kept: committed, but a newer draft of this person's stays; the // autosave's 409 brings it here, offered. await this.autosave(true) return 'kept' } if (answer.revision === undefined) return 'commit-failed' this.version = '0' this.forget() this.offered = false this.status('saved') // A day's first commit makes its page: Resolve and Make team page // need its address. const made = /^\/p\/([^/?#]+)/u.exec(answer.href ?? '') if (made && !this.page) this.page = made[1] if (answer.merged && this.deps.editor.current() === sent) { this.deps.editor.apply(answer.body) this.saved = this.deps.editor.current() this.base = answer.revision } else if (!answer.merged) { this.base = answer.revision } this.deps.ui?.committed?.(answer) return answer.merged ? 'merged' : 'saved' } // resolve posts the person's choice for each conflicting hunk, with // the version whose reply carried them (§6.5, N3). Text typed since // that reply is stored first, so Resolve commits from the text on // screen, and the editor takes no typing until the answer is applied: // the answer never lands over text it did not include (review M1). async resolve (choices) { if (!this.conflict || !this.page || this.resolving) return 'none' this.resolving = true try { return await this.resolveNow(choices) } finally { this.resolving = false } } async resolveNow (choices) { const shown = this.conflict if (this.deps.editor.current() !== shown.sent) { if (!(await this.flush())) return 'failed' // A different choice came back: it is on show, to choose again. if (this.conflict?.hunks !== shown.hunks) return 'conflicted' } const conflict = this.conflict const fields = { current: conflict.against, version: conflict.version, grammar: String(Grammar) } choices.forEach((choice, index) => { fields[`choice-${index}`] = choice }) let reply try { reply = await this.deps.post(`/p/${this.page}/resolve`, fields) } catch { return 'failed' } if (reply.status !== 200) return 'failed' const { outcome, revision, body } = reply.json if ((outcome === 'saved' || outcome === 'merged') && this.deps.editor.current() === conflict.sent) { this.settled() this.deps.editor.apply(body) this.saved = this.deps.editor.current() this.base = revision this.version = '0' this.forget() this.status('saved') this.deps.ui?.committed?.(reply.json) return 'saved' } if (outcome === 'noBase') { this.deps.ui?.notice?.('noBase', { page: this.page }) return 'nobase' } await this.autosave(true) return 'conflicted' } // took is a body the server wrote for this page and answered (Make // team page's note): the editor shows it and takes its revision. took (body, revision) { this.deps.editor.apply(body) this.saved = this.deps.editor.current() this.base = revision this.version = '0' this.forget() this.deps.ui?.committed?.({}) } // renamed is a rename of this page, made over revision from, which // minted to (title.mjs). A rename's revision holds exactly from's // body, so a base of from is a base of to: the store moved the // person's draft with it (carryDrafts), and this tab's base follows, // so a draft it starts from here is not merged against a revision // that changed nothing. Any other base stays; the merge settles it. renamed (from, to) { if (from && from !== '0' && to && this.base === from) this.base = to } // settled clears the inline choice. settled () { this.conflict = null this.deps.ui?.conflict?.(null) } // leave is following a link inside Mapa (§6.5): commit first, then // go; or stay, with the choice, when there is one to make. async leave (href) { if (!this.committable()) return this.deps.navigate(href) const outcome = await this.commit() if (outcome === 'conflict') { this.deps.ui?.leaving?.('conflict', () => { this.forget() this.stopped = true this.deps.navigate(href) }) return } if (outcome === 'flush-failed' || outcome === 'orphan') { this.deps.ui?.leaving?.(outcome === 'orphan' ? 'orphan' : 'failed', () => { this.stopped = true this.deps.navigate(href) }) return } this.deps.navigate(href) } // settle is a page loaded while its draft was being committed by the // page before (a reload, build note 38): it asks the server again, a // GET, until the draft is gone or plainly stays, and takes what the // page now holds as its base. async settle (tries = 8, wait = 150) { if (!this.closed) return for (let round = 0; round < tries; round++) { if (round > 0) await new Promise(resolve => (this.deps.timers ?? globalThis).setTimeout(resolve, wait)) let fresh = null try { fresh = await this.deps.refetch?.() } catch {} if (!fresh || fresh.draft?.version === this.version) continue if (this.version !== this.loadedVersion) return if (!fresh.draft) this.settled_(fresh) else this.newer(fresh) this.closed = false return } this.closed = false } // settled_ is the draft found committed. When the page holds exactly // its text, the tab goes on from that revision. Otherwise a merge put // a teammate's text in too: what is typed from here is a new draft // from the old base, as recover() does, so the server's merge keeps // both, and a close sends version 0, never the committed version, // which the store would refuse (review round 4, M-A). settled_ (fresh) { if (cleanBody(fresh.source) === this.saved) { this.base = fresh.base this.deps.ui?.committed?.({ settled: true }) } this.version = '0' this.forget() } // newer is a draft other than the one this page loaded, found while // settling (another tab wrote it). With nothing typed here yet the tab // shows it, offered, so typing goes on from it instead of being // replaced by it at the next autosave's 409 (review round 4). newer (fresh) { if (this.unsaved()) return this.deps.editor.apply(fresh.source) this.saved = this.deps.editor.current() this.version = fresh.draft.version this.base = fresh.draft.base this.own = false this.offered = true this.forget() this.deps.ui?.notice?.('newer', {}) } // closing is pagehide (D3): one keepalive POST, with commit=1, the // tab's draft version and any text not yet sent; past the keepalive // cap it carries no text and commits the last autosave. While commits // are held (a choice open, a page deleted, Show the saved version), // the text not yet sent is still written, as the draft only (review // M2). The text is the structure check's, as autosave's is. closing ({ reloading = false } = {}) { if (this.stopped) return if (this.token) return this.closingFirst() const body = this.deps.editor.prepare() if (this.orphan) return this.closingOrphan(body) const unsent = body !== this.saved if (!this.mayCommit()) { if (unsent && this.own && byteLength(body) <= KEEPALIVE_CAP) this.keep(body) return } if (!this.committable()) return // A reload is not a close: a draft already stored stays this tab's // own, and the page it loads offers it to no one but this tab. if (reloading && !unsent && !this.dirty) return const fields = { commit: '1', version: this.version, base: this.base } if (unsent && byteLength(body) <= KEEPALIVE_CAP) fields.body = body // Still settling: the version the page showed may be committed // already, or not; settling=1 asks the store to take either, so the // text is written whichever it was (build note 38, review M3). if (this.closed && this.version === this.loadedVersion) fields.settling = '1' if (fields.body === undefined && this.version === '0') return try { this.deps.storage?.set(`mapa-closing:${this.drafts}`, this.version) } catch {} this.deps.post(this.drafts, fields, { keepalive: true }).catch(() => {}) this.cancel('autosave') this.cancel('idle') this.dirty = false this.saved = body this.version = '0' this.forget() } // closingFirst is a new scratch page closing before its first commit // was answered: the text goes with the token, as autosave's would. closingFirst () { if (!this.committable()) return const body = this.deps.editor.prepare() if (goTrimSpace(body) !== '' && byteLength(body) <= KEEPALIVE_CAP) { this.deps.post('/scratch', { first: this.token, version: this.version, body }, { keepalive: true }).catch(() => {}) } this.dirty = false } // closingOrphan keeps what was typed on a page deleted before any of // it was stored: one keepalive POST /scratch makes it a scratch page // of the person's own, as the bar's button would have. closingOrphan (body) { if (!this.own || goTrimSpace(body) === '' || byteLength(body) > KEEPALIVE_CAP) return this.deps.post('/scratch', { body }, { keepalive: true }).catch(() => {}) this.stopped = true } // keep writes the text as the draft only, on the way out. keep (body) { this.deps.post(this.drafts, { base: this.base, version: this.version, body }, { keepalive: true }).catch(() => {}) this.cancel('autosave') this.cancel('idle') this.dirty = false this.saved = body } // shown is pageshow from the back/forward cache: with nothing // unsaved, the page is loaded again; otherwise autosave at once. shown () { if (this.unsaved()) { this.autosave(true) return } this.deps.reload?.() } } // sameHunks is whether a reply's conflict is the one on show: the same // revision and the same three sides of every hunk. function sameHunks (conflict, merge) { if (conflict.against !== merge.against || conflict.hunks.length !== merge.hunks.length) return false return conflict.hunks.every((hunk, index) => { const other = merge.hunks[index] return hunk.base === other.base && hunk.mine === other.mine && hunk.theirs === other.theirs }) } function byteLength (text) { return new TextEncoder().encode(text).length }