|
| 1 | +import pg from 'pg' |
| 2 | +import type { PoolConfig } from 'pg' |
| 3 | +import { DsqlSigner } from '@aws-sdk/dsql-signer' |
| 4 | +import type { Destination, DestinationInput, LogMessage } from '@stripe/sync-protocol' |
| 5 | +import { sql, upsert } from '@stripe/sync-util-postgres' |
| 6 | +import defaultSpec from './spec.js' |
| 7 | +import type { Config } from './spec.js' |
| 8 | + |
| 9 | +export { configSchema, type Config } from './spec.js' |
| 10 | +export { default as pg } from 'pg' |
| 11 | + |
| 12 | +function logMsg(message: string, level: LogMessage['log']['level'] = 'info'): LogMessage { |
| 13 | + return { type: 'log', log: { level, message } } |
| 14 | +} |
| 15 | + |
| 16 | +/** Generate a fresh DSQL IAM auth token. */ |
| 17 | +async function generateToken(endpoint: string, region: string): Promise<string> { |
| 18 | + const signer = new DsqlSigner({ hostname: endpoint, region }) |
| 19 | + return signer.getDbConnectAdminAuthToken() |
| 20 | +} |
| 21 | + |
| 22 | +/** Build a pg PoolConfig for DSQL with rotating IAM auth tokens. */ |
| 23 | +export async function buildPoolConfig(config: Config): Promise<PoolConfig> { |
| 24 | + const token = await generateToken(config.endpoint, config.region) |
| 25 | + return { |
| 26 | + host: config.endpoint, |
| 27 | + port: 5432, |
| 28 | + database: 'postgres', |
| 29 | + user: 'admin', |
| 30 | + password: token, |
| 31 | + ssl: true, |
| 32 | + } |
| 33 | +} |
| 34 | + |
| 35 | +function createPool(poolConfig: PoolConfig): pg.Pool { |
| 36 | + const pool = new pg.Pool(poolConfig) |
| 37 | + pool.on('error', (err) => { |
| 38 | + console.error('DSQL destination pool error:', err) |
| 39 | + }) |
| 40 | + return pool |
| 41 | +} |
| 42 | + |
| 43 | +/** |
| 44 | + * Build a CREATE TABLE IF NOT EXISTS statement for DSQL. |
| 45 | + * |
| 46 | + * DSQL does not support: triggers, generated columns, PL/pgSQL DO blocks, jsonb. |
| 47 | + * We store _raw_data as text (JSON-serialized) with id as primary key. |
| 48 | + */ |
| 49 | +function buildCreateTableSQL(schema: string, tableName: string): string { |
| 50 | + const q = (s: string) => `"${s.replace(/"/g, '""')}"` |
| 51 | + return sql` |
| 52 | + CREATE TABLE IF NOT EXISTS ${q(schema)}.${q(tableName)} ( |
| 53 | + "id" text NOT NULL, |
| 54 | + "_raw_data" text NOT NULL, |
| 55 | + "_last_synced_at" timestamptz, |
| 56 | + "_updated_at" timestamptz NOT NULL DEFAULT now(), |
| 57 | + PRIMARY KEY ("id") |
| 58 | + ) |
| 59 | + ` |
| 60 | +} |
| 61 | + |
| 62 | +/** |
| 63 | + * Upsert records into a DSQL table. |
| 64 | + * Explicitly sets _updated_at = now() since DSQL has no trigger support. |
| 65 | + */ |
| 66 | +async function upsertMany( |
| 67 | + pool: pg.Pool, |
| 68 | + schema: string, |
| 69 | + table: string, |
| 70 | + // eslint-disable-next-line @typescript-eslint/no-explicit-any |
| 71 | + entries: Record<string, any>[] |
| 72 | +): Promise<void> { |
| 73 | + if (!entries.length) return |
| 74 | + await upsert( |
| 75 | + pool, |
| 76 | + entries.map((e) => ({ |
| 77 | + id: String(e.id ?? ''), |
| 78 | + _raw_data: JSON.stringify(e), |
| 79 | + _updated_at: new Date().toISOString(), |
| 80 | + })), |
| 81 | + { |
| 82 | + schema, |
| 83 | + table, |
| 84 | + keyColumns: ['id'], |
| 85 | + noDiffColumns: ['_updated_at'], |
| 86 | + } |
| 87 | + ) |
| 88 | +} |
| 89 | + |
| 90 | +/** Check if an error looks transient. */ |
| 91 | +function isTransient(err: unknown): boolean { |
| 92 | + if (!(err instanceof Error)) return false |
| 93 | + const msg = err.message.toLowerCase() |
| 94 | + return msg.includes('econnrefused') || msg.includes('timeout') || msg.includes('connection') |
| 95 | +} |
| 96 | + |
| 97 | +const destination = { |
| 98 | + async *spec() { |
| 99 | + yield { type: 'spec' as const, spec: defaultSpec } |
| 100 | + }, |
| 101 | + |
| 102 | + async *check({ config }) { |
| 103 | + const pool = createPool(await buildPoolConfig(config)) |
| 104 | + try { |
| 105 | + await pool.query('SELECT 1') |
| 106 | + yield { |
| 107 | + type: 'connection_status' as const, |
| 108 | + connection_status: { status: 'succeeded' as const }, |
| 109 | + } |
| 110 | + } catch (err) { |
| 111 | + yield { |
| 112 | + type: 'connection_status' as const, |
| 113 | + connection_status: { |
| 114 | + status: 'failed' as const, |
| 115 | + message: err instanceof Error ? err.message : String(err), |
| 116 | + }, |
| 117 | + } |
| 118 | + } finally { |
| 119 | + await pool.end() |
| 120 | + } |
| 121 | + }, |
| 122 | + |
| 123 | + async *setup({ config, catalog }) { |
| 124 | + const pool = createPool(await buildPoolConfig(config)) |
| 125 | + try { |
| 126 | + yield logMsg(`Creating schema "${config.schema}" (${catalog.streams.length} streams)`) |
| 127 | + await pool.query(sql`CREATE SCHEMA IF NOT EXISTS "${config.schema}"`) |
| 128 | + // DSQL requires sequential DDL — concurrent CREATE TABLE causes OC001 conflicts |
| 129 | + for (const cs of catalog.streams) { |
| 130 | + await pool.query(buildCreateTableSQL(config.schema, cs.stream.name)) |
| 131 | + } |
| 132 | + } finally { |
| 133 | + await pool.end() |
| 134 | + } |
| 135 | + }, |
| 136 | + |
| 137 | + async *teardown({ config }) { |
| 138 | + const PROTECTED = new Set(['public', 'information_schema', 'pg_catalog', 'pg_toast']) |
| 139 | + if (PROTECTED.has(config.schema)) { |
| 140 | + throw new Error(`Refusing to drop protected schema "${config.schema}"`) |
| 141 | + } |
| 142 | + const pool = createPool(await buildPoolConfig(config)) |
| 143 | + try { |
| 144 | + await pool.query(sql`DROP SCHEMA IF EXISTS "${config.schema}" CASCADE`) |
| 145 | + } finally { |
| 146 | + await pool.end() |
| 147 | + } |
| 148 | + }, |
| 149 | + |
| 150 | + async *write({ config }, $stdin) { |
| 151 | + const pool = createPool(await buildPoolConfig(config)) |
| 152 | + const batchSize = config.batch_size |
| 153 | + // eslint-disable-next-line @typescript-eslint/no-explicit-any |
| 154 | + const streamBuffers = new Map<string, Record<string, any>[]>() |
| 155 | + |
| 156 | + const flushStream = async (streamName: string) => { |
| 157 | + const buffer = streamBuffers.get(streamName) |
| 158 | + if (!buffer || buffer.length === 0) return |
| 159 | + await upsertMany(pool, config.schema, streamName, buffer) |
| 160 | + streamBuffers.set(streamName, []) |
| 161 | + } |
| 162 | + |
| 163 | + const flushAll = async () => { |
| 164 | + for (const streamName of streamBuffers.keys()) { |
| 165 | + await flushStream(streamName) |
| 166 | + } |
| 167 | + } |
| 168 | + |
| 169 | + try { |
| 170 | + for await (const msg of $stdin as AsyncIterable<DestinationInput>) { |
| 171 | + if (msg.type === 'record') { |
| 172 | + const { stream, data } = msg.record |
| 173 | + if (!streamBuffers.has(stream)) streamBuffers.set(stream, []) |
| 174 | + const buffer = streamBuffers.get(stream)! |
| 175 | + buffer.push(data as Record<string, unknown>) |
| 176 | + if (buffer.length >= batchSize) await flushStream(stream) |
| 177 | + } else if (msg.type === 'source_state') { |
| 178 | + if (msg.source_state.state_type !== 'global') { |
| 179 | + await flushStream(msg.source_state.stream) |
| 180 | + } |
| 181 | + yield msg |
| 182 | + } |
| 183 | + } |
| 184 | + await flushAll() |
| 185 | + } catch (err: unknown) { |
| 186 | + try { |
| 187 | + await flushAll() |
| 188 | + } catch { |
| 189 | + // ignore flush errors during error handling |
| 190 | + } |
| 191 | + yield { |
| 192 | + type: 'trace' as const, |
| 193 | + trace: { |
| 194 | + trace_type: 'error' as const, |
| 195 | + error: { |
| 196 | + failure_type: isTransient(err) |
| 197 | + ? ('transient_error' as const) |
| 198 | + : ('system_error' as const), |
| 199 | + message: err instanceof Error ? err.message : String(err), |
| 200 | + stack_trace: err instanceof Error ? err.stack : undefined, |
| 201 | + }, |
| 202 | + }, |
| 203 | + } |
| 204 | + } finally { |
| 205 | + await pool.end() |
| 206 | + } |
| 207 | + |
| 208 | + yield logMsg(`DSQL destination: wrote to schema "${config.schema}"`) |
| 209 | + }, |
| 210 | +} satisfies Destination<Config> |
| 211 | + |
| 212 | +export default destination |
0 commit comments