Skip to content

⭐️⭐️⭐️ Open-source, self-hosted alternative to Linear and Plane. Project management and issue tracking where teams and AI agents work side by side to plan and ship products.

perf(api): read the sync markers without scanning every project (#729)

Croffe39c19819d8b
diff --git a/apps/api/src/modules/agents/queue/service.ts b/apps/api/src/modules/agents/queue/service.ts
index b8624b99..89df7d5a 100644
--- a/apps/api/src/modules/agents/queue/service.ts
+++ b/apps/api/src/modules/agents/queue/service.ts
@@ -12,6 +12,7 @@ import {
} from '@repo/db';
import { and, desc, eq, inArray, isNotNull, isNull, or, sql } from 'drizzle-orm';
import { getTeamAccess, readableProjectIds } from '#shared/access';
+import type { WorkspaceGrant } from '#shared/workspace-roles';
import { runsTeam } from '#modules/teams/service';
import { iso } from '#shared/lib';
import { getLimits, getRunLimit } from '#shared/limits';
@@ -33,14 +34,14 @@ const runnerPresence = sql<'push' | 'online' | 'offline' | 'never' | null>`CASE
WHEN ${aiAgent.lastSeenAt} > now() - interval '90 seconds' THEN 'online'
ELSE 'offline' END`;
-function queueProjectIds(userId: string, mcpOnly = false) {
+function queueProjectIds(userId: string, mcpOnly = false, grants?: Map<number, WorkspaceGrant>) {
return readableProjectIds(
userId,
[
['work_items', 'read'],
['ai_agents', 'read'],
],
- { mcpOnly, includeArchived: true },
+ { mcpOnly, includeArchived: true, grants },
);
}
@@ -193,11 +194,16 @@ async function runTeamProjectIds(userId: string): Promise<number[]> {
// as whoever runs its team also moves the marker. The runs in flight in those projects'
// workspaces are counted too: the queue's header shows them, projects the user does not
// read included.
-export async function runnerQueueRevision(userId: string, mcpOnly = false) {
- const readable = await queueProjectIds(userId, mcpOnly);
- const ids = mcpOnly
- ? readable
- : [...new Set([...readable, ...(await runTeamProjectIds(userId))])].sort((a, b) => a - b);
+export async function runnerQueueRevision(
+ userId: string,
+ grants: Map<number, WorkspaceGrant>,
+ mcpOnly = false,
+) {
+ const [readable, runTeam] = await Promise.all([
+ queueProjectIds(userId, mcpOnly, grants),
+ mcpOnly ? [] : runTeamProjectIds(userId),
+ ]);
+ const ids = mcpOnly ? readable : [...new Set([...readable, ...runTeam])].sort((a, b) => a - b);
if (!ids.length) return '0';
const workspaceIds = db
.selectDistinct({ id: team.workspaceId })
diff --git a/apps/api/src/modules/sync/index.ts b/apps/api/src/modules/sync/index.ts
index c71709c4..d33e02ec 100644
--- a/apps/api/src/modules/sync/index.ts
+++ b/apps/api/src/modules/sync/index.ts
@@ -1,5 +1,6 @@
import { isMcpRequest } from '#shared/mcp-request';
import { runnerQueueRevision } from '#modules/agents/queue/service';
+import { workspaceGrants } from '#modules/workspaces/service';
import { Elysia } from 'elysia';
import { authContext } from '#shared/auth-context';
import { requireUser } from '#shared/access';
@@ -44,16 +45,19 @@ export const syncRoutes = new Elysia({ name: 'sync', detail: { tags: ['Sync'] }
reads.set(scope, { key: spec.key(id, userId), resource: spec.resource });
}
- const found = await readRevs([...reads.values()], userId);
+ const grants = await workspaceGrants(userId);
+ const [found, runnerQueue, inboxAll] = await Promise.all([
+ readRevs([...reads.values()], userId, grants),
+ requested.includes('runnerQueue:1')
+ ? runnerQueueRevision(userId, grants, isMcpRequest(request.headers))
+ : null,
+ requested.includes('inbox:all') ? inboxAllRevision(userId, grants) : null,
+ ]);
const revs = Object.fromEntries(
[...reads].map(([scope, read]) => [scope, found[read.key] ?? NO_REV]),
);
- if (requested.includes('runnerQueue:1')) {
- revs['runnerQueue:1'] = await runnerQueueRevision(userId, isMcpRequest(request.headers));
- }
- if (requested.includes('inbox:all')) {
- revs['inbox:all'] = await inboxAllRevision(userId);
- }
+ if (runnerQueue !== null) revs['runnerQueue:1'] = runnerQueue;
+ if (inboxAll !== null) revs['inbox:all'] = inboxAll;
return { revs };
},
{
diff --git a/apps/api/src/modules/sync/service.ts b/apps/api/src/modules/sync/service.ts
index 5c269aa8..177c68e7 100644
--- a/apps/api/src/modules/sync/service.ts
+++ b/apps/api/src/modules/sync/service.ts
@@ -1,9 +1,9 @@
import { db, project, projectMember, teamRole, revision } from '@repo/db';
import { and, eq, inArray, isNotNull, or, sql } from 'drizzle-orm';
import { toMemberContext, type MemberRole } from '#modules/members/service';
-import { workspaceGrants } from '#modules/workspaces/service';
+import { reachedProjectIds } from '#shared/access';
import { hasPermission, type PermissionResource } from '#shared/permissions';
-import { projectAccess } from '#shared/workspace-roles';
+import { projectAccess, type WorkspaceGrant } from '#shared/workspace-roles';
// The revision engine's read side. The counters themselves are written by the
// triggers in migration 0070 — no application code bumps them, so a write moves
@@ -53,9 +53,9 @@ function memberOrGranted(grantedTeams: number[]) {
export async function readRevs(
wanted: ScopeRead[],
userId: string,
+ grants: Map<number, WorkspaceGrant>,
): Promise<Record<string, string>> {
if (wanted.length === 0) return {};
- const grants = await workspaceGrants(userId);
const grantedTeams = [...grants.keys()];
const rows = await db
.select({
@@ -99,17 +99,15 @@ export async function readRevs(
// One marker for the session user's inbox in every project they can read, so the app
// badge watches a single scope however many projects there are. It lists each
// project's marker, so it moves when any inbox moves and when a project is gained or lost.
-export async function inboxAllRevision(userId: string): Promise<string> {
- const grantedTeams = [...(await workspaceGrants(userId)).keys()];
+export async function inboxAllRevision(
+ userId: string,
+ grants: Map<number, WorkspaceGrant>,
+): Promise<string> {
const rows = await db
.select({ projectId: project.id, rev: revision.rev })
.from(project)
.innerJoin(revision, eq(revision.scope, sql`'inbox:' || ${project.id} || ':' || ${userId}`))
- .leftJoin(
- projectMember,
- and(eq(projectMember.projectId, project.id), eq(projectMember.userId, userId)),
- )
- .where(memberOrGranted(grantedTeams))
+ .where(inArray(project.id, reachedProjectIds(userId, [...grants.keys()])))
.orderBy(project.id);
if (rows.length === 0) return NO_REV;
return rows.map((row) => `${row.projectId}=${row.rev}`).join(',');
diff --git a/apps/api/src/shared/access.ts b/apps/api/src/shared/access.ts
index ef25be1a..d37a52f9 100644
--- a/apps/api/src/shared/access.ts
+++ b/apps/api/src/shared/access.ts
@@ -1,5 +1,5 @@
import { db, project, projectMember, team, teamRole } from '@repo/db';
-import { and, eq, inArray, isNotNull, isNull, or } from 'drizzle-orm';
+import { and, eq, inArray, isNull, type SQLWrapper } from 'drizzle-orm';
import { HttpError } from './lib';
import {
getProjectById,
@@ -36,6 +36,7 @@ import {
teamAccess,
type ProjectAccess,
type TeamAccess,
+ type WorkspaceGrant,
} from './workspace-roles';
// The authenticated user carried on the request context. Populated by the
@@ -423,15 +424,33 @@ export async function projectsWithPermission(
.map((entry) => entry.projectId);
}
+// The ids of the projects the user is a member of or reaches through a workspace role,
+// as a subquery. It starts from the user's own memberships and the granted teams, so it
+// reads indexes rather than every project of the instance.
+export function reachedProjectIds(userId: string, grantedTeams: number[]): SQLWrapper {
+ const member = db
+ .select({ id: projectMember.projectId })
+ .from(projectMember)
+ .where(eq(projectMember.userId, userId));
+ if (grantedTeams.length === 0) return member;
+ return member.union(
+ db.select({ id: project.id }).from(project).where(inArray(project.teamId, grantedTeams)),
+ );
+}
+
// Every project the user reaches, as a member or through their workspace role, where
// their access holds each permission. mcpOnly keeps the projects open to MCP clients.
+// A caller that already read the user's workspace grants passes them.
export async function readableProjectIds(
userId: string,
required: [PermissionResource, PermissionAction][],
- opts: { mcpOnly?: boolean; includeArchived?: boolean } = {},
+ opts: {
+ mcpOnly?: boolean;
+ includeArchived?: boolean;
+ grants?: Map<number, WorkspaceGrant>;
+ } = {},
): Promise<number[]> {
- const grants = await workspaceGrants(userId);
- const grantedTeams = [...grants.keys()];
+ const grants = opts.grants ?? (await workspaceGrants(userId));
const rows = await db
.select({
id: project.id,
@@ -450,10 +469,7 @@ export async function readableProjectIds(
and(
opts.includeArchived ? undefined : isNull(project.archivedAt),
opts.mcpOnly ? and(eq(project.mcpEnabled, true), eq(team.mcpEnabled, true)) : undefined,
- or(
- isNotNull(projectMember.userId),
- grantedTeams.length ? inArray(project.teamId, grantedTeams) : undefined,
- ),
+ inArray(project.id, reachedProjectIds(userId, [...grants.keys()])),
),
);
return rows