| 25 | |
| 26 | @Injectable() |
| 27 | export class TraceRepository implements OnModuleDestroy { |
| 28 | private pool: Pool; |
| 29 | |
| 30 | constructor( |
| 31 | @Inject(DRIZZLE_TOKEN) |
| 32 | private readonly db: NodePgDatabase, |
| 33 | ) { |
| 34 | // Create a separate pool for LISTEN/NOTIFY to avoid conflicts |
| 35 | this.pool = new Pool({ |
| 36 | connectionString: process.env.DATABASE_URL, |
| 37 | }); |
| 38 | } |
| 39 | |
| 40 | async onModuleDestroy() { |
| 41 | await this.pool.end(); |
| 42 | } |
| 43 | |
| 44 | /** |
| 45 | * Subscribe to real-time trace events for a specific run ID using Postgres LISTEN/NOTIFY |
| 46 | */ |
| 47 | async subscribeToRun( |
| 48 | runId: string, |
| 49 | callback: (payload: string) => void, |
| 50 | ): Promise<() => Promise<void>> { |
| 51 | const client = await this.pool.connect(); |
| 52 | const channel = `trace_events_${runId}`; |
| 53 | |
| 54 | try { |
| 55 | await client.query(`LISTEN "${channel}"`); |
| 56 | |
| 57 | client.on('notification', (msg) => { |
| 58 | if (msg.channel === channel && msg.payload) { |
| 59 | callback(msg.payload); |
| 60 | } |
| 61 | }); |
| 62 | |
| 63 | // Return unsubscribe function |
| 64 | return async () => { |
| 65 | try { |
| 66 | await client.query(`UNLISTEN "${channel}"`); |
| 67 | } finally { |
| 68 | client.release(); |
| 69 | } |
| 70 | }; |
| 71 | } catch (error) { |
| 72 | client.release(); |
| 73 | throw error; |
| 74 | } |
| 75 | } |
| 76 | |
| 77 | /** |
| 78 | * Notify subscribers of new trace events |
| 79 | */ |
| 80 | async notifyRun(runId: string, payload: string): Promise<void> { |
| 81 | const channel = `trace_events_${runId}`; |
| 82 | await this.pool.query('SELECT pg_notify($1, $2)', [channel, payload]); |
| 83 | } |
| 84 |
nothing calls this directly
no outgoing calls
no test coverage detected