Add version history with rollback and per-note created/synced info
Server (schema v2, auto-migrates): every accepted overwrite snapshots the
superseded revision into note_history (capped at 50 per note); new
GET /api/v1/notes/{id}/history endpoint; compact purges orphaned history.
Client: notes get a synced_at stamp on every confirmed server exchange;
an info footer under the editor and a Ctrl/Cmd+I panel show created/
modified/last-synced plus the revision list. Restoring a revision applies
it as a normal edit through the sync path, so rollback is non-destructive.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
@@ -31,6 +31,7 @@ Open `http://localhost:8420`, click `⋯` → set server URL + token → Save.
|
||||
| `Ctrl/Cmd+Shift+P` | toggle markdown preview (`[[wiki-links]]` open/create notes) |
|
||||
| `Ctrl/Cmd+K` | cycle tag filter |
|
||||
| `Ctrl/Cmd+J` / `+Shift` | next / previous note while editing |
|
||||
| `Ctrl/Cmd+I` | note info (created / last synced) & version history |
|
||||
|
||||
## CLI
|
||||
|
||||
@@ -96,6 +97,12 @@ edits of the same note never silently overwrite: the loser comes back as a new n
|
||||
tagged `conflict` with “(conflicted copy …)” in its title. Delete-vs-edit: the edit wins.
|
||||
Every client keeps a full offline copy in IndexedDB; a crash mid-sync loses nothing.
|
||||
|
||||
**Version history:** every time an accepted sync overwrites a note, the server keeps the
|
||||
previous state (last 50 revisions per note). `Ctrl/Cmd+I` (or the “History” button under
|
||||
the editor) shows a note’s revisions; restoring one applies the old text as a new edit,
|
||||
so the replaced text itself stays in history — rollback is never destructive.
|
||||
`tefterd compact` drops history along with the purged notes.
|
||||
|
||||
## Development
|
||||
|
||||
```sh
|
||||
|
||||
14
SPEC.md
14
SPEC.md
@@ -92,17 +92,29 @@ CREATE TABLE notes (
|
||||
CREATE INDEX idx_notes_version ON notes(version);
|
||||
|
||||
CREATE TABLE meta (k TEXT PRIMARY KEY, v TEXT); -- schema_version, next_version counter
|
||||
|
||||
CREATE TABLE note_history ( -- schema v2: version history
|
||||
note_id TEXT NOT NULL,
|
||||
version INTEGER NOT NULL, -- version of the superseded revision
|
||||
content TEXT NOT NULL DEFAULT '',
|
||||
tags TEXT NOT NULL DEFAULT '[]',
|
||||
modified_at INTEGER NOT NULL,
|
||||
replaced_at INTEGER NOT NULL, -- unix ms when it was overwritten
|
||||
PRIMARY KEY (note_id, version)
|
||||
);
|
||||
```
|
||||
|
||||
- **Title is derived**, never stored: first non-empty line of `content`, markdown heading markers stripped for display.
|
||||
- `version` is a single global monotonically increasing counter (like a Lamport clock per server). Every accepted write bumps the global counter and stamps the note. This makes "give me everything changed since cursor X" trivial.
|
||||
- Tombstones are kept forever (personal scale; millions of notes are not expected). A `tefterd compact` subcommand may purge tombstones older than N days.
|
||||
- **Version history:** whenever an accepted push overwrites an existing note (fast-forward or edit-over-tombstone), the superseded state is copied into `note_history`, capped at the newest 50 revisions per note. Conflict pushes touch nothing, so they record nothing. `compact` purges history rows of notes that no longer exist. Rollback is client-side: fetch a revision, apply its content as a normal edit.
|
||||
|
||||
### Client store (IndexedDB)
|
||||
|
||||
Object store `notes`: same fields as server, plus:
|
||||
- `dirty: boolean` — locally modified, not yet pushed.
|
||||
- `baseVersion: number` — server version this local copy was derived from (0 for never-synced).
|
||||
- `synced_at?: number` — unix ms of the last confirmed exchange with the server for this note (accepted push or applied pull); absent = never synced.
|
||||
|
||||
Object store `meta`: `cursor` (last server version pulled), `serverUrl`, `token`.
|
||||
|
||||
@@ -116,6 +128,7 @@ Design: **pull-then-push, last-write-wins with conflict copies** (Simplenote-sty
|
||||
|---|---|---|
|
||||
| GET | `/changes?since=<cursor>&limit=500` | Pull notes with `version > cursor`, ordered by version. Returns `{notes: [...], cursor: <max version returned>, more: bool}` |
|
||||
| POST | `/notes/batch` | Push local changes. Body: `{notes: [{id, content, tags, created_at, modified_at, deleted, baseVersion}]}` |
|
||||
| GET | `/notes/{id}/history` | Superseded revisions of a note, newest first: `{revisions: [{note_id, version, content, tags, modified_at, replaced_at}]}` (empty list for unknown ids) |
|
||||
| GET | `/health` | Liveness + schema version |
|
||||
| POST | `/import/simplenote` | Multipart upload of Simplenote export zip (also available as CLI) |
|
||||
|
||||
@@ -187,6 +200,7 @@ This section is the heart of the product. The NV model must be reproduced exactl
|
||||
| Cmd/Ctrl+Shift+P | Toggle markdown preview for current note |
|
||||
| Cmd/Ctrl+K | Cycle tag filter (simple tag dropdown) |
|
||||
| Cmd/Ctrl+J / Cmd/Ctrl+Shift+J | Next / previous note in list while in editor |
|
||||
| Cmd/Ctrl+I | Note info (created / modified / last synced) + version history panel; a revision can be previewed and restored (restore = normal edit, non-destructive) |
|
||||
|
||||
### Editor
|
||||
- CodeMirror 6, markdown mode, light syntax styling only (bold headings, dim syntax marks). Monospace or user-set font. No WYSIWYG.
|
||||
|
||||
@@ -102,10 +102,11 @@ export async function applyServerNote(sn: ServerNote): Promise<void> {
|
||||
export async function applyServerNotes(sns: ServerNote[]): Promise<void> {
|
||||
const m = get(notes);
|
||||
const updates: Note[] = [];
|
||||
const now = Date.now();
|
||||
for (const sn of sns) {
|
||||
const local = m.get(sn.id);
|
||||
if (local && local.dirty) continue; // push will resolve
|
||||
updates.push({ ...sn, baseVersion: sn.version, dirty: false });
|
||||
updates.push({ ...sn, baseVersion: sn.version, dirty: false, synced_at: now });
|
||||
}
|
||||
if (!updates.length) return;
|
||||
notes.update((map) => {
|
||||
@@ -120,14 +121,14 @@ export async function markPushed(id: string, sentModifiedAt: number, version: nu
|
||||
const n = get(notes).get(id);
|
||||
if (!n) return;
|
||||
const stillSame = n.modified_at === sentModifiedAt;
|
||||
const upd: Note = { ...n, version, baseVersion: version, dirty: stillSame ? false : n.dirty };
|
||||
const upd: Note = { ...n, version, baseVersion: version, dirty: stillSame ? false : n.dirty, synced_at: Date.now() };
|
||||
mutate(upd);
|
||||
await idbPutNote(upd);
|
||||
}
|
||||
|
||||
/** After a conflict: server truth replaces local; conflict copy arrives via next pull. */
|
||||
export async function replaceWithServer(sn: ServerNote): Promise<void> {
|
||||
const upd: Note = { ...sn, baseVersion: sn.version, dirty: false };
|
||||
const upd: Note = { ...sn, baseVersion: sn.version, dirty: false, synced_at: Date.now() };
|
||||
mutate(upd);
|
||||
await idbPutNote(upd);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { writable, get } from 'svelte/store';
|
||||
import type { PushResult, ServerNote, SyncState } from '../types';
|
||||
import type { PushResult, Revision, ServerNote, SyncState } from '../types';
|
||||
import { notes, settings, cursor, setCursor, applyServerNotes, markPushed, replaceWithServer } from '../db/store';
|
||||
|
||||
export const syncState = writable<SyncState>('local');
|
||||
@@ -66,6 +66,15 @@ async function push(): Promise<void> {
|
||||
}
|
||||
}
|
||||
|
||||
/** Fetch a note's server-side revision history (newest first). */
|
||||
export async function fetchHistory(id: string): Promise<Revision[]> {
|
||||
if (!configured()) throw new Error('no server configured');
|
||||
const res = await api(`/api/v1/notes/${encodeURIComponent(id)}/history`);
|
||||
if (!res.ok) throw new Error(`history: HTTP ${res.status}`);
|
||||
const body: { revisions: Revision[] } = await res.json();
|
||||
return body.revisions;
|
||||
}
|
||||
|
||||
/** Pull-then-push; safe to interrupt at any point (SPEC §4). */
|
||||
export async function syncNow(): Promise<void> {
|
||||
if (!configured()) {
|
||||
|
||||
13
frontend/src/time.ts
Normal file
13
frontend/src/time.ts
Normal file
@@ -0,0 +1,13 @@
|
||||
/** Absolute timestamp for metadata display, e.g. "Jul 25, 2026, 14:03". */
|
||||
export function fmtDateTime(ms: number): string {
|
||||
return new Date(ms).toLocaleString(undefined, { dateStyle: 'medium', timeStyle: 'short' });
|
||||
}
|
||||
|
||||
/** Coarse relative timestamp: "just now", "5 min ago", "3 h ago", else absolute. */
|
||||
export function fmtAgo(ms: number, now: number = Date.now()): string {
|
||||
const d = now - ms;
|
||||
if (d < 60_000) return 'just now';
|
||||
if (d < 3_600_000) return `${Math.floor(d / 60_000)} min ago`;
|
||||
if (d < 86_400_000) return `${Math.floor(d / 3_600_000)} h ago`;
|
||||
return fmtDateTime(ms);
|
||||
}
|
||||
@@ -8,6 +8,17 @@ export interface Note {
|
||||
version: number; // server-assigned version of the copy we derived from (0 = never synced)
|
||||
baseVersion: number; // server version this local copy was derived from
|
||||
dirty: boolean; // locally modified, not yet pushed
|
||||
synced_at?: number; // unix ms of last confirmed server exchange (absent = never synced)
|
||||
}
|
||||
|
||||
/** A superseded note state kept server-side (GET /notes/{id}/history). */
|
||||
export interface Revision {
|
||||
note_id: string;
|
||||
version: number;
|
||||
content: string;
|
||||
tags: string[];
|
||||
modified_at: number;
|
||||
replaced_at: number;
|
||||
}
|
||||
|
||||
export interface ServerNote {
|
||||
|
||||
@@ -10,13 +10,17 @@
|
||||
import Preview from './Preview.svelte';
|
||||
import StatusDot from './StatusDot.svelte';
|
||||
import SettingsMenu from './SettingsMenu.svelte';
|
||||
import NoteInfo from './NoteInfo.svelte';
|
||||
import Toast from './Toast.svelte';
|
||||
import { fmtDateTime, fmtAgo } from '../time';
|
||||
|
||||
let query = '';
|
||||
let selectedId: string | null = null;
|
||||
let tagFilter: string | null = null;
|
||||
let preview = false;
|
||||
let menuOpen = false;
|
||||
let infoOpen = false;
|
||||
let now = Date.now(); // periodic tick so "synced X ago" stays fresh
|
||||
let narrow = false;
|
||||
let mobileView: 'list' | 'editor' = 'list';
|
||||
let toast: { message: string; onAction: () => void } | null = null;
|
||||
@@ -142,6 +146,9 @@
|
||||
} else if (mod && e.shiftKey && e.key.toLowerCase() === 'p') {
|
||||
e.preventDefault();
|
||||
if (selected) preview = !preview;
|
||||
} else if (mod && !e.shiftKey && e.key.toLowerCase() === 'i') {
|
||||
e.preventDefault();
|
||||
if (selected) infoOpen = !infoOpen;
|
||||
} else if (mod && !e.shiftKey && e.key.toLowerCase() === 'k') {
|
||||
e.preventDefault();
|
||||
cycleTag();
|
||||
@@ -161,13 +168,17 @@
|
||||
narrow = mq.matches;
|
||||
const onMq = () => (narrow = mq.matches);
|
||||
mq.addEventListener('change', onMq);
|
||||
const tick = setInterval(() => (now = Date.now()), 30_000);
|
||||
omnibar?.focus();
|
||||
// First run: offer server config; Cancel = work locally only (SPEC §7).
|
||||
if (!localStorage.getItem('tefter-first-run-done')) {
|
||||
localStorage.setItem('tefter-first-run-done', '1');
|
||||
if (!notesArr.length && !$settings.serverUrl) menuOpen = true;
|
||||
}
|
||||
return () => mq.removeEventListener('change', onMq);
|
||||
return () => {
|
||||
mq.removeEventListener('change', onMq);
|
||||
clearInterval(tick);
|
||||
};
|
||||
});
|
||||
</script>
|
||||
|
||||
@@ -219,6 +230,24 @@
|
||||
<p>Type to search — <kbd>Enter</kbd> creates a note when nothing matches.</p>
|
||||
</div>
|
||||
{/if}
|
||||
{#if selected}
|
||||
<div class="note-meta">
|
||||
<span>Created {fmtDateTime(selected.created_at)}</span>
|
||||
<span class="meta-sep">·</span>
|
||||
<span>
|
||||
{#if selected.dirty}
|
||||
Sync pending
|
||||
{:else if selected.synced_at}
|
||||
Synced {fmtAgo(selected.synced_at, now)}
|
||||
{:else}
|
||||
Not synced
|
||||
{/if}
|
||||
</span>
|
||||
<button class="meta-btn" title="Note info & version history (Ctrl+I)" on:click={() => (infoOpen = true)}>
|
||||
History
|
||||
</button>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
@@ -227,6 +256,10 @@
|
||||
<SettingsMenu on:close={() => (menuOpen = false)} />
|
||||
{/if}
|
||||
|
||||
{#if infoOpen && selected}
|
||||
<NoteInfo note={selected} on:close={() => (infoOpen = false)} />
|
||||
{/if}
|
||||
|
||||
{#if toast}
|
||||
<Toast message={toast.message} actionLabel="Undo" onAction={toast.onAction} on:done={() => (toast = null)} />
|
||||
{/if}
|
||||
@@ -319,6 +352,30 @@
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.note-meta {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
padding: 3px 10px;
|
||||
border-top: 1px solid var(--sep);
|
||||
font-size: 11.5px;
|
||||
color: var(--fg-dim);
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
}
|
||||
.meta-sep {
|
||||
opacity: 0.6;
|
||||
}
|
||||
.meta-btn {
|
||||
margin-left: auto;
|
||||
color: var(--accent);
|
||||
font-size: 11.5px;
|
||||
padding: 2px 6px;
|
||||
border-radius: 5px;
|
||||
}
|
||||
.meta-btn:hover {
|
||||
background: var(--sel-bg);
|
||||
}
|
||||
.empty {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
|
||||
220
frontend/src/ui/NoteInfo.svelte
Normal file
220
frontend/src/ui/NoteInfo.svelte
Normal file
@@ -0,0 +1,220 @@
|
||||
<script lang="ts">
|
||||
import { onMount, createEventDispatcher } from 'svelte';
|
||||
import { get } from 'svelte/store';
|
||||
import { settings, updateContent } from '../db/store';
|
||||
import { fetchHistory, notifyEdit } from '../sync/engine';
|
||||
import { noteTitle } from '../search';
|
||||
import { fmtDateTime, fmtAgo } from '../time';
|
||||
import type { Note, Revision } from '../types';
|
||||
|
||||
export let note: Note;
|
||||
|
||||
const dispatch = createEventDispatcher<{ close: void }>();
|
||||
|
||||
let revisions: Revision[] = [];
|
||||
let loading = true;
|
||||
let error = '';
|
||||
let selected: Revision | null = null;
|
||||
|
||||
const hasServer = !!get(settings).serverUrl;
|
||||
|
||||
$: syncLabel = note.dirty
|
||||
? 'changes pending' + (note.synced_at ? ` · last synced ${fmtAgo(note.synced_at)}` : '')
|
||||
: note.synced_at
|
||||
? fmtAgo(note.synced_at)
|
||||
: 'never';
|
||||
|
||||
function fmtSize(chars: number): string {
|
||||
return chars < 1024 ? `${chars} chars` : `${(chars / 1024).toFixed(1)}k chars`;
|
||||
}
|
||||
|
||||
async function restore(rev: Revision) {
|
||||
await updateContent(note.id, rev.content);
|
||||
notifyEdit();
|
||||
dispatch('close');
|
||||
}
|
||||
|
||||
onMount(async () => {
|
||||
if (!hasServer) {
|
||||
loading = false;
|
||||
return;
|
||||
}
|
||||
try {
|
||||
revisions = await fetchHistory(note.id);
|
||||
} catch (e) {
|
||||
error = e instanceof Error ? e.message : String(e);
|
||||
} finally {
|
||||
loading = false;
|
||||
}
|
||||
});
|
||||
</script>
|
||||
|
||||
<!-- svelte-ignore a11y-click-events-have-key-events a11y-no-static-element-interactions -->
|
||||
<div class="backdrop" on:click|self={() => dispatch('close')}>
|
||||
<div class="panel">
|
||||
<h2>{noteTitle(note.content)}</h2>
|
||||
|
||||
<section>
|
||||
<h3>Info</h3>
|
||||
<dl>
|
||||
<dt>Created</dt>
|
||||
<dd>{fmtDateTime(note.created_at)}</dd>
|
||||
<dt>Modified</dt>
|
||||
<dd>{fmtDateTime(note.modified_at)}</dd>
|
||||
<dt>Last synced</dt>
|
||||
<dd>{syncLabel}</dd>
|
||||
{#if note.version > 0}
|
||||
<dt>Server version</dt>
|
||||
<dd>{note.version}</dd>
|
||||
{/if}
|
||||
</dl>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<h3>History</h3>
|
||||
{#if !hasServer}
|
||||
<div class="hint">Versions are recorded on the server — configure sync in Settings to get history.</div>
|
||||
{:else if loading}
|
||||
<div class="hint">Loading…</div>
|
||||
{:else if error}
|
||||
<div class="hint">Couldn’t load history: {error}</div>
|
||||
{:else if !revisions.length}
|
||||
<div class="hint">No older versions yet. A version is saved every time a synced note is overwritten.</div>
|
||||
{:else}
|
||||
<ul class="revs">
|
||||
{#each revisions as rev (rev.version)}
|
||||
<li>
|
||||
<button
|
||||
class="rev"
|
||||
class:active={selected?.version === rev.version}
|
||||
on:click={() => (selected = selected?.version === rev.version ? null : rev)}
|
||||
>
|
||||
<span class="rev-when">{fmtDateTime(rev.modified_at)}</span>
|
||||
<span class="rev-size">{fmtSize(rev.content.length)}</span>
|
||||
</button>
|
||||
{#if selected?.version === rev.version}
|
||||
<pre class="rev-preview">{rev.content}</pre>
|
||||
<button class="btn primary" on:click={() => restore(rev)}>Restore this version</button>
|
||||
{/if}
|
||||
</li>
|
||||
{/each}
|
||||
</ul>
|
||||
<div class="hint">Restoring applies the old text as a new edit — nothing is lost, the current text stays in history.</div>
|
||||
{/if}
|
||||
</section>
|
||||
|
||||
<div class="actions">
|
||||
<button class="btn" on:click={() => dispatch('close')}>Close</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<style>
|
||||
.backdrop {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
z-index: 40;
|
||||
background: rgba(0, 0, 0, 0.3);
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: center;
|
||||
padding-top: 8vh;
|
||||
}
|
||||
.panel {
|
||||
background: var(--bg-panel);
|
||||
border: 1px solid var(--sep);
|
||||
border-radius: 10px;
|
||||
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
|
||||
width: min(520px, 92vw);
|
||||
max-height: 84vh;
|
||||
overflow-y: auto;
|
||||
padding: 18px 22px;
|
||||
}
|
||||
h2 {
|
||||
margin: 0 0 6px;
|
||||
font-size: 17px;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
h3 {
|
||||
margin: 14px 0 6px;
|
||||
font-size: 13px;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.05em;
|
||||
color: var(--fg-dim);
|
||||
}
|
||||
dl {
|
||||
display: grid;
|
||||
grid-template-columns: auto 1fr;
|
||||
gap: 3px 14px;
|
||||
margin: 0;
|
||||
font-size: 13px;
|
||||
}
|
||||
dt {
|
||||
color: var(--fg-dim);
|
||||
}
|
||||
dd {
|
||||
margin: 0;
|
||||
}
|
||||
.hint {
|
||||
font-size: 12.5px;
|
||||
color: var(--fg-dim);
|
||||
margin-top: 6px;
|
||||
}
|
||||
.revs {
|
||||
list-style: none;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
}
|
||||
.rev {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
gap: 10px;
|
||||
width: 100%;
|
||||
text-align: left;
|
||||
padding: 5px 8px;
|
||||
border-radius: 6px;
|
||||
font-size: 13px;
|
||||
}
|
||||
.rev:hover,
|
||||
.rev.active {
|
||||
background: var(--sel-bg);
|
||||
}
|
||||
.rev-size {
|
||||
color: var(--fg-dim);
|
||||
white-space: nowrap;
|
||||
}
|
||||
.rev-preview {
|
||||
margin: 4px 0 2px;
|
||||
padding: 8px 10px;
|
||||
max-height: 180px;
|
||||
overflow: auto;
|
||||
border: 1px solid var(--sep);
|
||||
border-radius: 6px;
|
||||
background: var(--bg);
|
||||
font-family: var(--mono);
|
||||
font-size: 12px;
|
||||
white-space: pre-wrap;
|
||||
word-break: break-word;
|
||||
}
|
||||
.btn {
|
||||
border: 1px solid var(--sep);
|
||||
border-radius: 6px;
|
||||
padding: 5px 14px;
|
||||
margin-top: 4px;
|
||||
background: var(--bg);
|
||||
}
|
||||
.btn.primary {
|
||||
background: var(--accent);
|
||||
border-color: var(--accent);
|
||||
color: #fff;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
.actions {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
gap: 8px;
|
||||
margin-top: 10px;
|
||||
}
|
||||
</style>
|
||||
@@ -28,6 +28,7 @@ func (s *Server) Handler() http.Handler {
|
||||
mux.HandleFunc("GET /api/v1/health", s.handleHealth)
|
||||
mux.Handle("GET /api/v1/changes", s.auth(s.handleChanges))
|
||||
mux.Handle("POST /api/v1/notes/batch", s.auth(s.handleBatch))
|
||||
mux.Handle("GET /api/v1/notes/{id}/history", s.auth(s.handleHistory))
|
||||
mux.Handle("POST /api/v1/import/simplenote", s.auth(s.handleImport))
|
||||
mux.HandleFunc("OPTIONS /api/v1/", func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
@@ -108,6 +109,16 @@ func (s *Server) handleBatch(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(w, map[string]any{"results": results})
|
||||
}
|
||||
|
||||
func (s *Server) handleHistory(w http.ResponseWriter, r *http.Request) {
|
||||
revs, err := s.Store.History(r.PathValue("id"))
|
||||
if err != nil {
|
||||
log.Printf("history: %v", err)
|
||||
jsonError(w, http.StatusInternalServerError, "internal error")
|
||||
return
|
||||
}
|
||||
writeJSON(w, map[string]any{"revisions": revs})
|
||||
}
|
||||
|
||||
func (s *Server) handleImport(w http.ResponseWriter, r *http.Request) {
|
||||
if err := r.ParseMultipartForm(64 << 20); err != nil {
|
||||
jsonError(w, http.StatusBadRequest, "bad multipart form: "+err.Error())
|
||||
|
||||
@@ -229,6 +229,45 @@ func TestTwoClientsConverge(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestHistoryEndpoint(t *testing.T) {
|
||||
srv, tok := newTestServer(t)
|
||||
a := newClient(t, srv.URL, tok)
|
||||
|
||||
a.edit("n1", "v1")
|
||||
a.sync()
|
||||
a.edit("n1", "v2")
|
||||
a.notes["n1"].ModifiedAt = 2
|
||||
a.sync()
|
||||
|
||||
var body struct {
|
||||
Revisions []store.Revision `json:"revisions"`
|
||||
}
|
||||
if code := a.req("GET", "/api/v1/notes/n1/history", nil, &body); code != 200 {
|
||||
t.Fatalf("history HTTP %d", code)
|
||||
}
|
||||
if len(body.Revisions) != 1 || body.Revisions[0].Content != "v1" {
|
||||
t.Fatalf("history: %+v", body.Revisions)
|
||||
}
|
||||
|
||||
// Unknown note → empty list, not an error.
|
||||
if code := a.req("GET", "/api/v1/notes/nope/history", nil, &body); code != 200 {
|
||||
t.Fatalf("unknown note HTTP %d", code)
|
||||
}
|
||||
if len(body.Revisions) != 0 {
|
||||
t.Fatalf("want empty history, got %+v", body.Revisions)
|
||||
}
|
||||
|
||||
// Auth required.
|
||||
res, err := http.Get(srv.URL + "/api/v1/notes/n1/history")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
res.Body.Close()
|
||||
if res.StatusCode != http.StatusUnauthorized {
|
||||
t.Fatalf("want 401, got %d", res.StatusCode)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeleteEditConflictAcrossClients(t *testing.T) {
|
||||
srv, tok := newTestServer(t)
|
||||
a := newClient(t, srv.URL, tok)
|
||||
|
||||
@@ -17,7 +17,10 @@ import (
|
||||
_ "modernc.org/sqlite"
|
||||
)
|
||||
|
||||
const SchemaVersion = 1
|
||||
const SchemaVersion = 2
|
||||
|
||||
// historyKeep caps stored revisions per note; older ones are pruned on write.
|
||||
const historyKeep = 50
|
||||
|
||||
type Note struct {
|
||||
ID string `json:"id"`
|
||||
@@ -29,6 +32,16 @@ type Note struct {
|
||||
Version int64 `json:"version"`
|
||||
}
|
||||
|
||||
// Revision is a superseded note state, recorded when an accepted push overwrites it.
|
||||
type Revision struct {
|
||||
NoteID string `json:"note_id"`
|
||||
Version int64 `json:"version"`
|
||||
Content string `json:"content"`
|
||||
Tags []string `json:"tags"`
|
||||
ModifiedAt int64 `json:"modified_at"`
|
||||
ReplacedAt int64 `json:"replaced_at"`
|
||||
}
|
||||
|
||||
type IncomingNote struct {
|
||||
ID string `json:"id"`
|
||||
Content string `json:"content"`
|
||||
@@ -83,11 +96,22 @@ CREATE TABLE IF NOT EXISTS notes (
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_notes_version ON notes(version);
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS idx_notes_source ON notes(source_id) WHERE source_id IS NOT NULL;
|
||||
CREATE TABLE IF NOT EXISTS note_history (
|
||||
note_id TEXT NOT NULL,
|
||||
version INTEGER NOT NULL,
|
||||
content TEXT NOT NULL DEFAULT '',
|
||||
tags TEXT NOT NULL DEFAULT '[]',
|
||||
modified_at INTEGER NOT NULL,
|
||||
replaced_at INTEGER NOT NULL,
|
||||
PRIMARY KEY (note_id, version)
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS meta (k TEXT PRIMARY KEY, v TEXT);
|
||||
INSERT OR IGNORE INTO meta (k, v) VALUES ('schema_version', '1');
|
||||
INSERT OR IGNORE INTO meta (k, v) VALUES ('next_version', '1');
|
||||
`)
|
||||
return err
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return s.setMeta("schema_version", strconv.Itoa(SchemaVersion))
|
||||
}
|
||||
|
||||
// --- meta helpers ---
|
||||
@@ -228,6 +252,45 @@ func getNoteTx(tx *sql.Tx, id string) (*Note, error) {
|
||||
return &n, nil
|
||||
}
|
||||
|
||||
// recordHistoryTx snapshots the note state that is about to be overwritten,
|
||||
// then prunes revisions beyond historyKeep.
|
||||
func recordHistoryTx(tx *sql.Tx, n *Note, now time.Time) error {
|
||||
if _, err := tx.Exec(
|
||||
`INSERT OR REPLACE INTO note_history (note_id, version, content, tags, modified_at, replaced_at) VALUES (?,?,?,?,?,?)`,
|
||||
n.ID, n.Version, n.Content, tagsJSON(n.Tags), n.ModifiedAt, now.UnixMilli()); err != nil {
|
||||
return err
|
||||
}
|
||||
_, err := tx.Exec(
|
||||
`DELETE FROM note_history WHERE note_id = ? AND version NOT IN (
|
||||
SELECT version FROM note_history WHERE note_id = ? ORDER BY version DESC LIMIT ?)`,
|
||||
n.ID, n.ID, historyKeep)
|
||||
return err
|
||||
}
|
||||
|
||||
// History returns a note's superseded revisions, newest first.
|
||||
func (s *Store) History(noteID string) ([]Revision, error) {
|
||||
rows, err := s.db.Query(
|
||||
`SELECT note_id, version, content, tags, modified_at, replaced_at
|
||||
FROM note_history WHERE note_id = ? ORDER BY version DESC`, noteID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
revs := []Revision{}
|
||||
for rows.Next() {
|
||||
var r Revision
|
||||
var tags string
|
||||
if err := rows.Scan(&r.NoteID, &r.Version, &r.Content, &tags, &r.ModifiedAt, &r.ReplacedAt); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := json.Unmarshal([]byte(tags), &r.Tags); err != nil || r.Tags == nil {
|
||||
r.Tags = []string{}
|
||||
}
|
||||
revs = append(revs, r)
|
||||
}
|
||||
return revs, rows.Err()
|
||||
}
|
||||
|
||||
// conflictTitle appends the marker to the first non-empty line of content.
|
||||
func conflictTitle(content string, at time.Time) string {
|
||||
marker := at.Format(" (conflicted copy 2006-01-02 15:04)")
|
||||
@@ -281,6 +344,9 @@ func (s *Store) ApplyBatch(in []IncomingNote, now time.Time) ([]PushResult, erro
|
||||
|
||||
case inc.BaseVersion == cur.Version:
|
||||
// Rule 2: clean fast-forward.
|
||||
if err := recordHistoryTx(tx, cur, now); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
v, err := nextVersionTx(tx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -299,6 +365,9 @@ func (s *Store) ApplyBatch(in []IncomingNote, now time.Time) ([]PushResult, erro
|
||||
|
||||
case cur.Deleted:
|
||||
// Rule 4b: stale edit vs server tombstone → edit wins, overwrites the tombstone.
|
||||
if err := recordHistoryTx(tx, cur, now); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
v, err := nextVersionTx(tx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -370,13 +439,17 @@ func (s *Store) UpsertImported(sourceID string, n Note) (bool, error) {
|
||||
return true, tx.Commit()
|
||||
}
|
||||
|
||||
// Compact purges tombstones older than the given number of days.
|
||||
// Compact purges tombstones older than the given number of days, plus the
|
||||
// history of any note that no longer exists.
|
||||
func (s *Store) Compact(olderThanDays int) (int64, error) {
|
||||
cutoff := time.Now().AddDate(0, 0, -olderThanDays).UnixMilli()
|
||||
res, err := s.db.Exec(`DELETE FROM notes WHERE deleted = 1 AND modified_at < ?`, cutoff)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if _, err := s.db.Exec(`DELETE FROM note_history WHERE note_id NOT IN (SELECT id FROM notes)`); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return res.RowsAffected()
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
@@ -159,6 +160,104 @@ func TestChangesPaging(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestHistoryRecordsSupersededRevisions(t *testing.T) {
|
||||
s := newTestStore(t)
|
||||
|
||||
r1 := push(t, s, IncomingNote{ID: "a", Content: "v1", Tags: []string{"t"}, ModifiedAt: 1})
|
||||
if revs, _ := s.History("a"); len(revs) != 0 {
|
||||
t.Fatalf("insert must not create history, got %d", len(revs))
|
||||
}
|
||||
|
||||
r2 := push(t, s, IncomingNote{ID: "a", Content: "v2", ModifiedAt: 2, BaseVersion: r1.Version})
|
||||
r3 := push(t, s, IncomingNote{ID: "a", Content: "v3", ModifiedAt: 3, BaseVersion: r2.Version})
|
||||
|
||||
revs, err := s.History("a")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(revs) != 2 {
|
||||
t.Fatalf("want 2 revisions, got %d", len(revs))
|
||||
}
|
||||
// Newest first: the v2 state (superseded by the v3 push), then v1.
|
||||
if revs[0].Content != "v2" || revs[0].Version != r2.Version {
|
||||
t.Fatalf("revs[0] = %+v", revs[0])
|
||||
}
|
||||
if revs[1].Content != "v1" || revs[1].Version != r1.Version || !containsStr(revs[1].Tags, "t") {
|
||||
t.Fatalf("revs[1] = %+v", revs[1])
|
||||
}
|
||||
if revs[0].ReplacedAt == 0 {
|
||||
t.Fatal("replaced_at not stamped")
|
||||
}
|
||||
_ = r3
|
||||
}
|
||||
|
||||
func TestHistoryRecordedOnDeleteAndResurrect(t *testing.T) {
|
||||
s := newTestStore(t)
|
||||
|
||||
r1 := push(t, s, IncomingNote{ID: "a", Content: "precious", ModifiedAt: 1})
|
||||
r2 := push(t, s, IncomingNote{ID: "a", Content: "precious", Deleted: true, ModifiedAt: 2, BaseVersion: r1.Version})
|
||||
// Stale edit overwrites the tombstone (rule 4b) — tombstone state goes to history.
|
||||
push(t, s, IncomingNote{ID: "a", Content: "resurrected", ModifiedAt: 3, BaseVersion: r1.Version})
|
||||
|
||||
revs, err := s.History("a")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(revs) != 2 || revs[0].Version != r2.Version || revs[1].Content != "precious" {
|
||||
t.Fatalf("history after delete+resurrect: %+v", revs)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHistoryNotRecordedOnConflict(t *testing.T) {
|
||||
s := newTestStore(t)
|
||||
|
||||
r1 := push(t, s, IncomingNote{ID: "a", Content: "base", ModifiedAt: 1})
|
||||
push(t, s, IncomingNote{ID: "a", Content: "B's edit", ModifiedAt: 2, BaseVersion: r1.Version})
|
||||
// Stale edit → conflict copy; server note untouched, so no new history entry.
|
||||
push(t, s, IncomingNote{ID: "a", Content: "A's edit", ModifiedAt: 3, BaseVersion: r1.Version})
|
||||
|
||||
revs, _ := s.History("a")
|
||||
if len(revs) != 1 || revs[0].Content != "base" {
|
||||
t.Fatalf("conflict must not record history: %+v", revs)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHistoryPrunedToCap(t *testing.T) {
|
||||
s := newTestStore(t)
|
||||
r := push(t, s, IncomingNote{ID: "a", Content: "v0", ModifiedAt: 0})
|
||||
for i := 1; i <= historyKeep+10; i++ {
|
||||
r = push(t, s, IncomingNote{ID: "a", Content: fmt.Sprintf("v%d", i), ModifiedAt: int64(i), BaseVersion: r.Version})
|
||||
}
|
||||
revs, err := s.History("a")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(revs) != historyKeep {
|
||||
t.Fatalf("want %d revisions after prune, got %d", historyKeep, len(revs))
|
||||
}
|
||||
if revs[0].Content != fmt.Sprintf("v%d", historyKeep+9) {
|
||||
t.Fatalf("newest revision wrong: %q", revs[0].Content)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCompactPurgesOrphanHistory(t *testing.T) {
|
||||
s := newTestStore(t)
|
||||
old := time.Now().AddDate(0, 0, -200).UnixMilli()
|
||||
r1 := push(t, s, IncomingNote{ID: "a", Content: "x", ModifiedAt: old})
|
||||
push(t, s, IncomingNote{ID: "a", Deleted: true, ModifiedAt: old, BaseVersion: r1.Version})
|
||||
|
||||
if _, err := s.Compact(90); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
revs, err := s.History("a")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(revs) != 0 {
|
||||
t.Fatalf("history must be purged with the note, got %d", len(revs))
|
||||
}
|
||||
}
|
||||
|
||||
func TestTokenRoundtrip(t *testing.T) {
|
||||
s := newTestStore(t)
|
||||
tok, err := s.EnsureToken()
|
||||
|
||||
Reference in New Issue
Block a user