Skip to content
Source
Sign inSign up
samwillis/neon-glow-demo
Open History to see the last commit

database.ts

152 lines8.6 KB

1import { Pool, type PoolClient } from 'pg';
2import { attachDatabasePool } from '@neon/functions';
3import { config } from './config.ts';
4​
5let singleton: Pool | undefined;
6const coordination = new Map<string, Pool>();
7export function coordinationDatabaseUrl(env: NodeJS.ProcessEnv): string {
8 const url = env.DATABASE_URL_UNPOOLED ?? env.DATABASE_URL;
9 if (!url || new URL(url).hostname.includes('-pooler')) throw new Error('Session locks require a direct DATABASE_URL_UNPOOLED connection');
10 return url;
12export function coordinationDatabase(purpose: 'provisioning' | 'sandbox-policy') {
13 let pool = coordination.get(purpose);
14 if (!pool) {
15 pool = new Pool({ connectionString: coordinationDatabaseUrl(process.env), max: 2, connectionTimeoutMillis: 10_000, statement_timeout: 10_000, allowExitOnIdle: true });
16 attachDatabasePool(pool);
17 coordination.set(purpose, pool);
18 }
19 return pool;
21export function database() {
22 if (!singleton) {
23 singleton = new Pool({ connectionString: config().databaseUrl, max: 5, connectionTimeoutMillis: 10_000, statement_timeout: 10_000 });
24 attachDatabasePool(singleton);
25 }
26 return singleton;
28export async function transaction<T>(operation: (client: PoolClient) => Promise<T>): Promise<{ data: T; txid: string }> {
29 const client = await database().connect();
30 try {
31 await client.query('BEGIN');
32 const data = await operation(client);
33 const { rows } = await client.query<{ txid: string }>('SELECT pg_current_xact_id()::text AS txid');
34 await client.query('COMMIT');
35 return { data, txid: rows[0].txid };
36 } catch (error) {
37 await client.query('ROLLBACK');
38 throw error;
39 } finally { client.release(); }
41​
42export const migration = `
43CREATE TABLE IF NOT EXISTS glow_apps (
44 id uuid PRIMARY KEY, owner_id text NOT NULL, data jsonb NOT NULL,
45 CHECK (id::text=data->>'id'), CHECK (owner_id=data->>'ownerId')
46);
47CREATE INDEX IF NOT EXISTS glow_apps_owner ON glow_apps(owner_id);
48CREATE TABLE IF NOT EXISTS glow_messages (
49 id uuid PRIMARY KEY, app_id uuid NOT NULL REFERENCES glow_apps(id),
50 sequence bigint GENERATED ALWAYS AS IDENTITY, data jsonb NOT NULL,
51 CHECK(id::text=data->>'id')
52);
53CREATE INDEX IF NOT EXISTS glow_messages_app ON glow_messages(app_id,sequence DESC);
54CREATE TABLE IF NOT EXISTS glow_runs (
55 id uuid PRIMARY KEY, app_id uuid NOT NULL REFERENCES glow_apps(id), data jsonb NOT NULL,
56 operation_id uuid UNIQUE NOT NULL, dispatch_id uuid, owner_id uuid, activation_hash text,
57 lease_until timestamptz, checkpoint_key text, model_calls integer NOT NULL DEFAULT 0,
58 CHECK(id::text=data->>'id')
59);
60CREATE INDEX IF NOT EXISTS glow_runs_app ON glow_runs(app_id);
61ALTER TABLE glow_runs ADD COLUMN IF NOT EXISTS model_calls_total integer NOT NULL DEFAULT 0;
62UPDATE glow_runs SET model_calls_total=greatest(model_calls_total,model_calls);
63CREATE UNIQUE INDEX IF NOT EXISTS glow_one_active_run ON glow_runs(app_id)
64 WHERE data->>'status' IN ('running','stopping');
65CREATE TABLE IF NOT EXISTS glow_versions (
66 id uuid PRIMARY KEY, app_id uuid NOT NULL REFERENCES glow_apps(id), data jsonb NOT NULL,
67 object_key text NOT NULL, CHECK(id::text=data->>'id')
68);
69CREATE INDEX IF NOT EXISTS glow_versions_app ON glow_versions(app_id);
70CREATE TABLE IF NOT EXISTS glow_environments (
71 app_id uuid PRIMARY KEY REFERENCES glow_apps(id), project_id text NOT NULL,
72 branch_id text NOT NULL, database_url text NOT NULL, worker_url text,
73 UNIQUE(project_id,branch_id)
74);
75CREATE TABLE IF NOT EXISTS glow_operations (
76 id uuid PRIMARY KEY, owner_id text NOT NULL, kind text NOT NULL, result jsonb NOT NULL
77);
78CREATE TABLE IF NOT EXISTS glow_auth_identities (
79 neon_user_id text PRIMARY KEY, user_id text UNIQUE NOT NULL REFERENCES "user"(id)
80);
81CREATE TABLE IF NOT EXISTS glow_comments (
82 id uuid PRIMARY KEY, app_id uuid NOT NULL REFERENCES glow_apps(id) ON DELETE CASCADE,
83 author_id text NOT NULL REFERENCES "user"(id), operation_id uuid NOT NULL,
84 content text NOT NULL, created_at timestamptz NOT NULL DEFAULT date_trunc('milliseconds',now()), deleted_at timestamptz,
85 UNIQUE(author_id,operation_id), CHECK(length(content)<=2000 AND (deleted_at IS NOT NULL OR length(btrim(content))>0))
86);
87CREATE INDEX IF NOT EXISTS glow_comments_app ON glow_comments(app_id,created_at DESC,id DESC) WHERE deleted_at IS NULL;
88CREATE INDEX IF NOT EXISTS glow_comments_author ON glow_comments(author_id,created_at DESC);
89CREATE INDEX IF NOT EXISTS glow_apps_parent ON glow_apps((data->>'parentAppId'),(data->>'createdAt') DESC,id DESC);
90CREATE TABLE IF NOT EXISTS glow_provisioning (
91 app_id uuid PRIMARY KEY REFERENCES glow_apps(id), phase text NOT NULL, result jsonb,
92 updated_at timestamptz NOT NULL DEFAULT now()
93);
94CREATE TABLE IF NOT EXISTS glow_state (
95 app_id uuid NOT NULL, scope text NOT NULL, player_id text NOT NULL, key text NOT NULL,
96 value jsonb NOT NULL DEFAULT '{}', revision integer NOT NULL DEFAULT 0,
97 PRIMARY KEY(app_id,scope,player_id,key)
98);
99CREATE TABLE IF NOT EXISTS glow_state_receipts (
100 app_id uuid NOT NULL, player_id text NOT NULL, operation_id uuid NOT NULL,
101 fingerprint text NOT NULL, result jsonb NOT NULL, expires_at timestamptz NOT NULL,
102 PRIMARY KEY(app_id,player_id,operation_id)
103);
104CREATE TABLE IF NOT EXISTS glow_state_signals (
105 app_id uuid NOT NULL REFERENCES glow_apps(id) ON DELETE CASCADE,
106 scope text NOT NULL, player_id text NOT NULL, key text NOT NULL, revision integer NOT NULL,
107 PRIMARY KEY(app_id,scope,player_id,key)
108);
109CREATE TABLE IF NOT EXISTS glow_reports (
110 id uuid PRIMARY KEY, app_id uuid NOT NULL REFERENCES glow_apps(id),
111 reporter_id text NOT NULL, reason text NOT NULL, created_at timestamptz NOT NULL DEFAULT now()
112);
113CREATE TABLE IF NOT EXISTS glow_agent_releases(version text PRIMARY KEY,object_key text NOT NULL,digest text NOT NULL);
114CREATE TABLE IF NOT EXISTS glow_sandbox_revocations(digest text PRIMARY KEY,scopes jsonb NOT NULL,verified_at timestamptz NOT NULL DEFAULT now());
115CREATE TABLE IF NOT EXISTS glow_sandbox_policies(token_id text PRIMARY KEY,scopes jsonb NOT NULL,pending_secret jsonb,verified_at timestamptz);
116CREATE TABLE IF NOT EXISTS glow_capture_jobs (
117 id uuid PRIMARY KEY, kind text NOT NULL CHECK (kind IN ('agent','media')),
118 app_id uuid NOT NULL REFERENCES glow_apps(id) ON DELETE CASCADE, version_id uuid,
119 status text NOT NULL DEFAULT 'queued' CHECK (status IN ('queued','claimed','done','failed')),
120 request_key text NOT NULL, request jsonb NOT NULL DEFAULT '{}', result jsonb, attempts integer NOT NULL DEFAULT 0,
121 worker_id text, lease_until timestamptz, created_at timestamptz NOT NULL DEFAULT now(), finished_at timestamptz
122);
123CREATE INDEX IF NOT EXISTS glow_capture_jobs_queue ON glow_capture_jobs(kind DESC,created_at) WHERE status IN ('queued','claimed');
124CREATE UNIQUE INDEX IF NOT EXISTS glow_capture_jobs_media ON glow_capture_jobs(version_id) WHERE kind='media';
125CREATE TABLE IF NOT EXISTS glow_capture_workers (id text PRIMARY KEY, seen_at timestamptz NOT NULL DEFAULT now(), info jsonb NOT NULL DEFAULT '{}');
126CREATE TABLE IF NOT EXISTS glow_likes (
127 app_id uuid NOT NULL REFERENCES glow_apps(id) ON DELETE CASCADE, user_id text NOT NULL REFERENCES "user"(id),
128 created_at timestamptz NOT NULL DEFAULT now(), PRIMARY KEY(app_id,user_id)
129);
130CREATE INDEX IF NOT EXISTS glow_likes_user ON glow_likes(user_id,created_at DESC);
131CREATE TABLE IF NOT EXISTS glow_follows (
132 follower_id text NOT NULL REFERENCES "user"(id), followee_id text NOT NULL REFERENCES "user"(id),
133 created_at timestamptz NOT NULL DEFAULT now(), PRIMARY KEY(follower_id,followee_id), CHECK (follower_id<>followee_id)
134);
135CREATE INDEX IF NOT EXISTS glow_follows_followee ON glow_follows(followee_id,created_at DESC);
136CREATE TABLE IF NOT EXISTS glow_plays (
137 app_id uuid NOT NULL REFERENCES glow_apps(id) ON DELETE CASCADE, player_id text NOT NULL, day date NOT NULL DEFAULT current_date,
138 PRIMARY KEY(app_id,player_id,day)
139);
140CREATE TABLE IF NOT EXISTS glow_inbox_reads (user_id text PRIMARY KEY REFERENCES "user"(id), seen_at timestamptz NOT NULL DEFAULT now());
141CREATE TABLE IF NOT EXISTS glow_challenges (
142 id uuid PRIMARY KEY, title text NOT NULL, description text NOT NULL, seed_app_id uuid REFERENCES glow_apps(id) ON DELETE SET NULL,
143 starts_at timestamptz NOT NULL DEFAULT now(), ends_at timestamptz NOT NULL
144);
145CREATE TABLE IF NOT EXISTS glow_profiles (
146 user_id text PRIMARY KEY REFERENCES "user"(id), bio text CHECK (length(bio)<=160), avatar text,
147 pinned_app_id uuid REFERENCES glow_apps(id) ON DELETE SET NULL, updated_at timestamptz NOT NULL DEFAULT now()
148);
149ALTER TABLE glow_profiles ADD COLUMN IF NOT EXISTS handle text, ADD COLUMN IF NOT EXISTS display_name text;
150CREATE UNIQUE INDEX IF NOT EXISTS glow_profiles_handle ON glow_profiles(lower(handle));
151CREATE INDEX IF NOT EXISTS glow_apps_public ON glow_apps((data->>'updatedAt') DESC) WHERE data->>'visibility'='public';
152`;