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

state.ts

77 lines6.2 KB

1import { Pool, type PoolClient } from 'pg';
2import { createRealtime, rawSql } from '@neon/realtime/server';
3import { ApiError, applyStateOperations, type StateRecord, type stateMutationSchema } from '@glow/contracts';
4import type { z } from 'zod';
5import { database } from './database.ts';
6import { appById, fingerprint } from './store.ts';
7import type { Grant } from './tokens.ts';
8import { config } from './config.ts';
9​
10export function stateAddress(grant: Grant, scope: 'player' | 'shared') {
11 return { player: grant.preview || scope === 'player' ? grant.playerId! : 'shared', scope: grant.preview ? `preview-${scope}` : scope };
13export function stateSignalQuery(grant: Grant, scope: 'player' | 'shared', key: string) {
14 const address = stateAddress(grant, scope);
15 return rawSql<{ revision: number }>(`SELECT s.revision FROM glow_state_signals s JOIN glow_apps a ON a.id=s.app_id
16 WHERE s.app_id=$1 AND s.scope=$2 AND s.player_id=$3 AND s.key=$4
17 AND NOT coalesce((a.data->>'disabled')::boolean,false)
18 AND ($5::boolean OR a.data->>'visibility'<>'private')`, [grant.appId, address.scope, address.player, key, !!grant.preview]);
20export async function stateSubscription(grant: Grant, scope: 'player' | 'shared', key: string) {
21 const app = await appById(grant.appId);
22 if (!grant.preview && app.visibility === 'private') throw new ApiError(403, 'This app is private');
23 if (!process.env.NEON_REALTIME_SECRET || !process.env.NEON_REALTIME_URL) throw new ApiError(503, 'Live updates are unavailable. Try again shortly.');
24 const realtime = createRealtime({ secret: process.env.NEON_REALTIME_SECRET, db: new URL(config().databaseUrl).pathname.slice(1) });
25 return { url: process.env.NEON_REALTIME_URL, expiresAt: grant.exp! * 1000, query: await realtime.seal({ query: stateSignalQuery(grant, scope, key) }) };
27async function signalState(client: Pick<PoolClient, 'query'>, grant: Grant, scope: 'player' | 'shared', key: string, revision: number) {
28 const address = stateAddress(grant, scope);
29 await client.query(`INSERT INTO glow_state_signals(app_id,scope,player_id,key,revision) VALUES($1,$2,$3,$4,$5)
30 ON CONFLICT(app_id,scope,player_id,key) DO UPDATE SET revision=greatest(glow_state_signals.revision,excluded.revision)`, [grant.appId, address.scope, address.player, key, revision]);
32async function signalBranchState(grant: Grant, input: z.infer<typeof stateMutationSchema>, revision: number) {
33 // A branch commit is authoritative even if its cross-database notification fails.
34 try { await signalState(database(), grant, input.scope, input.key, revision); }
35 catch { console.error('Shared state committed; Realtime signal needs reconciliation'); }
37​
38async function stateTarget(grant: Grant, scope: 'player' | 'shared') {
39 const app = await appById(grant.appId);
40 if (!grant.preview && app.visibility === 'private') throw new ApiError(403, 'This app is private');
41 if (grant.preview || scope === 'player') return { pool: database(), table: 'glow_state', receipts: 'glow_state_receipts', ...stateAddress(grant, scope), close: false };
42 const { rows } = await database().query('SELECT database_url FROM glow_environments WHERE app_id=$1', [grant.appId]);
43 if (!rows[0]) throw new ApiError(503, 'The shared backend is not ready');
44 return { pool: new Pool({ connectionString: rows[0].database_url, max: 1, connectionTimeoutMillis: 5000, statement_timeout: 2000 }), table: 'glow_shared_state', receipts: 'glow_shared_receipts', player: 'shared', scope, close: true };
46export async function readState(grant: Grant, scope: 'player' | 'shared', key: string): Promise<StateRecord> {
47 const target = await stateTarget(grant, scope);
48 try {
49 const { rows } = await target.pool.query(`SELECT value,revision FROM ${target.table} WHERE app_id=$1 AND scope=$2 AND player_id=$3 AND key=$4`, [grant.appId, target.scope, target.player, key]);
50 return { value: rows[0]?.value ?? {}, revision: rows[0]?.revision ?? 0, schemaVersion: 1 };
51 } finally { if (target.close) await target.pool.end(); }
53export async function mutateState(grant: Grant, input: z.infer<typeof stateMutationSchema>) {
54 const target = await stateTarget(grant, input.scope), client = await target.pool.connect();
55 const digest = fingerprint(input);
56 try {
57 await client.query('BEGIN');
58 await client.query('SELECT pg_advisory_xact_lock(hashtextextended($1,0))', [`${grant.appId}:${grant.playerId}:${input.operationId}`]);
59 const receipt = await client.query(`SELECT * FROM ${target.receipts} WHERE app_id=$1 AND player_id=$2 AND operation_id=$3`, [grant.appId, grant.playerId, input.operationId]);
60 if (receipt.rows[0]) {
61 if (receipt.rows[0].fingerprint !== digest) throw new ApiError(409, 'Operation ID already used');
62 await client.query('COMMIT');
63 if (target.close) await signalBranchState(grant, input, receipt.rows[0].result.revision);
64 return receipt.rows[0].result as StateRecord;
65 }
66 await client.query(`INSERT INTO ${target.table}(app_id,scope,player_id,key) VALUES($1,$2,$3,$4) ON CONFLICT DO NOTHING`, [grant.appId, target.scope, target.player, input.key]);
67 const { rows } = await client.query(`SELECT value,revision FROM ${target.table} WHERE app_id=$1 AND scope=$2 AND player_id=$3 AND key=$4 FOR UPDATE`, [grant.appId, target.scope, target.player, input.key]);
68 const next = applyStateOperations({ ...rows[0], schemaVersion: 1 }, input.expectedRevision, input.operations);
69 await client.query(`UPDATE ${target.table} SET value=$5,revision=$6 WHERE app_id=$1 AND scope=$2 AND player_id=$3 AND key=$4`, [grant.appId, target.scope, target.player, input.key, JSON.stringify(next.value), next.revision]);
70 await client.query(`INSERT INTO ${target.receipts}(app_id,player_id,operation_id,fingerprint,result,expires_at) VALUES($1,$2,$3,$4,$5,to_timestamp($6)+interval '1 day')`, [grant.appId, grant.playerId, input.operationId, digest, JSON.stringify(next), grant.exp]);
71 if (!target.close) await signalState(client, grant, input.scope, input.key, next.revision);
72 await client.query('COMMIT');
73 if (target.close) await signalBranchState(grant, input, next.revision);
74 return next;
75 } catch (error) { await client.query('ROLLBACK'); throw error; }
76 finally { client.release(); if (target.close) await target.pool.end(); }