Branchwell

Lumen & Gesso / website · lumengesso.com / app / lib / studio-quota.ts

1import 'server-only';
2
3type Statement = {
4 bind(...values: (string | number)[]): Statement;
5 first<T>(): Promise<T | null>;
6};
7
8export type StudioDatabase = { prepare(sql: string): Statement };
9export type StudioLimits = { daily: number; perAccount: number; total: number };
10const providerKey = 'studio-provider-usage-v1';
11const authKey = 'studio-auth-usage-v1';
12
13function boundedInteger(value: string | undefined, maximum: number) {
14 if (!value || !/^[1-9][0-9]{0,6}$/.test(value)) return null;
15 const numeric = Number(value);
16 return numeric <= maximum ? numeric : null;
17}
18
19export function studioLimits(env: NodeJS.ProcessEnv = process.env): StudioLimits | null {
20 if (env.LUMEN_STUDIO_ENABLED !== 'true') return null;
21 const daily = boundedInteger(env.LUMEN_STUDIO_DAILY_CALLS, 1000);
22 const perAccount = boundedInteger(env.LUMEN_STUDIO_ACCOUNT_DAILY_CALLS, 30);
23 const total = boundedInteger(env.LUMEN_STUDIO_TOTAL_CALLS, 100_000);
24 if (daily === null || perAccount === null || total === null || perAccount > daily || daily > total) return null;
25 return { daily, perAccount, total };
26}
27
28export function studioAuthLimits(env: NodeJS.ProcessEnv = process.env): StudioLimits | null {
29 const daily = boundedInteger(env.LUMEN_STUDIO_AUTH_DAILY_SENDS, 1000);
30 const perAccount = boundedInteger(env.LUMEN_STUDIO_AUTH_IP_DAILY_SENDS, 20);
31 const total = boundedInteger(env.LUMEN_STUDIO_AUTH_TOTAL_SENDS, 100_000);
32 if (daily === null || perAccount === null || total === null || perAccount > daily || daily > total) return null;
33 return { daily, perAccount, total };
34}
35
36export async function studioStoreReady(db: StudioDatabase) {
37 // No schema changes: the integrations table already backs server-side data.
38 // This checks its availability without mutating any user or quota records.
39 await db.prepare('SELECT 1 AS ok FROM integrations WHERE key = ?').bind(providerKey).first();
40}
41
42/** Atomically reserve exactly one upstream call. Keep one durable total and
43 * the current UTC-day counters. On timeout/error the reservation is retained:
44 * an upstream call can be billable even if we never got back an image. */
45type QuotaScope = { kind: 'provider' } | { kind: 'auth'; email: string; salt: string };
46
47async function identifier(value: string) {
48 const hash = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(value));
49 return Array.from(new Uint8Array(hash), byte => byte.toString(16).padStart(2, '0')).join('');
50}
51
52export async function reserveStudioCall(
53 db: StudioDatabase, subjectId: string, limits: StudioLimits, scope: QuotaScope = {kind:'provider'},
54): Promise<boolean> {
55 const usageKey = scope.kind === 'provider' ? providerKey : authKey;
56 const user = await identifier(scope.kind === 'auth' ? scope.salt + '\0ip\0' + subjectId : subjectId);
57 const userPath = '$.users.' + user;
58 // Distinct keyed identifiers for IP and email prevent accidental matching.
59 // In provider scope the email predicates are disabled.
60 const target = scope.kind === 'auth' ? await identifier(scope.salt + '\0email\0' + scope.email) : 'none';
61 const targetPath = '$.targets.' + target;
62 const perEmail = scope.kind === 'auth' ? 2 : 0;
63 const row = await db.prepare(`
64 INSERT INTO integrations (key, value, updated_at)
65 VALUES (?1, json_object('day', date('now'), 'daily', 1, 'total', 1, 'users', json_object(?2, 1), 'targets', json_object(?7, 1)),
66 datetime('now'))
67 ON CONFLICT (key) DO UPDATE SET
68 value = CASE WHEN json_extract(integrations.value, '$.day') = date('now') THEN
69 json_set(integrations.value,
70 '$.daily', json_extract(integrations.value, '$.daily') + 1,
71 '$.total', json_extract(integrations.value, '$.total') + 1,
72 ?3, coalesce(json_extract(integrations.value, ?3), 0) + 1,
73 ?8, coalesce(json_extract(integrations.value, ?8), 0) + 1)
74 ELSE json_object('day', date('now'), 'daily', 1,
75 'total', json_extract(integrations.value, '$.total') + 1, 'users', json_object(?2, 1), 'targets', json_object(?7, 1)) END,
76 updated_at = datetime('now')
77 WHERE json_type(integrations.value, '$.total') = 'integer'
78 AND json_extract(integrations.value, '$.total') >= 0
79 AND json_extract(integrations.value, '$.total') < ?4
80 AND (json_extract(integrations.value, '$.day') <> date('now') OR (
81 json_type(integrations.value, '$.daily') = 'integer'
82 AND json_extract(integrations.value, '$.daily') < ?5
83 AND coalesce(json_extract(integrations.value, ?3), 0) < ?6
84 AND (?9 = 0 OR coalesce(json_extract(integrations.value, ?8), 0) < ?9)
85 ))
86 RETURNING key`).bind(usageKey, user, userPath, limits.total, limits.daily, limits.perAccount, target, targetPath, perEmail).first<{key: string}>();
87 return row?.key === usageKey;
88}