Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

⚡️ perf(channel): read a Channel or Thread view without the Channel write lock (#23641)

Arvin Xu1c4eae14d934
diff --git a/packages/database/src/repositories/channel/__tests__/viewLock.test.ts b/packages/database/src/repositories/channel/__tests__/viewLock.test.ts
new file mode 100644
index 00000000000..b7a1d5203c2
--- /dev/null
+++ b/packages/database/src/repositories/channel/__tests__/viewLock.test.ts
@@ -0,0 +1,77 @@
+// @vitest-environment node
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../../../core/getTestDB';
+import { ChannelRepository } from '..';
+import { lockChannel } from '../transaction';
+import { createChannelFixture } from './testUtils';
+
+const db = await getTestDB();
+const fixture = createChannelFixture(db, 'channel-view-lock');
+beforeEach(fixture.setup);
+afterEach(fixture.cleanup);
+
+const threadChannel = async () => {
+ const asOwner = new ChannelRepository(db, fixture.ownerId, fixture.workspaceId);
+ const { channel, member: owner } = await asOwner.create({ title: 'Busy' });
+ const say = (content: string) =>
+ asOwner.send(channel.id, {
+ content,
+ mentions: [owner.id],
+ requestKey: content,
+ routing: 'fallback',
+ });
+ const root = await say('Root');
+ const other = await say('Other root');
+ const thread = await asOwner.createThread(channel.id, { rootMessageId: root.id });
+ await asOwner.createThread(channel.id, { rootMessageId: other.id });
+ return { asOwner, channel, thread };
+};
+
+/** Runs `read` while another transaction holds the Channel's write lock. */
+const readWhileLocked = async <T>(channelId: string, read: () => Promise<T>) => {
+ let locked!: () => void;
+ const lockTaken = new Promise<void>((resolve) => (locked = resolve));
+ let release!: () => void;
+ const released = new Promise<void>((resolve) => (release = resolve));
+ const writer = db.transaction(async (tx) => {
+ await lockChannel(tx, channelId);
+ locked();
+ await released;
+ });
+ await lockTaken;
+ try {
+ return await Promise.race([
+ read(),
+ new Promise<never>((_, reject) =>
+ setTimeout(() => reject(new Error('read waited for the Channel lock')), 2000),
+ ),
+ ]);
+ } finally {
+ release();
+ await writer;
+ }
+};
+
+describe('Channel detail under a write', () => {
+ it('reads the main timeline and a Thread without waiting for the Channel lock', async () => {
+ const { asOwner, channel, thread } = await threadChannel();
+
+ const main = await readWhileLocked(channel.id, () => asOwner.detail(channel.id));
+ expect(main.joined).toBe(true);
+ expect(main.channel.canDelete).toBe(true);
+ expect(main.threads).toHaveLength(2);
+
+ const view = await readWhileLocked(channel.id, () =>
+ asOwner.detail(channel.id, { threadId: thread.id }),
+ );
+ expect(view.threads.map((entry) => entry.id)).toEqual([thread.id]);
+ });
+
+ it('still refuses a missing Thread', async () => {
+ const { asOwner, channel } = await threadChannel();
+ await expect(asOwner.detail(channel.id, { threadId: 'cht_missing' })).rejects.toMatchObject({
+ code: 'NOT_FOUND',
+ });
+ });
+});
diff --git a/packages/database/src/repositories/channel/index.ts b/packages/database/src/repositories/channel/index.ts
index f4ca7d29345..a514b941752 100644
--- a/packages/database/src/repositories/channel/index.ts
+++ b/packages/database/src/repositories/channel/index.ts
@@ -460,28 +460,26 @@ export class ChannelRepository {
});
};
+ /** Takes no channel lock, so a busy Channel's sends and job updates never queue a read. */
detail = async (channelId: string, options?: Parameters<typeof readChannelView>[2]) => {
- if (!(await this.findAccess(channelId)))
- return readOpenChannel(this.db, this.userId, this.workspaceId, channelId, options);
- return this.write(
- channelId,
- async (tx, access) => {
- if (access.channel.isDeleted) throw new ChannelError('NOT_FOUND', 'Channel not found');
- const admin = hasRole(access.member.role, 'admin');
- const notificationsMuted = access.member.metadata?.notificationsMuted === true;
- const view = await readChannelView(tx, channelId, options, this.userId);
- const shared = await sharedAgentView(tx, access.channel, this.userId);
- return {
- channel: { ...access.channel, canDelete: admin, notificationsMuted, ...shared.channel },
- joined: true,
- sharedAgentOwner: shared.owner,
- ...view,
- // Mirrors `stop`: the requester or an admin.
- jobs: viewerJobs(view.jobs, this.userId, (id) => admin || id === access.member.id),
- };
- },
- { allowArchived: true, allowTrashed: true },
- );
+ const view = await this.db.transaction(async (tx) => {
+ const access = await this.memberAccess(tx, channelId);
+ if (!access) return;
+ if (access.channel.isDeleted) throw new ChannelError('NOT_FOUND', 'Channel not found');
+ const admin = hasRole(access.member.role, 'admin');
+ const notificationsMuted = access.member.metadata?.notificationsMuted === true;
+ const view = await readChannelView(tx, channelId, options, this.userId);
+ const shared = await sharedAgentView(tx, access.channel, this.userId);
+ return {
+ channel: { ...access.channel, canDelete: admin, notificationsMuted, ...shared.channel },
+ joined: true,
+ sharedAgentOwner: shared.owner,
+ ...view,
+ // Mirrors `stop`: the requester or an admin.
+ jobs: viewerJobs(view.jobs, this.userId, (id) => admin || id === access.member.id),
+ };
+ });
+ return view ?? readOpenChannel(this.db, this.userId, this.workspaceId, channelId, options);
};
createThread = async (channelId: string, input: Parameters<typeof createChannelThread>[2]) =>
@@ -871,16 +869,7 @@ export class ChannelRepository {
// Read membership only after the lock: a removal or demotion committed by the previous
// lock holder must be visible here, not the snapshot from before the wait.
- const [row] = await tx
- .select({ channel: channels, member: channelMembers, role: this.callerRole() })
- .from(channels)
- .innerJoin(channelMembers, eq(channelMembers.channelId, channels.id))
- .where(and(eq(channels.id, channelId), this.membershipWhere()))
- .limit(1);
- let access: ChannelAccess | undefined = row && {
- channel: row.channel,
- member: { ...row.member, role: row.role },
- };
+ let access: ChannelAccess | undefined = await this.memberAccess(tx, channelId);
if (!access && options.joinOpen) {
// Joining is itself a write, so a trashed or archived Channel stays closed to newcomers.
const open = await findOpenChannel(tx, this.userId, this.workspaceId, channelId);
@@ -1167,6 +1156,17 @@ export class ChannelRepository {
return row;
};
+ /** The caller's active membership, with the role permission checks see. */
+ private memberAccess = async (tx: Transaction, channelId: string) => {
+ const [row] = await tx
+ .select({ channel: channels, member: channelMembers, role: this.callerRole() })
+ .from(channels)
+ .innerJoin(channelMembers, eq(channelMembers.channelId, channels.id))
+ .where(and(eq(channels.id, channelId), this.membershipWhere()))
+ .limit(1);
+ return row && { channel: row.channel, member: { ...row.member, role: row.role } };
+ };
+
/**
* The caller's role as permission checks see it. A workspace owner or admin counts at least as
* an admin of the group Channels they belong to in that workspace; direct and peer
diff --git a/packages/database/src/repositories/channel/view.ts b/packages/database/src/repositories/channel/view.ts
index 8c0738a4909..38ba1568126 100644
--- a/packages/database/src/repositories/channel/view.ts
+++ b/packages/database/src/repositories/channel/view.ts
@@ -578,7 +578,14 @@ export const readChannelView = async (
tx
.select()
.from(channelThreads)
- .where(and(eq(channelThreads.channelId, channelId), notTrashed(channelThreads.isDeleted)))
+ .where(
+ and(
+ eq(channelThreads.channelId, channelId),
+ notTrashed(channelThreads.isDeleted),
+ // A Thread's view needs only its own entry, not every Thread in the Channel.
+ options.threadId ? eq(channelThreads.id, options.threadId) : undefined,
+ ),
+ )
.orderBy(asc(channelThreads.createdAt)),
readJobs(
tx,