Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions apps/api/src/services/person.write.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ import { requireAuth } from '../auth/require.js';
import type { SessionContext } from '../auth/middleware.js';
import { applyTagsForEntity, type TagAssignmentInput, type TagNamespace } from './tag.write.js';
import type { PrivateStore } from '../store/private/index.js';
import { rekeyAttachment, restoreAttachments, takeAttachments } from './slug-rename.js';

function nowIso(): string {
return new Date().toISOString();
Expand Down Expand Up @@ -109,12 +110,15 @@ export class PersonWriteService {
slackHandle:
input.slackHandle === undefined ? (existing.slackHandle ?? null) : input.slackHandle,
slug: newSlug,
avatarKey: rekeyAttachment(existing.avatarKey, 'people', existing.slug, newSlug),
updatedAt: now,
});

const stateApply = new StateApply();

let attachments: Awaited<ReturnType<typeof takeAttachments>> = null;
if (newSlug !== existing.slug) {
attachments = await takeAttachments(tx.public.people, existing);
await tx.public.people.delete(existing);
const history = {
id: uuidv7(),
Expand All @@ -131,6 +135,7 @@ export class PersonWriteService {
}

await tx.public.people.upsert(updated);
await restoreAttachments(tx.public.people, updated, attachments);
stateApply.upsertPerson(updated);

// Email change → private profile update (no public diff)
Expand Down
11 changes: 9 additions & 2 deletions apps/api/src/services/project.write.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import {
import { requireAuth } from '../auth/require.js';
import type { SessionContext } from '../auth/middleware.js';
import { applyTagsForEntity, type TagAssignmentInput } from './tag.write.js';
import { rekeyAttachment, restoreAttachments, takeAttachments } from './slug-rename.js';

export interface CreateProjectInput {
readonly title: string;
Expand Down Expand Up @@ -280,15 +281,20 @@ export class ProjectWriteService {
featured: input.featured ?? existing.featured,
featuredImageKey:
input.featuredImageKey === undefined
? (existing.featuredImageKey ?? null)
? (slugRename
? rekeyAttachment(existing.featuredImageKey, 'projects', slugRename.oldSlug, slugRename.newSlug)
: existing.featuredImageKey) ?? null
: input.featuredImageKey,
updatedAt: now,
});

const stateApply = new StateApply();

let attachments: Awaited<ReturnType<typeof takeAttachments>> = null;
if (slugRename) {
// Delete the old path first, then upsert at the new path.
// Delete the old path first, then upsert at the new path, carrying
// the record's attachments across (delete removes them).
attachments = await takeAttachments(tx.public.projects, existing);
await tx.public.projects.delete(existing);
// SlugHistory record
const history = {
Expand All @@ -306,6 +312,7 @@ export class ProjectWriteService {
}

await tx.public.projects.upsert(updated);
await restoreAttachments(tx.public.projects, updated, attachments);
stateApply.upsertProject(updated);

// Tag replacement (per-namespace)
Expand Down
50 changes: 50 additions & 0 deletions apps/api/src/services/slug-rename.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
/**
* Keep a record's attachments across a slug rename.
*
* A rename deletes the record at its old path and upserts it at the new one.
* gitsheets' delete also removes the record's attachment folder, so without
* this the attachments (avatars, featured images) are lost and the on-record
* key points at a path that no longer exists. specs/behaviors/slug-handles.md:
* a rename changes the handle and nothing else about the entity.
*
* Interim until gitsheets can move a record together with its attachments
* (plans/slug-rename-attachments.md).
*/
import type { BlobHandle } from 'gitsheets';

interface AttachmentSheet<T> {
getAttachments(record: T | string): Promise<Record<string, BlobHandle> | null>;
setAttachments(record: T | string, attachments: Record<string, BlobHandle>): Promise<void>;
}

/** Read the record's attachments before its old path is deleted. */
export async function takeAttachments<T>(
sheet: AttachmentSheet<T>,
record: T,
): Promise<Record<string, BlobHandle> | null> {
const attachments = await sheet.getAttachments(record);
return attachments && Object.keys(attachments).length > 0 ? attachments : null;
}

/** Re-attach to the record at its new path (blobs are reused by hash). */
export async function restoreAttachments<T>(
sheet: AttachmentSheet<T>,
record: T,
attachments: Record<string, BlobHandle> | null,
): Promise<void> {
if (attachments) await sheet.setAttachments(record, attachments);
}

/**
* Rewrite an on-record attachment key (`<root>/<oldSlug>/<name>`) to the
* renamed record's path. Keys pointing anywhere else are returned unchanged.
*/
export function rekeyAttachment(
key: string | null | undefined,
root: string,
oldSlug: string,
newSlug: string,
): string | null | undefined {
const prefix = `${root}/${oldSlug}/`;
return key?.startsWith(prefix) ? `${root}/${newSlug}/${key.slice(prefix.length)}` : key;
}
41 changes: 41 additions & 0 deletions apps/api/tests/avatar-upload.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -331,3 +331,44 @@ describe('POST /api/people/:slug/avatar', () => {
expect([413, 422]).toContain(res.statusCode);
});
});

describe('slug rename keeps the avatar', () => {
it('serves the avatar at the renamed key and rewrites avatarKey', async () => {
const jpeg = await makeTestImage({ width: 300, height: 300, format: 'jpeg' });
const { accessToken } = await mintSessionFor(PERSON_ID, 'user', JWT_KEY);

const upload = await injectMultipart(app!, {
url: '/api/people/me/avatar',
field: 'image',
filename: 'avatar.jpg',
contentType: 'image/jpeg',
body: jpeg,
cookieToken: accessToken,
});
expect(upload.statusCode).toBe(200);

const rename = await app!.inject({
method: 'PATCH',
url: '/api/people/me',
headers: { cookie: `cfp_session=${accessToken}` },
payload: { slug: 'me-renamed' },
});
expect(rename.statusCode).toBe(200);

const person = await app!.inject({ method: 'GET', url: '/api/people/me-renamed' });
expect(person.statusCode).toBe(200);
const body = person.json<{ data: { avatarUrl: string | null } }>();
expect(body.data.avatarUrl).toBe('/api/attachments/people/me-renamed/avatar.jpg');

for (const name of ['avatar.jpg', 'avatar-128.jpg']) {
const res = await app!.inject({
method: 'GET',
url: `/api/attachments/people/me-renamed/${name}`,
});
expect(res.statusCode, name).toBe(200);
expect(res.rawPayload.length, name).toBeGreaterThan(0);
}
const old = await app!.inject({ method: 'GET', url: '/api/attachments/people/me/avatar.jpg' });
expect(old.statusCode).toBe(404);
});
});
41 changes: 40 additions & 1 deletion apps/api/tests/write-api.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import type { FastifyInstance } from 'fastify';
import { buildApp } from '../src/app.js';
import { mintSessionFor } from '../src/auth/issue.js';
import { createFullDataRepo, createPrivateStorageDir } from './helpers/test-full-repo.js';
import { seedFixtures, type SeededFixtures } from './helpers/seed-fixtures.js';
import { seedFixtures, seedRawBlob, type SeededFixtures } from './helpers/seed-fixtures.js';

// ---------------------------------------------------------------------------
// Test setup
Expand Down Expand Up @@ -203,6 +203,45 @@ describe('PATCH /api/projects/:slug', () => {
expect(res.statusCode).toBe(422);
});

it('staff rename carries project attachments and featuredImageKey to the new slug', async () => {
const hero = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x01, 0x02, 0x03]);
await seedRawBlob(
dataRepo.path,
`projects/${fixtures.projectSlug}/hero.png`,
hero,
'seed project hero image',
);
const cookie = await userCookie(fixtures.personId, 'staff');

const setKey = await app!.inject({
method: 'PATCH',
url: `/api/projects/${fixtures.projectSlug}`,
headers: { cookie, 'content-type': 'application/json' },
payload: { featuredImageKey: `projects/${fixtures.projectSlug}/hero.png` },
});
expect(setKey.statusCode).toBe(200);

const rename = await app!.inject({
method: 'PATCH',
url: `/api/projects/${fixtures.projectSlug}`,
headers: { cookie, 'content-type': 'application/json' },
payload: { slug: 'hero-renamed' },
});
expect(rename.statusCode).toBe(200);

const project = app!.inMemoryState.projects.get(fixtures.projectId);
expect(project?.featuredImageKey).toBe('projects/hero-renamed/hero.png');

const moved = await app!.inject({ method: 'GET', url: '/api/attachments/projects/hero-renamed/hero.png' });
expect(moved.statusCode).toBe(200);
expect(moved.rawPayload.equals(hero)).toBe(true);
const old = await app!.inject({
method: 'GET',
url: `/api/attachments/projects/${fixtures.projectSlug}/hero.png`,
});
expect(old.statusCode).toBe(404);
});

it('staff can rename slug; old slug becomes 404 and slug-history exists', async () => {
const cookie = await userCookie(fixtures.personId, 'staff');
const res = await app!.inject({
Expand Down
13 changes: 9 additions & 4 deletions plans/slug-rename-attachments.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
---
status: planned
status: in-progress
depends: [slug-history-config]
specs:
- specs/behaviors/slug-handles.md
Expand Down Expand Up @@ -48,16 +48,21 @@ later commit once the move API ships.

## Validation

- [ ] Test: rename a person with an avatar; the avatar is served at the new
- [x] Test: rename a person with an avatar; the avatar is served at the new
key and `avatarKey` matches
- [ ] Test: rename a project; no attachments are orphaned
- [x] Test: rename a project; no attachments are orphaned
- [ ] (after upstream) no delete-then-upsert left in the rename paths
- [ ] `type-check` + `lint` + full api suite green
- [x] `type-check` + `lint` + full api suite green

## Risks / unknowns

- Attachment-copy cost for records with many attachments; avatars are small.

## Notes

- Interim fix landed in PR #201 (`services/slug-rename.ts`): attachments are
read before the delete and re-attached by blob hash, and `avatarKey` /
`featuredImageKey` are rewritten. What's left is swapping this for a native
gitsheets move once one exists (see `awaits`).

## Follow-ups
1 change: 1 addition & 0 deletions specs/behaviors/slug-handles.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ Uniqueness violation on create or rename → `409 conflict`.
Slugs **can** change. When they do:

- The entity record's `slug` field is updated.
- The entity's attachments (avatar, featured image) move with the record, and any on-record attachment key (`avatarKey`, `featuredImageKey`) is rewritten to the new path. A rename changes the handle and nothing else about the entity.
- A `SlugHistory` record is written to the `slug-history` sheet (see [data-model.md](../data-model.md#slughistory)) with `oldSlug`, `newSlug`, `entityType`, `entityId`, `changedAt`, and `expiresAt = changedAt + 90 days`.
- On any request to a URL using an `oldSlug` that is *not yet* expired, the web layer serves a **301 redirect** to the current canonical URL.
- After `expiresAt`, the redirect is no longer served. The record is retained as part of the commit history but is removed from the sheet by a periodic sweeper task.
Expand Down
Loading