fix(sync): propagate tag link removals both ways and refuse foreign ids #187
9 changed files with 428 additions and 42 deletions
|
|
@ -1,9 +1,10 @@
|
|||
import { eq, and } from 'drizzle-orm';
|
||||
import { eq, and, inArray } from 'drizzle-orm';
|
||||
import { db } from '../client';
|
||||
import { tags, taskTags } from '../schema';
|
||||
import { randomUUID } from '@/src/lib/uuid';
|
||||
import { truncate } from '@/src/lib/validation';
|
||||
import { requestSync } from '@/src/services/syncTrigger';
|
||||
import { tagLinkDiff } from '@/src/services/syncRules';
|
||||
import { writeOutboxEntry } from './outbox';
|
||||
|
||||
export async function getAllTags() {
|
||||
|
|
@ -47,24 +48,37 @@ export async function getTagsForTask(taskId: string) {
|
|||
}
|
||||
|
||||
export async function setTagsForTask(taskId: string, tagIds: string[]) {
|
||||
await db.delete(taskTags).where(eq(taskTags.taskId, taskId));
|
||||
if (tagIds.length > 0) {
|
||||
await db.insert(taskTags).values(
|
||||
tagIds.map((tagId) => ({ taskId, tagId }))
|
||||
);
|
||||
const current = await db
|
||||
.select({ tagId: taskTags.tagId })
|
||||
.from(taskTags)
|
||||
.where(eq(taskTags.taskId, taskId));
|
||||
const { added, removed } = tagLinkDiff(current.map((r) => r.tagId), tagIds);
|
||||
if (removed.length > 0) {
|
||||
await db
|
||||
.delete(taskTags)
|
||||
.where(and(eq(taskTags.taskId, taskId), inArray(taskTags.tagId, removed)));
|
||||
}
|
||||
// Send individual taskTag create operations (server expects entityId=taskId, data.tagId)
|
||||
for (const tagId of tagIds) {
|
||||
if (added.length > 0) {
|
||||
await db.insert(taskTags).values(added.map((tagId) => ({ taskId, tagId }))).onConflictDoNothing();
|
||||
}
|
||||
// One taskTag operation per changed link (server expects entityId=taskId,
|
||||
// data.tagId): a removal must reach the server too (#180)
|
||||
for (const tagId of removed) {
|
||||
writeOutboxEntry('taskTag', taskId, 'delete', { tagId }).then(requestSync).catch(() => {});
|
||||
}
|
||||
for (const tagId of added) {
|
||||
writeOutboxEntry('taskTag', taskId, 'create', { tagId }).then(requestSync).catch(() => {});
|
||||
}
|
||||
}
|
||||
|
||||
export async function addTagToTask(taskId: string, tagId: string) {
|
||||
await db.insert(taskTags).values({ taskId, tagId }).onConflictDoNothing();
|
||||
writeOutboxEntry('taskTag', taskId, 'create', { tagId }).then(requestSync).catch(() => {});
|
||||
}
|
||||
|
||||
export async function removeTagFromTask(taskId: string, tagId: string) {
|
||||
await db
|
||||
.delete(taskTags)
|
||||
.where(and(eq(taskTags.taskId, taskId), eq(taskTags.tagId, tagId)));
|
||||
writeOutboxEntry('taskTag', taskId, 'delete', { tagId }).then(requestSync).catch(() => {});
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
import { asc, eq, inArray, isNull, not } from 'drizzle-orm';
|
||||
import { and, asc, eq, inArray, isNull, not } from 'drizzle-orm';
|
||||
import { db } from '@/src/db/client';
|
||||
import { syncOutbox, lists, tasks, tags, taskTags } from '@/src/db/schema';
|
||||
import { useSettingsStore } from '@/src/stores/useSettingsStore';
|
||||
|
|
@ -21,6 +21,8 @@ import {
|
|||
isSynced,
|
||||
parseRetryAfter,
|
||||
sendInBatches,
|
||||
pendingTagIdsByTask,
|
||||
alignedTagIds,
|
||||
remapInboxEntry,
|
||||
type PostResponse,
|
||||
} from '@/src/services/syncRules';
|
||||
|
|
@ -178,7 +180,16 @@ export async function pullChanges(since: string, tracker: RequestTracker): Promi
|
|||
const data: SyncPullResponse = await res.json();
|
||||
|
||||
let appliedChanges = 0;
|
||||
// Links are not applied one by one: the server sends the whole set of
|
||||
// links of every task it sends, aligned once all rows are in (#180)
|
||||
const pulledTaskIds = new Set<string>();
|
||||
const serverLinks = new Map<string, Set<string>>();
|
||||
for (const change of data.changes) {
|
||||
if (change.entity_type === 'task_tag') {
|
||||
collectServerLink(serverLinks, change.payload);
|
||||
continue;
|
||||
}
|
||||
if (change.entity_type === 'task' && change.action !== 'delete') pulledTaskIds.add(change.entity_id);
|
||||
try {
|
||||
await applyChange(change, since);
|
||||
appliedChanges++;
|
||||
|
|
@ -186,6 +197,11 @@ export async function pullChanges(since: string, tracker: RequestTracker): Promi
|
|||
console.warn(`[sync] failed to apply change for ${change.entity_type}/${change.entity_id}:`, err);
|
||||
}
|
||||
}
|
||||
try {
|
||||
if (await alignTaskTags(pulledTaskIds, serverLinks)) appliedChanges++;
|
||||
} catch (err) {
|
||||
console.warn('[sync] failed to align task tags:', err);
|
||||
}
|
||||
|
||||
// Update last sync timestamp
|
||||
if (data.sync_token) {
|
||||
|
|
@ -214,9 +230,7 @@ async function applyChange(change: SyncPullChange, since: string): Promise<void>
|
|||
case 'tag':
|
||||
await applyTagChange(entity_id, action, payload);
|
||||
break;
|
||||
case 'task_tag':
|
||||
await applyTaskTagChange(entity_id, action, payload);
|
||||
break;
|
||||
// task_tag changes are aligned per task by pullChanges (alignTaskTags)
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -286,23 +300,66 @@ async function applyTagChange(id: string, action: string, payload: Record<string
|
|||
}
|
||||
}
|
||||
|
||||
async function applyTaskTagChange(id: string, action: string, payload: Record<string, unknown>) {
|
||||
const taskId = payload.task_id as string;
|
||||
const tagId = payload.tag_id as string;
|
||||
function collectServerLink(serverLinks: Map<string, Set<string>>, payload: Record<string, unknown>) {
|
||||
const taskId = payload.task_id;
|
||||
const tagId = payload.tag_id;
|
||||
if (typeof taskId !== 'string' || typeof tagId !== 'string') return;
|
||||
const set = serverLinks.get(taskId) ?? new Set<string>();
|
||||
set.add(tagId);
|
||||
serverLinks.set(taskId, set);
|
||||
}
|
||||
|
||||
if (action === 'delete') {
|
||||
await db
|
||||
.delete(taskTags)
|
||||
.where(eq(taskTags.taskId, taskId));
|
||||
return;
|
||||
/**
|
||||
* Align the links of each pulled task on the set the server sent (#180), so
|
||||
* that a link removed on the web disappears from the app. Links with an
|
||||
* unsent taskTag entry keep their local state (alignedTagIds). Direct writes
|
||||
* on task_tags in one transaction: never the tags.ts helpers nor the outbox,
|
||||
* which would send each received change back and request another sync.
|
||||
* Returns true when a link was written.
|
||||
*/
|
||||
async function alignTaskTags(taskIds: Set<string>, serverLinks: Map<string, Set<string>>): Promise<boolean> {
|
||||
if (taskIds.size === 0) return false;
|
||||
|
||||
const pendingRows = await db
|
||||
.select({ entityType: syncOutbox.entityType, entityId: syncOutbox.entityId, payload: syncOutbox.payload })
|
||||
.from(syncOutbox)
|
||||
.where(and(isNull(syncOutbox.syncedAt), eq(syncOutbox.entityType, 'taskTag')));
|
||||
const pending = pendingTagIdsByTask(pendingRows);
|
||||
// Whole tables, filtered here: no bound-variable limit on large pulls
|
||||
const localTaskIds = new Set((await db.select({ id: tasks.id }).from(tasks)).map((r) => r.id));
|
||||
const localTagIds = new Set((await db.select({ id: tags.id }).from(tags)).map((r) => r.id));
|
||||
const localLinks = new Map<string, Set<string>>();
|
||||
for (const { taskId, tagId } of await db.select().from(taskTags)) {
|
||||
const set = localLinks.get(taskId) ?? new Set<string>();
|
||||
set.add(tagId);
|
||||
localLinks.set(taskId, set);
|
||||
}
|
||||
|
||||
// Upsert: insert if not exists
|
||||
try {
|
||||
await db.insert(taskTags).values({ taskId, tagId }).onConflictDoNothing();
|
||||
} catch {
|
||||
// Ignore constraint errors
|
||||
const removals: { taskId: string; tagId: string }[] = [];
|
||||
const additions: { taskId: string; tagId: string }[] = [];
|
||||
for (const taskId of taskIds) {
|
||||
if (!localTaskIds.has(taskId)) continue;
|
||||
const local = localLinks.get(taskId) ?? new Set<string>();
|
||||
const keep = alignedTagIds(serverLinks.get(taskId) ?? [], local, pending.get(taskId) ?? []);
|
||||
for (const tagId of local) {
|
||||
if (!keep.has(tagId)) removals.push({ taskId, tagId });
|
||||
}
|
||||
for (const tagId of keep) {
|
||||
// A link to a tag the device does not hold (deleted) is not written
|
||||
if (!local.has(tagId) && localTagIds.has(tagId)) additions.push({ taskId, tagId });
|
||||
}
|
||||
}
|
||||
if (removals.length === 0 && additions.length === 0) return false;
|
||||
|
||||
await db.transaction(async (tx) => {
|
||||
for (const { taskId, tagId } of removals) {
|
||||
await tx.delete(taskTags).where(and(eq(taskTags.taskId, taskId), eq(taskTags.tagId, tagId)));
|
||||
}
|
||||
for (const link of additions) {
|
||||
await tx.insert(taskTags).values(link).onConflictDoNothing();
|
||||
}
|
||||
});
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
|
|||
|
|
@ -596,6 +596,69 @@ export function firstSyncChoice({ dataOwnerId, signedInId, localInboxId }: First
|
|||
return 'reset-only';
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Task-tag links: removals both ways (#180)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Links a tag edit changes: the tags of `next` absent from `current` are
|
||||
* added, those of `current` absent from `next` are removed. setTagsForTask
|
||||
* writes one taskTag create per added tag and one taskTag delete per removed
|
||||
* one, so that a removal made on the phone reaches the server.
|
||||
*/
|
||||
export function tagLinkDiff(current: string[], next: string[]): { added: string[]; removed: string[] } {
|
||||
const before = new Set(current);
|
||||
const after = new Set(next);
|
||||
return {
|
||||
added: [...after].filter((id) => !before.has(id)),
|
||||
removed: [...before].filter((id) => !after.has(id)),
|
||||
};
|
||||
}
|
||||
|
||||
/** Outbox row fields read by pendingTagIdsByTask (unsynced entries only). */
|
||||
export interface PendingLinkEntry {
|
||||
entityType: string;
|
||||
entityId: string;
|
||||
payload: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Tags of each task that have an unsent taskTag entry, create or delete
|
||||
* alike: the pull leaves those links as they are locally.
|
||||
*/
|
||||
export function pendingTagIdsByTask(entries: PendingLinkEntry[]): Map<string, Set<string>> {
|
||||
const out = new Map<string, Set<string>>();
|
||||
for (const entry of entries) {
|
||||
if (entry.entityType !== 'taskTag') continue;
|
||||
const tagId = parsePayload(entry.payload)?.tagId;
|
||||
if (typeof tagId !== 'string') continue;
|
||||
const set = out.get(entry.entityId) ?? new Set<string>();
|
||||
set.add(tagId);
|
||||
out.set(entry.entityId, set);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Tags a pulled task keeps locally. The server sends the whole set of links
|
||||
* of every task it sends (GET /api/sync), and moves the task's updatedAt on
|
||||
* each link change: the local links are aligned on that set, except the
|
||||
* links with an unsent taskTag entry, which keep their local state (a link
|
||||
* added or removed on the phone and not pushed yet is not undone).
|
||||
*/
|
||||
export function alignedTagIds(server: Iterable<string>, local: Iterable<string>, pending: Iterable<string>): Set<string> {
|
||||
const localSet = new Set(local);
|
||||
const pendingSet = new Set(pending);
|
||||
const keep = new Set<string>();
|
||||
for (const id of server) {
|
||||
if (!pendingSet.has(id)) keep.add(id);
|
||||
}
|
||||
for (const id of pendingSet) {
|
||||
if (localSet.has(id)) keep.add(id);
|
||||
}
|
||||
return keep;
|
||||
}
|
||||
|
||||
/**
|
||||
* A pending outbox entry that names the fixed local Inbox, rewritten under the
|
||||
* server Inbox id that initialMerge gives it (#165): a task created or moved
|
||||
|
|
|
|||
|
|
@ -450,6 +450,47 @@ check('syncClient.ts wires the #149-#151 sync rules', () => {
|
|||
assert.match(push, /\.where\(inArray\(syncOutbox\.id, markIds\)\);\s*\/\/[^\n]*\s*syncWidgetData\(\)/);
|
||||
});
|
||||
|
||||
// Tag links both ways (#180). The rules are executed by tests/syncRules.test.mjs;
|
||||
// this check locks their wiring in files node cannot load: the tag helpers
|
||||
// write a taskTag entry per changed link, and the pull aligns the links by
|
||||
// direct writes, never through the helpers or the outbox.
|
||||
check('tag links: removals written by the app, pull aligned without the outbox (#180)', () => {
|
||||
const read = (rel) => fs.readFileSync(path.join(__dirname, '..', rel), 'utf8');
|
||||
const tags = read('src/db/repository/tags.ts');
|
||||
const fnOf = (src, name) => {
|
||||
const start = src.indexOf(`export async function ${name}(`);
|
||||
assert.ok(start >= 0, `${name} not found`);
|
||||
const end = src.indexOf('\n}\n', start);
|
||||
return src.slice(start, end);
|
||||
};
|
||||
const set = fnOf(tags, 'setTagsForTask');
|
||||
assert.match(set, /tagLinkDiff\(/, 'setTagsForTask must diff with the local links');
|
||||
assert.match(set, /for \(const tagId of removed\) \{\s*writeOutboxEntry\('taskTag', taskId, 'delete', \{ tagId \}\)/);
|
||||
assert.match(set, /for \(const tagId of added\) \{\s*writeOutboxEntry\('taskTag', taskId, 'create', \{ tagId \}\)/);
|
||||
assert.ok(!/db\s*\.delete\(taskTags\)\s*\.where\(eq\(taskTags\.taskId, taskId\)\)/.test(set), 'setTagsForTask must not wipe every link');
|
||||
assert.match(fnOf(tags, 'addTagToTask'), /writeOutboxEntry\('taskTag', taskId, 'create', \{ tagId \}\)\.then\(requestSync\)/);
|
||||
assert.match(fnOf(tags, 'removeTagFromTask'), /writeOutboxEntry\('taskTag', taskId, 'delete', \{ tagId \}\)\.then\(requestSync\)/);
|
||||
|
||||
const client = read('src/services/syncClient.ts');
|
||||
const start = client.indexOf('async function alignTaskTags(');
|
||||
assert.ok(start >= 0, 'alignTaskTags not found');
|
||||
const align = client.slice(start, client.indexOf('\n}\n', start));
|
||||
for (const banned of ['setTagsForTask', 'addTagToTask', 'removeTagFromTask', 'writeOutboxEntry', 'queueOutboxEntry', 'requestSync']) {
|
||||
assert.ok(!align.includes(banned), `alignTaskTags must not call ${banned}`);
|
||||
}
|
||||
assert.match(align, /alignedTagIds\(/, 'alignTaskTags must use the pure rule');
|
||||
assert.match(align, /pendingTagIdsByTask\(/, 'alignTaskTags must spare links with an unsent entry');
|
||||
assert.match(align, /isNull\(syncOutbox\.syncedAt\)/, 'only unsent entries are pending');
|
||||
assert.match(align, /await db\.transaction\(async \(tx\) => \{[^]*tx\.delete\(taskTags\)[^]*tx\.insert\(taskTags\)/, 'links written directly, in one transaction');
|
||||
assert.ok(!/from '@\/src\/db\/repository\/tags'/.test(client), 'syncClient.ts must not import the tag helpers');
|
||||
// The pull collects the links and aligns every pulled task once
|
||||
const pull = client.slice(client.indexOf('export async function pullChanges('), client.indexOf('\nasync function applyChange('));
|
||||
assert.match(pull, /if \(change\.entity_type === 'task_tag'\) \{\s*collectServerLink\(serverLinks, change\.payload\);\s*continue;\s*\}/);
|
||||
assert.match(pull, /pulledTaskIds\.add\(change\.entity_id\)/);
|
||||
assert.match(pull, /await alignTaskTags\(pulledTaskIds, serverLinks\)/);
|
||||
assert.ok(!/applyTaskTagChange/.test(client), 'links are no longer applied one by one');
|
||||
});
|
||||
|
||||
// The bounded wait on the persisted settings (review of PR #164) is executed
|
||||
// by tests/hydration.test.mjs through node's type stripping: hydration.ts
|
||||
// stays import-free, and useSettingsStore.ts (React Native, not loadable
|
||||
|
|
|
|||
|
|
@ -11,6 +11,9 @@ import { test } from 'node:test';
|
|||
import assert from 'node:assert/strict';
|
||||
import {
|
||||
SYNC_EPOCH,
|
||||
tagLinkDiff,
|
||||
pendingTagIdsByTask,
|
||||
alignedTagIds,
|
||||
pulledListValues,
|
||||
pulledTaskValues,
|
||||
pulledTagValues,
|
||||
|
|
@ -891,6 +894,59 @@ test('firstSyncChoice: data of A, signed in to B gives reset-only (regression)',
|
|||
);
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Task-tag links: removals both ways (#180)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const sorted = (set) => [...set].sort();
|
||||
|
||||
test('alignedTagIds: server {a}, local {a, b}, nothing pending -> keep {a} (web removal arrives)', () => {
|
||||
assert.deepEqual(sorted(alignedTagIds(['a'], ['a', 'b'], [])), ['a']);
|
||||
});
|
||||
|
||||
test('alignedTagIds: local {a, b} with create b pending -> keep {a, b}', () => {
|
||||
assert.deepEqual(sorted(alignedTagIds(['a'], ['a', 'b'], ['b'])), ['a', 'b']);
|
||||
});
|
||||
|
||||
test('alignedTagIds: server {a, b}, delete b pending -> keep {a} (phone removal not undone)', () => {
|
||||
// The phone removed b: it is absent locally and has a pending entry
|
||||
assert.deepEqual(sorted(alignedTagIds(['a', 'b'], ['a'], ['b'])), ['a']);
|
||||
});
|
||||
|
||||
test('alignedTagIds: server links absent locally are added, empty server set clears', () => {
|
||||
assert.deepEqual(sorted(alignedTagIds(['a', 'c'], ['a'], [])), ['a', 'c']);
|
||||
assert.deepEqual(sorted(alignedTagIds([], ['a', 'b'], [])), []);
|
||||
});
|
||||
|
||||
test('pendingTagIdsByTask: groups taskTag entries by task, create and delete alike', () => {
|
||||
const pending = pendingTagIdsByTask([
|
||||
{ entityType: 'taskTag', entityId: 't1', payload: JSON.stringify({ tagId: 'a' }) },
|
||||
{ entityType: 'taskTag', entityId: 't1', payload: JSON.stringify({ tagId: 'b' }) },
|
||||
{ entityType: 'taskTag', entityId: 't2', payload: JSON.stringify({ tagId: 'c' }) },
|
||||
{ entityType: 'task', entityId: 't1', payload: JSON.stringify({ tagId: 'x' }) },
|
||||
{ entityType: 'taskTag', entityId: 't3', payload: 'not json' },
|
||||
{ entityType: 'taskTag', entityId: 't3', payload: JSON.stringify({}) },
|
||||
]);
|
||||
assert.deepEqual(sorted(pending.get('t1')), ['a', 'b']);
|
||||
assert.deepEqual(sorted(pending.get('t2')), ['c']);
|
||||
assert.equal(pending.has('t3'), false);
|
||||
});
|
||||
|
||||
test('tagLinkDiff: a removed tag is listed (setTagsForTask writes a taskTag delete)', () => {
|
||||
assert.deepEqual(tagLinkDiff(['a', 'b'], ['a']), { added: [], removed: ['b'] });
|
||||
assert.deepEqual(tagLinkDiff(['a'], ['a', 'c']), { added: ['c'], removed: [] });
|
||||
assert.deepEqual(tagLinkDiff(['a', 'b'], ['b', 'c']), { added: ['c'], removed: ['a'] });
|
||||
assert.deepEqual(tagLinkDiff(['a'], ['a']), { added: [], removed: [] });
|
||||
});
|
||||
|
||||
test('phone removal then pull: the delete entry keeps the link removed until pushed', () => {
|
||||
// setTagsForTask(['a']) on a task linked to {a, b}: b is removed locally
|
||||
const { removed } = tagLinkDiff(['a', 'b'], ['a']);
|
||||
const pending = pendingTagIdsByTask(removed.map((tagId) => ({ entityType: 'taskTag', entityId: 't', payload: JSON.stringify({ tagId }) })));
|
||||
// A pull still carrying b on the server side does not bring it back
|
||||
assert.deepEqual(sorted(alignedTagIds(['a', 'b'], ['a'], pending.get('t'))), ['a']);
|
||||
});
|
||||
|
||||
// remapInboxEntry: writes made during « Fusionner » (/pr-brief 185, Max
|
||||
// 2026-11-03) still name the fixed local Inbox, which the merge replaces by a
|
||||
// server id; the pending entries follow it.
|
||||
|
|
|
|||
|
|
@ -43,7 +43,10 @@ vi.mock('@/lib/idempotency', async (importOriginal) => {
|
|||
};
|
||||
});
|
||||
|
||||
const { POST } = await import('./route');
|
||||
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 { NextRequest } = await import('next/server');
|
||||
|
||||
type Op = [entityType: string, action: string, entityId: string, data?: Record<string, unknown>];
|
||||
|
||||
|
|
@ -680,3 +683,127 @@ describe('POST /api/sync: open pages notified over WebSocket (#177)', () => {
|
|||
expect(calls).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('task-tag links move the task\'s updatedAt (#180)', () => {
|
||||
const OLD = '2020-01-01T00:00:00.000Z';
|
||||
|
||||
// Put the task back in the past, so that any write that moves it shows.
|
||||
async function age(taskId: string) {
|
||||
await h.pg.query('update sl_tasks set updated_at=$1 where id=$2', [OLD, taskId]);
|
||||
}
|
||||
|
||||
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();
|
||||
}
|
||||
|
||||
// GET /api/sync since OLD + 1 s, as the account: the task and its links.
|
||||
async function pulled(userId: string, taskId: 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)}`));
|
||||
expect(res.status).toBe(200);
|
||||
const { changes } = await res.json() as { changes: { entity_type: string; entity_id: string; payload: Record<string, unknown> }[] };
|
||||
return {
|
||||
task: changes.some((c) => c.entity_type === 'task' && c.entity_id === taskId),
|
||||
tags: changes
|
||||
.filter((c) => c.entity_type === 'task_tag' && c.payload.task_id === taskId)
|
||||
.map((c) => c.payload.tag_id as string)
|
||||
.sort(),
|
||||
};
|
||||
}
|
||||
|
||||
async function newTag(userId: string): Promise<string> {
|
||||
const id = u();
|
||||
expect(await push(userId, [['tag', 'create', id, { name: `t-${id.slice(0, 4)}`, color: '#4A90A4' }]])).toEqual(['applied']);
|
||||
return id;
|
||||
}
|
||||
|
||||
it('POST /api/sync taskTag create and delete move updatedAt; the pull sends the whole set', async () => {
|
||||
const { B } = await seed();
|
||||
const extra = await newTag(B.userId);
|
||||
|
||||
await age(B.task);
|
||||
expect(await push(B.userId, [['taskTag', 'create', B.task, { tagId: extra }]])).toEqual(['applied']);
|
||||
expect(await updatedAt(B.task)).not.toBe(OLD);
|
||||
expect(await pulled(B.userId, B.task)).toEqual({ task: true, tags: [B.tag, extra].sort() });
|
||||
|
||||
await age(B.task);
|
||||
expect(await push(B.userId, [['taskTag', 'delete', B.task, { tagId: B.tag }]])).toEqual(['applied']);
|
||||
expect(await updatedAt(B.task)).not.toBe(OLD);
|
||||
expect(await pulled(B.userId, B.task)).toEqual({ task: true, tags: [extra] });
|
||||
|
||||
// Last link removed: the task still comes, with an empty set
|
||||
await age(B.task);
|
||||
expect(await push(B.userId, [['taskTag', 'delete', B.task, { tagId: extra }]])).toEqual(['applied']);
|
||||
expect(await pulled(B.userId, B.task)).toEqual({ task: true, tags: [] });
|
||||
});
|
||||
|
||||
it('REST add and remove of a link move updatedAt; the pull sends the whole set', async () => {
|
||||
const { B } = await seed();
|
||||
const extra = await newTag(B.userId);
|
||||
h.userId = B.userId;
|
||||
|
||||
await age(B.task);
|
||||
const added = await postTaskTags(
|
||||
new Request('http://localhost', { method: 'POST', body: JSON.stringify({ tagIds: [extra] }) }),
|
||||
{ params: Promise.resolve({ id: B.task }) },
|
||||
);
|
||||
expect(added.status).toBe(201);
|
||||
expect(await updatedAt(B.task)).not.toBe(OLD);
|
||||
expect(await pulled(B.userId, B.task)).toEqual({ task: true, tags: [B.tag, extra].sort() });
|
||||
|
||||
await age(B.task);
|
||||
h.userId = B.userId;
|
||||
const removed = await deleteTaskTag(
|
||||
new Request('http://localhost', { method: 'DELETE' }),
|
||||
{ params: Promise.resolve({ id: B.task, tagId: B.tag }) },
|
||||
);
|
||||
expect(removed.status).toBe(200);
|
||||
expect(await updatedAt(B.task)).not.toBe(OLD);
|
||||
expect(await pulled(B.userId, B.task)).toEqual({ task: true, tags: [extra] });
|
||||
});
|
||||
|
||||
it('a refused link change leaves another account\'s task untouched', async () => {
|
||||
const { A, B } = await seed();
|
||||
await age(A.task);
|
||||
expect(await push(B.userId, [['taskTag', 'delete', A.task, { tagId: A.tag }]])).toEqual(['skipped']);
|
||||
h.userId = B.userId;
|
||||
const res = await deleteTaskTag(
|
||||
new Request('http://localhost', { method: 'DELETE' }),
|
||||
{ params: Promise.resolve({ id: A.task, tagId: A.tag }) },
|
||||
);
|
||||
expect(res.status).toBe(404);
|
||||
expect(await updatedAt(A.task)).toBe(OLD);
|
||||
});
|
||||
});
|
||||
|
||||
describe('POST /api/sync: task and tag creation with an id taken by another account (#180)', () => {
|
||||
it('refuses a task create on another account\'s task id, without notification', async () => {
|
||||
const { A, B } = await seed();
|
||||
h.notified.length = 0;
|
||||
const [result] = await pushResults(B.userId, [['task', 'create', A.task, { title: 'stolen', listId: B.list }]]);
|
||||
expect(result.status).toBe('skipped');
|
||||
expect(result.error).toBeDefined();
|
||||
expect(h.notified).toEqual([]);
|
||||
expect(await row('select user_id, title from sl_tasks where id=$1', [A.task])).toEqual({ user_id: A.userId, title: 'A task' });
|
||||
});
|
||||
|
||||
it('refuses a tag create on another account\'s tag id, without notification', async () => {
|
||||
const { A, B } = await seed();
|
||||
h.notified.length = 0;
|
||||
const [result] = await pushResults(B.userId, [['tag', 'create', A.tag, { name: 'stolen', color: '#4A90A4' }]]);
|
||||
expect(result.status).toBe('skipped');
|
||||
expect(result.error).toBeDefined();
|
||||
expect(h.notified).toEqual([]);
|
||||
expect(await row('select user_id, name from sl_tags where id=$1', [A.tag])).toEqual({ user_id: A.userId, name: 'a-tag' });
|
||||
});
|
||||
|
||||
it('still applies a create pushed again on the caller\'s own ids (initialMerge)', async () => {
|
||||
const { B } = await seed();
|
||||
expect(await push(B.userId, [
|
||||
['task', 'create', B.task, { title: 'B task', listId: B.list }],
|
||||
['tag', 'create', B.tag, { name: 'b-tag', color: '#8BA889' }],
|
||||
])).toEqual(['applied', 'applied']);
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -282,6 +282,9 @@ async function processOperation(op: SyncOperation, userId: string, ctx: RequestC
|
|||
case 'task': {
|
||||
if (action === 'create') {
|
||||
const d = taskCreateData.parse(data);
|
||||
// An id of another account would hit onConflictDoNothing and answer
|
||||
// `applied` without creating anything (#180)
|
||||
await assertIdNotTaken(slTasks, entityId, userId);
|
||||
const listId = await resolveTaskListId(d.listId, userId);
|
||||
// Not verifyOwnership: initialMerge pushes all tasks in one batch, a
|
||||
// subtask may arrive before its parent (parent_id has no FK).
|
||||
|
|
@ -322,6 +325,7 @@ async function processOperation(op: SyncOperation, userId: string, ctx: RequestC
|
|||
case 'tag': {
|
||||
if (action === 'create') {
|
||||
const d = tagCreateData.parse(data);
|
||||
await assertIdNotTaken(slTags, entityId, userId);
|
||||
await db.insert(slTags).values({
|
||||
id: entityId,
|
||||
userId,
|
||||
|
|
@ -349,14 +353,23 @@ async function processOperation(op: SyncOperation, userId: string, ctx: RequestC
|
|||
const { tagId } = taskTagData.parse(data);
|
||||
await verifyOwnership(slTasks, entityId, userId);
|
||||
await verifyTagOwnership(tagId, userId);
|
||||
if (action === 'create') {
|
||||
await db.insert(slTaskTags)
|
||||
.values({ taskId: entityId, tagId })
|
||||
.onConflictDoNothing();
|
||||
} else if (action === 'delete') {
|
||||
await db.delete(slTaskTags)
|
||||
.where(and(eq(slTaskTags.taskId, entityId), eq(slTaskTags.tagId, tagId)));
|
||||
}
|
||||
// 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') {
|
||||
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 })
|
||||
.where(and(eq(slTasks.id, entityId), eq(slTasks.userId, userId)));
|
||||
});
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -27,9 +27,17 @@ export async function DELETE(
|
|||
return NextResponse.json({ error: 'Task not found' }, { status: 404 });
|
||||
}
|
||||
|
||||
await db
|
||||
.delete(slTaskTags)
|
||||
.where(and(eq(slTaskTags.taskId, taskId), eq(slTaskTags.tagId, tagId)));
|
||||
// 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)
|
||||
await db.transaction(async (tx) => {
|
||||
await tx
|
||||
.delete(slTaskTags)
|
||||
.where(and(eq(slTaskTags.taskId, taskId), eq(slTaskTags.tagId, tagId)));
|
||||
await tx
|
||||
.update(slTasks)
|
||||
.set({ updatedAt: new Date() })
|
||||
.where(and(eq(slTasks.id, taskId), eq(slTasks.userId, auth.userId)));
|
||||
});
|
||||
|
||||
notifyUserChanged(auth.userId);
|
||||
return NextResponse.json({ ok: true });
|
||||
|
|
|
|||
|
|
@ -41,11 +41,18 @@ export async function POST(
|
|||
return NextResponse.json({ error: 'Some tags not found' }, { status: 404 });
|
||||
}
|
||||
|
||||
// Insert (ignore conflicts)
|
||||
await db
|
||||
.insert(slTaskTags)
|
||||
.values(body.data.tagIds.map((tagId) => ({ taskId, tagId })))
|
||||
.onConflictDoNothing();
|
||||
// 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) => {
|
||||
await tx
|
||||
.insert(slTaskTags)
|
||||
.values(body.data.tagIds.map((tagId) => ({ taskId, tagId })))
|
||||
.onConflictDoNothing();
|
||||
await tx
|
||||
.update(slTasks)
|
||||
.set({ updatedAt: new Date() })
|
||||
.where(and(eq(slTasks.id, taskId), eq(slTasks.userId, auth.userId)));
|
||||
});
|
||||
|
||||
notifyUserChanged(auth.userId);
|
||||
return NextResponse.json({ ok: true }, { status: 201 });
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue