diff --git a/.changeset/local-update-conflict-check.md b/.changeset/local-update-conflict-check.md new file mode 100644 index 000000000..07d105259 --- /dev/null +++ b/.changeset/local-update-conflict-check.md @@ -0,0 +1,5 @@ +--- +'@keystatic/core': patch +--- + +Detect concurrent local storage edits and deletions by validating expected file and directory SHAs in `/api/keystatic/update`, returning HTTP `409 Conflict` without partial disk writes and showing an actionable conflict notice in the editor. diff --git a/packages/keystatic/src/api/api-node.test.ts b/packages/keystatic/src/api/api-node.test.ts new file mode 100644 index 000000000..60aef1b60 --- /dev/null +++ b/packages/keystatic/src/api/api-node.test.ts @@ -0,0 +1,438 @@ +/** @vitest-environment node */ +import fs from 'node:fs/promises'; +import path from 'node:path'; +import { webcrypto } from 'node:crypto'; +import { describe, expect, test } from 'vitest'; +import { Config, collection, singleton, fields } from '..'; +import { localModeApiHandler } from './api-node'; +import { KeystaticRequest } from './internal-utils'; +import { TreeEntry } from '../app/trees'; +import { testdir } from '../../test/test-utils'; +import { base64Encode } from '#base64'; + +if (!globalThis.crypto) { + globalThis.crypto = webcrypto as any; +} + +const textEncoder = new TextEncoder(); + +function encodeText(text: string) { + return base64Encode(textEncoder.encode(text)); +} + +function makeRequest(args: { + method: 'GET' | 'POST'; + url?: string; + headers?: Record; + body?: unknown; +}): KeystaticRequest { + const headerMap = new Map( + Object.entries(args.headers ?? {}).map(([k, v]) => [k.toLowerCase(), v]) + ); + return { + method: args.method, + url: args.url ?? 'http://localhost/api/keystatic/update', + headers: { + get: name => headerMap.get(name.toLowerCase()) ?? null, + }, + json: async () => args.body, + }; +} + +async function getTree( + handler: ReturnType +): Promise> { + const res = await handler( + makeRequest({ + method: 'GET', + url: 'http://localhost/api/keystatic/tree', + headers: { 'no-cors': '1' }, + }), + ['tree'] + ); + expect(res.status).toBe(200); + const entries: TreeEntry[] = JSON.parse(res.body as string); + return new Map(entries.map(e => [e.path, e])); +} + +async function postUpdate( + handler: ReturnType, + body: unknown +) { + return handler( + makeRequest({ + method: 'POST', + url: 'http://localhost/api/keystatic/update', + headers: { + 'no-cors': '1', + 'content-type': 'application/json', + }, + body, + }), + ['update'] + ); +} + +const testConfig: Config = { + storage: { kind: 'local' }, + collections: { + posts: collection({ + label: 'Posts', + slugField: 'title', + path: 'posts/*/', + format: { contentField: 'content' }, + schema: { + title: fields.slug({ name: { label: 'Title' } }), + content: fields.markdoc({ label: 'Content' }), + }, + }), + notes: collection({ + label: 'Notes', + slugField: 'title', + path: 'notes/*', + schema: { + title: fields.slug({ name: { label: 'Title' } }), + body: fields.text({ label: 'Body' }), + }, + }), + }, + singletons: { + settings: singleton({ + label: 'Settings', + path: 'settings/', + schema: { + siteName: fields.text({ label: 'Site Name' }), + }, + }), + }, +}; + +describe('localModeApiHandler update conflict checks', () => { + test('succeeds when expectedShas match current disk state and rejects subsequent stale update with 409', async () => { + const dir = await testdir({ + 'posts/hello/index.mdoc': '---\ntitle: Original\n---\nHello world\n', + 'posts/hello/extra.txt': 'unchanged\n', + }); + const handler = localModeApiHandler(testConfig, dir); + const initialTree = await getTree(handler); + + // Tab B saves a newer version first. + const tabBRes = await postUpdate(handler, { + additions: [ + { + path: 'posts/hello/index.mdoc', + contents: encodeText( + '---\ntitle: Updated by B\n---\nTab B content\n' + ), + }, + ], + deletions: [], + expectedShas: [ + { path: 'posts/hello', sha: initialTree.get('posts/hello')!.sha }, + { + path: 'posts/hello/index.mdoc', + sha: initialTree.get('posts/hello/index.mdoc')!.sha, + }, + ], + }); + expect(tabBRes.status).toBe(200); + + // Tab A still holds initialTree SHAs and tries to overwrite index.mdoc and write a new asset. + const tabARes = await postUpdate(handler, { + additions: [ + { + path: 'posts/hello/index.mdoc', + contents: encodeText('---\ntitle: Stale A\n---\nStale content\n'), + }, + { + path: 'posts/hello/new-asset.txt', + contents: encodeText('should not be written'), + }, + ], + deletions: [{ path: 'posts/hello/extra.txt' }], + expectedShas: [ + { path: 'posts/hello', sha: initialTree.get('posts/hello')!.sha }, + { + path: 'posts/hello/index.mdoc', + sha: initialTree.get('posts/hello/index.mdoc')!.sha, + }, + ], + }); + + expect(tabARes.status).toBe(409); + const conflictBody = JSON.parse(tabARes.body as string); + expect(conflictBody.code).toBe('CONFLICT'); + expect(conflictBody.conflicts.length).toBeGreaterThan(0); + + // Disk must remain untouched: Tab B's content intact, no partial writes or deletions. + expect( + await fs.readFile(path.join(dir, 'posts/hello/index.mdoc'), 'utf8') + ).toBe('---\ntitle: Updated by B\n---\nTab B content\n'); + expect( + await fs.readFile(path.join(dir, 'posts/hello/extra.txt'), 'utf8') + ).toBe('unchanged\n'); + await expect( + fs.access(path.join(dir, 'posts/hello/new-asset.txt')) + ).rejects.toThrow(); + }); + + test('detects conflict when another file in the entry directory changed even if additions do not touch that file', async () => { + const dir = await testdir({ + 'posts/hello/index.mdoc': '---\ntitle: Hello\n---\nBody v1\n', + 'posts/hello/cover.txt': 'cover-v1', + }); + const handler = localModeApiHandler(testConfig, dir); + const initialTree = await getTree(handler); + + // Tab B modifies index.mdoc while Tab A only changes cover.txt. + const tabBRes = await postUpdate(handler, { + additions: [ + { + path: 'posts/hello/index.mdoc', + contents: encodeText('---\ntitle: Hello B\n---\nBody v2\n'), + }, + ], + deletions: [], + expectedShas: [ + { path: 'posts/hello', sha: initialTree.get('posts/hello')!.sha }, + ], + }); + expect(tabBRes.status).toBe(200); + + const tabARes = await postUpdate(handler, { + additions: [ + { + path: 'posts/hello/cover.txt', + contents: encodeText('cover-v2-by-A'), + }, + ], + deletions: [], + expectedShas: [ + { path: 'posts/hello', sha: initialTree.get('posts/hello')!.sha }, + { + path: 'posts/hello/cover.txt', + sha: initialTree.get('posts/hello/cover.txt')!.sha, + }, + ], + }); + expect(tabARes.status).toBe(409); + expect( + await fs.readFile(path.join(dir, 'posts/hello/cover.txt'), 'utf8') + ).toBe('cover-v1'); + }); + + test('blocks concurrent creation of the same slug when expectedSha is null', async () => { + const dir = await testdir({ + 'notes/existing.yaml': 'title: Existing\nbody: Keep\n', + }); + const handler = localModeApiHandler(testConfig, dir); + + // Tab B creates notes/new-note first. + const tabBRes = await postUpdate(handler, { + additions: [ + { + path: 'notes/new-note.yaml', + contents: encodeText('title: New Note B\nbody: Created by B\n'), + }, + ], + deletions: [], + expectedShas: [ + { path: 'notes/new-note', sha: null }, + { path: 'notes/new-note.yaml', sha: null }, + ], + }); + expect(tabBRes.status).toBe(200); + + // Stale Tab A tries to create the same slug expecting null. + const tabARes = await postUpdate(handler, { + additions: [ + { + path: 'notes/new-note.yaml', + contents: encodeText('title: New Note A\nbody: Overwrite attempt\n'), + }, + ], + deletions: [], + expectedShas: [ + { path: 'notes/new-note', sha: null }, + { path: 'notes/new-note.yaml', sha: null }, + ], + }); + expect(tabARes.status).toBe(409); + expect( + await fs.readFile(path.join(dir, 'notes/new-note.yaml'), 'utf8') + ).toBe('title: New Note B\nbody: Created by B\n'); + }); + + test('blocks stale delete when entry was concurrently modified or deleted', async () => { + const dir = await testdir({ + 'notes/target.yaml': 'title: Target\nbody: v1\n', + }); + const handler = localModeApiHandler(testConfig, dir); + const initialTree = await getTree(handler); + + // Tab B updates notes/target.yaml. + const editRes = await postUpdate(handler, { + additions: [ + { + path: 'notes/target.yaml', + contents: encodeText('title: Target\nbody: v2\n'), + }, + ], + deletions: [], + expectedShas: [ + { path: 'notes/target', sha: null }, + { + path: 'notes/target.yaml', + sha: initialTree.get('notes/target.yaml')!.sha, + }, + ], + }); + expect(editRes.status).toBe(200); + + // Stale Tab A tries to delete notes/target.yaml. + const deleteRes = await postUpdate(handler, { + additions: [], + deletions: [{ path: 'notes/target.yaml' }], + expectedShas: [ + { path: 'notes/target', sha: null }, + { + path: 'notes/target.yaml', + sha: initialTree.get('notes/target.yaml')!.sha, + }, + ], + }); + expect(deleteRes.status).toBe(409); + expect(await fs.readFile(path.join(dir, 'notes/target.yaml'), 'utf8')).toBe( + 'title: Target\nbody: v2\n' + ); + }); + + test('allows saving when an unrelated entry changed concurrently and supports consecutive saves', async () => { + const dir = await testdir({ + 'notes/first.yaml': 'title: First\nbody: v1\n', + 'notes/second.yaml': 'title: Second\nbody: v1\n', + }); + const handler = localModeApiHandler(testConfig, dir); + const initialTree = await getTree(handler); + + // Tab B modifies notes/second.yaml. + const tabBRes = await postUpdate(handler, { + additions: [ + { + path: 'notes/second.yaml', + contents: encodeText('title: Second\nbody: v2\n'), + }, + ], + deletions: [], + expectedShas: [ + { path: 'notes/second', sha: null }, + { + path: 'notes/second.yaml', + sha: initialTree.get('notes/second.yaml')!.sha, + }, + ], + }); + expect(tabBRes.status).toBe(200); + + // Tab A still has initialTree for notes/first.yaml and saves cleanly. + const tabARes1 = await postUpdate(handler, { + additions: [ + { + path: 'notes/first.yaml', + contents: encodeText('title: First\nbody: v2\n'), + }, + ], + deletions: [], + expectedShas: [ + { path: 'notes/first', sha: null }, + { + path: 'notes/first.yaml', + sha: initialTree.get('notes/first.yaml')!.sha, + }, + ], + }); + expect(tabARes1.status).toBe(200); + + const updatedEntries: TreeEntry[] = JSON.parse(tabARes1.body as string); + const updatedTree = new Map(updatedEntries.map(e => [e.path, e])); + + // Tab A performs a consecutive save using SHAs from the previous 200 response. + const tabARes2 = await postUpdate(handler, { + additions: [ + { + path: 'notes/first.yaml', + contents: encodeText('title: First\nbody: v3\n'), + }, + ], + deletions: [], + expectedShas: [ + { path: 'notes/first', sha: null }, + { + path: 'notes/first.yaml', + sha: updatedTree.get('notes/first.yaml')!.sha, + }, + ], + }); + expect(tabARes2.status).toBe(200); + expect(await fs.readFile(path.join(dir, 'notes/first.yaml'), 'utf8')).toBe( + 'title: First\nbody: v3\n' + ); + }); + + test('serializes concurrent updates on the same directory so the second sees 409', async () => { + const dir = await testdir({ + 'settings/index.yaml': 'siteName: Initial\n', + }); + const handler = localModeApiHandler(testConfig, dir); + const initialTree = await getTree(handler); + const expectedShas = [ + { path: 'settings', sha: initialTree.get('settings')!.sha }, + { + path: 'settings/index.yaml', + sha: initialTree.get('settings/index.yaml')!.sha, + }, + ]; + + const [res1, res2] = await Promise.all([ + postUpdate(handler, { + additions: [ + { + path: 'settings/index.yaml', + contents: encodeText('siteName: First\n'), + }, + ], + deletions: [], + expectedShas, + }), + postUpdate(handler, { + additions: [ + { + path: 'settings/index.yaml', + contents: encodeText('siteName: Second\n'), + }, + ], + deletions: [], + expectedShas, + }), + ]); + + expect([res1.status, res2.status]).toEqual([200, 409]); + expect( + await fs.readFile(path.join(dir, 'settings/index.yaml'), 'utf8') + ).toBe('siteName: First\n'); + }); + + test('rejects invalid or disallowed paths in expectedShas', async () => { + const dir = await testdir({ + 'notes/first.yaml': 'title: First\nbody: v1\n', + }); + const handler = localModeApiHandler(testConfig, dir); + + const res = await postUpdate(handler, { + additions: [], + deletions: [], + expectedShas: [{ path: '../secret.txt', sha: null }], + }); + expect(res.status).toBe(400); + }); +}); diff --git a/packages/keystatic/src/api/api-node.ts b/packages/keystatic/src/api/api-node.ts index a1b9d65cc..56ce27cb1 100644 --- a/packages/keystatic/src/api/api-node.ts +++ b/packages/keystatic/src/api/api-node.ts @@ -172,6 +172,24 @@ const base64Schema = s.coerce(s.instance(Uint8Array), s.string(), val => base64UrlDecode(val) ); +const updateLocks = new Map>(); + +async function withDirectoryLock( + dir: string, + fn: () => Promise +): Promise { + const prev = updateLocks.get(dir) ?? Promise.resolve(); + const next = prev.catch(() => {}).then(fn); + updateLocks.set(dir, next); + try { + return await next; + } finally { + if (updateLocks.get(dir) === next) { + updateLocks.delete(dir); + } + } +} + async function update( req: KeystaticRequest, config: Config, @@ -198,26 +216,71 @@ async function update( }) ), deletions: s.array(s.object({ path: filepath })), + expectedShas: s.optional( + s.array( + s.object({ + path: filepath, + sha: s.nullable(s.string()), + }) + ) + ), }) ); } catch { return { status: 400, body: 'Bad data' }; } - for (const addition of updates.additions) { - await fs.mkdir(path.dirname(path.join(baseDirectory, addition.path)), { - recursive: true, - }); - await fs.writeFile( - path.join(baseDirectory, addition.path), - addition.contents - ); - } - for (const deletion of updates.deletions) { - await fs.rm(path.join(baseDirectory, deletion.path), { force: true }); - } - return { - status: 200, - headers: { 'content-type': 'application/json' }, - body: JSON.stringify(await readToDirEntries(baseDirectory)), - }; + + return withDirectoryLock(baseDirectory, async () => { + if (updates.expectedShas && updates.expectedShas.length > 0) { + const currentEntries = await readToDirEntries(baseDirectory); + const currentShaByPath = new Map( + currentEntries.map(entry => [entry.path, entry.sha]) + ); + const conflicts: { + path: string; + expectedSha: string | null; + actualSha: string | null; + }[] = []; + for (const expected of updates.expectedShas) { + const actualSha = currentShaByPath.get(expected.path) ?? null; + if (actualSha !== expected.sha) { + conflicts.push({ + path: expected.path, + expectedSha: expected.sha, + actualSha, + }); + } + } + if (conflicts.length > 0) { + return { + status: 409, + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ + code: 'CONFLICT', + message: + 'Conflict: one or more files have changed since they were loaded.', + conflicts, + }), + }; + } + } + + for (const addition of updates.additions) { + await fs.mkdir(path.dirname(path.join(baseDirectory, addition.path)), { + recursive: true, + }); + await fs.writeFile( + path.join(baseDirectory, addition.path), + addition.contents + ); + } + for (const deletion of updates.deletions) { + await fs.rm(path.join(baseDirectory, deletion.path), { force: true }); + } + return { + status: 200, + headers: { 'content-type': 'application/json' }, + body: JSON.stringify(await readToDirEntries(baseDirectory)), + }; + }); } diff --git a/packages/keystatic/src/app/ItemPage.tsx b/packages/keystatic/src/app/ItemPage.tsx index f19cc2de7..c39f30eea 100644 --- a/packages/keystatic/src/app/ItemPage.tsx +++ b/packages/keystatic/src/app/ItemPage.tsx @@ -52,6 +52,7 @@ import { } from './branch-selection'; import { FormForEntry, containerWidthForEntryLayout } from './entry-form'; import { ForkRepoDialog } from './fork-repo'; +import { LocalConflictNotice } from './local-conflict-notice'; import l10nMessages from './l10n'; import { NotFoundBoundary, notFound } from './not-found'; import { getDataFileExtension, getPathPrefix } from './path-utils'; @@ -59,7 +60,12 @@ import { useRouter } from './router'; import { HeaderBreadcrumbs } from './shell/HeaderBreadcrumbs'; import { useYjsIfAvailable } from './shell/collab'; import { useConfig } from './shell/context'; -import { useBaseCommit, useCurrentBranch, useRepoInfo } from './shell/data'; +import { + useBaseCommit, + useCurrentBranch, + useRefreshLocalTree, + useRepoInfo, +} from './shell/data'; import { PageBody, PageHeader, PageRoot } from './shell/page'; import { useSlugFieldInfo } from './slugs'; import { delDraft, getDraft, setDraft } from './persistence'; @@ -117,6 +123,7 @@ function ItemPageInner( onReset: () => void; updateResult: ReturnType[0]; onResetUpdateItem: () => void; + onDiscardDraft?: () => void; previewProps: GenericPreviewProps< ObjectField>, undefined @@ -140,6 +147,7 @@ function ItemPageInner( const formatInfo = getCollectionFormat(config, collection); const currentBranch = useCurrentBranch(); const repoInfo = useRepoInfo(); + const refreshLocalTree = useRefreshLocalTree(); const [forceValidation, setForceValidation] = useState(false); const previewHref = collectionConfig.previewUrl ? collectionConfig.previewUrl @@ -229,6 +237,16 @@ function ItemPageInner( const formID = 'item-edit-form'; + const onResetUpdateItem = props.onResetUpdateItem; + const onDiscardDraft = props.onDiscardDraft; + const onReloadLatest = useEventCallback(async () => { + await delDraft(['collection', collection, itemSlug]); + onDiscardDraft?.(); + await refreshLocalTree(); + onResetUpdateItem(); + resetDeleteItem(); + }); + // allow shortcuts "cmd+s" and "ctrl+s" to save useEffect(() => { const listener = (event: KeyboardEvent) => { @@ -266,9 +284,22 @@ function ItemPageInner( {updateResult.kind === 'error' && ( {updateResult.error.message} )} + {updateResult.kind === 'conflict' && ( + + )} {deleteResult.kind === 'error' && ( {deleteResult.error.message} )} + {deleteResult.kind === 'conflict' && ( + + )} void; draft: | { state: Record; savedAt: Date; treeKey: string } | undefined; @@ -479,6 +511,7 @@ function LocalItemPage( onReset={onReset} updateResult={updateResult} onResetUpdateItem={resetUpdateItem} + onDiscardDraft={props.onDiscardDraft} previewProps={previewProps} state={state} hasChanged={hasChanged} @@ -853,6 +886,11 @@ function ItemPageOuterWrapper(props: ItemPageWrapperProps) { return { slug: props.itemSlug, field: collectionConfig.slugField }; }, [collectionConfig.slugField, props.itemSlug]); + const [discardedDraftKey, setDiscardedDraftKey] = useState( + null + ); + const draftKey = `${props.collection}/${props.itemSlug}`; + const draftData = useData( useCallback(async () => { try { @@ -969,6 +1007,8 @@ function ItemPageOuterWrapper(props: ItemPageWrapperProps) { mapData={mapData} draftData={draftData} itemData={itemData} + isDraftDiscarded={discardedDraftKey === draftKey} + onDiscardDraft={() => setDiscardedDraftKey(draftKey)} {...props} /> @@ -982,6 +1022,8 @@ function ItemPageWrapper( draftData: DataState< { state: any; savedAt: Date; treeKey: string } | undefined >; + isDraftDiscarded: boolean; + onDiscardDraft: () => void; mapData: DataState | undefined>; itemData: DataState< | 'not-found' @@ -1036,7 +1078,8 @@ function ItemPageWrapper( itemSlug={props.itemSlug} initialState={itemData.initialState} initialFiles={itemData.initialFiles} - draft={loadedDraft} + draft={props.isDraftDiscarded ? undefined : loadedDraft} + onDiscardDraft={props.onDiscardDraft} localTreeKey={itemData.localTreeKey} /> ); diff --git a/packages/keystatic/src/app/SingletonPage.tsx b/packages/keystatic/src/app/SingletonPage.tsx index e64eef51e..bd2c74737 100644 --- a/packages/keystatic/src/app/SingletonPage.tsx +++ b/packages/keystatic/src/app/SingletonPage.tsx @@ -33,7 +33,13 @@ import { import { CreateBranchDuringUpdateDialog } from './ItemPage'; import { PageBody, PageHeader, PageRoot } from './shell/page'; -import { useBaseCommit, useCurrentBranch, useRepoInfo } from './shell/data'; +import { + useBaseCommit, + useCurrentBranch, + useRefreshLocalTree, + useRepoInfo, +} from './shell/data'; +import { LocalConflictNotice } from './local-conflict-notice'; import { useHasChanged } from './useHasChanged'; import { parseEntry, useItemData } from './useItemData'; import { serializeEntryToFiles, useUpsertItem } from './updating'; @@ -79,6 +85,7 @@ function SingletonPageInner( updateResult: ReturnType[0]; onUpdate: ReturnType[1]; onResetUpdateItem: ReturnType[2]; + onDiscardDraft?: () => void; hasChanged: boolean; state: Record; onReset: () => void; @@ -88,6 +95,7 @@ function SingletonPageInner( const isBelowDesktop = useMediaQuery(breakpointQueries.below.desktop); const repoInfo = useRepoInfo(); const currentBranch = useCurrentBranch(); + const refreshLocalTree = useRefreshLocalTree(); const [forceValidation, setForceValidation] = useState(false); const { schema, singletonConfig } = useSingleton(props.singleton); @@ -208,6 +216,13 @@ function SingletonPageInner( } }; + const onReloadLatest = useEventCallback(async () => { + await delDraft(['singleton', props.singleton]); + props.onDiscardDraft?.(); + await refreshLocalTree(); + props.onResetUpdateItem(); + }); + return ( @@ -288,6 +303,12 @@ function SingletonPageInner( {props.updateResult.kind === 'error' && ( {props.updateResult.error.message} )} + {props.updateResult.kind === 'conflict' && ( + + )} void; draft: | { state: Record; @@ -452,6 +474,7 @@ function LocalSingletonPage( onReset={onReset} onUpdate={update} onResetUpdateItem={resetUpdateItem} + onDiscardDraft={props.onDiscardDraft} updateResult={updateResult} state={state} previewProps={previewProps} @@ -541,6 +564,7 @@ function SingletonPageWrapper(props: { singleton: string; config: Config }) { ); const dirpath = getSingletonPath(props.config, props.singleton); + const [hasDiscardedDraft, setHasDiscardedDraft] = useState(false); const draftData = useData( useCallback(async () => { @@ -703,7 +727,12 @@ function SingletonPageWrapper(props: { singleton: string; config: Config }) { localTreeKey={ itemData.data === 'not-found' ? undefined : itemData.data.localTreeKey } - draft={draftData.kind === 'loaded' ? draftData.data : undefined} + draft={ + hasDiscardedDraft || draftData.kind !== 'loaded' + ? undefined + : draftData.data + } + onDiscardDraft={() => setHasDiscardedDraft(true)} /> ); } diff --git a/packages/keystatic/src/app/create-item.tsx b/packages/keystatic/src/app/create-item.tsx index 6f8d2417e..3351395f9 100644 --- a/packages/keystatic/src/app/create-item.tsx +++ b/packages/keystatic/src/app/create-item.tsx @@ -19,8 +19,13 @@ import { clientSideValidateProp } from '../form/errors'; import { useEventCallback } from '../form/fields/document/DocumentEditor/ui-utils'; import { CreateBranchDuringUpdateDialog } from './ItemPage'; +import { LocalConflictNotice } from './local-conflict-notice'; import l10nMessages from './l10n'; -import { useBaseCommit, useCurrentBranch } from './shell/data'; +import { + useBaseCommit, + useCurrentBranch, + useRefreshLocalTree, +} from './shell/data'; import { PageRoot, PageHeader, PageBody } from './shell/page'; import { ForkRepoDialog } from './fork-repo'; import { FormForEntry, containerWidthForEntryLayout } from './entry-form'; @@ -428,6 +433,7 @@ function CreateItemInner(props: { const stringFormatter = useLocalizedStringFormatter(l10nMessages); const router = useRouter(); const config = useConfig(); + const refreshLocalTree = useRefreshLocalTree(); const { collectionConfig, schema } = useCollection(props.collection); @@ -485,6 +491,11 @@ function CreateItemInner(props: { } }; + const onReloadLatest = useEventCallback(async () => { + await refreshLocalTree(); + props.resetCreateItemState(); + }); + // note we're still "loading" when it's already been created // since we're waiting to go to the item page const isLoading = @@ -574,6 +585,12 @@ function CreateItemInner(props: { {createResult.kind === 'error' && ( {createResult.error.message} )} + {createResult.kind === 'conflict' && ( + + )} Promise; +}) { + return render( + + + + ); +} + +describe('LocalConflictNotice', () => { + test('renders conflict reason and reloads when Reload latest is pressed', async () => { + const user = userEvent.setup(); + let resolveReload!: () => void; + const onReload = vi.fn( + () => + new Promise(resolve => { + resolveReload = resolve; + }) + ); + + renderNotice({ + reason: 'This entry has changed on disk since it was opened.', + onReload, + }); + + expect(screen.getByRole('alert')).toBeInTheDocument(); + expect(screen.getByText('Save conflict')).toBeInTheDocument(); + expect( + screen.getByText('This entry has changed on disk since it was opened.') + ).toBeInTheDocument(); + + const button = screen.getByRole('button', { name: 'Reload latest' }); + await user.click(button); + + expect(onReload).toHaveBeenCalledTimes(1); + expect(button).toBeDisabled(); + + resolveReload(); + await waitFor(() => { + expect(button).toBeEnabled(); + }); + }); + + test('renders custom heading and surfaces reload failure message', async () => { + const user = userEvent.setup(); + const onReload = vi.fn(async () => { + throw new Error('Failed to fetch tree'); + }); + + renderNotice({ + heading: 'Delete conflict', + reason: 'Modified in another tab.', + onReload, + }); + + expect(screen.getByText('Delete conflict')).toBeInTheDocument(); + + const button = screen.getByRole('button', { name: 'Reload latest' }); + await user.click(button); + + expect(await screen.findByText('Failed to fetch tree')).toBeInTheDocument(); + expect(button).toBeEnabled(); + }); +}); diff --git a/packages/keystatic/src/app/local-conflict-notice.tsx b/packages/keystatic/src/app/local-conflict-notice.tsx new file mode 100644 index 000000000..78cd8ce38 --- /dev/null +++ b/packages/keystatic/src/app/local-conflict-notice.tsx @@ -0,0 +1,43 @@ +import { useState } from 'react'; + +import { Button, ButtonGroup } from '@keystar/ui/button'; +import { Notice } from '@keystar/ui/notice'; +import { Content } from '@keystar/ui/slots'; +import { Heading, Text } from '@keystar/ui/typography'; + +export function LocalConflictNotice(props: { + heading?: string; + reason: string; + onReload: () => Promise; +}) { + const [isReloading, setIsReloading] = useState(false); + const [reloadError, setReloadError] = useState(null); + + return ( + + {props.heading ?? 'Save conflict'} + + {props.reason} + {reloadError && {reloadError.message}} + + + + + + ); +} diff --git a/packages/keystatic/src/app/shell/data.tsx b/packages/keystatic/src/app/shell/data.tsx index d19ac523e..d77f4672a 100644 --- a/packages/keystatic/src/app/shell/data.tsx +++ b/packages/keystatic/src/app/shell/data.tsx @@ -70,12 +70,32 @@ export const SetTreeShaContext = createContext<(sha: string) => void>(() => { throw new Error('SetTreeShaContext not set'); }); +const RefreshLocalTreeContext = createContext<() => Promise>( + async () => {} +); + +export function useRefreshLocalTree() { + return useContext(RefreshLocalTreeContext); +} + export function LocalAppShellProvider(props: { config: LocalConfig; children: ReactNode; }) { const [currentTreeSha, setCurrentTreeSha] = useState('initial'); + const refreshLocalTree = useCallback(async () => { + const res = await fetch('/api/keystatic/tree', { + headers: { 'no-cors': '1' }, + }); + if (!res.ok) { + throw new Error(await res.text()); + } + const entries: TreeEntry[] = await res.json(); + const { tree } = await hydrateTreeCacheWithEntries(entries); + setCurrentTreeSha(await treeSha(tree)); + }, []); + const tree = useData( useCallback(() => fetchLocalTree(currentTreeSha), [currentTreeSha]) ); @@ -110,13 +130,15 @@ export function LocalAppShellProvider(props: { }, [allTreeData, props.config]); return ( - - - - {props.children} - - - + + + + + {props.children} + + + + ); } diff --git a/packages/keystatic/src/app/updating.test.tsx b/packages/keystatic/src/app/updating.test.tsx index 039edde95..9843b7b11 100644 --- a/packages/keystatic/src/app/updating.test.tsx +++ b/packages/keystatic/src/app/updating.test.tsx @@ -16,8 +16,13 @@ const mocks = vi.hoisted(() => ({ remoteHeads: [] as { oid: string; entries: TreeEntry[] }[], fetchRef: vi.fn(), fetchTree: vi.fn(), + setTreeSha: vi.fn(), + fetch: vi.fn(), + unscopedTree: [] as TreeEntry[], })); +vi.stubGlobal('fetch', mocks.fetch); + vi.mock('urql', () => ({ useMutation: () => [undefined, mocks.mutate], })); @@ -31,7 +36,7 @@ vi.mock('./provider', () => ({ vi.mock('./shell/data', () => ({ useBaseCommit: () => 'opened-head', useCurrentBranch: () => 'main', - useSetTreeSha: () => () => {}, + useSetTreeSha: () => mocks.setTreeSha, useRepoInfo: () => ({ owner: 'owner', name: 'repo', @@ -39,7 +44,7 @@ vi.mock('./shell/data', () => ({ }), useCurrentUnscopedTree: () => ({ kind: 'loaded', - data: { tree: treeEntriesToTreeNodes([]) }, + data: { tree: treeEntriesToTreeNodes(mocks.unscopedTree) }, }), fetchGitHubTreeData: (...args: unknown[]) => mocks.fetchTree(...args), hydrateTreeCacheWithEntries: async (entries: TreeEntry[]) => ({ @@ -53,7 +58,7 @@ vi.mock('./useItemData', () => ({ })); // imported after the mocks are registered -const { useUpsertItem } = await import('./updating'); +const { useDeleteItem, useUpsertItem } = await import('./updating'); const config: Config = { storage: { kind: 'github', repo: 'owner/repo' }, @@ -141,6 +146,9 @@ beforeEach(() => { mocks.mutate.mockReset(); mocks.fetchRef.mockReset(); mocks.fetchTree.mockReset(); + mocks.setTreeSha.mockReset(); + mocks.fetch.mockReset(); + mocks.unscopedTree = []; }); // CreateItemLocal and CreateItemCollab (create-item.tsx) both call @@ -218,3 +226,168 @@ describe('editing an entry (local tree key)', () => { expect(mocks.mutate).toHaveBeenCalledTimes(1); }); }); + +describe('local storage mode', () => { + const localConfig: Config = { + storage: { kind: 'local' }, + collections: { + posts: { + label: 'Posts', + slugField: 'title', + path: 'posts/*', + schema: { title: fields.slug({ name: { label: 'Title' } }) }, + }, + }, + }; + + function renderLocalUpsert(args: { + initialFiles?: string[]; + currentLocalTreeKey?: string; + slug?: string; + }) { + const slug = args.slug ?? 'my-post'; + return renderHook(() => + useUpsertItem({ + state: { title: { name: 'My post', slug } }, + initialFiles: args.initialFiles, + schema: localConfig.collections!.posts.schema, + config: localConfig, + format: { + data: 'yaml', + contentField: undefined, + dataLocation: 'index', + }, + currentLocalTreeKey: args.currentLocalTreeKey, + basePath: `posts/${slug}`, + slug: { field: 'title', value: slug }, + }) + ); + } + + test('sends expectedShas and updates tree SHA on 200', async () => { + mocks.unscopedTree = remoteTree({ 'my-post': 'v1' }); + mocks.fetch.mockResolvedValueOnce( + new Response(JSON.stringify(remoteTree({ 'my-post': 'v2' })), { + status: 200, + headers: { 'content-type': 'application/json' }, + }) + ); + + const { saved, state } = await save( + renderLocalUpsert({ + initialFiles: ['posts/my-post/index.yaml'], + currentLocalTreeKey: 'v1', + }) + ); + + expect(saved).toBe(true); + expect(state).toEqual({ kind: 'updated' }); + expect(mocks.setTreeSha).toHaveBeenCalledTimes(1); + const reqBody = JSON.parse(mocks.fetch.mock.calls[0][1].body); + expect(reqBody.expectedShas).toEqual([ + { path: 'posts/my-post', sha: 'v1' }, + { path: 'posts/my-post/index.yaml', sha: 'v1-file' }, + ]); + }); + + test('returns conflict state without updating tree SHA on 409 during edit', async () => { + mocks.unscopedTree = remoteTree({ 'my-post': 'v1' }); + mocks.fetch.mockResolvedValueOnce( + new Response( + JSON.stringify({ code: 'CONFLICT', message: 'Changed on disk' }), + { status: 409, headers: { 'content-type': 'application/json' } } + ) + ); + + const { saved, state } = await save( + renderLocalUpsert({ + initialFiles: ['posts/my-post/index.yaml'], + currentLocalTreeKey: 'v1', + }) + ); + + expect(saved).toBe(false); + expect(state.kind).toBe('conflict'); + if (state.kind === 'conflict') { + expect(state.reason).toContain('changed on disk'); + } + expect(mocks.setTreeSha).not.toHaveBeenCalled(); + }); + + test('sends null expectedShas when creating and surfaces slug conflict on 409', async () => { + mocks.unscopedTree = remoteTree({ other: 'other-v1' }); + mocks.fetch.mockResolvedValueOnce( + new Response(JSON.stringify({ code: 'CONFLICT', message: 'Conflict' }), { + status: 409, + headers: { 'content-type': 'application/json' }, + }) + ); + + const { saved, state } = await save(renderLocalUpsert({})); + + expect(saved).toBe(false); + expect(state.kind).toBe('conflict'); + if (state.kind === 'conflict') { + expect(state.reason).toContain('slug already exists'); + } + expect(mocks.setTreeSha).not.toHaveBeenCalled(); + const reqBody = JSON.parse(mocks.fetch.mock.calls[0][1].body); + expect(reqBody.expectedShas).toEqual([ + { path: 'posts/my-post', sha: null }, + { path: 'posts/my-post/index.yaml', sha: null }, + ]); + }); + + test('sets error state on non-conflict HTTP failure', async () => { + mocks.unscopedTree = remoteTree({ 'my-post': 'v1' }); + mocks.fetch.mockResolvedValueOnce( + new Response('Internal Server Error', { status: 500 }) + ); + + const { saved, state } = await save( + renderLocalUpsert({ + initialFiles: ['posts/my-post/index.yaml'], + currentLocalTreeKey: 'v1', + }) + ); + + expect(saved).toBe(false); + expect(state.kind).toBe('error'); + if (state.kind === 'error') { + expect(state.error.message).toBe('Internal Server Error'); + } + expect(mocks.setTreeSha).not.toHaveBeenCalled(); + }); + + test('useDeleteItem sends expectedShas and handles 409 conflict without updating tree SHA', async () => { + mocks.unscopedTree = remoteTree({ 'my-post': 'v1' }); + mocks.fetch.mockResolvedValueOnce( + new Response(JSON.stringify({ code: 'CONFLICT', message: 'Conflict' }), { + status: 409, + headers: { 'content-type': 'application/json' }, + }) + ); + + const hook = renderHook(() => + useDeleteItem({ + basePath: 'posts/my-post', + initialFiles: ['posts/my-post/index.yaml'], + storage: localConfig.storage, + }) + ); + + let deleted: boolean | undefined; + await act(async () => { + deleted = await hook.result.current[1](); + }); + + expect(deleted).toBe(false); + expect(hook.result.current[0].kind).toBe('conflict'); + expect(mocks.setTreeSha).not.toHaveBeenCalled(); + const reqBody = JSON.parse(mocks.fetch.mock.calls[0][1].body); + expect(reqBody.expectedShas).toEqual([ + { path: 'posts/my-post', sha: 'v1' }, + { path: 'posts/my-post/index.yaml', sha: 'v1-file' }, + ]); + }); +}); diff --git a/packages/keystatic/src/app/updating.tsx b/packages/keystatic/src/app/updating.tsx index d9e87d11b..e02bbe5cc 100644 --- a/packages/keystatic/src/app/updating.tsx +++ b/packages/keystatic/src/app/updating.tsx @@ -19,6 +19,7 @@ import { FormatInfo, getEntryDataFilepath, getPathPrefix } from './path-utils'; import { getTreeNodeAtPath, TreeEntry, + TreeNode, treeSha, updateTreeWithChanges, } from './trees'; @@ -106,6 +107,57 @@ export function serializeEntryToFiles(args: { ]; } +function getExpectedShas( + unscopedTree: Map, + paths: Iterable +) { + return [...new Set(paths)].map(path => ({ + path, + sha: getTreeNodeAtPath(unscopedTree, path)?.entry.sha ?? null, + })); +} + +async function sendLocalUpdate(args: { + additions: { path: string; contents: string }[]; + deletions: { path: string }[]; + expectedShas: { path: string; sha: string | null }[]; +}): Promise< + | { kind: 'updated'; tree: Map } + | { kind: 'conflict'; message: string } +> { + const res = await fetch('/api/keystatic/update', { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'no-cors': '1', + }, + body: JSON.stringify(args), + }); + if (res.status === 409) { + let message = 'This entry has changed on disk since it was loaded.'; + try { + const text = await res.text(); + if (text) { + try { + const parsed = JSON.parse(text); + if (typeof parsed?.message === 'string' && parsed.message) { + message = parsed.message; + } + } catch { + message = text; + } + } + } catch {} + return { kind: 'conflict', message }; + } + if (!res.ok) { + throw new Error(await res.text()); + } + const newTree: TreeEntry[] = await res.json(); + const { tree } = await hydrateTreeCacheWithEntries(newTree); + return { kind: 'updated', tree }; +} + export function useUpsertItem(args: { state: unknown; initialFiles: string[] | undefined; @@ -123,6 +175,7 @@ export function useUpsertItem(args: { | { kind: 'needs-fork' } | { kind: 'error'; error: Error } | { kind: 'needs-new-branch'; reason: string } + | { kind: 'conflict'; reason: string } >({ kind: 'idle', }); @@ -194,15 +247,15 @@ export function useUpsertItem(args: { const deletions: { path: string }[] = [...filesToDelete].map(path => ({ path, })); - const updatedTree = await updateTreeWithChanges(unscopedTree, { - additions, - deletions: [...filesToDelete], - }); - await hydrateTreeCacheWithEntries(updatedTree.entries); if ( args.config.storage.kind === 'github' || args.config.storage.kind === 'cloud' ) { + const updatedTree = await updateTreeWithChanges(unscopedTree, { + additions, + deletions: [...filesToDelete], + }); + await hydrateTreeCacheWithEntries(updatedTree.entries); if (!repoInfo) { throw new Error('Repo info not loaded'); } @@ -314,26 +367,37 @@ export function useUpsertItem(args: { } throw new Error('Failed to update'); } else { - const res = await fetch('/api/keystatic/update', { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - 'no-cors': '1', - }, - body: JSON.stringify({ - additions: additions.map(addition => ({ - ...addition, - contents: base64Encode(addition.contents), - })), - deletions, - }), + const directoriesForTreeKey = getDirectoriesForTreeKey( + fields.object(args.schema), + args.basePath, + args.slug?.value, + args.format + ).map(dir => pathPrefix + dir); + const expectedShas = getExpectedShas(unscopedTree, [ + ...directoriesForTreeKey, + ...(args.initialFiles?.map(x => pathPrefix + x) ?? []), + ...additions.map(addition => addition.path), + ...deletions.map(deletion => deletion.path), + ]); + const result = await sendLocalUpdate({ + additions: additions.map(addition => ({ + ...addition, + contents: base64Encode(addition.contents), + })), + deletions, + expectedShas, }); - if (!res.ok) { - throw new Error(await res.text()); + if (result.kind === 'conflict') { + const isCreating = !args.initialFiles?.length; + const reason = isCreating + ? args.slug + ? 'An entry with this slug already exists on disk. Change the slug or reload to view the existing entry.' + : 'This entry has already been created or modified on disk since it was opened. Reload to load the latest version, or copy your changes before reloading.' + : 'This entry has changed on disk since it was opened (for example, in another browser tab). Reload to get the latest version — your unsaved changes are still in the editor if you want to copy them first.'; + setState({ kind: 'conflict', reason }); + return false; } - const newTree: TreeEntry[] = await res.json(); - const { tree } = await hydrateTreeCacheWithEntries(newTree); - setTreeSha(await treeSha(tree)); + setTreeSha(await treeSha(result.tree)); setState({ kind: 'updated' }); return true; } @@ -379,6 +443,7 @@ export function useDeleteItem(args: { | { kind: 'loading' } | { kind: 'needs-fork' } | { kind: 'error'; error: Error } + | { kind: 'conflict'; reason: string } >({ kind: 'idle', }); @@ -410,15 +475,14 @@ export function useDeleteItem(args: { return false; } setState({ kind: 'loading' }); - const deletions = args.initialFiles.map( - x => (getPathPrefix(args.storage) ?? '') + x - ); - const updatedTree = await updateTreeWithChanges(unscopedTree, { - additions: [], - deletions, - }); - await hydrateTreeCacheWithEntries(updatedTree.entries); + const pathPrefix = getPathPrefix(args.storage) ?? ''; + const deletions = args.initialFiles.map(x => pathPrefix + x); if (args.storage.kind === 'github' || args.storage.kind === 'cloud') { + const updatedTree = await updateTreeWithChanges(unscopedTree, { + additions: [], + deletions, + }); + await hydrateTreeCacheWithEntries(updatedTree.entries); if (!repoInfo) { throw new Error('Repo info not loaded'); } @@ -453,28 +517,30 @@ export function useDeleteItem(args: { setState({ kind: 'updated' }); return true; } else { - const res = await fetch('/api/keystatic/update', { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - 'no-cors': '1', - }, - body: JSON.stringify({ - additions: [], - deletions: deletions.map(path => ({ path })), - }), + const expectedShas = getExpectedShas(unscopedTree, [ + ...(args.basePath ? [pathPrefix + args.basePath] : []), + ...deletions, + ]); + const result = await sendLocalUpdate({ + additions: [], + deletions: deletions.map(path => ({ path })), + expectedShas, }); - if (!res.ok) { - throw new Error(await res.text()); + if (result.kind === 'conflict') { + setState({ + kind: 'conflict', + reason: + 'This entry has changed on disk since it was opened (for example, in another browser tab). Reload to review the latest version before deleting.', + }); + return false; } - const newTree: TreeEntry[] = await res.json(); - const { tree } = await hydrateTreeCacheWithEntries(newTree); - setTreeSha(await treeSha(tree)); + setTreeSha(await treeSha(result.tree)); setState({ kind: 'updated' }); return true; } } catch (err) { setState({ kind: 'error', error: err as Error }); + return false; } }, () => {