|
| 1 | +/** |
| 2 | + * Runs zbugs' backend for the Swift app, in development and in the |
| 3 | + * end-to-end tests: a fresh Postgres database with zbugs' migrations and |
| 4 | + * seed data, zbugs' API server (apps/zbugs/api), and zero-cache, all from |
| 5 | + * this repository's sources. |
| 6 | + * |
| 7 | + * node apps/zbugs-swift/server/server.ts |
| 8 | + * |
| 9 | + * Needs Node 24 and `psql` on the PATH, and Postgres with |
| 10 | + * `wal_level = logical`. Prints a token for the seeded crew user, then |
| 11 | + * `ready <zero-cache URL> <API URL>` once both serve, and stops everything |
| 12 | + * on SIGINT or SIGTERM. |
| 13 | + * |
| 14 | + * Environment: |
| 15 | + * ZBUGS_PG admin connection URL |
| 16 | + * (default postgresql://postgres@127.0.0.1:5432/postgres) |
| 17 | + * ZBUGS_DB database to (re)create (default zbugs_swift) |
| 18 | + * ZBUGS_SEED seed data directory in apps/zbugs/db/seed-data |
| 19 | + * (default github) |
| 20 | + * ZBUGS_HOST interface to listen on (default 127.0.0.1) |
| 21 | + * ZBUGS_PORT zero-cache port (default 4848) |
| 22 | + * ZBUGS_API_PORT API server port (default 5173) |
| 23 | + * ZBUGS_DIR working directory for the replica (default a temp dir) |
| 24 | + */ |
| 25 | +import {execFileSync, spawn} from 'node:child_process'; |
| 26 | +import {mkdtempSync, readdirSync} from 'node:fs'; |
| 27 | +import {registerHooks} from 'node:module'; |
| 28 | +import {tmpdir} from 'node:os'; |
| 29 | +import {join} from 'node:path'; |
| 30 | +import {fileURLToPath, pathToFileURL} from 'node:url'; |
| 31 | +import {createJwkPair} from '../../../packages/zero-cache/src/auth/jwt.ts'; |
| 32 | + |
| 33 | +const env = process.env; |
| 34 | +const adminURL = |
| 35 | + env['ZBUGS_PG'] ?? 'postgresql://postgres@127.0.0.1:5432/postgres'; |
| 36 | +const dbName = env['ZBUGS_DB'] ?? 'zbugs_swift'; |
| 37 | +const host = env['ZBUGS_HOST'] ?? '127.0.0.1'; |
| 38 | +const port = Number(env['ZBUGS_PORT'] ?? 4848); |
| 39 | +const apiPort = Number(env['ZBUGS_API_PORT'] ?? 5173); |
| 40 | +const workDir = env['ZBUGS_DIR'] ?? mkdtempSync(join(tmpdir(), 'zbugs-swift-')); |
| 41 | + |
| 42 | +const here = (path: string) => fileURLToPath(new URL(path, import.meta.url)); |
| 43 | +const zbugs = here('../../zbugs/'); |
| 44 | +const upstreamURL = (() => { |
| 45 | + const url = new URL(adminURL); |
| 46 | + url.pathname = `/${dbName}`; |
| 47 | + return url.toString(); |
| 48 | +})(); |
| 49 | + |
| 50 | +function psql(url: string, ...args: string[]) { |
| 51 | + execFileSync('psql', [url, '-v', 'ON_ERROR_STOP=1', '-q', ...args], { |
| 52 | + stdio: ['ignore', 'ignore', 'inherit'], |
| 53 | + }); |
| 54 | +} |
| 55 | + |
| 56 | +// The database: zbugs' migrations, then its seed script. |
| 57 | +psql(adminURL, '-c', `DROP DATABASE IF EXISTS ${dbName} WITH (FORCE)`); |
| 58 | +psql(adminURL, '-c', `CREATE DATABASE ${dbName}`); |
| 59 | +const migrations = join(zbugs, 'db/migrations'); |
| 60 | +for (const file of readdirSync(migrations) |
| 61 | + .filter(f => f.endsWith('.sql')) |
| 62 | + .sort()) { |
| 63 | + // In a transaction each, as drizzle-kit applies them. |
| 64 | + psql(upstreamURL, '--single-transaction', '-f', join(migrations, file)); |
| 65 | +} |
| 66 | +execFileSync(process.execPath, [join(zbugs, 'scripts/seed.ts')], { |
| 67 | + cwd: zbugs, |
| 68 | + stdio: ['ignore', 'ignore', 'inherit'], |
| 69 | + env: { |
| 70 | + ...env, |
| 71 | + ['ZERO_UPSTREAM_DB']: upstreamURL, |
| 72 | + ['ZERO_SEED_DATA_DIR']: join( |
| 73 | + zbugs, |
| 74 | + 'db/seed-data', |
| 75 | + env['ZBUGS_SEED'] ?? 'github', |
| 76 | + ), |
| 77 | + }, |
| 78 | +}); |
| 79 | +const crewID = execFileSync( |
| 80 | + 'psql', |
| 81 | + [ |
| 82 | + upstreamURL, |
| 83 | + '-tAc', |
| 84 | + `SELECT id FROM "user" WHERE role = 'crew' ORDER BY login LIMIT 1`, |
| 85 | + ], |
| 86 | + {encoding: 'utf8'}, |
| 87 | +).trim(); |
| 88 | + |
| 89 | +// The API server, as `pnpm dev` runs it in apps/zbugs, with keys of its own. |
| 90 | +const {privateJwk, publicJwk} = await createJwkPair(); |
| 91 | +env['ZERO_UPSTREAM_DB'] = upstreamURL; |
| 92 | +env['PRIVATE_JWK'] = JSON.stringify(privateJwk); |
| 93 | +env['VITE_PUBLIC_JWK'] = JSON.stringify(publicJwk); |
| 94 | +const zeroSources: Record<string, string> = { |
| 95 | + '@rocicorp/zero': 'zero.ts', |
| 96 | + '@rocicorp/zero/server': 'server.ts', |
| 97 | + '@rocicorp/zero/server/adapters/postgresjs': 'adapters/postgresjs.ts', |
| 98 | +}; |
| 99 | +// What Vite does for apps/zbugs: `@rocicorp/zero` is its sources, and a |
| 100 | +// relative `.js` import may name a `.ts` file. |
| 101 | +registerHooks({ |
| 102 | + resolve(specifier, context, next) { |
| 103 | + const source = zeroSources[specifier]; |
| 104 | + if (source) { |
| 105 | + return { |
| 106 | + url: pathToFileURL(here(`../../../packages/zero/src/${source}`)).href, |
| 107 | + shortCircuit: true, |
| 108 | + }; |
| 109 | + } |
| 110 | + try { |
| 111 | + return next(specifier, context); |
| 112 | + } catch (e) { |
| 113 | + if (specifier.startsWith('.') && specifier.endsWith('.js')) { |
| 114 | + return next(specifier.slice(0, -3) + '.ts', context); |
| 115 | + } |
| 116 | + throw e; |
| 117 | + } |
| 118 | + }, |
| 119 | +}); |
| 120 | +const {fastify} = (await import('../../zbugs/api/index.ts')) as { |
| 121 | + fastify: { |
| 122 | + listen(o: {port: number; host: string}): Promise<string>; |
| 123 | + close(): Promise<void>; |
| 124 | + }; |
| 125 | +}; |
| 126 | +await fastify.listen({port: apiPort, host}); |
| 127 | + |
| 128 | +const zeroCache = spawn( |
| 129 | + process.execPath, |
| 130 | + [here('../../../packages/zero-cache/src/server/runner/main.ts')], |
| 131 | + { |
| 132 | + stdio: ['ignore', 'inherit', 'inherit'], |
| 133 | + env: { |
| 134 | + ...env, |
| 135 | + ['NODE_ENV']: 'development', |
| 136 | + ['ZERO_UPSTREAM_DB']: upstreamURL, |
| 137 | + ['ZERO_REPLICA_FILE']: join(workDir, 'replica.db'), |
| 138 | + ['ZERO_PORT']: String(port), |
| 139 | + ['ZERO_QUERY_URL']: `http://${host}:${apiPort}/api/query`, |
| 140 | + ['ZERO_MUTATE_URL']: `http://${host}:${apiPort}/api/mutate`, |
| 141 | + ['ZERO_NUM_SYNC_WORKERS']: '1', |
| 142 | + ['ZERO_LOG_LEVEL']: env['ZERO_LOG_LEVEL'] ?? 'info', |
| 143 | + }, |
| 144 | + }, |
| 145 | +); |
| 146 | + |
| 147 | +function stop(code: number) { |
| 148 | + zeroCache.kill('SIGTERM'); |
| 149 | + void fastify.close(); |
| 150 | + process.exit(code); |
| 151 | +} |
| 152 | +zeroCache.on('exit', code => { |
| 153 | + process.stderr.write(`zero-cache exited with ${code}\n`); |
| 154 | + stop(1); |
| 155 | +}); |
| 156 | +process.on('SIGINT', () => stop(0)); |
| 157 | +process.on('SIGTERM', () => stop(0)); |
| 158 | + |
| 159 | +for (let i = 0; ; i++) { |
| 160 | + try { |
| 161 | + const res = await fetch(`http://${host}:${port}/`); |
| 162 | + if (res.ok) { |
| 163 | + break; |
| 164 | + } |
| 165 | + } catch { |
| 166 | + // Not listening yet. |
| 167 | + } |
| 168 | + if (i > 600) { |
| 169 | + process.stderr.write('zero-cache did not start\n'); |
| 170 | + stop(1); |
| 171 | + } |
| 172 | + await new Promise(resolve => setTimeout(resolve, 100)); |
| 173 | +} |
| 174 | + |
| 175 | +// The token a client logs in with: the crew user's, as `pnpm dev-token` |
| 176 | +// mints it. |
| 177 | +const token = execFileSync( |
| 178 | + process.execPath, |
| 179 | + [join(zbugs, 'scripts/dev-token.ts'), crewID, 'crew'], |
| 180 | + { |
| 181 | + cwd: zbugs, |
| 182 | + encoding: 'utf8', |
| 183 | + }, |
| 184 | +).trim(); |
| 185 | +process.stdout.write(`token ${token}\n`); |
| 186 | +process.stdout.write(`ready ws://${host}:${port} http://${host}:${apiPort}\n`); |
0 commit comments