:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(image-scrub-sidecar): serve /metrics + health on a scrapable listener (#69675)
Robbiec84cb247c0d1
diff --git a/.github/workflows/ci-ml-mirror-image-scrub-container.yml b/.github/workflows/ci-ml-mirror-image-scrub-container.ymlindex 578cbe9aae84..ef86fa0512b6 100644--- a/.github/workflows/ci-ml-mirror-image-scrub-container.yml+++ b/.github/workflows/ci-ml-mirror-image-scrub-container.yml@@ -137,7 +137,9 @@ jobs:file: Dockerfile.ml-mirror-image-scrubtags: ${{ steps.docker-meta.outputs.tags }}labels: ${{ steps.docker-meta.outputs.labels }}- platforms: linux/amd64+ # Both arches: the charts-side Karpenter NodePool defaults to arm64 (Graviton), and an+ # amd64-only manifest fails there with "no match for platform in manifest".+ platforms: linux/amd64,linux/arm64build-args: |COMMIT_HASH=${{ github.sha }}diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/README.md b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/README.mdindex 4a6831f57f8a..9219cb5b7564 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/README.md+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/README.md@@ -4,7 +4,9 @@ This package builds a small sidecar that is installed alongside the image scrubbIt is intentionally kept separate from the root pnpm workspace, as the ML deps are several hundred MB. I did not want to add this to every CI run, every dev's local machine's worktree, etc-It runs a simple http server, receives an image and replies with the scrubbed image. The interface is fully trusted as it only communicates with the kafka consumer in the same pod. It binds loopback only, so it must run as a sidecar container sharing the consumer's network namespace, not as its own service.+It runs a simple http server, receives an image and replies with the scrubbed image. The `/scrub` interface is fully trusted as it only communicates with the kafka consumer in the same pod. It binds loopback only, so it must run as a sidecar container sharing the consumer's network namespace, not as its own service.++`/metrics` and the health probes are served on a separate listener bound to all interfaces (default port `9011`, `IMAGE_SCRUB_METRICS_PORT`) so Prometheus and the kubelet can reach them on the pod IP. That listener exposes no image bytes, only counters and probes.## HTTP contractdiff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/config.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/config.tsindex 570c87e97802..6b0fb4080285 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/config.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/config.ts@@ -1,5 +1,8 @@export interface Config {port: number+ // Loopback-only /scrub must not be reachable off-pod, but Prometheus scrapes the pod IP, so /metrics + health+ // live on a separate listener bound to all interfaces.+ metricsPort: numbermaxConcurrency: number// 413 above the ~10 MiB Kafka message ceiling — bigger is anomalous. The service owns its own memory bound.maxBodyBytes: number@@ -8,6 +11,7 @@ export interface Config {export function loadConfig(): Config {return {port: Number(process.env.IMAGE_SCRUB_PORT ?? 9010),+ metricsPort: Number(process.env.IMAGE_SCRUB_METRICS_PORT ?? 9011),maxConcurrency: Number(process.env.IMAGE_SCRUB_CONCURRENCY ?? 8),maxBodyBytes: Number(process.env.IMAGE_SCRUB_MAX_BODY_BYTES ?? 20 * 1024 * 1024),}diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/main.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/main.tsindex ffb74f2b2d63..0b79f802f7b8 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/main.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/main.ts@@ -2,17 +2,23 @@ import { loadConfig } from './config.ts'import { startServer } from './server.ts'const cfg = loadConfig()-const server = startServer(cfg.port, cfg.maxConcurrency, cfg.maxBodyBytes)+const { scrub, metrics } = startServer(cfg.port, cfg.metricsPort, cfg.maxConcurrency, cfg.maxBodyBytes)for (const sig of ['SIGINT', 'SIGTERM'] as const) {process.on(sig, () => {// Backstop: force-exit before the pod's termination grace period elapses.const force = setTimeout(() => process.exit(1), 10_000)force.unref()- server.close(() => {- clearTimeout(force)- process.exit(0)- })- server.closeIdleConnections()+ let remaining = 2+ const exitWhenBothClosed = (): void => {+ if (--remaining === 0) {+ clearTimeout(force)+ process.exit(0)+ }+ }+ for (const server of [scrub, metrics]) {+ server.close(exitWhenBothClosed)+ server.closeIdleConnections()+ }})}diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/server.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/server.test.tsindex 563d66df2912..b271b1b9d8c5 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/server.test.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/server.test.ts@@ -10,16 +10,21 @@ const PNG = Buffer.from(describe('image-scrub sidecar server', () => {let base: string- let server: ReturnType<typeof startServer>+ let metricsBase: string+ let servers: ReturnType<typeof startServer>beforeAll(async () => {- server = startServer(0, 4, 1024)- await once(server, 'listening')- base = `http://127.0.0.1:${(server.address() as AddressInfo).port}`+ servers = startServer(0, 0, 4, 1024)+ await Promise.all([once(servers.scrub, 'listening'), once(servers.metrics, 'listening')])+ base = `http://127.0.0.1:${(servers.scrub.address() as AddressInfo).port}`+ metricsBase = `http://127.0.0.1:${(servers.metrics.address() as AddressInfo).port}`})afterAll((done) => {- server.closeAllConnections()- server.close(() => done())+ let remaining = 2+ for (const server of [servers.scrub, servers.metrics]) {+ server.closeAllConnections()+ server.close(() => --remaining === 0 && done())+ }})it('scrubs posted image bytes into different (blurred) bytes', async () => {@@ -50,10 +55,21 @@ describe('image-scrub sidecar server', () => {expect(res.status).toBe(422)})- it('serves health + metrics', async () => {- expect((await fetch(`${base}/_health`)).status).toBe(200)- const metrics = await fetch(`${base}/metrics`)+ it('serves health + metrics on the metrics listener, not the scrub listener', async () => {+ expect((await fetch(`${metricsBase}/_health`)).status).toBe(200)+ const metrics = await fetch(`${metricsBase}/metrics`)expect(metrics.status).toBe(200)expect(await metrics.text()).toContain('ml_mirror_image_scrub_scrubbed_total')})++ it('does not expose /scrub on the metrics listener', async () => {+ const res = await fetch(`${metricsBase}/scrub`, { method: 'POST', body: PNG })+ expect(res.status).toBe(404)+ })++ it('does not serve health or metrics on the scrub listener', async () => {+ expect((await fetch(`${base}/_health`)).status).toBe(404)+ expect((await fetch(`${base}/_ready`)).status).toBe(404)+ expect((await fetch(`${base}/metrics`)).status).toBe(404)+ })})diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/server.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/server.tsindex 091c91d6053d..f05807f1a583 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/server.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/server.ts@@ -14,23 +14,24 @@ async function scrub(input: Buffer, signal: AbortSignal): Promise<Buffer> {return blurOnly(input)}-export function startServer(port: number, maxConcurrency: number, maxBodyBytes: number): Server {+export interface SidecarServers {+ // /scrub, bound to loopback — the pod IP must never expose it.+ scrub: Server+ // /metrics + health, bound to all interfaces so Prometheus and the kubelet can reach the pod IP.+ metrics: Server+}++export function startServer(+ port: number,+ metricsPort: number,+ maxConcurrency: number,+ maxBodyBytes: number+): SidecarServers {let inFlight = 0const app = express()app.disable('x-powered-by')app.disable('etag')- app.get(['/_health', '/_ready'], (_req, res) => {- res.status(200).send('ok')- })-- app.get('/metrics', (_req, res, next) => {- register- .metrics()- .then((body) => res.set('Content-Type', register.contentType).send(body))- .catch(next)- })-const shedIfBusy = (_req: Request, res: Response, next: NextFunction): void => {if (inFlight >= maxConcurrency) {ScrubMetrics.incRejected()@@ -115,12 +116,36 @@ export function startServer(port: number, maxConcurrency: number, maxBodyBytes:})// Loopback only: the consumer shares the pod netns; the pod IP must not expose /scrub.- const server = app.listen(port, '127.0.0.1', () =>+ const scrubServer = app.listen(port, '127.0.0.1', () =>console.log(`image-scrub sidecar listening on 127.0.0.1:${port} (maxConcurrency ${maxConcurrency})`))- server.on('error', (err) => {- console.error(`image-scrub sidecar server error: ${String(err)}`)- process.exit(1)++ // Observability lives on its own listener bound to all interfaces: Prometheus scrapes the pod IP, which the+ // loopback /scrub listener above deliberately can't answer. It exposes no image bytes, only counters + probes.+ const obs = express()+ obs.disable('x-powered-by')+ obs.disable('etag')+ obs.get(['/_health', '/_ready'], (_req, res) => {+ res.status(200).send('ok')})- return server+ obs.get('/metrics', (_req, res, next) => {+ register+ .metrics()+ .then((body) => res.set('Content-Type', register.contentType).send(body))+ .catch(next)+ })+ const metricsServer = obs.listen(metricsPort, '0.0.0.0', () =>+ console.log(`image-scrub sidecar metrics listening on 0.0.0.0:${metricsPort}`)+ )++ for (const [name, server] of [+ ['scrub', scrubServer],+ ['metrics', metricsServer],+ ] as const) {+ server.on('error', (err) => {+ console.error(`image-scrub sidecar ${name} listener error: ${String(err)}`)+ process.exit(1)+ })+ }+ return { scrub: scrubServer, metrics: metricsServer }}