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
40 changes: 40 additions & 0 deletions backend/src/tasks/page-cursor.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import { describe, expect, test } from "bun:test";
import { encodeTaskPageCursor, parseTaskPageCursor } from "./page-cursor";

const CURSOR = {
orderKey: 2.5,
createdAtMicros: "1793865600123456",
id: "0b6f6bb4-4a7e-4a55-9a37-2f1b0a1b9f10",
};

function encodeRaw(value: unknown): string {
return Buffer.from(JSON.stringify(value), "utf8").toString("base64url");
}

describe("task page cursor", () => {
test("round-trips a page's last sort key, fractional and negative positions included", () => {
expect(parseTaskPageCursor(encodeTaskPageCursor(CURSOR))).toEqual(CURSOR);
const negative = { ...CURSOR, orderKey: -0.123456789012345 };
expect(parseTaskPageCursor(encodeTaskPageCursor(negative))).toEqual(negative);
});

test("refuses anything that is not a cursor it made", () => {
for (const value of [
"",
"not base64!",
"a".repeat(600),
encodeRaw({ orderKey: 1 }),
encodeRaw([1, "1793865600123456"]),
encodeRaw(["1", CURSOR.createdAtMicros, CURSOR.id]),
encodeRaw([null, CURSOR.createdAtMicros, CURSOR.id]),
encodeRaw([1, 1793865600123456, CURSOR.id]),
encodeRaw([1, "-5", CURSOR.id]),
encodeRaw([1, "1.5", CURSOR.id]),
encodeRaw([1, "999999999999999999", CURSOR.id]),
encodeRaw([1, CURSOR.createdAtMicros, "not-a-uuid"]),
Buffer.from("[1,", "utf8").toString("base64url"),
]) {
expect(parseTaskPageCursor(value)).toBeNull();
}
});
});
43 changes: 43 additions & 0 deletions backend/src/tasks/page-cursor.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
/**
* The `cursor` of `GET /api/tasks`: a task page's last sort key, as opaque
* base64url text. The key is the board order, column position then newest
* first (see `listTaskPageForOrg` in ./repo).
*/
import type { TaskPageCursor } from "./repo";

const MAX_CURSOR_LENGTH = 512;
/** 9999-12-31T23:59:59.999999Z, the last instant Postgres timestamps reach in this form. */
const MAX_CURSOR_MICROSECONDS = 253_402_300_799_999_999n;
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;

export function encodeTaskPageCursor(cursor: TaskPageCursor): string {
return Buffer.from(
JSON.stringify([cursor.orderKey, cursor.createdAtMicros, cursor.id]),
"utf8",
).toString("base64url");
}

/** Decode a cursor from `encodeTaskPageCursor`; null for anything else. */
export function parseTaskPageCursor(value: string): TaskPageCursor | null {
if (!value || value.length > MAX_CURSOR_LENGTH || !/^[A-Za-z0-9_-]+$/.test(value)) return null;
let decoded: unknown;
try {
decoded = JSON.parse(Buffer.from(value, "base64url").toString("utf8"));
} catch {
return null;
}
if (!Array.isArray(decoded) || decoded.length !== 3) return null;
const [orderKey, createdAtMicros, id] = decoded as unknown[];
if (
typeof orderKey !== "number" ||
!Number.isFinite(orderKey) ||
typeof createdAtMicros !== "string" ||
!/^[0-9]{1,18}$/.test(createdAtMicros) ||
BigInt(createdAtMicros) > MAX_CURSOR_MICROSECONDS ||
typeof id !== "string" ||
!UUID_RE.test(id)
) {
return null;
}
return { orderKey, createdAtMicros, id };
}
132 changes: 132 additions & 0 deletions backend/src/tasks/repo.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
import { afterAll, describe, expect, test } from "bun:test";
import { eq, sql } from "drizzle-orm";
import "../index"; // side-effect: run committed migrations before DB assertions
import { db } from "../db/client";
import { tasks } from "../db/schema";
import { createTask, listTaskPageForOrg, listTasksForOrg, type TaskPageCursor } from "./repo";

// Paging the task list through `listTaskPageForOrg` against the real database:
// past 100 tasks, through ties the cursor has to break, and without archived
// tasks taking places on a page.

const orgIds: string[] = [];

function newOrg(label: string): string {
const orgId = `org-tasks-${label}-${crypto.randomUUID()}`;
orgIds.push(orgId);
return orgId;
}

afterAll(async () => {
for (const orgId of orgIds) await db.delete(tasks).where(eq(tasks.orgId, orgId));
});

async function readAll(
orgId: string,
options: { limit: number; excludeArchived?: boolean },
): Promise<{ titles: string[]; pages: number }> {
const titles: string[] = [];
let cursor: TaskPageCursor | null = null;
let pages = 0;
do {
const page = await listTaskPageForOrg(orgId, { scope: "all" }, { ...options, cursor });
titles.push(...page.tasks.map((task) => task.title));
cursor = page.nextCursor;
pages += 1;
expect(pages).toBeLessThanOrEqual(50);
} while (cursor);
return { titles, pages };
}

describe("task pages", () => {
test("the newest of 101 tasks is on the second page, and every task is read once", async () => {
const orgId = newOrg("101");
for (let index = 0; index < 101; index += 1) {
await createTask({ orgId, title: `task ${index}` });
}

// One page of 100, in board order, stops short of the newest task.
const first = await listTaskPageForOrg(orgId, { scope: "all" }, { limit: 100 });
expect(first.tasks.map((task) => task.title)).toEqual(
Array.from({ length: 100 }, (_, index) => `task ${index}`),
);
expect(first.nextCursor).not.toBeNull();
const second = await listTaskPageForOrg(
orgId,
{ scope: "all" },
{ limit: 100, cursor: first.nextCursor },
);
expect(second.tasks.map((task) => task.title)).toEqual(["task 100"]);
expect(second.nextCursor).toBeNull();

// The old one-shot read still answers its first 100 for the agent's tools.
expect(await listTasksForOrg(orgId, { scope: "all" }, 100)).toHaveLength(100);
});

test("a page cut inside tasks with one position and one creation time keeps the id order", async () => {
const orgId = newOrg("ties");
const at = new Date(Date.now() - 60_000);
// Twelve tasks share position 1 and the exact creation instant, so only the
// id orders them; three more one microsecond apart share position 2.
await db.insert(tasks).values(
Array.from({ length: 12 }, (_, index) => ({
orgId,
title: `tie ${index}`,
orderKey: 1,
createdAt: at,
updatedAt: at,
})),
);
await db.insert(tasks).values(
[0, 1, 2].map((index) => ({
orgId,
title: `micro ${index}`,
orderKey: 2,
createdAt: sql`${at.toISOString()}::timestamptz + ${index}::int * interval '1 microsecond'`,
updatedAt: at,
})),
);
// A fractional position from a drag between two cards.
await db.insert(tasks).values({ orgId, title: "between", orderKey: 1.5 });

const oneShot = (await listTaskPageForOrg(orgId, { scope: "all" }, { limit: 500 })).tasks.map(
(task) => task.title,
);
expect(oneShot).toHaveLength(16);
expect(oneShot.slice(12)).toEqual(["between", "micro 2", "micro 1", "micro 0"]);
for (const limit of [1, 5, 7]) {
const { titles } = await readAll(orgId, { limit });
expect(titles).toEqual(oneShot);
}
});

test("archived tasks are left out of the pages when asked", async () => {
const orgId = newOrg("archived");
for (let index = 0; index < 120; index += 1) {
await createTask({
orgId,
title: `task ${index}`,
status: index < 110 ? "archived" : "todo",
});
}

const board = await listTaskPageForOrg(orgId, { scope: "all" }, { limit: 100, excludeArchived: true });
expect(board.tasks.map((task) => task.title)).toEqual(
Array.from({ length: 10 }, (_, index) => `task ${110 + index}`),
);
expect(board.nextCursor).toBeNull();

const everything = await readAll(orgId, { limit: 100 });
expect(everything.titles).toHaveLength(120);
expect(everything.pages).toBe(2);
});

test("a page never reaches another workspace's tasks", async () => {
const mine = newOrg("mine");
const theirs = newOrg("theirs");
await createTask({ orgId: mine, title: "mine" });
await createTask({ orgId: theirs, title: "theirs" });
const page = await listTaskPageForOrg(mine, { scope: "all" }, { limit: 100 });
expect(page.tasks.map((task) => task.title)).toEqual(["mine"]);
});
});
77 changes: 67 additions & 10 deletions backend/src/tasks/repo.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import { and, asc, desc, eq, sql } from "drizzle-orm";
import { and, asc, desc, eq, ne, sql } from "drizzle-orm";
import { db } from "../db/client";
import { tasks, type TaskStatus } from "../db/schema";
import { ensureProject, getProjectForOrg } from "../projects/repo";

// ---------------------------------------------------------------------------
// Tasks data access. Every function is ORG-SCOPED and fail-closed: a cross-org
// (or missing) id resolves to null. The board reads through `listTasksForOrg`
// (or missing) id resolves to null. The board pages through `listTaskPageForOrg`
// (optionally filtered to one project); the gateway tools and REST routes share
// this one module so there is a single place tenancy is enforced.
// ---------------------------------------------------------------------------
Expand Down Expand Up @@ -96,7 +96,38 @@ export async function listTasksForOrg(
selection: TaskListScope = { projectKey: null },
requestedLimit = 100,
): Promise<TaskRecord[]> {
const limit = Math.min(Math.max(requestedLimit, 1), 500);
return (await listTaskPageForOrg(orgId, selection, { limit: requestedLimit })).tasks;
}

/** Where a page of the task list stopped: the last row's full sort key. The
* creation time is whole microseconds since the epoch (a decimal string), the
* precision Postgres stores, so tasks created in the same millisecond are
* neither repeated nor skipped. */
export interface TaskPageCursor {
readonly orderKey: number;
readonly createdAtMicros: string;
readonly id: string;
}

export interface TaskPage {
readonly tasks: TaskRecord[];
/** Pass back as `cursor` for the next page; null on the last page. */
readonly nextCursor: TaskPageCursor | null;
}

/** One page of org-scoped tasks in board order (column position, then newest
* first), after `cursor` when given. `excludeArchived` leaves archived tasks
* out, so they never take a place on a page of the board. */
export async function listTaskPageForOrg(
orgId: string,
selection: TaskListScope = { projectKey: null },
options: {
limit?: number;
cursor?: TaskPageCursor | null;
excludeArchived?: boolean;
} = {},
): Promise<TaskPage> {
const limit = Math.min(Math.max(options.limit ?? 100, 1), 500);
const projectScope =
"scope" in selection
? undefined
Expand All @@ -105,15 +136,41 @@ export async function listTasksForOrg(
: selection.projectKey === null || selection.projectKey === ""
? sql`${tasks.projectId} is null`
: eq(tasks.projectKey, selection.projectKey);
const scope = projectScope
? and(eq(tasks.orgId, orgId), projectScope)
: eq(tasks.orgId, orgId);
return db
.select()
const cursor = options.cursor ?? null;
// order_key sorts up and the rest down, so "after the cursor" is a later
// position, or the same position and an older (created_at, id).
const afterCursor = cursor
? sql`(${tasks.orderKey} > ${cursor.orderKey}::double precision
or (${tasks.orderKey} = ${cursor.orderKey}::double precision
and (${tasks.createdAt}, ${tasks.id})
< ('epoch'::timestamptz + ${cursor.createdAtMicros}::bigint * interval '1 microsecond',
${cursor.id}::uuid)))`
: undefined;
const rows = await db
.select({
task: tasks,
createdAtMicros: sql<string>`((extract(epoch from ${tasks.createdAt}) * 1000000)::bigint)::text`,
})
.from(tasks)
.where(scope)
.where(
and(
eq(tasks.orgId, orgId),
projectScope,
options.excludeArchived ? ne(tasks.status, "archived") : undefined,
afterCursor,
),
)
.orderBy(asc(tasks.orderKey), desc(tasks.createdAt), desc(tasks.id))
.limit(limit);
.limit(limit + 1);
const page = rows.slice(0, limit);
const last = page.at(-1);
return {
tasks: page.map((row) => row.task),
nextCursor:
rows.length > limit && last
? { orderKey: last.task.orderKey, createdAtMicros: last.createdAtMicros, id: last.task.id }
: null,
};
}

/** Org-scoped fetch - a cross-org (or missing) id resolves to null. */
Expand Down
26 changes: 20 additions & 6 deletions backend/src/tasks/routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,11 @@ import { orgScope } from "../middleware/org";
import {
createTask,
deleteTask,
listTasksForOrg,
listTaskPageForOrg,
updateTask,
type TaskRecord,
} from "./repo";
import { encodeTaskPageCursor, parseTaskPageCursor } from "./page-cursor";

export const tasksRoutes = new Hono<AppEnv>();

Expand Down Expand Up @@ -38,22 +39,35 @@ function isTaskStatus(v: unknown): v is TaskStatus {
return typeof v === "string" && (TASK_STATUSES as readonly string[]).includes(v);
}

// List tasks for the active org. `?project=<key>` or `?project_id=<uuid>` scopes
// to one project; the default is unfiled, and `?scope=all` is the explicit
// bounded cross-project read.
// List tasks for the active org in board order. `?project=<key>` or
// `?project_id=<uuid>` scopes to one project; the default is unfiled, and
// `?scope=all` is the explicit cross-project read. Pages: pass `next_cursor`
// back as `?cursor=` with the same filters and limit for the next page.
// `?exclude_archived=1` leaves archived tasks out (the board shows none).
tasksRoutes.get("/", async (c) => {
const project = c.req.query("project");
const projectId = c.req.query("project_id");
const rawLimit = Number(c.req.query("limit") ?? 100);
const limit = Number.isFinite(rawLimit) ? Math.trunc(rawLimit) : 100;
const rawCursor = c.req.query("cursor");
const cursor = rawCursor === undefined ? null : parseTaskPageCursor(rawCursor);
if (rawCursor !== undefined && !cursor) return c.json({ error: "cursor is invalid" }, 400);
const selection =
c.req.query("scope") === "all"
? ({ scope: "all" } as const)
: projectId
? ({ projectId } as const)
: ({ projectKey: project ?? null } as const);
const rows = await listTasksForOrg(c.get("orgId"), selection, limit);
return c.json({ tasks: rows.map(toTask) });
const page = await listTaskPageForOrg(c.get("orgId"), selection, {
limit,
cursor,
excludeArchived: c.req.query("exclude_archived") === "1",
});
return c.json({
tasks: page.tasks.map(toTask),
has_more: page.nextCursor !== null,
next_cursor: page.nextCursor ? encodeTaskPageCursor(page.nextCursor) : null,
});
});

// Create a task (org-scoped). `title` is required; `status` defaults to "todo".
Expand Down
Loading
Loading