Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

fix(web): release Pro seats before the first snapshot read in each removal transaction

Richie McIlroyd0f2d64fbe44
diff --git a/apps/web/__tests__/unit/invite-decline-pro-seat.test.ts b/apps/web/__tests__/unit/invite-decline-pro-seat.test.ts
index 788d0dfc6..a83297315 100644
--- a/apps/web/__tests__/unit/invite-decline-pro-seat.test.ts
+++ b/apps/web/__tests__/unit/invite-decline-pro-seat.test.ts
@@ -30,6 +30,7 @@ const tables = vi.hoisted(() => ({
}));
const lockRows = vi.fn();
+const reads: { table: unknown; joined: boolean; locked: boolean }[] = [];
const deletes: unknown[] = [];
type SelectQuery = Promise<unknown[]> & {
@@ -41,19 +42,24 @@ type SelectQuery = Promise<unknown[]> & {
};
function selectQuery() {
- let source: unknown;
+ const read = { table: undefined as unknown, joined: false, locked: false };
+ reads.push(read);
const query: SelectQuery = Object.assign(
Promise.resolve(mocks.selectResults.shift() ?? []),
{
from: (table: unknown) => {
- source = table;
+ read.table = table;
+ return query;
+ },
+ innerJoin: () => {
+ read.joined = true;
return query;
},
- innerJoin: () => query,
where: () => query,
limit: () => query,
for: (mode: string) => {
- lockRows(mode, source);
+ read.locked = true;
+ lockRows(mode, read.table);
return query;
},
},
@@ -103,10 +109,10 @@ async function declineProSeat(
},
],
[{ id: "member-1", hasProSeat: true }],
- [],
- [],
[{ id: "user-1" }],
remainingSeats,
+ [],
+ [],
];
const { POST } = await import("@/app/api/invite/decline/route");
return POST(
@@ -126,6 +132,7 @@ describe("POST /api/invite/decline with a Pro seat", () => {
beforeEach(() => {
vi.clearAllMocks();
deletes.length = 0;
+ reads.length = 0;
mocks.user.thirdPartyStripeSubscriptionId = "sub_org_1";
mocks.getCurrentUser.mockResolvedValue({
id: "user-1",
@@ -179,4 +186,14 @@ describe("POST /api/invite/decline with a Pro seat", () => {
["update", tables.users],
]);
});
+
+ it("reads the remaining seats before any other plain read", async () => {
+ await declineProSeat([{ stripeSubscriptionId: "sub_other" }]);
+
+ expect(reads.find((read) => !read.locked)).toEqual({
+ table: tables.organizationMembers,
+ joined: true,
+ locked: false,
+ });
+ });
});
diff --git a/apps/web/__tests__/unit/remove-organization-member.test.ts b/apps/web/__tests__/unit/remove-organization-member.test.ts
index bb187eaa5..2f7e222ad 100644
--- a/apps/web/__tests__/unit/remove-organization-member.test.ts
+++ b/apps/web/__tests__/unit/remove-organization-member.test.ts
@@ -98,9 +98,9 @@ async function removeSeat(
hasProSeat: true,
},
],
- [],
[{ id: "teammate" }],
remainingSeats,
+ [],
];
const { removeOrganizationMember } = await import(
"@/actions/organization/remove-member"
diff --git a/apps/web/__tests__/unit/toggle-pro-seat.test.ts b/apps/web/__tests__/unit/toggle-pro-seat.test.ts
index df4288275..a90267495 100644
--- a/apps/web/__tests__/unit/toggle-pro-seat.test.ts
+++ b/apps/web/__tests__/unit/toggle-pro-seat.test.ts
@@ -27,6 +27,7 @@ const tables = vi.hoisted(() => ({
}));
const lockRows = vi.fn();
+const reads: { table: unknown; joined: boolean; locked: boolean }[] = [];
const updates: { table: unknown; value: Record<string, unknown> }[] = [];
type SelectQuery = Promise<unknown[]> & {
@@ -38,19 +39,24 @@ type SelectQuery = Promise<unknown[]> & {
};
function selectQuery() {
- let source: unknown;
+ const read = { table: undefined as unknown, joined: false, locked: false };
+ reads.push(read);
const query: SelectQuery = Object.assign(
Promise.resolve(mocks.selectResults.shift() ?? []),
{
from: (table: unknown) => {
- source = table;
+ read.table = table;
+ return query;
+ },
+ innerJoin: () => {
+ read.joined = true;
return query;
},
- innerJoin: () => query,
where: () => query,
limit: () => query,
for: (mode: string) => {
- lockRows(mode, source);
+ read.locked = true;
+ lockRows(mode, read.table);
return query;
},
},
@@ -114,6 +120,7 @@ describe("toggleProSeat", () => {
beforeEach(() => {
vi.clearAllMocks();
updates.length = 0;
+ reads.length = 0;
mocks.selectResults = [];
mocks.user.thirdPartyStripeSubscriptionId = "sub_this_org";
mocks.getCurrentUser.mockResolvedValue({ id: "owner" });
@@ -165,6 +172,11 @@ describe("toggleProSeat", () => {
["update", tables.organizationMembers],
["update", tables.users],
]);
+ expect(reads.find((read) => !read.locked)).toEqual({
+ table: tables.organizationMembers,
+ joined: true,
+ locked: false,
+ });
});
it("does nothing when the seat is already off", async () => {
diff --git a/apps/web/actions/organization/remove-member.ts b/apps/web/actions/organization/remove-member.ts
index c08d15ab0..b275f31c7 100644
--- a/apps/web/actions/organization/remove-member.ts
+++ b/apps/web/actions/organization/remove-member.ts
@@ -73,6 +73,21 @@ export async function removeOrganizationMember(
throw new Error("You do not have permission to remove this member");
}
+ const [result] = await tx
+ .delete(organizationMembers)
+ .where(
+ and(
+ eq(organizationMembers.id, memberId),
+ eq(organizationMembers.organizationId, organizationId),
+ ),
+ );
+
+ if (result.affectedRows === 0) throw new Error("Member not found");
+
+ if (member.hasProSeat) {
+ await releaseProSeatSubscription(tx, member.userId);
+ }
+
const organizationSpaces = await tx
.select({ id: spaces.id })
.from(spaces)
@@ -98,21 +113,6 @@ export async function removeOrganizationMember(
eq(organizationInvites.invitedEmail, member.email.toLowerCase()),
),
);
-
- const [result] = await tx
- .delete(organizationMembers)
- .where(
- and(
- eq(organizationMembers.id, memberId),
- eq(organizationMembers.organizationId, organizationId),
- ),
- );
-
- if (result.affectedRows === 0) throw new Error("Member not found");
-
- if (member.hasProSeat) {
- await releaseProSeatSubscription(tx, member.userId);
- }
});
revalidatePath("/dashboard/settings/organization");
diff --git a/apps/web/app/api/invite/decline/route.ts b/apps/web/app/api/invite/decline/route.ts
index 1cc09e947..2344c7604 100644
--- a/apps/web/app/api/invite/decline/route.ts
+++ b/apps/web/app/api/invite/decline/route.ts
@@ -65,6 +65,14 @@ export async function POST(request: NextRequest) {
.for("update");
if (membership) {
+ await tx
+ .delete(organizationMembers)
+ .where(eq(organizationMembers.id, membership.id));
+
+ if (membership.hasProSeat) {
+ await releaseProSeatSubscription(tx, user.id);
+ }
+
const organizationSpaces = await tx
.select({ id: spaces.id })
.from(spaces)
@@ -82,10 +90,6 @@ export async function POST(request: NextRequest) {
);
}
- await tx
- .delete(organizationMembers)
- .where(eq(organizationMembers.id, membership.id));
-
const [remainingMembership] = await tx
.select({ organizationId: organizationMembers.organizationId })
.from(organizationMembers)
@@ -101,10 +105,6 @@ export async function POST(request: NextRequest) {
if (user.defaultOrgId === invite.organizationId) {
userUpdate.defaultOrgId = remainingMembership?.organizationId ?? null;
}
- if (membership.hasProSeat) {
- await releaseProSeatSubscription(tx, user.id);
- }
-
if (Object.keys(userUpdate).length > 0) {
await tx.update(users).set(userUpdate).where(eq(users.id, user.id));
}
diff --git a/apps/web/app/api/v1/[...route]/route.ts b/apps/web/app/api/v1/[...route]/route.ts
index 33be6b8ff..1f5fb7add 100644
--- a/apps/web/app/api/v1/[...route]/route.ts
+++ b/apps/web/app/api/v1/[...route]/route.ts
@@ -5299,6 +5299,21 @@ const AgentManagementHandlersLive = HttpApiBuilder.group(
) {
return { state: "forbidden" };
}
+ const result = await tx
+ .delete(Db.organizationMembers)
+ .where(
+ and(
+ eq(Db.organizationMembers.id, path.memberId),
+ eq(
+ Db.organizationMembers.organizationId,
+ path.organizationId,
+ ),
+ ),
+ );
+ if (affectedRows(result) === 0) return { state: "not_found" };
+ if (member.hasProSeat) {
+ await releaseProSeatSubscription(tx, member.userId);
+ }
const organizationSpaces = await tx
.select({ id: Db.spaces.id })
.from(Db.spaces)
@@ -5325,21 +5340,6 @@ const AgentManagementHandlersLive = HttpApiBuilder.group(
sql`LOWER(TRIM(${Db.organizationInvites.invitedEmail})) = ${member.email.toLowerCase()}`,
),
);
- const result = await tx
- .delete(Db.organizationMembers)
- .where(
- and(
- eq(Db.organizationMembers.id, path.memberId),
- eq(
- Db.organizationMembers.organizationId,
- path.organizationId,
- ),
- ),
- );
- if (affectedRows(result) === 0) return { state: "not_found" };
- if (member.hasProSeat) {
- await releaseProSeatSubscription(tx, member.userId);
- }
const now = new Date();
return {
state: "success",
diff --git a/packages/database/pro-seat-subscription.ts b/packages/database/pro-seat-subscription.ts
index 2d4ca0549..e4a9aa641 100644
--- a/packages/database/pro-seat-subscription.ts
+++ b/packages/database/pro-seat-subscription.ts
@@ -10,7 +10,10 @@ type Transaction = Parameters<
// Call after a member's Pro seat row is gone. Seats don't record who sponsored
// them, so when only manager-sponsored seats remain the current pointer stays.
// The user row lock serializes releases for one user. Locking the remaining
-// seat rows instead deadlocks two orgs turning off the same user's seats.
+// seat rows instead deadlocks two orgs turning off the same user's seats. Run
+// this before the transaction's first plain read: under REPEATABLE READ that
+// read pins the snapshot, and a release committed while this one waited on the
+// user lock would stay invisible.
export async function releaseProSeatSubscription(
tx: Transaction,
userId: User.UserId,
diff --git a/packages/web-backend/src/Organisations/index.ts b/packages/web-backend/src/Organisations/index.ts
index 715358a3e..49212ec16 100644
--- a/packages/web-backend/src/Organisations/index.ts
+++ b/packages/web-backend/src/Organisations/index.ts
@@ -157,11 +157,6 @@ export class Organisations extends Effect.Service<Organisations>()(
yield* db.use((db) =>
db.transaction(async (tx) => {
- const videoIds = videos.map((video) => video.id);
- const spaceRows = await tx
- .select({ id: Db.spaces.id })
- .from(Db.spaces)
- .where(Dz.eq(Db.spaces.organizationId, id));
const memberRows = await tx
.select({
userId: Db.organizationMembers.userId,
@@ -170,6 +165,26 @@ export class Organisations extends Effect.Service<Organisations>()(
.from(Db.organizationMembers)
.where(Dz.eq(Db.organizationMembers.organizationId, id))
.for("update");
+ await tx
+ .delete(Db.organizationMembers)
+ .where(Dz.eq(Db.organizationMembers.organizationId, id));
+
+ const proSeatUserIds = [
+ ...new Set(
+ memberRows
+ .filter((member) => member.hasProSeat)
+ .map((member) => member.userId),
+ ),
+ ].sort();
+ for (const proSeatUserId of proSeatUserIds) {
+ await releaseProSeatSubscription(tx, proSeatUserId);
+ }
+
+ const videoIds = videos.map((video) => video.id);
+ const spaceRows = await tx
+ .select({ id: Db.spaces.id })
+ .from(Db.spaces)
+ .where(Dz.eq(Db.spaces.organizationId, id));
const integrationRows = await tx
.select({ id: Db.storageIntegrations.id })
.from(Db.storageIntegrations)
@@ -257,9 +272,6 @@ export class Organisations extends Effect.Service<Organisations>()(
await tx
.delete(Db.integrationInstallations)
.where(Dz.eq(Db.integrationInstallations.organizationId, id));
- await tx
- .delete(Db.organizationMembers)
- .where(Dz.eq(Db.organizationMembers.organizationId, id));
await tx
.delete(Db.storageIntegrations)
.where(Dz.eq(Db.storageIntegrations.organizationId, id));
@@ -270,17 +282,6 @@ export class Organisations extends Effect.Service<Organisations>()(
.delete(Db.organizations)
.where(Dz.eq(Db.organizations.id, id));
- const proSeatUserIds = [
- ...new Set(
- memberRows
- .filter((member) => member.hasProSeat)
- .map((member) => member.userId),
- ),
- ].sort();
- for (const proSeatUserId of proSeatUserIds) {
- await releaseProSeatSubscription(tx, proSeatUserId);
- }
-
for (const affectedUserId of affectedUserIds) {
const [otherOrg] = await tx
.select({ id: Db.organizations.id })