From 300ecc29fa78da370501b41dccbfcee7600f88a0 Mon Sep 17 00:00:00 2001 From: Bhanu Prakash Bathini Date: Mon, 30 Nov 2026 17:06:51 -0600 Subject: [PATCH 1/6] Add pagination to GET /api/workflows (issue #3435) --- apps/sim/app/api/workflows/route.test.ts | 93 +++++++++++++++++++++++- 1 file changed, 92 insertions(+), 1 deletion(-) diff --git a/apps/sim/app/api/workflows/route.test.ts b/apps/sim/app/api/workflows/route.test.ts index 53ddf9390ee..b2c7ad83be5 100644 --- a/apps/sim/app/api/workflows/route.test.ts +++ b/apps/sim/app/api/workflows/route.test.ts @@ -36,7 +36,7 @@ vi.mock('@/lib/workflows/defaults', () => ({ vi.mock('@/lib/workflows/persistence/utils', () => workflowsPersistenceUtilsMock) -import { POST } from '@/app/api/workflows/route' +import { GET, POST } from '@/app/api/workflows/route' describe('Workflows API Route - POST ordering', () => { afterAll(() => { @@ -103,3 +103,94 @@ describe('Workflows API Route - POST ordering', () => { expect(dbChainMockFns.values).toHaveBeenCalledWith(expect.objectContaining({ sortOrder: 1 })) }) }) + +/** One row of the workflow list, shaped as the `listColumns` projection. */ +const workflowListRow = (id: string, sortOrder: number) => ({ + id, + name: `Workflow ${id}`, + description: null, + workspaceId: 'ws-1', + folderId: null, + sortOrder, + createdAt: new Date(Date.UTC(2026, 0, 1, 0, sortOrder, 0)), + updatedAt: new Date(Date.UTC(2026, 0, 1, 0, sortOrder, 0)), + archivedAt: null, + locked: false, + forkSyncExcluded: false, + isDeployed: false, +}) + +describe('Workflows API Route - GET pagination', () => { + beforeEach(() => { + permissionsMockFns.mockWorkspaceExists.mockResolvedValue(true) + }) + + const getWorkflows = (searchParams: Record) => + GET(createMockRequest({ method: 'GET', url: '/api/workflows', searchParams })) + + it('returns one page with nextCursor null when the workspace fits in a page', async () => { + queueTableRows(schemaMock.workflow, [workflowListRow('w-1', 1), workflowListRow('w-2', 2)]) + + const response = await getWorkflows({ workspaceId: 'ws-1' }) + const data = await response.json() + expect(response.status).toBe(200) + expect(data.data).toHaveLength(2) + expect(data.nextCursor).toBeNull() + }) + + it('caps the page at limit and returns a cursor when more workflows remain', async () => { + const rows = Array.from({ length: 51 }, (_, i) => workflowListRow(`w-${i + 1}`, i + 1)) + dbChainMockFns.limit.mockResolvedValueOnce(rows) + + const response = await getWorkflows({ workspaceId: 'ws-1', limit: '50' }) + const data = await response.json() + expect(response.status).toBe(200) + expect(data.data).toHaveLength(50) + expect(data.data[49].id).toBe('w-50') + expect(data.nextCursor).toEqual(expect.any(String)) + }) + + /** + * A cursor minted under one scope must not resume under another: the keys + * name a position in the first scope's row set, and replaying them under a + * narrower filter would return a coherent page silently missing every match + * sorting before that position. The refusal happens at decode time, before + * the query runs — the same split the v2 workflow list test pins. + * + * A full page-two resume through `resumeKeyset` is deliberately not covered + * here: the mocked schema columns are plain strings, so the timestamp key's + * `column.getSQLType()` has nothing to call on (see `timestampKey.bind`). + * That path is covered at the SQL level by `lib/api/list-query.test.ts` + * (real drizzle columns) and needs a real Postgres read to prove end to end. + */ + it('refuses a cursor replayed under a different scope', async () => { + const rows = Array.from({ length: 3 }, (_, i) => workflowListRow(`w-${i + 1}`, i + 1)) + dbChainMockFns.limit.mockResolvedValueOnce(rows) + + const first = await getWorkflows({ workspaceId: 'ws-1', limit: '2' }) + const firstData = await first.json() + expect(first.status).toBe(200) + expect(firstData.data).toHaveLength(2) + expect(firstData.nextCursor).toEqual(expect.any(String)) + + const replayed = await getWorkflows({ + workspaceId: 'ws-1', + scope: 'archived', + cursor: firstData.nextCursor, + }) + expect(replayed.status).toBe(400) + }) + + it('rejects a cursor that cannot be decoded', async () => { + const response = await getWorkflows({ workspaceId: 'ws-1', cursor: 'not-a-cursor' }) + expect(response.status).toBe(400) + }) + + it('rejects limit values outside 1-100', async () => { + for (const limit of ['0', '101', '2.5']) { + const response = await getWorkflows({ workspaceId: 'ws-1', limit }) + expect(response.status).toBe(400) + } + }) +}) + From f8e88961725dfba7fc238986786f9a158e3b8b93 Mon Sep 17 00:00:00 2001 From: Bhanu Prakash Bathini Date: Mon, 30 Nov 2026 17:08:06 -0600 Subject: [PATCH 2/6] Add pagination to GET /api/workflows (issue #3435) --- apps/sim/app/api/workflows/route.test.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/apps/sim/app/api/workflows/route.test.ts b/apps/sim/app/api/workflows/route.test.ts index b2c7ad83be5..dc99395b0e6 100644 --- a/apps/sim/app/api/workflows/route.test.ts +++ b/apps/sim/app/api/workflows/route.test.ts @@ -193,4 +193,3 @@ describe('Workflows API Route - GET pagination', () => { } }) }) - From feb385dae0c3f05546308875479bd39b38de0d4c Mon Sep 17 00:00:00 2001 From: Bhanu Prakash Bathini Date: Mon, 30 Nov 2026 17:37:43 -0600 Subject: [PATCH 3/6] Add pagination to GET /api/workflows (issue #3435) --- apps/sim/app/api/workflows/route.ts | 53 ++++++++++++++++++++++++++--- 1 file changed, 48 insertions(+), 5 deletions(-) diff --git a/apps/sim/app/api/workflows/route.ts b/apps/sim/app/api/workflows/route.ts index 6758f56c55d..2723504475c 100644 --- a/apps/sim/app/api/workflows/route.ts +++ b/apps/sim/app/api/workflows/route.ts @@ -1,15 +1,23 @@ import { createLogger } from '@sim/logger' import { assertFolderMutable, FolderLockedError } from '@sim/platform-authz/workflow' import { type NextRequest, NextResponse } from 'next/server' -import { createWorkflowContract, workflowListQuerySchema } from '@/lib/api/contracts/workflows' +import { + createWorkflowContract, + listWorkflowsContract, + workflowListQuerySchema, +} from '@/lib/api/contracts/workflows' +import { cursorRoute, cursorScopeKey } from '@/lib/api/cursor-binding' +import type { CursorKey } from '@/lib/api/list-query' import { parseRequest } from '@/lib/api/server' import { checkSessionOrInternalAuth } from '@/lib/auth/hybrid' +import { OrchestrationError } from '@/lib/core/orchestration/types' import { generateRequestId } from '@/lib/core/utils/request' import { withRouteHandler } from '@/lib/core/utils/with-route-handler' import { captureServerEvent } from '@/lib/posthog/server' import { performCreateWorkflow } from '@/lib/workflows/orchestration' -import { listWorkflowsForUser } from '@/lib/workflows/queries' +import { listWorkflowsPageForUser } from '@/lib/workflows/queries' import { getUserEntityPermissions, workspaceExists } from '@/lib/workspaces/permissions/utils' +import { readSortedCursor, writeSortedCursor } from '@/app/api/v2/lib/response' import { verifyWorkspaceMembership } from '@/app/api/workflows/utils' const logger = createLogger('WorkflowAPI') @@ -24,7 +32,30 @@ export const GET = withRouteHandler(async (request: NextRequest) => { { status: 400 } ) } - const { workspaceId, scope } = query.data + const { workspaceId, scope, limit, cursor } = query.data + + // The list is keyset-paged in workspace (position) order. The cursor is + // stamped with the sort and filters it was minted under, so replaying it + // under different filters is a 400, not a page from a nonsense position. + // `scope` carries `.default('active')`, so it is always present on the + // parsed query; binding it unconditionally would put a constant in every + // fingerprint and reject every cursor minted before the field existed. + // Decoded before the handler body: `readSortedCursor` throws an + // `OrchestrationError`, which is not an `HttpError`, so letting it bubble + // would surface a bad cursor as a 500. + const workflowCursorScope = cursorScopeKey(cursorRoute(listWorkflowsContract), { + workspaceId, + scope: scope === 'active' ? undefined : scope, + }) + let cursorKeys: CursorKey[] | undefined + try { + cursorKeys = readSortedCursor(cursor, 'position', 'asc', workflowCursorScope) + } catch (error) { + if (error instanceof OrchestrationError) { + return NextResponse.json({ error: error.message }, { status: 400 }) + } + throw error + } try { const auth = await checkSessionOrInternalAuth(request, { requireWorkflowId: false }) @@ -58,9 +89,21 @@ export const GET = withRouteHandler(async (request: NextRequest) => { } } - const workflows = await listWorkflowsForUser({ userId, workspaceId, scope }) + const page = await listWorkflowsPageForUser({ + userId, + workspaceId, + scope, + limit, + cursorKeys, + }) - return NextResponse.json({ data: workflows }, { status: 200 }) + return NextResponse.json( + { + data: page.data, + nextCursor: writeSortedCursor(page.nextCursorKeys, 'position', 'asc', workflowCursorScope), + }, + { status: 200 } + ) } catch (error: any) { const elapsed = Date.now() - startTime logger.error(`Workflow fetch error after ${elapsed}ms`, error) From fa9465674f6f83d876d6ccc33edcf3291949da3c Mon Sep 17 00:00:00 2001 From: Bhanu Prakash Bathini Date: Mon, 30 Nov 2026 17:44:40 -0600 Subject: [PATCH 4/6] Add pagination to GET /api/workflows (issue #3435) Added v2 pagination fields to workflow list query schema. --- apps/sim/lib/api/contracts/workflows.ts | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/apps/sim/lib/api/contracts/workflows.ts b/apps/sim/lib/api/contracts/workflows.ts index 5886725417c..8e43965914e 100644 --- a/apps/sim/lib/api/contracts/workflows.ts +++ b/apps/sim/lib/api/contracts/workflows.ts @@ -13,6 +13,7 @@ import { workspaceIdSchema, } from '@/lib/api/contracts/primitives' import { defineRouteContract } from '@/lib/api/contracts/types' +import { v2PaginationFields } from '@/lib/api/contracts/v2/shared' import { MAX_WORKFLOW_EXECUTION_TIMEOUT_SECONDS } from '@/lib/billing/execution-timeout-defaults' import { PRIVATE_SECRET_PROVENANCE_FIELD } from '@/lib/execution/private-tool-metadata' @@ -238,6 +239,9 @@ export const workflowIdParamsSchema = z.object({ export const workflowListQuerySchema = z.object({ workspaceId: z.string().min(1).optional(), scope: workflowScopeSchema.default('active'), + // Same page shape as the v2 workflow list: `limit` 1-100, default 50, and an + // opaque `cursor` minted by the previous page's `nextCursor`. + ...v2PaginationFields(), }) export type WorkflowListItem = z.output @@ -719,6 +723,12 @@ export const listWorkflowsContract = defineRouteContract({ mode: 'json', schema: z.object({ data: z.array(workflowListItemSchema), + nextCursor: z + .string() + .nullable() + .describe( + 'Opaque cursor for the next page. Send it back as `cursor`; `null` means there are no more pages.' + ), }), }, }) From 8443c0513b70c5e16349098980a136f6c5bf5b88 Mon Sep 17 00:00:00 2001 From: Bhanu Prakash Bathini Date: Mon, 30 Nov 2026 18:20:45 -0600 Subject: [PATCH 5/6] Add pagination to GET /api/workflows (issue #3435) --- apps/sim/lib/workflows/queries.ts | 102 +++++++++++++++++++++++++----- 1 file changed, 85 insertions(+), 17 deletions(-) diff --git a/apps/sim/lib/workflows/queries.ts b/apps/sim/lib/workflows/queries.ts index 8a4b9a7a5b6..9b929753ec1 100644 --- a/apps/sim/lib/workflows/queries.ts +++ b/apps/sim/lib/workflows/queries.ts @@ -336,6 +336,62 @@ function scopeCondition( return and(base, isNull(workflow.archivedAt)) } +/** Keyset behind the workspace-ordered workflow list: manual position, then creation time, then id. */ +const listWorkflowKeys = WORKFLOW_SORTS.position + +interface FetchWorkflowListRowsInput { + userId: string + workspaceId?: string + scope: WorkflowListScope + limit?: number + cursorKeys?: CursorKey[] +} + +/** + * Raw rows for {@link listWorkflowsForUser} and {@link listWorkflowsPageForUser}. + * With `limit`, reads one page past the cursor in workspace order (`limit + 1`) + * rows, so the caller can tell whether another page exists); without it, reads + * the whole set exactly as before. The paged read orders on the keyset + * expressions (millisecond-truncated `createdAt`) so the ordering is exactly + * the ordering a cursor can express — ordering on the raw column would + * re-admit the page's last row. + */ +async function fetchWorkflowListRows({ + userId, + workspaceId, + scope, + limit, + cursorKeys, +}: FetchWorkflowListRowsInput): Promise { + const resumeAfter = + limit === undefined ? undefined : resumeKeyset(listWorkflowKeys, cursorKeys, 'asc') + const orderBy = + limit === undefined ? orderByClause : listOrderBy(keysetColumns(listWorkflowKeys), 'asc') + + const selectPage = (where: SQL | undefined) => { + const query = db + .select(listColumns) + .from(workflow) + .where(where) + .orderBy(...orderBy) + return limit === undefined ? query : query.limit(limit + 1) + } + + if (workspaceId) { + return selectPage( + and(scopeCondition(scope, eq(workflow.workspaceId, workspaceId)), resumeAfter) + ) + } + + const accessibleRows = await listAccessibleWorkspaceRowsForUser(userId, 'all') + const workspaceIds = accessibleRows.map((row) => row.workspace.id) + if (workspaceIds.length === 0) return [] + + return selectPage( + and(scopeCondition(scope, inArray(workflow.workspaceId, workspaceIds)), resumeAfter) + ) +} + /** * Lists workflows visible to a user as the contract wire shape, shared by the * `GET /api/workflows` route and the workspace sidebar prefetch. Performs no auth @@ -353,23 +409,35 @@ export async function listWorkflowsForUser({ workspaceId?: string scope: WorkflowListScope }): Promise { - if (workspaceId) { - const rows = await db - .select(listColumns) - .from(workflow) - .where(scopeCondition(scope, eq(workflow.workspaceId, workspaceId))) - .orderBy(...orderByClause) - return rows.map(toListItem) - } + const rows = await fetchWorkflowListRows({ userId, workspaceId, scope }) + return rows.map(toListItem) +} - const accessibleRows = await listAccessibleWorkspaceRowsForUser(userId, 'all') - const workspaceIds = accessibleRows.map((row) => row.workspace.id) - if (workspaceIds.length === 0) return [] +export interface WorkflowListPage { + data: WorkflowListItem[] + nextCursorKeys: CursorKey[] | null +} - const rows = await db - .select(listColumns) - .from(workflow) - .where(scopeCondition(scope, inArray(workflow.workspaceId, workspaceIds))) - .orderBy(...orderByClause) - return rows.map(toListItem) +/** + * One cursor page of the workflows visible to a user, in workspace order, + * for `GET /api/workflows`. Same rows and access rules as + * {@link listWorkflowsForUser}, but capped at `limit` rows past `cursorKeys` + * with the keys that resume the next page (`null` on the last page). + */ +export async function listWorkflowsPageForUser({ + userId, + workspaceId, + scope, + limit, + cursorKeys, +}: { + userId: string + workspaceId?: string + scope: WorkflowListScope + limit: number + cursorKeys?: CursorKey[] +}): Promise { + const rows = await fetchWorkflowListRows({ userId, workspaceId, scope, limit, cursorKeys }) + const page = keysetPage(listWorkflowKeys, rows, limit) + return { data: page.data.map(toListItem), nextCursorKeys: page.nextCursorKeys } } From 55417dc59c633ac2a91d7a6cf59133b2334a9c3f Mon Sep 17 00:00:00 2001 From: Bhanu Prakash Bathini Date: Tue, 1 Dec 2026 15:44:39 +0000 Subject: [PATCH 6/6] fix(api): return 400 for invalid cursor keys in GET /api/workflows Greptile review on #10526: a cursor with valid stamps but keys that do not fit the position sort reached resumeKeyset, whose OrchestrationError bubbled to the generic catch and surfaced as a 500. Wrap the paged read and map OrchestrationError to a 400, mirroring the decode step; other errors still rethrow to the 500 catch. Adds a regression test: a cursor minted with one key instead of three returns 500 before this fix and 400 after (verified by reverting the guard and watching it go red). Also runs biome format over the four PR files, which were not biome-formatted. --- apps/sim/app/api/workflows/route.test.ts | 23 +++++ apps/sim/app/api/workflows/route.ts | 60 ++++++----- apps/sim/lib/api/contracts/workflows.ts | 18 ++-- apps/sim/lib/workflows/queries.ts | 126 +++++++++++------------ 4 files changed, 131 insertions(+), 96 deletions(-) diff --git a/apps/sim/app/api/workflows/route.test.ts b/apps/sim/app/api/workflows/route.test.ts index dc99395b0e6..5a7e23ea797 100644 --- a/apps/sim/app/api/workflows/route.test.ts +++ b/apps/sim/app/api/workflows/route.test.ts @@ -36,6 +36,9 @@ vi.mock('@/lib/workflows/defaults', () => ({ vi.mock('@/lib/workflows/persistence/utils', () => workflowsPersistenceUtilsMock) +import { listWorkflowsContract } from '@/lib/api/contracts/workflows' +import { cursorRoute, cursorScopeKey } from '@/lib/api/cursor-binding' +import { writeSortedCursor } from '@/app/api/v2/lib/response' import { GET, POST } from '@/app/api/workflows/route' describe('Workflows API Route - POST ordering', () => { @@ -186,6 +189,26 @@ describe('Workflows API Route - GET pagination', () => { expect(response.status).toBe(400) }) + /** + * A cursor that decodes under the request's scope but carries keys that do + * not fit the position sort (three keys: sortOrder, createdAt, id) is a + * 400, not a 500: `resumeKeyset` throws an `OrchestrationError` for it, + * and the route maps that to a 400 around the paged read, mirroring the + * decode step. Minted with `writeSortedCursor` so the stamps are valid + * and only the key count is wrong. + */ + it('rejects a cursor whose keys do not fit the position sort', async () => { + const scope = cursorScopeKey(cursorRoute(listWorkflowsContract), { + workspaceId: 'ws-1', + scope: undefined, + }) + const cursor = writeSortedCursor([1], 'position', 'asc', scope) + expect(cursor).toEqual(expect.any(String)) + + const response = await getWorkflows({ workspaceId: 'ws-1', cursor: cursor ?? '' }) + expect(response.status).toBe(400) + }) + it('rejects limit values outside 1-100', async () => { for (const limit of ['0', '101', '2.5']) { const response = await getWorkflows({ workspaceId: 'ws-1', limit }) diff --git a/apps/sim/app/api/workflows/route.ts b/apps/sim/app/api/workflows/route.ts index 2723504475c..bd12c399337 100644 --- a/apps/sim/app/api/workflows/route.ts +++ b/apps/sim/app/api/workflows/route.ts @@ -2,9 +2,9 @@ import { createLogger } from '@sim/logger' import { assertFolderMutable, FolderLockedError } from '@sim/platform-authz/workflow' import { type NextRequest, NextResponse } from 'next/server' import { - createWorkflowContract, - listWorkflowsContract, - workflowListQuerySchema, + createWorkflowContract, + listWorkflowsContract, + workflowListQuerySchema, } from '@/lib/api/contracts/workflows' import { cursorRoute, cursorScopeKey } from '@/lib/api/cursor-binding' import type { CursorKey } from '@/lib/api/list-query' @@ -44,17 +44,17 @@ export const GET = withRouteHandler(async (request: NextRequest) => { // `OrchestrationError`, which is not an `HttpError`, so letting it bubble // would surface a bad cursor as a 500. const workflowCursorScope = cursorScopeKey(cursorRoute(listWorkflowsContract), { - workspaceId, - scope: scope === 'active' ? undefined : scope, + workspaceId, + scope: scope === 'active' ? undefined : scope, }) let cursorKeys: CursorKey[] | undefined try { - cursorKeys = readSortedCursor(cursor, 'position', 'asc', workflowCursorScope) + cursorKeys = readSortedCursor(cursor, 'position', 'asc', workflowCursorScope) } catch (error) { - if (error instanceof OrchestrationError) { - return NextResponse.json({ error: error.message }, { status: 400 }) - } - throw error + if (error instanceof OrchestrationError) { + return NextResponse.json({ error: error.message }, { status: 400 }) + } + throw error } try { @@ -89,21 +89,33 @@ export const GET = withRouteHandler(async (request: NextRequest) => { } } - const page = await listWorkflowsPageForUser({ - userId, - workspaceId, - scope, - limit, - cursorKeys, - }) + // `resumeKeyset` throws an `OrchestrationError` for a cursor whose + // keys do not fit this sort, and that throw reaches here, not the + // decode step above — map it to a 400 the same way, so a bad cursor + // is never a 500. Anything else rethrows into the outer catch. + let page + try { + page = await listWorkflowsPageForUser({ + userId, + workspaceId, + scope, + limit, + cursorKeys, + }) + } catch (error) { + if (error instanceof OrchestrationError) { + return NextResponse.json({ error: error.message }, { status: 400 }) + } + throw error + } - return NextResponse.json( - { - data: page.data, - nextCursor: writeSortedCursor(page.nextCursorKeys, 'position', 'asc', workflowCursorScope), - }, - { status: 200 } - ) + return NextResponse.json( + { + data: page.data, + nextCursor: writeSortedCursor(page.nextCursorKeys, 'position', 'asc', workflowCursorScope), + }, + { status: 200 } + ) } catch (error: any) { const elapsed = Date.now() - startTime logger.error(`Workflow fetch error after ${elapsed}ms`, error) diff --git a/apps/sim/lib/api/contracts/workflows.ts b/apps/sim/lib/api/contracts/workflows.ts index 8e43965914e..e63cf77c4f1 100644 --- a/apps/sim/lib/api/contracts/workflows.ts +++ b/apps/sim/lib/api/contracts/workflows.ts @@ -239,9 +239,9 @@ export const workflowIdParamsSchema = z.object({ export const workflowListQuerySchema = z.object({ workspaceId: z.string().min(1).optional(), scope: workflowScopeSchema.default('active'), - // Same page shape as the v2 workflow list: `limit` 1-100, default 50, and an - // opaque `cursor` minted by the previous page's `nextCursor`. - ...v2PaginationFields(), + // Same page shape as the v2 workflow list: `limit` 1-100, default 50, and an + // opaque `cursor` minted by the previous page's `nextCursor`. + ...v2PaginationFields(), }) export type WorkflowListItem = z.output @@ -723,12 +723,12 @@ export const listWorkflowsContract = defineRouteContract({ mode: 'json', schema: z.object({ data: z.array(workflowListItemSchema), - nextCursor: z - .string() - .nullable() - .describe( - 'Opaque cursor for the next page. Send it back as `cursor`; `null` means there are no more pages.' - ), + nextCursor: z + .string() + .nullable() + .describe( + 'Opaque cursor for the next page. Send it back as `cursor`; `null` means there are no more pages.' + ), }), }, }) diff --git a/apps/sim/lib/workflows/queries.ts b/apps/sim/lib/workflows/queries.ts index 9b929753ec1..b82c24ce87b 100644 --- a/apps/sim/lib/workflows/queries.ts +++ b/apps/sim/lib/workflows/queries.ts @@ -340,56 +340,56 @@ function scopeCondition( const listWorkflowKeys = WORKFLOW_SORTS.position interface FetchWorkflowListRowsInput { - userId: string - workspaceId?: string - scope: WorkflowListScope - limit?: number - cursorKeys?: CursorKey[] + userId: string + workspaceId?: string + scope: WorkflowListScope + limit?: number + cursorKeys?: CursorKey[] } /** * Raw rows for {@link listWorkflowsForUser} and {@link listWorkflowsPageForUser}. - * With `limit`, reads one page past the cursor in workspace order (`limit + 1`) - * rows, so the caller can tell whether another page exists); without it, reads - * the whole set exactly as before. The paged read orders on the keyset - * expressions (millisecond-truncated `createdAt`) so the ordering is exactly - * the ordering a cursor can express — ordering on the raw column would - * re-admit the page's last row. - */ + * With `limit`, reads one page past the cursor in workspace order (`limit + 1`) + * rows, so the caller can tell whether another page exists); without it, reads + * the whole set exactly as before. The paged read orders on the keyset + * expressions (millisecond-truncated `createdAt`) so the ordering is exactly + * the ordering a cursor can express — ordering on the raw column would + * re-admit the page's last row. + */ async function fetchWorkflowListRows({ - userId, - workspaceId, - scope, - limit, - cursorKeys, + userId, + workspaceId, + scope, + limit, + cursorKeys, }: FetchWorkflowListRowsInput): Promise { - const resumeAfter = - limit === undefined ? undefined : resumeKeyset(listWorkflowKeys, cursorKeys, 'asc') - const orderBy = - limit === undefined ? orderByClause : listOrderBy(keysetColumns(listWorkflowKeys), 'asc') - - const selectPage = (where: SQL | undefined) => { - const query = db - .select(listColumns) - .from(workflow) - .where(where) - .orderBy(...orderBy) - return limit === undefined ? query : query.limit(limit + 1) - } - - if (workspaceId) { - return selectPage( - and(scopeCondition(scope, eq(workflow.workspaceId, workspaceId)), resumeAfter) - ) - } - - const accessibleRows = await listAccessibleWorkspaceRowsForUser(userId, 'all') - const workspaceIds = accessibleRows.map((row) => row.workspace.id) - if (workspaceIds.length === 0) return [] + const resumeAfter = + limit === undefined ? undefined : resumeKeyset(listWorkflowKeys, cursorKeys, 'asc') + const orderBy = + limit === undefined ? orderByClause : listOrderBy(keysetColumns(listWorkflowKeys), 'asc') + + const selectPage = (where: SQL | undefined) => { + const query = db + .select(listColumns) + .from(workflow) + .where(where) + .orderBy(...orderBy) + return limit === undefined ? query : query.limit(limit + 1) + } + if (workspaceId) { return selectPage( - and(scopeCondition(scope, inArray(workflow.workspaceId, workspaceIds)), resumeAfter) - ) + and(scopeCondition(scope, eq(workflow.workspaceId, workspaceId)), resumeAfter) + ) + } + + const accessibleRows = await listAccessibleWorkspaceRowsForUser(userId, 'all') + const workspaceIds = accessibleRows.map((row) => row.workspace.id) + if (workspaceIds.length === 0) return [] + + return selectPage( + and(scopeCondition(scope, inArray(workflow.workspaceId, workspaceIds)), resumeAfter) + ) } /** @@ -409,35 +409,35 @@ export async function listWorkflowsForUser({ workspaceId?: string scope: WorkflowListScope }): Promise { - const rows = await fetchWorkflowListRows({ userId, workspaceId, scope }) - return rows.map(toListItem) + const rows = await fetchWorkflowListRows({ userId, workspaceId, scope }) + return rows.map(toListItem) } export interface WorkflowListPage { - data: WorkflowListItem[] - nextCursorKeys: CursorKey[] | null + data: WorkflowListItem[] + nextCursorKeys: CursorKey[] | null } /** * One cursor page of the workflows visible to a user, in workspace order, - * for `GET /api/workflows`. Same rows and access rules as - * {@link listWorkflowsForUser}, but capped at `limit` rows past `cursorKeys` - * with the keys that resume the next page (`null` on the last page). - */ + * for `GET /api/workflows`. Same rows and access rules as + * {@link listWorkflowsForUser}, but capped at `limit` rows past `cursorKeys` + * with the keys that resume the next page (`null` on the last page). + */ export async function listWorkflowsPageForUser({ - userId, - workspaceId, - scope, - limit, - cursorKeys, + userId, + workspaceId, + scope, + limit, + cursorKeys, }: { - userId: string - workspaceId?: string - scope: WorkflowListScope - limit: number - cursorKeys?: CursorKey[] + userId: string + workspaceId?: string + scope: WorkflowListScope + limit: number + cursorKeys?: CursorKey[] }): Promise { - const rows = await fetchWorkflowListRows({ userId, workspaceId, scope, limit, cursorKeys }) - const page = keysetPage(listWorkflowKeys, rows, limit) - return { data: page.data.map(toListItem), nextCursorKeys: page.nextCursorKeys } + const rows = await fetchWorkflowListRows({ userId, workspaceId, scope, limit, cursorKeys }) + const page = keysetPage(listWorkflowKeys, rows, limit) + return { data: page.data.map(toListItem), nextCursorKeys: page.nextCursorKeys } }