Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

improve: reduce Loops profile database queries

Richie McIlroy2bb9a004d335
diff --git a/.github/workflows/database-profile-reliability.yml b/.github/workflows/database-profile-reliability.yml
new file mode 100644
index 000000000..26d2b2c4c
--- /dev/null
+++ b/.github/workflows/database-profile-reliability.yml
@@ -0,0 +1,59 @@
+name: Database Profile Reliability
+
+on:
+ workflow_dispatch:
+ pull_request:
+ paths:
+ - "packages/database/**"
+ - "scripts/loops/**"
+ - "bun.lock"
+ - ".github/actions/setup-js/**"
+ - ".github/workflows/database-profile-reliability.yml"
+ push:
+ branches: [main]
+ paths:
+ - "packages/database/**"
+ - "scripts/loops/**"
+ - "bun.lock"
+ - ".github/actions/setup-js/**"
+ - ".github/workflows/database-profile-reliability.yml"
+
+permissions:
+ contents: read
+
+concurrency:
+ group: database-profile-reliability-${{ github.head_ref || github.ref_name }}
+ cancel-in-progress: true
+
+jobs:
+ profile-contract:
+ name: Profile, activation, and consent compatibility
+ runs-on: ubuntu-24.04
+ timeout-minutes: 10
+ services:
+ mysql:
+ image: mysql:8.4
+ env:
+ MYSQL_ALLOW_EMPTY_PASSWORD: "yes"
+ MYSQL_ROOT_HOST: "%"
+ MYSQL_DATABASE: loops_profile_tests
+ ports:
+ - 3306:3306
+ options: >-
+ --health-cmd="mysqladmin ping --host=127.0.0.1 --user=root"
+ --health-interval=5s
+ --health-timeout=3s
+ --health-retries=30
+ steps:
+ - uses: actions/checkout@v4
+ - uses: ./.github/actions/setup-js
+ - name: Verify profile queries and lifecycle decisions without database writes
+ env:
+ LOOPS_ACTIVATION_READONLY_TEST_URL: mysql://[email protected]:3306/loops_profile_tests
+ run: >-
+ bun test
+ scripts/loops/activation.test.ts
+ scripts/loops/sources.test.ts
+ scripts/loops/profile.test.ts
+ scripts/loops/lifecycle.test.ts
+ scripts/loops/watchdog.test.ts
diff --git a/packages/database/loops/activation.ts b/packages/database/loops/activation.ts
index 04c6423b5..84f1c3057 100644
--- a/packages/database/loops/activation.ts
+++ b/packages/database/loops/activation.ts
@@ -1,3 +1,9 @@
+export const legacyActivationQuery = `
+ SELECT
+ EXISTS(SELECT 1 FROM videos WHERE ownerId = ? LIMIT 1) AS hasVideo,
+ EXISTS(SELECT 1 FROM videos WHERE ownerId = ? AND public = 1 LIMIT 1) AS hasSharedVideo
+`;
+
export const activationQuery = `
SELECT
MAX(CASE WHEN u.video_id IS NOT NULL OR (j.video_id IS NOT NULL AND j.state <> 'verified') THEN 1 ELSE 0 END) AS hasPendingUpload,
diff --git a/packages/database/loops/sources.ts b/packages/database/loops/sources.ts
index 9e886410a..e5aeb20b3 100644
--- a/packages/database/loops/sources.ts
+++ b/packages/database/loops/sources.ts
@@ -1,5 +1,5 @@
import type { Connection, RowDataPacket } from "mysql2/promise";
-import { activationQuery } from "./activation";
+import { activationQuery, legacyActivationQuery } from "./activation";
import { activationSignalsAfter, inFreeExperiment } from "./experiment";
import {
type CapUser,
@@ -14,6 +14,25 @@ type RuntimeUser = CapUser & {
stripeCustomerId: string | null;
};
+type UserSignals = {
+ hasAccount: number;
+ hasWorkosAccount: number;
+ hasInvite: number;
+ hasPendingInvite: number;
+};
+
+export const profileUserQuery = `
+ SELECT u.id,u.email,u.name,u.lastName,u.emailVerified,u.stripeCustomerId,
+ u.stripeSubscriptionStatus,u.thirdPartyStripeSubscriptionId,u.created_at,
+ u.defaultOrgId,u.marketingOrigin,
+ EXISTS(SELECT 1 FROM accounts a WHERE a.userId = u.id LIMIT 1) AS hasAccount,
+ EXISTS(SELECT 1 FROM accounts a WHERE a.userId = u.id AND BINARY a.provider = 'workos' LIMIT 1) AS hasWorkosAccount,
+ EXISTS(SELECT 1 FROM organization_invites i WHERE i.invitedEmail = u.email AND i.status IN ('pending','accepted') LIMIT 1) AS hasInvite,
+ EXISTS(SELECT 1 FROM organization_invites i WHERE i.invitedEmail = u.email AND BINARY i.status = 'pending' LIMIT 1) AS hasPendingInvite
+ FROM users u
+ WHERE u.id = ?
+`;
+
export type LoopsProfileSource = {
input: ProfileInput & { user: CapUser };
signedUp: boolean;
@@ -31,27 +50,19 @@ export async function readLoopsProfile(
licenses: Connection,
userId: string,
): Promise<LoopsProfileSource | null> {
- const [user] = await rows<RuntimeUser>(
+ const [record] = await rows<RuntimeUser & UserSignals>(
cap,
- "SELECT id,email,name,lastName,emailVerified,stripeCustomerId,stripeSubscriptionStatus,thirdPartyStripeSubscriptionId,created_at,defaultOrgId,marketingOrigin FROM users WHERE id=?",
+ profileUserQuery,
[userId],
);
- if (!user) return null;
+ if (!record) return null;
+ const { hasAccount, hasWorkosAccount, hasInvite, hasPendingInvite, ...user } =
+ record;
const memberships = await rows<Membership>(
cap,
"SELECT m.userId,m.organizationId,m.hasProSeat,o.ownerId,o.tombstoneAt,o.workosConnectionId,o.createdAt FROM organization_members m JOIN organizations o ON o.id=m.organizationId WHERE m.userId=?",
[userId],
);
- const accounts = await rows<{ provider: string }>(
- cap,
- "SELECT provider FROM accounts WHERE userId=?",
- [userId],
- );
- const invites = await rows<{ status: string }>(
- cap,
- "SELECT status FROM organization_invites WHERE invitedEmail=? AND status IN ('pending','accepted')",
- [user.email],
- );
let activation: {
hasVideo: number | boolean | null;
hasSharedVideo: number | boolean | null;
@@ -64,17 +75,11 @@ export async function readLoopsProfile(
]);
activation = result;
} else {
- const [video] = await rows<{ id: string }>(
- cap,
- "SELECT id FROM videos WHERE ownerId=? LIMIT 1",
- [userId],
- );
- const [shared] = await rows<{ id: string }>(
- cap,
- "SELECT id FROM videos WHERE ownerId=? AND public=1 LIMIT 1",
- [userId],
- );
- activation = { hasVideo: Boolean(video), hasSharedVideo: Boolean(shared) };
+ const [result] = await rows<typeof activation>(cap, legacyActivationQuery, [
+ userId,
+ userId,
+ ]);
+ activation = result;
}
const entitlement = await rows<License>(
licenses,
@@ -87,16 +92,16 @@ export async function readLoopsProfile(
user,
memberships,
licenses: entitlement,
- invited: invites.length > 0,
- sso: accounts.some((account) => account.provider === "workos"),
+ invited: Boolean(hasInvite),
+ sso: Boolean(hasWorkosAccount),
hasVideo: Boolean(activation?.hasVideo),
hasSharedVideo: Boolean(activation?.hasSharedVideo),
lastActivationNotificationAt: activation?.lastActivationNotificationAt,
hasPendingUpload: Boolean(activation?.hasPendingUpload),
now: new Date(),
},
- signedUp: Boolean(user.emailVerified || accounts.length),
- pendingInvite: invites.some((invite) => invite.status === "pending"),
+ signedUp: Boolean(user.emailVerified || hasAccount),
+ pendingInvite: Boolean(hasPendingInvite),
stripeCustomerId: user.stripeCustomerId,
};
}
diff --git a/scripts/loops/activation.test.ts b/scripts/loops/activation.test.ts
index cea672163..a1ef917e2 100644
--- a/scripts/loops/activation.test.ts
+++ b/scripts/loops/activation.test.ts
@@ -1,6 +1,9 @@
import { afterAll, beforeAll, describe, expect, test } from "bun:test";
import mysql, { type Connection, type RowDataPacket } from "mysql2/promise";
-import { activationQuery } from "../../packages/database/loops/activation";
+import {
+ activationQuery,
+ legacyActivationQuery,
+} from "../../packages/database/loops/activation";
const url = process.env.LOOPS_ACTIVATION_READONLY_TEST_URL;
@@ -85,5 +88,47 @@ describe.skipIf(!url)(
(await signals({ viewed: true, upload: true })).hasSharedVideo,
).toBe(0);
});
+
+ for (const [name, videos] of [
+ ["no videos", []],
+ ["private video", [{ ownerId: "owner", public: 0 }]],
+ ["public video", [{ ownerId: "owner", public: 1 }]],
+ ["another owner's public video", [{ ownerId: "other", public: 1 }]],
+ ["null visibility", [{ ownerId: "owner", public: null }]],
+ [
+ "mixed ownership and visibility",
+ [
+ { ownerId: "other", public: 1 },
+ { ownerId: "owner", public: 0 },
+ { ownerId: "owner", public: 1 },
+ ],
+ ],
+ ] as const) {
+ test(`legacy activation preserves both previous reads for ${name}`, async () => {
+ const fixture = videos.length
+ ? videos
+ .map(() => "SELECT 'video' AS id, ? AS ownerId, ? AS public")
+ .join(" UNION ALL ")
+ : "SELECT NULL AS id, NULL AS ownerId, NULL AS public WHERE FALSE";
+ const cte = `WITH videos AS (${fixture})`;
+ const values = videos.flatMap((video) => [video.ownerId, video.public]);
+ const [previousVideo] = await database.query<RowDataPacket[]>(
+ `${cte} SELECT id FROM videos WHERE ownerId = ? LIMIT 1`,
+ [...values, "owner"],
+ );
+ const [previousShared] = await database.query<RowDataPacket[]>(
+ `${cte} SELECT id FROM videos WHERE ownerId = ? AND public = 1 LIMIT 1`,
+ [...values, "owner"],
+ );
+ const [combined] = await database.query<RowDataPacket[]>(
+ `${cte} ${legacyActivationQuery}`,
+ [...values, "owner", "owner"],
+ );
+ expect(Boolean(combined[0].hasVideo)).toBe(previousVideo.length > 0);
+ expect(Boolean(combined[0].hasSharedVideo)).toBe(
+ previousShared.length > 0,
+ );
+ });
+ }
},
);
diff --git a/scripts/loops/sources.test.ts b/scripts/loops/sources.test.ts
new file mode 100644
index 000000000..7406b1f54
--- /dev/null
+++ b/scripts/loops/sources.test.ts
@@ -0,0 +1,154 @@
+import { afterAll, beforeAll, describe, expect, test } from "bun:test";
+import mysql, { type Connection, type RowDataPacket } from "mysql2/promise";
+import { profileUserQuery } from "../../packages/database/loops/sources";
+
+const url = process.env.LOOPS_ACTIVATION_READONLY_TEST_URL;
+
+describe.skipIf(!url)("profile source SQL preserves the previous reads", () => {
+ let database: Connection;
+ beforeAll(async () => {
+ if (!url) throw new Error("Missing read-only test connection");
+ database = await mysql.createConnection({
+ uri: url,
+ dateStrings: true,
+ timezone: "Z",
+ });
+ });
+ afterAll(async () => {
+ await database?.end();
+ });
+
+ const userQuery =
+ "SELECT id,email,name,lastName,emailVerified,stripeCustomerId,stripeSubscriptionStatus,thirdPartyStripeSubscriptionId,created_at,defaultOrgId,marketingOrigin FROM users WHERE id=?";
+
+ function fixtureRows(columns: string[], values: (string | null)[][]) {
+ return values.length
+ ? values
+ .map(
+ () =>
+ `SELECT ${columns
+ .map(
+ (column) =>
+ `CAST(? AS CHAR CHARACTER SET utf8mb4) COLLATE utf8mb4_0900_ai_ci AS ${column}`,
+ )
+ .join(",")}`,
+ )
+ .join(" UNION ALL ")
+ : `SELECT ${columns.map((column) => `NULL AS ${column}`).join(",")} WHERE FALSE`;
+ }
+
+ for (const [name, accounts, invites] of [
+ ["no account or invitation", [], []],
+ ["OAuth signup", [["owner", "google"]], []],
+ ["SSO signup", [["owner", "workos"]], []],
+ [
+ "multiple accounts",
+ [
+ ["owner", "google"],
+ ["owner", "workos"],
+ ],
+ [],
+ ],
+ ["another user's account", [["other", "workos"]], []],
+ ["case-sensitive provider", [["owner", "WORKOS"]], []],
+ ["provider with trailing whitespace", [["owner", "workos "]], []],
+ ["pending invitation", [], [["[email protected]", "pending"]]],
+ ["accepted invitation", [], [["[email protected]", "accepted"]]],
+ ["declined invitation", [], [["[email protected]", "declined"]]],
+ ["expired invitation", [], [["[email protected]", "expired"]]],
+ [
+ "case-sensitive pending decision",
+ [],
+ [["[email protected]", "PENDING"]],
+ ],
+ ["case-insensitive email lookup", [], [["[email protected]", "pending"]]],
+ ["another email's invitation", [], [["[email protected]", "pending"]]],
+ [
+ "mixed invitation states",
+ [["owner", "google"]],
+ [
+ ["[email protected]", "declined"],
+ ["[email protected]", "accepted"],
+ ["[email protected]", "pending"],
+ ["[email protected]", "pending"],
+ ],
+ ],
+ ] satisfies [string, string[][], string[][]][]) {
+ for (const verified of [false, true]) {
+ test(`${name}, ${verified ? "verified" : "unverified"} email`, async () => {
+ const user = [
+ "owner",
+ "Person",
+ null,
+ verified ? "2026-09-12 01:00:00" : null,
+ null,
+ "active",
+ null,
+ "2026-09-12 01:00:00",
+ "organization",
+ "independent",
+ ];
+ const cte = `WITH
+ users AS (${fixtureRows(
+ [
+ "id",
+ "email",
+ "name",
+ "lastName",
+ "emailVerified",
+ "stripeCustomerId",
+ "stripeSubscriptionStatus",
+ "thirdPartyStripeSubscriptionId",
+ "created_at",
+ "defaultOrgId",
+ "marketingOrigin",
+ ],
+ [user],
+ )}),
+ accounts AS (${fixtureRows(["userId", "provider"], accounts)}),
+ organization_invites AS (${fixtureRows(["invitedEmail", "status"], invites)})`;
+ const values = [...user, ...accounts.flat(), ...invites.flat()];
+ const [previousUsers] = await database.query<RowDataPacket[]>(
+ `${cte} ${userQuery}`,
+ [...values, "owner"],
+ );
+ const [previousAccounts] = await database.query<RowDataPacket[]>(
+ `${cte} SELECT provider FROM accounts WHERE userId=?`,
+ [...values, "owner"],
+ );
+ const [previousInvites] = await database.query<RowDataPacket[]>(
+ `${cte} SELECT status FROM organization_invites WHERE invitedEmail=? AND status IN ('pending','accepted')`,
+ [...values, "[email protected]"],
+ );
+ const [combined] = await database.query<RowDataPacket[]>(
+ `${cte} ${profileUserQuery}`,
+ [...values, "owner"],
+ );
+ const {
+ hasAccount,
+ hasWorkosAccount,
+ hasInvite,
+ hasPendingInvite,
+ ...combinedUser
+ } = combined[0];
+ expect(combinedUser).toEqual(previousUsers[0]);
+ expect(Boolean(combinedUser.emailVerified || hasAccount)).toBe(
+ Boolean(previousUsers[0].emailVerified || previousAccounts.length),
+ );
+ expect(Boolean(hasWorkosAccount)).toBe(
+ previousAccounts.some((account) => account.provider === "workos"),
+ );
+ expect(Boolean(hasInvite)).toBe(previousInvites.length > 0);
+ expect(Boolean(hasPendingInvite)).toBe(
+ previousInvites.some((invite) => invite.status === "pending"),
+ );
+ const [missing] = await database.query<RowDataPacket[]>(
+ `${cte} ${profileUserQuery}`,
+ [...values, "missing"],
+ );
+ expect(missing).toEqual([]);
+ });
+ }
+ }
+});