fix(sync): a task delete takes its subtasks and tag links with it #197

Merged
maximus merged 3 commits from issue-196-task-delete-cascade into master 2026-11-08 18:30:35 +00:00
11 changed files with 342 additions and 26 deletions

View file

@ -114,7 +114,7 @@ Chaque règle cite sa source. Elles valent quel que soit le niveau : une PR norm
- Une suppression côté serveur est un soft-delete (`deletedAt`), relayé à l'app par le pull. — `web/src/app/api/sync/route.ts`
- Le pull garde le `createdAt` local d'une ligne existante, et le `calendarEventId` d'une tâche (colonne absente du serveur). — `src/services/syncRules.ts` (`pulled*Values`), #149
- Dans un pull depuis `SYNC_EPOCH` (première sync, ou après une déconnexion qui remet `lastSyncAt` à null), une liste ou une tâche locale strictement plus récente que le serveur est gardée et remise dans l'outbox (`queueOutboxEntry`, action `update`, écrite même sync éteinte : la première sync tourne avant l'activation, #165). Jamais une étiquette : l'app ne garde pas de date de modification pour les étiquettes, donc un renommage hors connexion d'étiquette reste perdu face au serveur (check smoke « applyTagChange never keeps a local tag »). — `src/services/syncRules.ts` (`keepLocal`), `src/services/syncClient.ts`, #149, #181
- Une étiquette a un `updatedAt` serveur (migration `0003_tag_updated_at`, rempli par `created_at` pour les lignes existantes) : `GET /api/sync` la tire sur `updatedAt >= since` et renvoie `updated_at` = `updatedAt`. Toute écriture d'une étiquette (`PUT`/`DELETE /api/tags/[id]`, `tag update`/`tag delete` de `POST /api/sync`) avance `updatedAt`. La suppression d'une étiquette retire ses liens `sl_task_tags` et avance `updatedAt` des tâches touchées dans la même transaction, pour que l'app réaligne leurs liens. — `web/src/db/schema.ts`, `web/src/app/api/sync/route.ts`, `web/src/app/api/tags/[id]/route.ts`, `web/src/app/api/sync/route.test.ts`, #181
- Une étiquette a un `updatedAt` serveur (migration `0003_tag_updated_at`, rempli par `created_at` pour les lignes existantes) : `GET /api/sync` la tire sur `updatedAt >= since` et renvoie `updated_at` = `updatedAt`. Toute écriture d'une étiquette (`PUT`/`DELETE /api/tags/[id]`, `tag update`/`tag delete` de `POST /api/sync`) avance `updatedAt`. La suppression d'une étiquette retire ses liens `sl_task_tags` et avance `updatedAt` des tâches touchées dans la même transaction, pour que l'app réaligne leurs liens. La suppression d'une tâche (`task delete` de `POST /api/sync`, `DELETE /api/tasks/[id]`) passe par `deleteTask` : dans une transaction, la tâche et ses sous-tâches actives du même compte, sur un seul niveau, reçoivent `deletedAt`, et les liens de la tâche et de ses sous-tâches sont retirés. Un lien créé vers une tâche ou une étiquette supprimée n'est jamais écrit : `taskTag create` répond `applied`, `POST /api/tasks/[id]/tags` écarte les étiquettes supprimées et répond 404 pour une tâche supprimée ; la vérification se fait dans la transaction de l'écriture. Toute transaction qui écrit un lien `sl_task_tags` pour une tâche verrouille d'abord la ligne de cette tâche (`lockTaskForLinks`, `FOR NO KEY UPDATE`), avant toute autre ligne : un autre ordre fait s'interbloquer deux écritures simultanées (`40P01`), ce qu'aucun test PGlite ne voit (une seule connexion). La sonde attend 0 au contrôle 3 (`lien_tache_supprimee`). — `web/src/db/schema.ts`, `web/src/app/api/sync/route.ts`, `web/src/app/api/tags/[id]/route.ts`, `web/src/lib/taskDelete.ts`, `web/src/app/api/tasks/[id]/route.ts`, `web/src/app/api/tasks/[id]/tags/route.ts`, `web/src/app/api/tasks/[id]/tags/[tagId]/route.ts`, `web/src/db/migrations/0004_cleanup_deleted_task_links.sql`, `web/src/app/api/sync/route.test.ts`, #181, #196
- Après la fusion de la première sync, `initialMerge` tire tout le serveur depuis `SYNC_EPOCH` ; `lastSyncAt` est posé à cette date avant le pull, pour qu'un pull raté se rejoue au `fullSync` suivant (#150). — `src/services/syncClient.ts`, `src/services/syncRules.ts` (`mergeTaskData`)
- Une suppression serveur s'applique toujours, même sur une ligne locale plus récente : le protocole n'a pas de restauration. — `src/services/syncClient.ts`, #149
- `src/services/syncRules.ts` reste sans import, pour que `tests/syncRules.test.mjs` le charge par le type stripping de Node (check smoke `syncRules.ts stays import-free`). `src/services/syncSchedule.ts` et `src/services/syncTrigger.ts` suivent la même règle pour `tests/syncSchedule.test.mjs`, et `src/services/syncSocket.ts` pour `tests/syncSocket.test.mjs` (check smoke `syncSchedule.ts, syncTrigger.ts and syncSocket.ts stay import-free`). — `tests/smoke.test.cjs`, `tests/syncRules.test.mjs`, `tests/syncSchedule.test.mjs`, `tests/syncSocket.test.mjs`, #149, #178, #175

View file

@ -15,10 +15,9 @@
-- 2. lien_etiquette_supprimee sl_task_tags links from an active task to a
-- deleted tag. anomaly
-- 3. lien_tache_supprimee sl_task_tags links from a deleted task. anomaly
-- GET /api/sync does not filter them: it returns the links of every task
-- updated since `since`, soft-deleted tasks included, and a task delete
-- does not remove its links. So the count grows with every deleted tagged
-- task; read it against the previous run's baseline.
-- Expected 0: a task delete removes its links and its subtasks' links,
-- and migration 0004 removed the older ones (#196). GET /api/sync does
-- not filter them, so a non-zero count means the defect is back.
-- 4. tache_liste_supprimee active tasks whose list is deleted. anomaly
-- 5. sous_tache_parent_absent active tasks whose parent_id matches no row
-- (parent_id has no foreign key). anomaly

View file

@ -47,6 +47,7 @@ const { GET, POST } = await import('./route');
const { POST: postTaskTags } = await import('../tasks/[id]/tags/route');
const { DELETE: deleteTaskTag } = await import('../tasks/[id]/tags/[tagId]/route');
const { PUT: putTag, DELETE: deleteTag } = await import('../tags/[id]/route');
const { DELETE: deleteTaskRoute } = await import('../tasks/[id]/route');
const { NextRequest } = await import('next/server');
type Op = [entityType: string, action: string, entityId: string, data?: Record<string, unknown>];
@ -923,3 +924,236 @@ describe('tags carry an updatedAt that the pull follows (#181)', () => {
expect(taskIds(await pull(A.userId))).toEqual([]);
});
});
describe('a task delete takes its subtasks and every link with it (#196)', () => {
const OLD = '2020-01-01T00:00:00.000Z';
// B.parent gets B.sub (seed) plus an already-deleted subtask, and A slips a
// task of its own under B.parent (cross-account parent, probe control 8):
// the delete must leave both alone. B.tag is linked to B.parent and B.sub.
async function setup() {
const { A, B } = await seed();
expect(await push(B.userId, [
['taskTag', 'create', B.parent, { tagId: B.tag }],
['taskTag', 'create', B.sub, { tagId: B.tag }],
])).toEqual(['applied', 'applied']);
const gone = u();
await h.pg.query(
'insert into sl_tasks (id, user_id, title, list_id, parent_id, deleted_at, updated_at) values ($1, $2, $3, $4, $5, $6, $6)',
[gone, B.userId, 'gone', B.list, B.parent, OLD],
);
const foreign = u();
await h.pg.query(
'insert into sl_tasks (id, user_id, title, list_id, parent_id) values ($1, $2, $3, $4, $5)',
[foreign, A.userId, 'foreign', A.list, B.parent],
);
await h.pg.query('insert into sl_task_tags (task_id, tag_id) values ($1, $2)', [foreign, A.tag]);
return { A, B, gone, foreign };
}
async function links(taskIds: string[]): Promise<number> {
return (await row<{ c: number }>('select count(*)::int c from sl_task_tags where task_id = any($1::uuid[])', [taskIds]))!.c;
}
async function deletedAt(taskId: string): Promise<string | null> {
const r = await row<{ d: Date | null }>('select deleted_at d from sl_tasks where id=$1', [taskId]);
return r!.d ? new Date(r!.d).toISOString() : null;
}
async function updatedAt(taskId: string): Promise<string> {
const r = await row<{ t: Date }>('select updated_at t from sl_tasks where id=$1', [taskId]);
return new Date(r!.t).toISOString();
}
async function expectCascade({ B, gone, foreign }: Awaited<ReturnType<typeof setup>>) {
expect(await links([B.parent, B.sub, gone])).toBe(0);
expect(await deletedAt(B.parent)).not.toBeNull();
expect(await deletedAt(B.sub)).not.toBeNull();
// Already deleted: its date does not move. Another account: untouched.
expect(await deletedAt(gone)).toBe(OLD);
expect(await deletedAt(foreign)).toBeNull();
expect(await links([foreign])).toBe(1);
// The other tagged task of the account keeps its link
expect(await links([B.task])).toBe(1);
}
async function pulledSubDelete(userId: string, subId: string) {
h.userId = userId;
const since = new Date(new Date(OLD).getTime() + 1000).toISOString();
const res = await GET(new NextRequest(`http://localhost/api/sync?since=${encodeURIComponent(since)}`));
const { changes } = await res.json() as { changes: { entity_type: string; entity_id: string; action: string }[] };
return changes.find((c) => c.entity_type === 'task' && c.entity_id === subId)?.action;
}
it('POST /api/sync task delete of a tagged task leaves no link', async () => {
const { B } = await seed();
expect(await push(B.userId, [['task', 'delete', B.task, { id: B.task }]])).toEqual(['applied']);
expect(await links([B.task])).toBe(0);
});
it('POST /api/sync task delete of a parent deletes its active subtasks and all their links', async () => {
const s = await setup();
await h.pg.query('update sl_tasks set updated_at=$1 where id=$2', [OLD, s.B.sub]);
expect(await push(s.B.userId, [['task', 'delete', s.B.parent, { id: s.B.parent }]])).toEqual(['applied']);
await expectCascade(s);
expect(await pulledSubDelete(s.B.userId, s.B.sub)).toBe('delete');
});
it('DELETE /api/tasks/[id] of a parent deletes its active subtasks and all their links', async () => {
const s = await setup();
h.userId = s.B.userId;
h.notified.length = 0;
const res = await deleteTaskRoute(new Request('http://localhost', { method: 'DELETE' }), { params: Promise.resolve({ id: s.B.parent }) });
expect(res.status).toBe(200);
expect(h.notified).toEqual([s.B.userId]);
await expectCascade(s);
});
it('DELETE /api/tasks/[id] of a tagged task leaves no link', async () => {
const { B } = await seed();
h.userId = B.userId;
const res = await deleteTaskRoute(new Request('http://localhost', { method: 'DELETE' }), { params: Promise.resolve({ id: B.task }) });
expect(res.status).toBe(200);
expect(await links([B.task])).toBe(0);
});
it('DELETE /api/tasks/[id] on another account\'s task: 404, its task, subtasks and links untouched', async () => {
const s = await setup();
h.userId = s.A.userId;
h.notified.length = 0;
const res = await deleteTaskRoute(new Request('http://localhost', { method: 'DELETE' }), { params: Promise.resolve({ id: s.B.parent }) });
expect(res.status).toBe(404);
expect(h.notified).toEqual([]);
expect(await deletedAt(s.B.parent)).toBeNull();
expect(await deletedAt(s.B.sub)).toBeNull();
expect(await links([s.B.parent, s.B.sub])).toBe(2);
expect(await deletedAt(s.foreign)).toBeNull();
});
it('POST /api/sync taskTag create to a deleted task: applied, nothing written', async () => {
const { B } = await seed();
expect(await push(B.userId, [['task', 'delete', B.task, { id: B.task }]])).toEqual(['applied']);
await h.pg.query('update sl_tasks set updated_at=$1 where id=$2', [OLD, B.task]);
expect(await pushResults(B.userId, [['taskTag', 'create', B.task, { tagId: B.tag }]])).toEqual([{ status: 'applied' }]);
expect(await links([B.task])).toBe(0);
expect(await updatedAt(B.task)).toBe(OLD);
});
it('POST /api/sync taskTag create to a deleted tag: applied, nothing written', async () => {
const { B } = await seed();
const gone = u();
expect(await push(B.userId, [
['tag', 'create', gone, { name: 'gone', color: '#4A90A4' }],
['tag', 'delete', gone, { id: gone }],
])).toEqual(['applied', 'applied']);
await h.pg.query('update sl_tasks set updated_at=$1 where id=$2', [OLD, B.task]);
expect(await pushResults(B.userId, [['taskTag', 'create', B.task, { tagId: gone }]])).toEqual([{ status: 'applied' }]);
expect(await row('select count(*)::int c from sl_task_tags where tag_id=$1', [gone])).toEqual({ c: 0 });
expect(await updatedAt(B.task)).toBe(OLD);
});
it('POST /api/sync taskTag create still refuses another account\'s deleted task', async () => {
const { A, B } = await seed();
expect(await push(A.userId, [['task', 'delete', A.task, { id: A.task }]])).toEqual(['applied']);
expect(await push(B.userId, [['taskTag', 'create', A.task, { tagId: B.tag }]])).toEqual(['skipped']);
});
async function addTags(userId: string, taskId: string, tagIds: string[]) {
h.userId = userId;
return postTaskTags(
new Request('http://localhost', { method: 'POST', body: JSON.stringify({ tagIds }) }),
{ params: Promise.resolve({ id: taskId }) },
);
}
it('POST /api/tasks/[id]/tags on a deleted task: 404, nothing written', async () => {
const { B } = await seed();
expect(await push(B.userId, [['task', 'delete', B.task, { id: B.task }]])).toEqual(['applied']);
await h.pg.query('update sl_tasks set updated_at=$1 where id=$2', [OLD, B.task]);
expect((await addTags(B.userId, B.task, [B.tag])).status).toBe(404);
expect(await links([B.task])).toBe(0);
expect(await updatedAt(B.task)).toBe(OLD);
});
it('POST /api/tasks/[id]/tags drops deleted tags and inserts the active ones', async () => {
const { B } = await seed();
const [active, gone] = [u(), u()];
expect(await push(B.userId, [
['tag', 'create', active, { name: 'active', color: '#4A90A4' }],
['tag', 'create', gone, { name: 'gone', color: '#4A90A4' }],
['tag', 'delete', gone, { id: gone }],
])).toEqual(['applied', 'applied', 'applied']);
expect((await addTags(B.userId, B.parent, [active, gone])).status).toBe(201);
const r = await h.pg.query<{ tag_id: string }>('select tag_id from sl_task_tags where task_id=$1', [B.parent]);
expect(r.rows.map((x) => x.tag_id)).toEqual([active]);
});
it('POST /api/tasks/[id]/tags with only deleted tags: 201, nothing written, no notification', async () => {
const { B } = await seed();
const gone = u();
expect(await push(B.userId, [
['tag', 'create', gone, { name: 'gone', color: '#4A90A4' }],
['tag', 'delete', gone, { id: gone }],
])).toEqual(['applied', 'applied']);
await h.pg.query('update sl_tasks set updated_at=$1 where id=$2', [OLD, B.parent]);
h.notified.length = 0;
expect((await addTags(B.userId, B.parent, [gone])).status).toBe(201);
expect(await links([B.parent])).toBe(0);
expect(await updatedAt(B.parent)).toBe(OLD);
expect(h.notified).toEqual([]);
});
it('POST /api/tasks/[id]/tags still answers 404 for another account\'s deleted tag', async () => {
const { A, B } = await seed();
expect(await push(A.userId, [['tag', 'delete', A.tag, { id: A.tag }]])).toEqual(['applied']);
expect((await addTags(B.userId, B.task, [A.tag])).status).toBe(404);
});
it('the probe counts no link of a deleted task after the delete scenarios', async () => {
const s = await setup();
expect(await push(s.B.userId, [['task', 'delete', s.B.parent, { id: s.B.parent }]])).toEqual(['applied']);
h.userId = s.B.userId;
await deleteTaskRoute(new Request('http://localhost', { method: 'DELETE' }), { params: Promise.resolve({ id: s.B.task }) });
const probe = fs.readFileSync(path.join(__dirname, '../../../../scripts/probe.sql'), 'utf8');
const results = await h.pg.exec(probe);
const rows = results.filter((r) => r.fields.length > 0)[0].rows as { controle: string; nombre: number }[];
expect(rows.find((r) => r.controle === 'lien_tache_supprimee')).toEqual({ controle: 'lien_tache_supprimee', nombre: 0 });
});
it('migration 0004 removes the links of deleted tasks, keeps the others, and replays without effect', async () => {
const { PGlite } = await import('electric-sql-pglite');
const pg = new PGlite();
const dir = path.join(__dirname, '../../../db/migrations');
const files = fs.readdirSync(dir).filter((f) => f.endsWith('.sql')).sort();
const at = files.findIndex((f) => f.startsWith('0004_'));
expect(at).toBeGreaterThan(0);
const apply = async (f: string) => {
for (const stmt of fs.readFileSync(path.join(dir, f), 'utf8').split('--> statement-breakpoint')) {
if (stmt.trim()) await pg.exec(stmt);
}
};
for (const f of files.slice(0, at)) await apply(f);
const [list, live, dead, tag, deadTag] = [u(), u(), u(), u(), u()];
await pg.query("insert into sl_lists (id, user_id, name) values ($1, 'user-old', 'l')", [list]);
await pg.query("insert into sl_tasks (id, user_id, title, list_id) values ($1, 'user-old', 'live', $2)", [live, list]);
await pg.query("insert into sl_tasks (id, user_id, title, list_id, deleted_at) values ($1, 'user-old', 'dead', $2, $3)", [dead, list, OLD]);
await pg.query("insert into sl_tags (id, user_id, name) values ($1, 'user-old', 't')", [tag]);
await pg.query("insert into sl_tags (id, user_id, name, deleted_at) values ($1, 'user-old', 'gone', $2)", [deadTag, OLD]);
await pg.query('insert into sl_task_tags (task_id, tag_id) values ($1, $2), ($1, $3), ($4, $2)', [dead, tag, deadTag, live]);
// A link from an active task to a deleted tag (control 2) is not touched,
// nor an active subtask of the deleted task (control 6) and its link
await pg.query('insert into sl_task_tags (task_id, tag_id) values ($1, $2)', [live, deadTag]);
const orphan = u();
await pg.query("insert into sl_tasks (id, user_id, title, list_id, parent_id) values ($1, 'user-old', 'orphan', $2, $3)", [orphan, list, dead]);
await pg.query('insert into sl_task_tags (task_id, tag_id) values ($1, $2)', [orphan, tag]);
const all = async () => (await pg.query<{ task_id: string; tag_id: string }>('select task_id, tag_id from sl_task_tags order by task_id, tag_id')).rows;
await apply(files[at]);
const after = await all();
const kept = [{ task_id: live, tag_id: tag }, { task_id: live, tag_id: deadTag }, { task_id: orphan, tag_id: tag }];
expect(after).toEqual(kept.sort((a, b) => a.task_id.localeCompare(b.task_id) || a.tag_id.localeCompare(b.tag_id)));
expect((await pg.query('select deleted_at from sl_tasks where id=$1', [orphan])).rows).toEqual([{ deleted_at: null }]);
await apply(files[at]);
expect(await all()).toEqual(after);
await pg.close();
}, 30_000);
});

View file

@ -7,6 +7,7 @@ import { rateLimit } from '@/lib/rateLimit';
import { syncPushSchema, type SyncOperation } from '@/lib/validators';
import { createIdempotencyStore } from '@/lib/idempotency';
import { notifyUserChanged } from '@/lib/ws';
import { deleteTask, lockTaskForLinks } from '@/lib/taskDelete';
import {
listCreateData,
listUpdateData,
@ -316,9 +317,8 @@ async function processOperation(op: SyncOperation, userId: string, ctx: RequestC
.where(and(eq(slTasks.id, entityId), eq(slTasks.userId, userId)));
} else if (action === 'delete') {
await verifyOwnership(slTasks, entityId, userId);
await db.update(slTasks)
.set({ deletedAt: now, updatedAt: now })
.where(and(eq(slTasks.id, entityId), eq(slTasks.userId, userId)));
// Subtasks and every link go with the task (#196)
await deleteTask(entityId, userId, now);
}
break;
}
@ -368,15 +368,23 @@ async function processOperation(op: SyncOperation, userId: string, ctx: RequestC
// A link change moves the task's updatedAt: GET /api/sync then sends
// the task with the whole set of its links (#180)
await db.transaction(async (tx) => {
if (action !== 'create' && action !== 'delete') return;
// Task row first, for both actions (lock rule in lib/taskDelete.ts)
const task = await lockTaskForLinks(tx, entityId);
if (action === 'create') {
// A link to a deleted task or tag (a device offline while it was
// deleted elsewhere) is dropped without a refusal: `applied`, nothing
// written (#196). The row locks wait for a concurrent delete, so the
// check cannot miss it.
const [tag] = await tx.select({ deletedAt: slTags.deletedAt }).from(slTags)
.where(eq(slTags.id, tagId)).for('share');
if (task?.deletedAt || tag?.deletedAt) return;
await tx.insert(slTaskTags)
.values({ taskId: entityId, tagId })
.onConflictDoNothing();
} else if (action === 'delete') {
await tx.delete(slTaskTags)
.where(and(eq(slTaskTags.taskId, entityId), eq(slTaskTags.tagId, tagId)));
} else {
return;
}
await tx.update(slTasks)
.set({ updatedAt: now })

View file

@ -5,6 +5,7 @@ import { eq, and } from 'drizzle-orm';
import { requireAuth, parseBody } from '@/lib/api';
import { rateLimit } from '@/lib/rateLimit';
import { notifyUserChanged } from '@/lib/ws';
import { deleteTask } from '@/lib/taskDelete';
import { updateTaskSchema } from '@/lib/validators';
export async function PUT(
@ -60,13 +61,8 @@ export async function DELETE(
const { id } = await params;
const [deleted] = await db
.update(slTasks)
.set({ deletedAt: new Date(), updatedAt: new Date() })
.where(and(eq(slTasks.id, id), eq(slTasks.userId, auth.userId)))
.returning();
if (!deleted) {
// Subtasks and every link go with the task (#196)
if (!(await deleteTask(id, auth.userId))) {
return NextResponse.json({ error: 'Not found' }, { status: 404 });
}

View file

@ -5,6 +5,7 @@ import { eq, and } from 'drizzle-orm';
import { requireAuth } from '@/lib/api';
import { rateLimit } from '@/lib/rateLimit';
import { notifyUserChanged } from '@/lib/ws';
import { lockTaskForLinks } from '@/lib/taskDelete';
export async function DELETE(
_request: Request,
@ -28,8 +29,10 @@ export async function DELETE(
}
// Remove the link and move the task's updatedAt: GET /api/sync then sends
// the task with the whole set of its links, without this one (#180)
// the task with the whole set of its links, without this one (#180). Task
// row first (lock rule in lib/taskDelete.ts, #196).
await db.transaction(async (tx) => {
await lockTaskForLinks(tx, taskId);
await tx
.delete(slTaskTags)
.where(and(eq(slTaskTags.taskId, taskId), eq(slTaskTags.tagId, tagId)));

View file

@ -1,11 +1,12 @@
import { NextResponse } from 'next/server';
import { db } from '@/db/client';
import { slTasks, slTags, slTaskTags } from '@/db/schema';
import { eq, and, inArray } from 'drizzle-orm';
import { eq, and, inArray, isNull } from 'drizzle-orm';
import { requireAuth, parseBody } from '@/lib/api';
import { rateLimit } from '@/lib/rateLimit';
import { notifyUserChanged } from '@/lib/ws';
import { assignTagsSchema } from '@/lib/validators';
import { lockTaskForLinks } from '@/lib/taskDelete';
export async function POST(
request: Request,
@ -21,11 +22,11 @@ export async function POST(
const body = await parseBody(request, (d) => assignTagsSchema.parse(d));
if (body.error) return body.error;
// Verify task belongs to user
// Verify task belongs to user; a deleted task answers like a missing one (#196)
const [task] = await db
.select({ id: slTasks.id })
.from(slTasks)
.where(and(eq(slTasks.id, taskId), eq(slTasks.userId, auth.userId)));
.where(and(eq(slTasks.id, taskId), eq(slTasks.userId, auth.userId), isNull(slTasks.deletedAt)));
if (!task) {
return NextResponse.json({ error: 'Task not found' }, { status: 404 });
@ -42,18 +43,28 @@ export async function POST(
}
// Insert (ignore conflicts), and move the task's updatedAt: GET /api/sync
// then sends the task with the whole set of its links (#180)
await db.transaction(async (tx) => {
// then sends the task with the whole set of its links (#180). Deleted tags
// are dropped from the insert without an error, and with none left nothing
// is written (#196). The row locks wait for a concurrent delete of the task
// or a tag, so a row deleted meanwhile is seen. Task row first (lock rule in
// lib/taskDelete.ts).
const written = await db.transaction(async (tx) => {
const live = await lockTaskForLinks(tx, taskId);
if (!live || live.deletedAt) return false;
const liveTags = await tx.select({ id: slTags.id }).from(slTags)
.where(and(inArray(slTags.id, body.data.tagIds), isNull(slTags.deletedAt))).for('share');
if (liveTags.length === 0) return false;
await tx
.insert(slTaskTags)
.values(body.data.tagIds.map((tagId) => ({ taskId, tagId })))
.values(liveTags.map((t) => ({ taskId, tagId: t.id })))
.onConflictDoNothing();
await tx
.update(slTasks)
.set({ updatedAt: new Date() })
.where(and(eq(slTasks.id, taskId), eq(slTasks.userId, auth.userId)));
return true;
});
notifyUserChanged(auth.userId);
if (written) notifyUserChanged(auth.userId);
return NextResponse.json({ ok: true }, { status: 201 });
}

View file

@ -0,0 +1,7 @@
-- Drop the tag links of soft-deleted tasks (#196). A task delete left its
-- sl_task_tags rows in place until then; no function restores a deleted task,
-- so these links serve nothing (probe control 3, lien_tache_supprimee).
-- Links from an active task to a deleted tag (control 2) and active subtasks
-- of a deleted parent (control 6) are left as they are. Replays without effect.
DELETE FROM sl_task_tags
WHERE task_id IN (SELECT id FROM sl_tasks WHERE deleted_at IS NOT NULL);

View file

@ -29,6 +29,13 @@
"when": 1793673039382,
"tag": "0003_tag_updated_at",
"breakpoints": true
},
{
"idx": 4,
"version": "7",
"when": 1794153811697,
"tag": "0004_cleanup_deleted_task_links",
"breakpoints": true
}
]
}

51
web/src/lib/taskDelete.ts Normal file
View file

@ -0,0 +1,51 @@
import { db } from '@/db/client';
import { slTasks, slTaskTags } from '@/db/schema';
import { eq, and, or, isNull, inArray } from 'drizzle-orm';
type Tx = Parameters<Parameters<typeof db.transaction>[0]>[0];
// Lock rule for sl_task_tags (#196): every transaction that writes a link for
// a task locks that task's row first, FOR NO KEY UPDATE (the lock its
// updatedAt write takes anyway). Writers then queue on the task row in one
// order and cannot deadlock each other: two link creates, a create and a
// delete of the same link, or a link write and deleteTask (whose first
// statement updates the task row). The lock also waits for a concurrent
// delete, so the deletedAt it returns is current. A tag delete still takes the
// tag first, then the linked tasks; that rarer order is left as is.
export async function lockTaskForLinks(tx: Tx, taskId: string) {
const [task] = await tx.select({ deletedAt: slTasks.deletedAt }).from(slTasks)
.where(eq(slTasks.id, taskId)).for('no key update');
return task;
}
// Soft-delete a task with its subtasks and drop every tag link they hold, in
// one transaction (#196). Shared by POST /api/sync `task delete` and
// DELETE /api/tasks/[id], so that both paths stay the same.
//
// One level of subtasks only: POST /api/tasks refuses a subtask of a subtask
// and the app goes down one level (src/db/repository/tasks.ts). POST /api/sync
// does not check the depth, so a grandchild sent by a client is not cascaded.
//
// Subtasks already deleted keep their deletedAt; subtasks of another account
// placed under this task are not touched. Returns false when the task is not
// the caller's.
export async function deleteTask(taskId: string, userId: string, now = new Date()): Promise<boolean> {
return db.transaction(async (tx) => {
const [task] = await tx.update(slTasks)
.set({ deletedAt: now, updatedAt: now })
.where(and(eq(slTasks.id, taskId), eq(slTasks.userId, userId)))
.returning({ id: slTasks.id });
if (!task) return false;
await tx.update(slTasks)
.set({ deletedAt: now, updatedAt: now })
.where(and(eq(slTasks.parentId, taskId), eq(slTasks.userId, userId), isNull(slTasks.deletedAt)));
await tx.delete(slTaskTags).where(inArray(
slTaskTags.taskId,
tx.select({ id: slTasks.id }).from(slTasks).where(and(
eq(slTasks.userId, userId),
or(eq(slTasks.id, taskId), eq(slTasks.parentId, taskId)),
)),
));
return true;
});
}

View file

@ -38,7 +38,7 @@ beforeAll(async () => {
if (stmt.trim()) await pg.exec(stmt);
}
}
});
}, 30_000); // PGlite boots in seconds, slower while other files boot theirs (#196)
beforeEach(async () => {
await pg.exec('TRUNCATE sl_task_tags, sl_tasks, sl_tags, sl_lists');