: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(personhog): configurable http2 receive windows for the node client (#109450)
Nick Best6bcb56fb6e5f
diff --git a/nodejs/src/common/config.ts b/nodejs/src/common/config.tsindex e33d93554ef1..5bc76615de93 100644--- a/nodejs/src/common/config.ts+++ b/nodejs/src/common/config.ts@@ -138,6 +138,8 @@ export type CommonConfig = BaseServerConfig & {PERSONHOG_PING_IDLE_CONNECTION: booleanPERSONHOG_IDLE_CONNECTION_TIMEOUT_MS: numberPERSONHOG_STATE_MONITOR_POLL_INTERVAL_MS: number+ PERSONHOG_INITIAL_STREAM_WINDOW_BYTES: number+ PERSONHOG_INITIAL_CONNECTION_WINDOW_BYTES: number// Usage ingestion gRPC. One team list per deployment, because each reporting site is its// own service: '' reports nothing, '*' every team, '1,2' those teams. No percentage: it@@ -354,6 +356,8 @@ export function getDefaultCommonConfig(): CommonConfig {PERSONHOG_PING_IDLE_CONNECTION: true,PERSONHOG_IDLE_CONNECTION_TIMEOUT_MS: 15 * 60 * 1000,PERSONHOG_STATE_MONITOR_POLL_INTERVAL_MS: 5_000,+ PERSONHOG_INITIAL_STREAM_WINDOW_BYTES: 0,+ PERSONHOG_INITIAL_CONNECTION_WINDOW_BYTES: 0,// Usage ingestion gRPCUSAGE_INGESTION_ADDR: isDevEnv() ? 'localhost:7143' : '',diff --git a/nodejs/src/common/personhog/client.test.ts b/nodejs/src/common/personhog/client.test.tsindex bb9c3ab186bd..5e533b80ca3c 100644--- a/nodejs/src/common/personhog/client.test.ts+++ b/nodejs/src/common/personhog/client.test.ts@@ -1,6 +1,7 @@import { create } from '@bufbuild/protobuf'-import { Code, ConnectError, type ServiceImpl, createRouterTransport } from '@connectrpc/connect'+import { Code, ConnectError, type ServiceImpl, createClient, createRouterTransport } from '@connectrpc/connect'import { DateTime } from 'luxon'+import * as http2 from 'node:http2'import { PersonHogService } from '~/common/generated/personhog/personhog/service/v1/service_pb'import { ConsistencyLevel } from '~/common/generated/personhog/personhog/types/v1/common_pb'@@ -23,6 +24,8 @@ import type {import {PersonHogClient,+ type PersonHogClientConfig,+ createPersonhogTransport,parseRolloutTeamIds,resolveConsistencyHeader,resolvePersonRoutingKey,@@ -1272,3 +1275,73 @@ describe('PersonHogClient', () => {})})})++describe('PersonHogClient HTTP/2 windows', () => {+ const NODE_DEFAULT_WINDOW = 65_535++ async function observeAdvertisedWindows(+ windows: Pick<PersonHogClientConfig, 'initialStreamWindowBytes' | 'initialConnectionWindowBytes'>,+ expectedConnection: number+ ): Promise<{ stream: number; connection: number }> {+ const server = http2.createServer()+ const sessions: http2.ServerHttp2Session[] = []+ let deadlineTimer: ReturnType<typeof setTimeout> | undefined+ const observed = new Promise<{ stream: number; connection: number }>((resolve, reject) => {+ deadlineTimer = setTimeout(() => reject(new Error('no stream reached the server')), 4_000)+ server.on('session', (session) => {+ sessions.push(session)+ session.on('stream', (stream) => {+ stream.respond(+ { ':status': 200, 'content-type': 'application/grpc', 'grpc-status': '12' },+ { endStream: true }+ )+ const deadline = Date.now() + 2_000+ const poll = (): void => {+ if (session.state.remoteWindowSize === expectedConnection || Date.now() > deadline) {+ resolve({+ stream: session.remoteSettings.initialWindowSize ?? -1,+ connection: session.state.remoteWindowSize ?? -1,+ })+ } else {+ setImmediate(poll)+ }+ }+ poll()+ })+ session.on('error', reject)+ })+ })+ await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve))+ const address = server.address() as { port: number }+ const { transport, stateMonitor } = createPersonhogTransport({+ addr: `127.0.0.1:${address.port}`,+ timeoutMs: 2_000,+ ...windows,+ })+ try {+ await createClient(PersonHogService, transport)+ .getPerson({ teamId: 1n, personId: 1n })+ .catch(() => undefined)+ return await observed+ } finally {+ clearTimeout(deadlineTimer)+ stateMonitor.close()+ for (const session of sessions) {+ session.destroy()+ }+ await new Promise<void>((resolve) => server.close(() => resolve()))+ }+ }++ it.each([+ ['defaults', {}, NODE_DEFAULT_WINDOW, NODE_DEFAULT_WINDOW],+ [+ 'configured',+ { initialStreamWindowBytes: 4 * 1024 * 1024, initialConnectionWindowBytes: 8 * 1024 * 1024 },+ 4 * 1024 * 1024,+ 8 * 1024 * 1024,+ ],+ ])('advertises the %s windows to the server', async (_label, windows, stream, connection) => {+ await expect(observeAdvertisedWindows(windows, connection)).resolves.toEqual({ stream, connection })+ })+})diff --git a/nodejs/src/common/personhog/client.ts b/nodejs/src/common/personhog/client.tsindex a616e3390786..d0aee3c32fa4 100644--- a/nodejs/src/common/personhog/client.ts+++ b/nodejs/src/common/personhog/client.ts@@ -7,6 +7,7 @@ import { PersonHogService } from '~/common/generated/personhog/personhog/serviceimport { ConsistencyLevel, ReadOptionsSchema } from '~/common/generated/personhog/personhog/types/v1/common_pb'import { parseJSON } from '~/common/utils/json-parse'+import { ConnectionWindowSessionManager } from './connection-window-session-manager'import { PersonHogGroupOperations } from './groups'import { PersonHogPersonOperations } from './persons'import { SessionStateMonitor } from './session-state-monitor'@@ -185,6 +186,9 @@ export interface PersonHogClientConfig {*/idleConnectionTimeoutMs?: number+ initialStreamWindowBytes?: number+ initialConnectionWindowBytes?: number+// -- Attribution --/** Identifies the code path / feature area within this service (e.g., "ingestion/event-processing"). */@@ -228,6 +232,18 @@ export class PersonHogClient {}}+export const MAX_HTTP2_WINDOW_BYTES = 2 ** 31 - 1++function windowBytes(value: number | undefined, name: string): number | undefined {+ if (value === undefined || value === 0) {+ return undefined+ }+ if (!Number.isInteger(value) || value < 0 || value > MAX_HTTP2_WINDOW_BYTES) {+ throw new Error(`${name} must be an integer between 0 and ${MAX_HTTP2_WINDOW_BYTES}, got ${value}`)+ }+ return value+}+/*** The transport every personhog gRPC client shares: caller headers,* consistency and routing-key stamping, and an HTTP/2 session kept alive@@ -271,12 +287,18 @@ export function createPersonhogTransport(config: PersonHogClientConfig): {return await next(req)})- const sessionManager = new Http2SessionManager(`${scheme}://${config.addr}`, {- pingIntervalMs: config.pingIntervalMs ?? 30_000,- pingTimeoutMs: config.pingTimeoutMs ?? 5_000,- pingIdleConnection: config.pingIdleConnection ?? true,- idleConnectionTimeoutMs: config.idleConnectionTimeoutMs,- })+ const streamWindowBytes = windowBytes(config.initialStreamWindowBytes, 'initialStreamWindowBytes')+ const connectionWindowBytes = windowBytes(config.initialConnectionWindowBytes, 'initialConnectionWindowBytes')+ const sessionManager = new Http2SessionManager(+ `${scheme}://${config.addr}`,+ {+ pingIntervalMs: config.pingIntervalMs ?? 30_000,+ pingTimeoutMs: config.pingTimeoutMs ?? 5_000,+ pingIdleConnection: config.pingIdleConnection ?? true,+ idleConnectionTimeoutMs: config.idleConnectionTimeoutMs,+ },+ streamWindowBytes === undefined ? undefined : { settings: { initialWindowSize: streamWindowBytes } }+ )const stateMonitor = new SessionStateMonitor(sessionManager,@@ -289,7 +311,10 @@ export function createPersonhogTransport(config: PersonHogClientConfig): {defaultTimeoutMs: config.timeoutMs ?? 1_000,readMaxBytes: config.readMaxBytes ?? 128 * 1024 * 1024,writeMaxBytes: config.writeMaxBytes ?? 4 * 1024 * 1024,- sessionManager: stateMonitor,+ sessionManager:+ connectionWindowBytes === undefined+ ? stateMonitor+ : new ConnectionWindowSessionManager(stateMonitor, connectionWindowBytes),interceptors,})return { transport, stateMonitor }diff --git a/nodejs/src/common/personhog/connection-window-session-manager.test.ts b/nodejs/src/common/personhog/connection-window-session-manager.test.tsnew file mode 100644index 000000000000..17a591c4c855--- /dev/null+++ b/nodejs/src/common/personhog/connection-window-session-manager.test.ts@@ -0,0 +1,42 @@+import { ConnectionWindowSessionManager } from './connection-window-session-manager'++function makeSession(): { setLocalWindowSize: jest.Mock } {+ return { setLocalWindowSize: jest.fn() }+}++function makeInner(streams: { session: unknown }[]): {+ authority: string+ request: jest.Mock+ notifyResponseByteRead: jest.Mock+} {+ const request = jest.fn()+ for (const stream of streams) {+ request.mockResolvedValueOnce(stream)+ }+ return { authority: 'localhost:1', request, notifyResponseByteRead: jest.fn() }+}++describe('ConnectionWindowSessionManager', () => {+ it('widens each session once, however many streams it carries', async () => {+ const first = makeSession()+ const second = makeSession()+ const inner = makeInner([{ session: first }, { session: first }, { session: second }])+ const manager = new ConnectionWindowSessionManager(inner as any, 8 * 1024 * 1024)++ for (let i = 0; i < 3; i++) {+ await manager.request('POST', '/svc/Method', {}, {})+ }++ expect(first.setLocalWindowSize).toHaveBeenCalledTimes(1)+ expect(first.setLocalWindowSize).toHaveBeenCalledWith(8 * 1024 * 1024)+ expect(second.setLocalWindowSize).toHaveBeenCalledTimes(1)+ })++ it('passes through a stream that has already lost its session', async () => {+ const stream = { session: undefined }+ const inner = makeInner([stream])+ const manager = new ConnectionWindowSessionManager(inner as any, 1024)++ await expect(manager.request('POST', '/svc/Method', {}, {})).resolves.toBe(stream)+ })+})diff --git a/nodejs/src/common/personhog/connection-window-session-manager.ts b/nodejs/src/common/personhog/connection-window-session-manager.tsnew file mode 100644index 000000000000..1d489e13d5d2--- /dev/null+++ b/nodejs/src/common/personhog/connection-window-session-manager.ts@@ -0,0 +1,36 @@+import type { GrpcTransportOptions } from '@connectrpc/connect-node'+import type * as http2 from 'node:http2'++type SessionManager = NonNullable<GrpcTransportOptions['sessionManager']>++export class ConnectionWindowSessionManager implements SessionManager {+ private readonly sized = new WeakSet<http2.ClientHttp2Session>()++ constructor(+ private readonly inner: SessionManager,+ private readonly connectionWindowBytes: number+ ) {}++ get authority(): string {+ return this.inner.authority+ }++ async request(+ method: string,+ path: string,+ headers: http2.OutgoingHttpHeaders,+ options: Omit<http2.ClientSessionRequestOptions, 'signal'>+ ): Promise<http2.ClientHttp2Stream> {+ const stream = await this.inner.request(method, path, headers, options)+ const session = stream.session as http2.ClientHttp2Session | undefined+ if (session && !this.sized.has(session)) {+ this.sized.add(session)+ session.setLocalWindowSize(this.connectionWindowBytes)+ }+ return stream+ }++ notifyResponseByteRead(stream: http2.ClientHttp2Stream): void {+ this.inner.notifyResponseByteRead(stream)+ }+}diff --git a/nodejs/src/common/personhog/index.ts b/nodejs/src/common/personhog/index.tsindex 6bc51a4e120a..96adab25e199 100644--- a/nodejs/src/common/personhog/index.ts+++ b/nodejs/src/common/personhog/index.ts@@ -33,6 +33,8 @@ export type PersonHogConfig = Pick<| 'PERSONHOG_PING_IDLE_CONNECTION'| 'PERSONHOG_IDLE_CONNECTION_TIMEOUT_MS'| 'PERSONHOG_STATE_MONITOR_POLL_INTERVAL_MS'+ | 'PERSONHOG_INITIAL_STREAM_WINDOW_BYTES'+ | 'PERSONHOG_INITIAL_CONNECTION_WINDOW_BYTES'| 'PLUGIN_SERVER_MODE'>@@ -55,6 +57,8 @@ export function createPersonHogClient(config: PersonHogConfig): PersonHogClientpingIdleConnection: config.PERSONHOG_PING_IDLE_CONNECTION,idleConnectionTimeoutMs: config.PERSONHOG_IDLE_CONNECTION_TIMEOUT_MS,stateMonitorPollIntervalMs: config.PERSONHOG_STATE_MONITOR_POLL_INTERVAL_MS,+ initialStreamWindowBytes: config.PERSONHOG_INITIAL_STREAM_WINDOW_BYTES,+ initialConnectionWindowBytes: config.PERSONHOG_INITIAL_CONNECTION_WINDOW_BYTES,})}diff --git a/nodejs/src/servers/ingestion-api-server.ts b/nodejs/src/servers/ingestion-api-server.tsindex 13c3cd834cb8..09c41b8a6fb1 100644--- a/nodejs/src/servers/ingestion-api-server.ts+++ b/nodejs/src/servers/ingestion-api-server.ts@@ -371,6 +371,8 @@ export class IngestionApiServer implements NodeServer {readMaxBytes: this.config.PERSONHOG_READ_MAX_BYTES,writeMaxBytes: this.config.PERSONHOG_WRITE_MAX_BYTES,clientName: 'ingestion-persons-store',+ initialStreamWindowBytes: this.config.PERSONHOG_INITIAL_STREAM_WINDOW_BYTES,+ initialConnectionWindowBytes: this.config.PERSONHOG_INITIAL_CONNECTION_WINDOW_BYTES,})const identityClients = createIdentityClients({@@ -378,6 +380,8 @@ export class IngestionApiServer implements NodeServer {useTls: this.config.PERSONHOG_TLS,timeoutMs: this.config.PERSONHOG_TIMEOUT_MS,clientName: 'ingestion-persons-store',+ initialStreamWindowBytes: this.config.PERSONHOG_INITIAL_STREAM_WINDOW_BYTES,+ initialConnectionWindowBytes: this.config.PERSONHOG_INITIAL_CONNECTION_WINDOW_BYTES,},{ mergeTimeoutMs: this.config.PERSONHOG_MERGE_TIMEOUT_MS })