|
| 1 | +import { createCodeTransformer } from '@apm-js-collab/code-transformer-bundler-plugins/core'; |
| 2 | +import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; |
| 3 | +import { createRequire } from 'node:module'; |
| 4 | +import { tmpdir } from 'node:os'; |
| 5 | +import { dirname, join } from 'node:path'; |
| 6 | +import { pathToFileURL } from 'node:url'; |
| 7 | +import { tracingChannel } from 'node:diagnostics_channel'; |
| 8 | +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; |
| 9 | +import { neonChannels, neonConfig } from '../../src/orchestrion/config/neon'; |
| 10 | + |
| 11 | +// The selectors key on internals of Neon's minified bundles, so this runs the bundler plugins' |
| 12 | +// code transformer over the real published files and executes the result: a release that |
| 13 | +// reshapes the bundle fails here rather than silently dropping spans. |
| 14 | +const nodeRequire = createRequire(import.meta.url); |
| 15 | +const packageDir = dirname(nodeRequire.resolve('@neondatabase/serverless')); |
| 16 | + |
| 17 | +interface NeonModule { |
| 18 | + neon: (connectionString: string) => { |
| 19 | + (strings: TemplateStringsArray, ...values: unknown[]): Promise<unknown>; |
| 20 | + query: (text: string, params?: unknown[]) => Promise<unknown>; |
| 21 | + transaction: (queries: Promise<unknown>[]) => Promise<unknown>; |
| 22 | + }; |
| 23 | + neonConfig: { fetchFunction: unknown }; |
| 24 | + Client: new (connectionString: string) => { |
| 25 | + query: (text: string) => Promise<unknown>; |
| 26 | + end: () => Promise<void>; |
| 27 | + }; |
| 28 | +} |
| 29 | + |
| 30 | +function neonResponse(body: unknown): () => Promise<Response> { |
| 31 | + return () => Promise.resolve(new Response(JSON.stringify(body), { status: 200 })); |
| 32 | +} |
| 33 | + |
| 34 | +const EMPTY_RESULT = { rows: [], fields: [], command: 'SELECT', rowCount: 0 }; |
| 35 | + |
| 36 | +// Every wrapper opens with a `hasSubscribers` guard on its channel, one per instrumented site. |
| 37 | +function countWrappedSites(code: string, channelVariable: string): number { |
| 38 | + return code.split(`tr_ch_apm_hasSubscribers(${channelVariable})`).length - 1; |
| 39 | +} |
| 40 | + |
| 41 | +describe('neon orchestrion config on the published bundles', () => { |
| 42 | + let outDir: string; |
| 43 | + const events: string[] = []; |
| 44 | + |
| 45 | + beforeAll(() => { |
| 46 | + outDir = mkdtempSync(join(tmpdir(), 'neon-bundle-')); |
| 47 | + for (const name of ['query', 'http-query', 'resolve-connection']) { |
| 48 | + tracingChannel(`orchestrion:@neondatabase/serverless:${name}`).subscribe({ |
| 49 | + start: data => { |
| 50 | + const ctx = data as { arguments: unknown[]; self?: { connectionParameters?: { database?: string } } }; |
| 51 | + events.push(`${name}:start:${ctx.self?.connectionParameters?.database ?? JSON.stringify(ctx.arguments[0])}`); |
| 52 | + }, |
| 53 | + end: () => {}, |
| 54 | + asyncStart: () => {}, |
| 55 | + asyncEnd: data => { |
| 56 | + const ctx = data as { result?: { resolvedURL?: URL } }; |
| 57 | + events.push(`${name}:asyncEnd:${ctx.result?.resolvedURL?.hostname ?? ''}`); |
| 58 | + }, |
| 59 | + error: () => {}, |
| 60 | + }); |
| 61 | + } |
| 62 | + }); |
| 63 | + |
| 64 | + afterAll(() => rmSync(outDir, { recursive: true, force: true })); |
| 65 | + |
| 66 | + it.each([ |
| 67 | + ['index.js', 'cjs'], |
| 68 | + ['index.mjs', 'esm'], |
| 69 | + ])('instruments both drivers in %s', async (file, format) => { |
| 70 | + const transformer = createCodeTransformer({ instrumentations: neonConfig }); |
| 71 | + const source = join(packageDir, file); |
| 72 | + const result = transformer.transform(readFileSync(source, 'utf8'), source); |
| 73 | + expect(result).not.toBeNull(); |
| 74 | + |
| 75 | + for (const channel of Object.values(neonChannels)) { |
| 76 | + expect(result!.code).toContain(channel); |
| 77 | + } |
| 78 | + // Only pg's `Client.prototype.query` gets the channel, not the pool or wire-protocol `query`. |
| 79 | + expect(countWrappedSites(result!.code, 'tr_ch_apm$query')).toBe(1); |
| 80 | + expect(countWrappedSites(result!.code, 'tr_ch_apm$http_query')).toBe(1); |
| 81 | + expect(countWrappedSites(result!.code, 'tr_ch_apm$resolve_connection')).toBe(1); |
| 82 | + // The query wrapper exposes `self`, which carries pg's `connectionParameters`. |
| 83 | + const querySite = result!.code.indexOf('Client was passed a null or undefined query'); |
| 84 | + expect(result!.code.slice(result!.code.lastIndexOf('__apm$ctx = {', querySite), querySite)).toContain('self: this'); |
| 85 | + |
| 86 | + const outFile = join(outDir, file); |
| 87 | + writeFileSync(outFile, result!.code); |
| 88 | + const mod: NeonModule = |
| 89 | + format === 'cjs' ? nodeRequire(outFile) : ((await import(pathToFileURL(outFile).href)) as NeonModule); |
| 90 | + |
| 91 | + events.length = 0; |
| 92 | + mod.neonConfig.fetchFunction = neonResponse(EMPTY_RESULT); |
| 93 | + const sql = mod.neon('postgres://user:pass@ep-x.aws.neon.tech/neondb'); |
| 94 | + await sql.query('SELECT $1', [1]); |
| 95 | + await sql`SELECT 2`; |
| 96 | + mod.neonConfig.fetchFunction = neonResponse({ results: [EMPTY_RESULT, EMPTY_RESULT] }); |
| 97 | + await sql.transaction([sql`SELECT 3`, sql`SELECT 4`]); |
| 98 | + |
| 99 | + const client = new mod.Client('postgres://user:pass@ep-x.aws.neon.tech/neondb'); |
| 100 | + // Never connects: the channel fires at the call, before the socket is needed. |
| 101 | + client.query('SELECT 5').catch(() => {}); |
| 102 | + await client.end().catch(() => {}); |
| 103 | + |
| 104 | + const resolve = [ |
| 105 | + 'resolve-connection:start:"postgres://user:pass@ep-x.aws.neon.tech/neondb"', |
| 106 | + 'resolve-connection:asyncEnd:ep-x.aws.neon.tech', |
| 107 | + ]; |
| 108 | + expect(events).toEqual([ |
| 109 | + 'http-query:start:{"query":"SELECT $1","params":[1]}', |
| 110 | + ...resolve, |
| 111 | + 'http-query:asyncEnd:', |
| 112 | + 'http-query:start:{"strings":["SELECT 2"],"values":[]}', |
| 113 | + ...resolve, |
| 114 | + 'http-query:asyncEnd:', |
| 115 | + 'http-query:start:[{"strings":["SELECT 3"],"values":[]},{"strings":["SELECT 4"],"values":[]}]', |
| 116 | + ...resolve, |
| 117 | + 'http-query:asyncEnd:', |
| 118 | + 'query:start:neondb', |
| 119 | + ]); |
| 120 | + }); |
| 121 | +}); |
0 commit comments