diff --git a/web/src/lib/rateLimit.ts b/web/src/lib/rateLimit.ts index 8230ef6..0725fd3 100644 --- a/web/src/lib/rateLimit.ts +++ b/web/src/lib/rateLimit.ts @@ -15,18 +15,31 @@ setInterval(() => { } }, 300_000); -export function rateLimit( - userId: string, - category: "sync" | "create" | "read" | "ws-ticket", -): NextResponse | null { - const limits: Record = { - sync: { max: 10, windowMs: 60_000 }, - create: { max: 30, windowMs: 60_000 }, - read: { max: 200, windowMs: 60_000 }, - "ws-ticket": { max: 10, windowMs: 60_000 }, - }; +// Calls allowed per account in a sliding window. The three `mcp-*` categories +// (#202) count per account, all agent tokens together: `mcp-read` and +// `mcp-write` count tool calls and are refused by a tool result the model can +// read, `mcp-http` counts the HTTP requests of POST /api/mcp and is the +// backstop behind them (a JSON-RPC batch holds up to 100 tool calls). +const LIMITS = { + sync: { max: 10, windowMs: 60_000 }, + create: { max: 30, windowMs: 60_000 }, + read: { max: 200, windowMs: 60_000 }, + "ws-ticket": { max: 10, windowMs: 60_000 }, + "mcp-read": { max: 120, windowMs: 60_000 }, + "mcp-write": { max: 30, windowMs: 60_000 }, + "mcp-http": { max: 600, windowMs: 60_000 }, +} as const; - const { max, windowMs } = limits[category]; +export type RateLimitCategory = keyof typeof LIMITS; + +// Seconds to wait before a call of this category is allowed again, or null +// when the call is allowed, in which case it is counted. A refused call is +// not counted. +export function rateLimitDelay( + userId: string, + category: RateLimitCategory, +): number | null { + const { max, windowMs } = LIMITS[category]; const key = `${userId}:${category}`; const now = Date.now(); @@ -39,18 +52,24 @@ export function rateLimit( entry.timestamps = entry.timestamps.filter((t) => now - t < windowMs); if (entry.timestamps.length >= max) { - const retryAfter = Math.ceil( - (entry.timestamps[0] + windowMs - now) / 1000, - ); - return NextResponse.json( - { error: "Too many requests" }, - { - status: 429, - headers: { "Retry-After": String(retryAfter) }, - }, - ); + return Math.ceil((entry.timestamps[0] + windowMs - now) / 1000); } entry.timestamps.push(now); return null; } + +export function rateLimit( + userId: string, + category: RateLimitCategory, +): NextResponse | null { + const retryAfter = rateLimitDelay(userId, category); + if (retryAfter === null) return null; + return NextResponse.json( + { error: "Too many requests" }, + { + status: 429, + headers: { "Retry-After": String(retryAfter) }, + }, + ); +} diff --git a/web/src/lib/taskQueries.test.ts b/web/src/lib/taskQueries.test.ts index 16bfa8f..c176817 100644 --- a/web/src/lib/taskQueries.test.ts +++ b/web/src/lib/taskQueries.test.ts @@ -26,7 +26,10 @@ vi.mock('@/lib/api', async (importOriginal) => ({ })); vi.mock('@/lib/rateLimit', () => ({ rateLimit: () => null })); -const { loadTaskTags, queryListTasks, loadSubtasks } = await import('./taskQueries'); +const { + loadTaskTags, queryListTasks, loadSubtasks, + queryAccountTasks, loadAccountTask, loadAccountLists, loadOpenTaskCounts, +} = await import('./taskQueries'); const { GET } = await import('@/app/api/lists/[id]/tasks/route'); const { NextRequest } = await import('next/server'); @@ -203,3 +206,395 @@ describe('GET /api/lists/[id]/tasks?tags=', () => { expect(res.status).toBe(404); }); }); + +// Account-wide reads of the MCP read tools (#202). Each test creates its own +// accounts; creation instants are written explicitly, because the order and +// the cursor of queryAccountTasks rest on them. + +type ListFields = { name?: string; position?: number; createdAt?: string; deletedAt?: string }; +type TaskFields = { + createdAt?: string; + title?: string; + notes?: string; + completed?: boolean; + priority?: number; + dueDate?: string; + parentId?: string; + deletedAt?: string; + id?: string; + // Account the row is written for, when it is not the account of the list: + // a row the sync never writes, but that the reads must not trust. + userId?: string; +}; + +type Account = { userId: string; list: string }; + +async function addList(userId: string, fields: ListFields = {}): Promise { + const id = u(); + await exec( + 'INSERT INTO sl_lists (id, user_id, name, position, created_at, deleted_at) VALUES ($1, $2, $3, $4, $5, $6)', + [id, userId, fields.name ?? 'L', fields.position ?? 0, fields.createdAt ?? '2026-01-01T00:00:00Z', fields.deletedAt ?? null], + ); + return id; +} + +async function newAccount(): Promise { + const userId = `user-${u()}`; + return { userId, list: await addList(userId) }; +} + +// Tasks are created one minute apart unless a test says when. +let minute = 0; + +async function addTask(account: Account, listId: string, fields: TaskFields = {}): Promise { + const id = fields.id ?? u(); + const createdAt = fields.createdAt ?? new Date(Date.UTC(2026, 1, 1, 0, minute++)).toISOString(); + await exec( + `INSERT INTO sl_tasks (id, user_id, title, notes, completed, priority, due_date, list_id, parent_id, created_at, deleted_at) + VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)`, + [ + id, fields.userId ?? account.userId, fields.title ?? 'task', fields.notes ?? null, fields.completed ?? false, + fields.priority ?? 0, fields.dueDate ?? null, listId, fields.parentId ?? null, createdAt, fields.deletedAt ?? null, + ], + ); + return id; +} + +async function addTag(userId: string, fields: { deletedAt?: string } = {}): Promise { + const id = u(); + await exec('INSERT INTO sl_tags (id, user_id, name, deleted_at) VALUES ($1, $2, $3, $4)', [id, userId, 'tag', fields.deletedAt ?? null]); + return id; +} + +async function link(taskId: string, tagId: string) { + await exec('INSERT INTO sl_task_tags (task_id, tag_id) VALUES ($1, $2)', [taskId, tagId]); +} + +type Filters = Parameters[1]; + +// Ids of the first page (100 tasks at most) for these filters. +async function ids(account: Account, filters: Filters = {}): Promise { + const { tasks } = await queryAccountTasks(account.userId, filters, { limit: 100 }); + return tasks.map((t) => t.id); +} + +// Every page, read one after the other with the cursor of the previous one. +async function pages(account: Account, limit: number, filters: Filters = {}): Promise { + const out: string[][] = []; + let cursor: Awaited>['nextCursor'] = null; + do { + const page = await queryAccountTasks(account.userId, filters, { limit, cursor }); + out.push(page.tasks.map((t) => t.id)); + cursor = page.nextCursor; + } while (cursor !== null && out.length < 50); + return out; +} + +const GONE = '2026-02-01T00:00:00Z'; + +describe('queryAccountTasks', () => { + it('returns the top-level tasks of every live list of the account, oldest first', async () => { + const a = await newAccount(); + const second = await addList(a.userId); + // Written in another order than they were created. + const t3 = await addTask(a, a.list, { createdAt: '2026-03-03T10:00:00Z' }); + const t1 = await addTask(a, second, { createdAt: '2026-03-01T10:00:00Z' }); + const t2 = await addTask(a, a.list, { createdAt: '2026-03-02T10:00:00Z', completed: true }); + await addTask(a, a.list, { parentId: t1 }); + + const { tasks, nextCursor } = await queryAccountTasks(a.userId, {}, { limit: 50 }); + expect(tasks.map((t) => t.id)).toEqual([t1, t2, t3]); + expect(nextCursor).toBeNull(); + expect(tasks[0]).toMatchObject({ id: t1, listId: second, userId: a.userId, parentId: null, completed: false }); + }); + + it('never returns a deleted task, a subtask, or a task of a deleted list', async () => { + const a = await newAccount(); + const deletedList = await addList(a.userId, { deletedAt: GONE }); + const kept = await addTask(a, a.list); + await addTask(a, a.list, { deletedAt: GONE }); + await addTask(a, a.list, { parentId: kept }); + await addTask(a, deletedList); + expect(await ids(a)).toEqual([kept]); + // Naming the deleted list does not bring its tasks back. + expect(await ids(a, { listId: deletedList })).toEqual([]); + }); + + it('never returns a task of another account, whatever the filters', async () => { + const [a, b] = [await newAccount(), await newAccount()]; + const own = await addTask(a, a.list, { title: 'shared words', priority: 2, dueDate: '2026-06-01T12:00:00Z' }); + const foreign = await addTask(b, b.list, { title: 'shared words', priority: 2, dueDate: '2026-06-01T12:00:00Z' }); + const tagB = await addTag(b.userId); + await link(foreign, tagB); + + expect(await ids(a)).toEqual([own]); + expect(await ids(b)).toEqual([foreign]); + // Every filter, with a value that names or matches the other account's row. + expect(await ids(a, { listId: b.list })).toEqual([]); + expect(await ids(a, { tagIds: [tagB] })).toEqual([]); + expect(await ids(a, { query: 'shared' })).toEqual([own]); + expect(await ids(a, { priority: 2, status: 'all', dueBefore: new Date('2026-12-31T00:00:00Z') })).toEqual([own]); + // An account without a row reads nothing, even when it names a list. + const nobody = { userId: `user-${u()}`, list: a.list }; + expect(await ids(nobody)).toEqual([]); + expect(await ids(nobody, { listId: a.list })).toEqual([]); + }); + + // Rows the sync never writes (it checks the owner of a list), but that the + // reads must not trust: each account filter is needed on its own. + it('never returns a task of another account that sits in a list of the account', async () => { + const [a, b] = [await newAccount(), await newAccount()]; + const own = await addTask(a, a.list); + await addTask(a, a.list, { userId: b.userId }); + expect(await ids(a)).toEqual([own]); + expect(await ids(a, { listId: a.list })).toEqual([own]); + // Nor to its owner: the list is not one of theirs. + expect(await ids(b)).toEqual([]); + }); + + it('never returns a task of the account that sits in a list of another account', async () => { + const [a, b] = [await newAccount(), await newAccount()]; + const own = await addTask(a, a.list); + await addTask(a, b.list); + expect(await ids(a)).toEqual([own]); + expect(await ids(a, { listId: b.list })).toEqual([]); + }); + + it('filters by list', async () => { + const a = await newAccount(); + const second = await addList(a.userId); + const [t1, t2] = [await addTask(a, a.list), await addTask(a, second)]; + expect(await ids(a, { listId: a.list })).toEqual([t1]); + expect(await ids(a, { listId: second })).toEqual([t2]); + expect(await ids(a, { listId: u() })).toEqual([]); + }); + + it('filters by status: open, completed, all, and all when absent', async () => { + const a = await newAccount(); + const [open, done] = [await addTask(a, a.list), await addTask(a, a.list, { completed: true })]; + expect(await ids(a, { status: 'open' })).toEqual([open]); + expect(await ids(a, { status: 'completed' })).toEqual([done]); + expect(await ids(a, { status: 'all' })).toEqual([open, done]); + expect(await ids(a, {})).toEqual([open, done]); + }); + + it('filters by priority, 0 included', async () => { + const a = await newAccount(); + const [none, high] = [await addTask(a, a.list), await addTask(a, a.list, { priority: 3 })]; + expect(await ids(a, { priority: 0 })).toEqual([none]); + expect(await ids(a, { priority: 3 })).toEqual([high]); + expect(await ids(a, { priority: 1 })).toEqual([]); + }); + + it('filters by due date with inclusive bounds, and leaves out a task without one', async () => { + const a = await newAccount(); + const early = await addTask(a, a.list, { dueDate: '2026-05-01T12:00:00Z' }); + const exact = await addTask(a, a.list, { dueDate: '2026-05-02T12:00:00Z' }); + const late = await addTask(a, a.list, { dueDate: '2026-05-03T12:00:00Z' }); + await addTask(a, a.list); + const bound = new Date('2026-05-02T12:00:00Z'); + + expect(await ids(a, { dueBefore: bound })).toEqual([early, exact]); + expect(await ids(a, { dueAfter: bound })).toEqual([exact, late]); + expect(await ids(a, { dueAfter: bound, dueBefore: bound })).toEqual([exact]); + // One millisecond inside the bound: the task due at the bound is out. + expect(await ids(a, { dueBefore: new Date(bound.getTime() - 1) })).toEqual([early]); + expect(await ids(a, { dueAfter: new Date(bound.getTime() + 1) })).toEqual([late]); + }); + + it('filters by tags: at least one of them, live and of the account', async () => { + const [a, b] = [await newAccount(), await newAccount()]; + const [red, blue, gone, foreign] = [ + await addTag(a.userId), await addTag(a.userId), await addTag(a.userId, { deletedAt: GONE }), await addTag(b.userId), + ]; + const [t1, t2, t3, t4] = [await addTask(a, a.list), await addTask(a, a.list), await addTask(a, a.list), await addTask(a, a.list)]; + await link(t1, red); + await link(t1, blue); + await link(t2, blue); + await link(t3, gone); + await link(t4, foreign); + + expect(await ids(a, { tagIds: [red] })).toEqual([t1]); + expect(await ids(a, { tagIds: [blue] })).toEqual([t1, t2]); + expect(await ids(a, { tagIds: [red, blue] })).toEqual([t1, t2]); + expect(await ids(a, { tagIds: [gone] })).toEqual([]); + expect(await ids(a, { tagIds: [foreign] })).toEqual([]); + expect(await ids(a, { tagIds: [u()] })).toEqual([]); + // No tag named: no filter. + expect(await ids(a, { tagIds: [] })).toEqual([t1, t2, t3, t4]); + }); + + it('searches the title and the notes, whatever the case', async () => { + const a = await newAccount(); + const inTitle = await addTask(a, a.list, { title: 'Buy MILK and bread' }); + const inNotes = await addTask(a, a.list, { title: 'groceries', notes: 'do not forget the milk' }); + await addTask(a, a.list, { title: 'call the bank' }); + + expect(await ids(a, { query: 'milk' })).toEqual([inTitle, inNotes]); + expect(await ids(a, { query: 'MiLk' })).toEqual([inTitle, inNotes]); + expect(await ids(a, { query: 'bread' })).toEqual([inTitle]); + expect(await ids(a, { query: 'nothing like it' })).toEqual([]); + // An empty text filters nothing. + expect(await ids(a, { query: '' })).toHaveLength(3); + }); + + it('reads %, _ and \\ of a search text as themselves', async () => { + const a = await newAccount(); + const percent = await addTask(a, a.list, { title: '100% done' }); + const underscore = await addTask(a, a.list, { title: 'snake_case name' }); + const backslash = await addTask(a, a.list, { title: 'path C:\\temp' }); + const plain = await addTask(a, a.list, { title: '100 percent, snakeXcase, C:temp' }); + + expect(await ids(a, { query: '%' })).toEqual([percent]); + expect(await ids(a, { query: '0% d' })).toEqual([percent]); + expect(await ids(a, { query: '_' })).toEqual([underscore]); + expect(await ids(a, { query: 'snake_case' })).toEqual([underscore]); + expect(await ids(a, { query: '\\' })).toEqual([backslash]); + expect(await ids(a, { query: 'C:\\temp' })).toEqual([backslash]); + // Control: the fourth task matches a plain text. + expect(await ids(a, { query: 'percent' })).toEqual([plain]); + }); + + it('reads the pages one after the other: three tasks by one give three pages, the last without a cursor', async () => { + const a = await newAccount(); + const [t1, t2, t3] = [await addTask(a, a.list), await addTask(a, a.list), await addTask(a, a.list)]; + + const first = await queryAccountTasks(a.userId, {}, { limit: 1 }); + expect(first.tasks.map((t) => t.id)).toEqual([t1]); + expect(first.nextCursor).toEqual({ createdAt: first.tasks[0].createdAt, id: t1 }); + + expect(await pages(a, 1)).toEqual([[t1], [t2], [t3]]); + expect(await pages(a, 2)).toEqual([[t1, t2], [t3]]); + // A page that holds exactly the rest announces nothing after it. + expect(await pages(a, 3)).toEqual([[t1, t2, t3]]); + expect(await pages(a, 100)).toEqual([[t1, t2, t3]]); + }); + + it('keeps the filters between the pages', async () => { + const a = await newAccount(); + const t1 = await addTask(a, a.list, { priority: 1 }); + await addTask(a, a.list, { priority: 2 }); + const t3 = await addTask(a, a.list, { priority: 1 }); + await addTask(a, a.list, { priority: 1, completed: true }); + expect(await pages(a, 1, { priority: 1, status: 'open' })).toEqual([[t1], [t3]]); + }); + + // created_at holds microseconds, a JavaScript Date milliseconds: a cursor + // compared to the raw column would stand before its own row. + it('returns each of two tasks created in the same millisecond exactly once', async () => { + const a = await newAccount(); + // Lowercase hexadecimal: the order of the strings is the order of the uuids. + const [low, high] = [u(), u()].sort(); + // The larger id is created first, 998 microseconds before the other. + await addTask(a, a.list, { id: high, createdAt: '2026-04-01T10:00:00.123001Z' }); + await addTask(a, a.list, { id: low, createdAt: '2026-04-01T10:00:00.123999Z' }); + const after = await addTask(a, a.list, { createdAt: '2026-04-01T10:00:00.124000Z' }); + const before = await addTask(a, a.list, { createdAt: '2026-04-01T10:00:00.122999Z' }); + + // Control: the database holds the microseconds. + const stored = await h.pg.query<{ at: string }>( + "SELECT to_char(created_at AT TIME ZONE 'UTC', 'SS.US') AS at FROM sl_tasks WHERE id IN ($1, $2) ORDER BY created_at", + [low, high], + ); + expect(stored.rows.map((r) => r.at)).toEqual(['00.123001', '00.123999']); + + // In the millisecond, the id decides. + expect(await ids(a)).toEqual([before, low, high, after]); + expect(await pages(a, 1)).toEqual([[before], [low], [high], [after]]); + expect(await pages(a, 2)).toEqual([[before, low], [high, after]]); + expect(await pages(a, 3)).toEqual([[before, low, high], [after]]); + }); +}); + +describe('loadAccountTask', () => { + it('returns a top-level task and a subtask of the account', async () => { + const a = await newAccount(); + const parent = await addTask(a, a.list, { title: 'parent' }); + const child = await addTask(a, a.list, { title: 'child', parentId: parent }); + expect(await loadAccountTask(a.userId, parent)).toMatchObject({ id: parent, title: 'parent', parentId: null }); + expect(await loadAccountTask(a.userId, child)).toMatchObject({ id: child, title: 'child', parentId: parent }); + }); + + it('returns null for an unknown task, a deleted task and a task of a deleted list', async () => { + const a = await newAccount(); + const deletedList = await addList(a.userId, { deletedAt: GONE }); + const deleted = await addTask(a, a.list, { deletedAt: GONE }); + const inDeletedList = await addTask(a, deletedList); + expect(await loadAccountTask(a.userId, u())).toBeNull(); + expect(await loadAccountTask(a.userId, deleted)).toBeNull(); + expect(await loadAccountTask(a.userId, inDeletedList)).toBeNull(); + }); + + it('returns null for a task of another account', async () => { + const [a, b] = [await newAccount(), await newAccount()]; + const foreign = await addTask(b, b.list); + expect(await loadAccountTask(a.userId, foreign)).toBeNull(); + expect(await loadAccountTask(b.userId, foreign)).toMatchObject({ id: foreign }); + }); + + it('returns null for a task of another account that sits in a list of the account, and the reverse', async () => { + const [a, b] = [await newAccount(), await newAccount()]; + const foreignInOwnList = await addTask(a, a.list, { userId: b.userId }); + const ownInForeignList = await addTask(a, b.list); + expect(await loadAccountTask(a.userId, foreignInOwnList)).toBeNull(); + expect(await loadAccountTask(a.userId, ownInForeignList)).toBeNull(); + expect(await loadAccountTask(b.userId, foreignInOwnList)).toBeNull(); + expect(await loadAccountTask(b.userId, ownInForeignList)).toBeNull(); + }); +}); + +describe('loadAccountLists', () => { + it('returns the live lists of the account, by position then by creation', async () => { + const userId = `user-${u()}`; + const third = await addList(userId, { position: 1, createdAt: '2026-01-01T00:00:00Z' }); + const second = await addList(userId, { position: 0, createdAt: '2026-01-02T00:00:00Z' }); + const first = await addList(userId, { position: 0, createdAt: '2026-01-01T00:00:00Z' }); + await addList(userId, { deletedAt: GONE }); + const other = await newAccount(); + + const lists = await loadAccountLists(userId); + expect(lists.map((l) => l.id)).toEqual([first, second, third]); + expect(lists.every((l) => l.userId === userId && l.deletedAt === null)).toBe(true); + expect((await loadAccountLists(other.userId)).map((l) => l.id)).toEqual([other.list]); + expect(await loadAccountLists(`user-${u()}`)).toEqual([]); + }); + + it('returns one list by id, only if it is a live list of the account', async () => { + const [a, b] = [await newAccount(), await newAccount()]; + const deleted = await addList(a.userId, { deletedAt: GONE }); + expect((await loadAccountLists(a.userId, a.list)).map((l) => l.id)).toEqual([a.list]); + expect(await loadAccountLists(a.userId, deleted)).toEqual([]); + expect(await loadAccountLists(a.userId, b.list)).toEqual([]); + expect(await loadAccountLists(a.userId, u())).toEqual([]); + }); +}); + +describe('loadOpenTaskCounts', () => { + it('counts the open top-level tasks of the account by list', async () => { + const a = await newAccount(); + const second = await addList(a.userId); + const empty = await addList(a.userId); + const parent = await addTask(a, a.list); + await addTask(a, a.list); + await addTask(a, a.list, { completed: true }); + await addTask(a, a.list, { deletedAt: GONE }); + await addTask(a, a.list, { parentId: parent }); + await addTask(a, second); + + const counts = await loadOpenTaskCounts(a.userId); + expect(counts).toEqual({ [a.list]: 2, [second]: 1 }); + expect(counts[empty]).toBeUndefined(); + expect(await loadOpenTaskCounts(`user-${u()}`)).toEqual({}); + }); + + it('never counts a task of another account, even in a list of the account', async () => { + const [a, b] = [await newAccount(), await newAccount()]; + await addTask(a, a.list); + await addTask(b, b.list); + await addTask(a, a.list, { userId: b.userId }); + expect(await loadOpenTaskCounts(a.userId)).toEqual({ [a.list]: 1 }); + // The misplaced task is counted for its owner, under a list that is not + // theirs: list_lists never shows that list to them. + expect(await loadOpenTaskCounts(b.userId)).toEqual({ [b.list]: 1, [a.list]: 1 }); + }); +}); diff --git a/web/src/lib/taskQueries.ts b/web/src/lib/taskQueries.ts index 3021535..c4dc305 100644 --- a/web/src/lib/taskQueries.ts +++ b/web/src/lib/taskQueries.ts @@ -1,10 +1,11 @@ -// Task reads shared by the list page (web/src/app/(app)/lists/[id]/page.tsx) -// and GET /api/lists/[id]/tasks (#179). Every query is scoped to the account: -// tasks by sl_tasks.user_id, tags by sl_tags.user_id and deleted_at IS NULL. +// Task reads shared by the list page (web/src/app/(app)/lists/[id]/page.tsx), +// GET /api/lists/[id]/tasks (#179) and the read tools of the MCP server +// (#202). Every query is scoped to the account: tasks by sl_tasks.user_id, +// lists by sl_lists.user_id, tags by sl_tags.user_id, and deleted_at IS NULL. import { db } from '@/db/client'; -import { slTasks, slTags, slTaskTags } from '@/db/schema'; -import { eq, and, isNull, asc, desc, inArray, lte, type SQL } from 'drizzle-orm'; +import { slLists, slTasks, slTags, slTaskTags } from '@/db/schema'; +import { eq, and, or, isNull, asc, desc, inArray, lte, gte, gt, ilike, count, sql, type SQL } from 'drizzle-orm'; import type { TagPill } from './types'; export interface ListTaskFilters { @@ -50,18 +51,7 @@ export async function queryListTasks(userId: string, listId: string, filters: Li conditions.push(lte(slTasks.dueDate, filters.dueBefore)); } if (filters.tagIds && filters.tagIds.length > 0) { - // Only a live tag of this account can select a task: an id from another - // account, or a deleted tag, matches nothing. - const tagged = db - .select({ taskId: slTaskTags.taskId }) - .from(slTaskTags) - .innerJoin(slTags, eq(slTags.id, slTaskTags.tagId)) - .where(and( - inArray(slTaskTags.tagId, filters.tagIds), - eq(slTags.userId, userId), - isNull(slTags.deletedAt), - )); - conditions.push(inArray(slTasks.id, tagged)); + conditions.push(inArray(slTasks.id, taggedTaskIds(userId, filters.tagIds))); } const orderFn = filters.sortOrder === 'desc' ? desc : asc; @@ -72,6 +62,178 @@ export async function queryListTasks(userId: string, listId: string, filters: Li .orderBy(orderFn(sortColumn(filters.sortBy))); } +// Ids of the tasks carrying at least one of these tags. Only a live tag of +// this account can select a task: an id from another account, or a deleted +// tag, matches nothing. +function taggedTaskIds(userId: string, tagIds: string[]) { + return db + .select({ taskId: slTaskTags.taskId }) + .from(slTaskTags) + .innerJoin(slTags, eq(slTags.id, slTaskTags.tagId)) + .where(and( + inArray(slTaskTags.tagId, tagIds), + eq(slTags.userId, userId), + isNull(slTags.deletedAt), + )); +} + +// Ids of the live lists of the account. +function liveListIds(userId: string) { + return db + .select({ id: slLists.id }) + .from(slLists) + .where(and(eq(slLists.userId, userId), isNull(slLists.deletedAt))); +} + +export type TaskStatusFilter = 'open' | 'completed' | 'all'; + +export interface AccountTaskFilters { + listId?: string; + // Absent: `all`. + status?: TaskStatusFilter; + // Inclusive bounds on the due date; a task without one matches neither. + dueBefore?: Date; + dueAfter?: Date; + // Tasks carrying at least one of these tags, live and of the account. + tagIds?: string[]; + priority?: number; + // Substring of the title or of the notes, whatever the case. + query?: string; +} + +// Where a task stands in the order of queryAccountTasks: its creation instant +// cut to the millisecond, then its id. +export interface TaskCursor { + createdAt: Date; + id: string; +} + +export interface TaskPage { + limit: number; + // Only the tasks after this one. + cursor?: TaskCursor | null; +} + +// created_at holds microseconds and a JavaScript Date milliseconds: compared +// as it is, a cursor read back from a row would stand before that row, and the +// next page would return it again. The order and the cursor both use the +// instant cut to the millisecond. +const createdAtMs = sql`date_trunc('milliseconds', ${slTasks.createdAt})`; + +// A search text as a LIKE pattern that matches it anywhere: `%`, `_` and `\` +// stand for themselves (`\` is the escape character of LIKE). +function likePattern(text: string): string { + return `%${text.replace(/[\\%_]/g, (c) => `\\${c}`)}%`; +} + +// Top-level tasks of the account, not deleted, in its live lists, across +// lists (#202). Total order: creation instant, then id, both ascending (the +// tasks created on the site all have position 0). One row more than the page +// is read, to know whether another page follows: `nextCursor` is then the +// last task returned, null on the last page. +export async function queryAccountTasks(userId: string, filters: AccountTaskFilters, page: TaskPage) { + const conditions: (SQL | undefined)[] = [ + eq(slTasks.userId, userId), + isNull(slTasks.deletedAt), + isNull(slTasks.parentId), + inArray(slTasks.listId, liveListIds(userId)), + ]; + + if (filters.listId !== undefined) { + conditions.push(eq(slTasks.listId, filters.listId)); + } + if (filters.status === 'open' || filters.status === 'completed') { + conditions.push(eq(slTasks.completed, filters.status === 'completed')); + } + if (filters.priority !== undefined) { + conditions.push(eq(slTasks.priority, filters.priority)); + } + if (filters.dueBefore) { + conditions.push(lte(slTasks.dueDate, filters.dueBefore)); + } + if (filters.dueAfter) { + conditions.push(gte(slTasks.dueDate, filters.dueAfter)); + } + if (filters.tagIds && filters.tagIds.length > 0) { + conditions.push(inArray(slTasks.id, taggedTaskIds(userId, filters.tagIds))); + } + if (filters.query) { + const pattern = likePattern(filters.query); + conditions.push(or(ilike(slTasks.title, pattern), ilike(slTasks.notes, pattern))); + } + if (page.cursor) { + const at = sql`${page.cursor.createdAt.toISOString()}::timestamptz`; + conditions.push(or( + sql`${createdAtMs} > ${at}`, + and(sql`${createdAtMs} = ${at}`, gt(slTasks.id, page.cursor.id)), + )); + } + + const rows = await db + .select() + .from(slTasks) + .where(and(...conditions)) + .orderBy(asc(createdAtMs), asc(slTasks.id)) + .limit(page.limit + 1); + + const tasks = rows.slice(0, page.limit); + const last = tasks[tasks.length - 1]; + const nextCursor: TaskCursor | null = rows.length > page.limit && last + ? { createdAt: last.createdAt, id: last.id } + : null; + return { tasks, nextCursor }; +} + +// One live task of the account, top-level or subtask, in a live list of the +// account. Null for a task that is unknown, deleted, another account's, or in +// a deleted list. +export async function loadAccountTask(userId: string, taskId: string) { + const [row] = await db + .select() + .from(slTasks) + .where(and( + eq(slTasks.id, taskId), + eq(slTasks.userId, userId), + isNull(slTasks.deletedAt), + inArray(slTasks.listId, liveListIds(userId)), + )); + return row ?? null; +} + +// Live lists of the account, in the order of the app: by position, then by +// creation. With `listId`, that list alone, if it is one of them. +export async function loadAccountLists(userId: string, listId?: string) { + return db + .select() + .from(slLists) + .where(and( + eq(slLists.userId, userId), + isNull(slLists.deletedAt), + listId === undefined ? undefined : eq(slLists.id, listId), + )) + .orderBy(asc(slLists.position), asc(slLists.createdAt), asc(slLists.id)); +} + +// Number of open top-level tasks of the account, by list id. A list without +// one has no entry. +export async function loadOpenTaskCounts(userId: string) { + const map: Record = {}; + const rows = await db + .select({ listId: slTasks.listId, open: count() }) + .from(slTasks) + .where(and( + eq(slTasks.userId, userId), + isNull(slTasks.deletedAt), + isNull(slTasks.parentId), + eq(slTasks.completed, false), + )) + .groupBy(slTasks.listId); + for (const row of rows) { + map[row.listId] = row.open; + } + return map; +} + // Live subtasks of the given parents, grouped by parent id. export async function loadSubtasks(userId: string, parentIds: string[]) { const map: Record = {};