Skip to content

: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.

feat(cdp): add dry-run mode to the push registration service (#113683)

Daniel Marchuk3cfb8b055847
diff --git a/nodejs/src/messaging/push-subscriptions/push-capture.ts b/nodejs/src/messaging/push-subscriptions/push-capture.ts
index 2cae5ce6f10f..17812b2a28ba 100644
--- a/nodejs/src/messaging/push-subscriptions/push-capture.ts
+++ b/nodejs/src/messaging/push-subscriptions/push-capture.ts
@@ -136,6 +136,15 @@ export class PushCaptureService {
}
}
+/** Answers like a capture that accepted the event, and sends nothing. A mirrored copy of traffic that
+ * Django already stores goes here, so the copy writes and bills nothing twice. */
+export class DryRunPushCaptureService {
+ public capture(_event: PushCaptureEvent): Promise<void> {
+ captureCounter.inc({ outcome: 'dry_run' })
+ return Promise.resolve()
+ }
+}
+
/** Django's session retries these statuses and connection errors three times, backing off 0, 200 and
* 400ms (urllib3 `Retry(total=3, backoff_factor=0.1)`). */
const TRANSPORT_RETRY_STATUSES = new Set([500, 502, 503, 504])
diff --git a/nodejs/src/messaging/push-subscriptions/push-subscriptions-http.test.ts b/nodejs/src/messaging/push-subscriptions/push-subscriptions-http.test.ts
index 8b7a361377c8..9e74551b13a5 100644
--- a/nodejs/src/messaging/push-subscriptions/push-subscriptions-http.test.ts
+++ b/nodejs/src/messaging/push-subscriptions/push-subscriptions-http.test.ts
@@ -11,7 +11,13 @@ import { PushHandlerResult, PushSubscriptionsService } from './push-subscription
describe('push subscriptions http', () => {
let server: Server
let base: string
- let seen: { method: string; body: string; contentType?: string; compression?: string | null }[]
+ let seen: {
+ method: string
+ body: string
+ contentType?: string
+ compression?: string | null
+ mirrored?: boolean
+ }[]
let answer: PushHandlerResult
let failure: Error | null
@@ -26,6 +32,7 @@ describe('push subscriptions http', () => {
body: request.body.toString('utf8'),
contentType: request.contentType,
compression: request.query?.get('compression') ?? null,
+ mirrored: request.mirrored,
})
return failure ? Promise.reject(failure) : Promise.resolve(answer)
},
@@ -49,6 +56,24 @@ describe('push subscriptions http', () => {
const post = (path: string, init: Record<string, any> = {}): Promise<FetchResponse> =>
internalFetch(`${base}${path}`, { method: 'POST', ...init })
+ it.each([
+ ['us.i.posthog.com-shadow', true],
+ ['us.i.posthog.com', false],
+ ['shadow.example.com', false],
+ ])('marks a request with Host %s as mirrored: %s', async (host, mirrored) => {
+ await new Promise<void>((resolve, reject) => {
+ const req = httpRequest(
+ `${base}/api/push_subscriptions/`,
+ { method: 'POST', headers: { Host: host, 'Content-Type': 'application/json' } },
+ (res) => res.resume().on('end', resolve)
+ )
+ req.on('error', reject)
+ req.end('{}')
+ })
+
+ expect(seen[0].mirrored).toEqual(mirrored)
+ })
+
it('delivers a DELETE body to the service', async () => {
// The reason this endpoint is not on the plugin server's express framework: that one drops
// the body on DELETE, and DELETE with a body is how every released SDK unregisters a device.
@@ -61,7 +86,9 @@ describe('push subscriptions http', () => {
})
expect(response.status).toEqual(200)
- expect(seen).toEqual([{ method: 'DELETE', body, contentType: 'application/json', compression: null }])
+ expect(seen).toEqual([
+ { method: 'DELETE', body, contentType: 'application/json', compression: null, mirrored: false },
+ ])
})
it('passes the content type and query through untouched', async () => {
diff --git a/nodejs/src/messaging/push-subscriptions/push-subscriptions-http.ts b/nodejs/src/messaging/push-subscriptions/push-subscriptions-http.ts
index 4a1592d6d096..5abb1be3644b 100644
--- a/nodejs/src/messaging/push-subscriptions/push-subscriptions-http.ts
+++ b/nodejs/src/messaging/push-subscriptions/push-subscriptions-http.ts
@@ -83,6 +83,7 @@ export function createPushSubscriptionsHandler(service: PushSubscriptionsService
contentType: header(req, 'content-type'),
contentEncoding: header(req, 'content-encoding'),
query,
+ mirrored: header(req, 'host')?.endsWith('-shadow') ?? false,
})
} catch (error) {
// The server answers a throw with a 500, and the error-rate alert reads this histogram.
diff --git a/nodejs/src/messaging/push-subscriptions/push-subscriptions.service.test.ts b/nodejs/src/messaging/push-subscriptions/push-subscriptions.service.test.ts
index a4d29b58d8af..4aff986f5662 100644
--- a/nodejs/src/messaging/push-subscriptions/push-subscriptions.service.test.ts
+++ b/nodejs/src/messaging/push-subscriptions/push-subscriptions.service.test.ts
@@ -65,6 +65,30 @@ describe('PushSubscriptionsService', () => {
})
})
+ it.each([
+ ['a mirrored copy goes to the mirrored capture', true, 'mirrored'],
+ ['a direct request is stored even when mirrored copies are not', false, 'direct'],
+ ])('%s', async (_name, mirrored, expected) => {
+ const direct = { capture: jest.fn(() => Promise.resolve()) }
+ const mirror = { capture: jest.fn(() => Promise.resolve()) }
+ service = new PushSubscriptionsService(
+ teamManager,
+ postgres,
+ { encrypt: (value: string) => `enc:${value}` } as any,
+ direct,
+ 'secret',
+ mirror
+ )
+
+ const result = await service.handle(request(valid, 'POST', { mirrored }))
+
+ expect(result).toMatchObject({ status: 200, body: { distinct_id: 'user-1' } })
+ expect({ direct: direct.capture.mock.calls.length, mirrored: mirror.capture.mock.calls.length }).toEqual({
+ direct: expected === 'direct' ? 1 : 0,
+ mirrored: expected === 'mirrored' ? 1 : 0,
+ })
+ })
+
it('reports a rejected capture rather than telling the SDK the token was stored', async () => {
// The SDK marks a registration delivered on a 2xx and stops re-sending it, so a capture that
// did not happen has to surface as an error or the device is never registered.
diff --git a/nodejs/src/messaging/push-subscriptions/push-subscriptions.service.ts b/nodejs/src/messaging/push-subscriptions/push-subscriptions.service.ts
index 073b131981d8..4d65ddcb7b07 100644
--- a/nodejs/src/messaging/push-subscriptions/push-subscriptions.service.ts
+++ b/nodejs/src/messaging/push-subscriptions/push-subscriptions.service.ts
@@ -84,8 +84,9 @@ export class PushSubscriptionsService {
private projectTokens: Pick<ProjectTokenLookup, 'getTeamByToken'>,
private postgres: PostgresRouter,
private encryptedFields: EncryptedFields,
- private capture: PushCaptureService,
- private secretKey: string
+ private capture: Pick<PushCaptureService, 'capture'>,
+ private secretKey: string,
+ private mirroredCapture: Pick<PushCaptureService, 'capture'> = capture
) {
this.invalidTokens = new LRUCache({ max: INVALID_TOKEN_CACHE_SIZE, ttl: INVALID_TOKEN_CACHE_TTL_MS })
this.configuredAppIdsCache = new LRUCache({
@@ -249,7 +250,8 @@ export class PushSubscriptionsService {
try {
// An SDK told the registration was stored stops re-sending it, so a capture that did
// not happen has to surface here.
- await this.capture.capture({
+ const capture = request.mirrored ? this.mirroredCapture : this.capture
+ await capture.capture({
token: team.api_token,
event: '$set',
distinctId,
diff --git a/nodejs/src/messaging/push-subscriptions/request-decoding.ts b/nodejs/src/messaging/push-subscriptions/request-decoding.ts
index 8d5f69853e23..14a9e9ac7e36 100644
--- a/nodejs/src/messaging/push-subscriptions/request-decoding.ts
+++ b/nodejs/src/messaging/push-subscriptions/request-decoding.ts
@@ -28,6 +28,8 @@ export type RawRequest = {
contentEncoding?: string
/** Parsed from the URL. Django reads `compression` from the query string for POST. */
query?: URLSearchParams
+ /** Envoy appends `-shadow` to the Host of a mirrored copy. */
+ mirrored?: boolean
}
/** The decoded body, plus the form fields Django's `get_token` reads directly off `request.POST`. */
diff --git a/nodejs/src/servers/push-api-server.ts b/nodejs/src/servers/push-api-server.ts
index a52e853324db..06c67009a611 100644
--- a/nodejs/src/servers/push-api-server.ts
+++ b/nodejs/src/servers/push-api-server.ts
@@ -6,7 +6,7 @@ import { PostgresRouter, PostgresRouterConfig } from '~/common/utils/db/postgres
import { isProdEnv, isTestEnv } from '~/common/utils/env-utils'
import { logger } from '~/common/utils/logger'
import { ProjectTokenLookup } from '~/messaging/push-subscriptions/project-token-lookup'
-import { PushCaptureService } from '~/messaging/push-subscriptions/push-capture'
+import { DryRunPushCaptureService, PushCaptureService } from '~/messaging/push-subscriptions/push-capture'
import { createPushSubscriptionsHandler } from '~/messaging/push-subscriptions/push-subscriptions-http'
import { PushSubscriptionsService } from '~/messaging/push-subscriptions/push-subscriptions.service'
@@ -21,6 +21,9 @@ export type PushApiConfig = {
* fingerprint the same in both services' logs while both serve the endpoint. The key also stops a
* secret API key submitted in the wrong field from being confirmable out of the log. */
SECRET_KEY: string
+ /** Skips the person update for a mirrored copy and still answers as if it was stored. A request
+ * that reaches the service directly is still stored. */
+ PUSH_API_DRY_RUN: boolean
}
export function getDefaultPushApiConfig(): PushApiConfig {
@@ -28,6 +31,7 @@ export function getDefaultPushApiConfig(): PushApiConfig {
PUSH_API_PORT: 6750,
PUSH_API_HOST: '0.0.0.0',
SECRET_KEY: '',
+ PUSH_API_DRY_RUN: false,
}
}
@@ -86,12 +90,18 @@ export class PushApiServer implements NodeServer {
this.postgres = new PostgresRouter(this.config, this.config.PLUGIN_SERVER_MODE ?? undefined)
logger.info('👍', 'Postgres Router ready')
+ if (this.config.PUSH_API_DRY_RUN) {
+ logger.warn('push-api is in dry-run mode: mirrored registrations are answered but not stored')
+ }
+
+ const capture = new PushCaptureService(this.config.CAPTURE_INTERNAL_URL)
const service = new PushSubscriptionsService(
new ProjectTokenLookup(this.postgres),
this.postgres,
new EncryptedFields(this.config.ENCRYPTION_SALT_KEYS),
- new PushCaptureService(this.config.CAPTURE_INTERNAL_URL),
- this.config.SECRET_KEY
+ capture,
+ this.config.SECRET_KEY,
+ this.config.PUSH_API_DRY_RUN ? new DryRunPushCaptureService() : capture
)
if (!isTestEnv()) {