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.

chore(nodejs): decouple the Hub from ingestion (cookieless) (#65482)

José Sequeira00a3b9265e13
diff --git a/nodejs/src/ingestion/common/cookieless/cookieless-manager.test.ts b/nodejs/src/ingestion/common/cookieless/cookieless-manager.test.ts
index 99874cbef464..e14ae8a5841c 100644
--- a/nodejs/src/ingestion/common/cookieless/cookieless-manager.test.ts
+++ b/nodejs/src/ingestion/common/cookieless/cookieless-manager.test.ts
@@ -6,10 +6,10 @@ import { cookielessRedisErrorCounter } from '~/common/metrics'
import { PipelineResultType, isOkResult } from '~/ingestion/framework/results'
import type { PluginEvent } from '~/plugin-scaffold'
import { createTestEventHeaders } from '~/tests/helpers/event-headers'
+import { IngestionTestInfra, createIngestionTestInfra } from '~/tests/helpers/ingestion-e2e'
import { createOrganization, createTeam, getTeam } from '~/tests/helpers/sql'
-import { CookielessServerHashMode, EventHeaders, Hub, PipelineEvent, Team } from '~/types'
+import { CookielessServerHashMode, EventHeaders, PipelineEvent, Team } from '~/types'
import { RedisOperationError } from '~/utils/db/error'
-import { closeHub, createHub } from '~/utils/db/hub'
import { PostgresUse } from '~/utils/db/postgres'
import { parseJSON } from '~/utils/json-parse'
import { UUID7 } from '~/utils/utils'
@@ -168,7 +168,7 @@ describe('CookielessManager', () => {
})
describe('pipeline step', () => {
- let hub: Hub
+ let infra: IngestionTestInfra
let organizationId: string
let teamId: number
let team: Team
@@ -195,8 +195,8 @@ describe('CookielessManager', () => {
} as unknown as Message
beforeAll(async () => {
- hub = await createHub({})
- organizationId = await createOrganization(hub.postgres)
+ infra = await createIngestionTestInfra({})
+ organizationId = await createOrganization(infra.postgres)
jest.useFakeTimers({
now,
@@ -204,32 +204,32 @@ describe('CookielessManager', () => {
})
})
afterAll(async () => {
- await closeHub(hub)
+ await infra.close()
jest.clearAllTimers()
})
const setModeForTeam = async (mode: CookielessServerHashMode) => {
- await hub.postgres.query(
+ await infra.postgres.query(
PostgresUse.COMMON_WRITE,
`UPDATE posthog_team SET cookieless_server_hash_mode = $1 WHERE id = $2`,
[mode, teamId],
'set team to cookieless'
)
- team = (await getTeam(hub.postgres, teamId))!
+ team = (await getTeam(infra.postgres, teamId))!
}
const clearRedis = async () => {
- const client = await hub.redisPool.acquire()
+ const client = await infra.redisPool.acquire()
await client.flushall()
- await hub.redisPool.release(client)
+ await infra.redisPool.release(client)
}
beforeEach(async () => {
await clearRedis()
- hub.cookielessManager.deleteAllLocalSalts()
- teamId = await createTeam(hub.postgres, organizationId)
- team = (await getTeam(hub.postgres, teamId))!
+ infra.cookielessManager.deleteAllLocalSalts()
+ teamId = await createTeam(infra.postgres, organizationId)
+ team = (await getTeam(infra.postgres, teamId))!
event = deepFreeze({
event: 'test event',
distinct_id: COOKIELESS_SENTINEL_VALUE,
@@ -336,7 +336,7 @@ describe('CookielessManager', () => {
event: PipelineEvent,
headers: EventHeaders = createTestEventHeaders()
): Promise<PipelineEvent | undefined> {
- const response = await hub.cookielessManager.doBatch([{ event, team, message, headers }])
+ const response = await infra.cookielessManager.doBatch([{ event, team, message, headers }])
expect(response.length).toBe(1)
const result = response[0]
return isOkResult(result) ? result.value.event : undefined
@@ -349,7 +349,7 @@ describe('CookielessManager', () => {
event: PipelineEvent | undefined
headers: EventHeaders
}> {
- const response = await hub.cookielessManager.doBatch([{ event, team, message, headers }])
+ const response = await infra.cookielessManager.doBatch([{ event, team, message, headers }])
expect(response.length).toBe(1)
const result = response[0]
return {
@@ -431,7 +431,7 @@ describe('CookielessManager', () => {
})
it('should work even if the local salt map is torn down between events (as it can use redis)', async () => {
const actual1 = await processEvent(event)
- hub.cookielessManager.deleteAllLocalSalts()
+ infra.cookielessManager.deleteAllLocalSalts()
const actual2 = await processEvent(eventABitLater)
if (!actual1?.properties || !actual2?.properties) {
@@ -608,7 +608,7 @@ describe('CookielessManager', () => {
it('should increment the redis error counter if redis errors', async () => {
const operation = 'scard'
const error = new RedisOperationError('redis error', new Error(), operation, { key: 'key' })
- jest.spyOn(hub.cookielessManager.redisHelpers, 'redisSMembersMulti').mockImplementationOnce(() => {
+ jest.spyOn(infra.cookielessManager.redisHelpers, 'redisSMembersMulti').mockImplementationOnce(() => {
throw error
})
const spy = jest.spyOn(cookielessRedisErrorCounter, 'labels')
@@ -620,11 +620,11 @@ describe('CookielessManager', () => {
it('should DLQ cookieless events when Redis error occurs', async () => {
const operation = 'scard'
const redisError = new RedisOperationError('redis error', new Error(), operation, { key: 'key' })
- jest.spyOn(hub.cookielessManager.redisHelpers, 'redisSMembersMulti').mockImplementationOnce(() => {
+ jest.spyOn(infra.cookielessManager.redisHelpers, 'redisSMembersMulti').mockImplementationOnce(() => {
throw redisError
})
- const response = await hub.cookielessManager.doBatch([
+ const response = await infra.cookielessManager.doBatch([
{ event, team, message, headers: createTestEventHeaders() },
{ event: nonCookielessEvent, team, message, headers: createTestEventHeaders() },
])
@@ -648,11 +648,11 @@ describe('CookielessManager', () => {
it('should DLQ cookieless events when unexpected error occurs', async () => {
const unexpectedError = new Error('Something went wrong')
- jest.spyOn(hub.cookielessManager.redisHelpers, 'redisSMembersMulti').mockImplementationOnce(() => {
+ jest.spyOn(infra.cookielessManager.redisHelpers, 'redisSMembersMulti').mockImplementationOnce(() => {
throw unexpectedError
})
- const response = await hub.cookielessManager.doBatch([
+ const response = await infra.cookielessManager.doBatch([
{ event, team, message, headers: createTestEventHeaders() },
{ event: nonCookielessEvent, team, message, headers: createTestEventHeaders() },
])
@@ -678,13 +678,13 @@ describe('CookielessManager', () => {
// Batch has one cookieless event: pass 1 calls doHashForDay once (base hash),
// pass 3 calls it once (final hash with identify offset). We let pass 1 succeed
// then fail pass 3 to simulate a day-boundary race.
- const originalDoHashForDay = hub.cookielessManager.doHashForDay.bind(hub.cookielessManager)
+ const originalDoHashForDay = infra.cookielessManager.doHashForDay.bind(infra.cookielessManager)
const spy = jest
- .spyOn(hub.cookielessManager, 'doHashForDay')
+ .spyOn(infra.cookielessManager, 'doHashForDay')
.mockImplementationOnce((args) => originalDoHashForDay(args))
.mockImplementationOnce(() => Promise.resolve({ success: false, reason: 'date_out_of_range' }))
- const response = await hub.cookielessManager.doBatch([
+ const response = await infra.cookielessManager.doBatch([
{ event, team, message, headers: createTestEventHeaders() },
{ event: nonCookielessEvent, team, message, headers: createTestEventHeaders() },
])
@@ -724,8 +724,8 @@ describe('CookielessManager', () => {
// call 3: pass 3 re-hash for identifyEvent ← fail this one
// call 4: pass 3 re-hash for eventABitLater ← should succeed
let callCount = 0
- const originalDoHashForDay = hub.cookielessManager.doHashForDay.bind(hub.cookielessManager)
- const spy = jest.spyOn(hub.cookielessManager, 'doHashForDay').mockImplementation((args) => {
+ const originalDoHashForDay = infra.cookielessManager.doHashForDay.bind(infra.cookielessManager)
+ const spy = jest.spyOn(infra.cookielessManager, 'doHashForDay').mockImplementation((args) => {
callCount++
if (callCount === 3) {
return Promise.resolve({ success: false, reason: 'date_out_of_range' })
@@ -733,7 +733,7 @@ describe('CookielessManager', () => {
return originalDoHashForDay(args)
})
- const response = await hub.cookielessManager.doBatch([
+ const response = await infra.cookielessManager.doBatch([
{ event: identifyEvent, team, message, headers: createTestEventHeaders() },
{ event: eventABitLater, team, message, headers: createTestEventHeaders() },
])
@@ -771,7 +771,7 @@ describe('CookielessManager', () => {
uuid: new UUID7(oldTimestamp.getTime()).toString(),
})
- const response = await hub.cookielessManager.doBatch([
+ const response = await infra.cookielessManager.doBatch([
{
event: eventWithOldTimestamp,
team,
@@ -811,7 +811,7 @@ describe('CookielessManager', () => {
uuid: new UUID7(futureTimestamp.getTime()).toString(),
})
- const response = await hub.cookielessManager.doBatch([
+ const response = await infra.cookielessManager.doBatch([
{
event: eventWithFutureTimestamp,
team,
@@ -842,7 +842,7 @@ describe('CookielessManager', () => {
uuid: new UUID7(oldTimestamp.getTime()).toString(),
})
- const response = await hub.cookielessManager.doBatch([
+ const response = await infra.cookielessManager.doBatch([
{
event: eventWithOldTimestamp,
team,
@@ -917,7 +917,7 @@ describe('CookielessManager', () => {
sent_at: undefined as any,
})
- const response = await hub.cookielessManager.doBatch([
+ const response = await infra.cookielessManager.doBatch([
{
event: eventWithoutTimestamp,
team,
@@ -952,7 +952,7 @@ describe('CookielessManager', () => {
},
})
- const response = await hub.cookielessManager.doBatch([
+ const response = await infra.cookielessManager.doBatch([
{ event: eventWithoutUA, team, message, headers: createTestEventHeaders() },
])
expect(response.length).toBe(1)
@@ -983,7 +983,7 @@ describe('CookielessManager', () => {
},
})
- const response = await hub.cookielessManager.doBatch([
+ const response = await infra.cookielessManager.doBatch([
{ event: eventWithoutIP, team, message, headers: createTestEventHeaders() },
])
expect(response.length).toBe(1)
@@ -1014,7 +1014,7 @@ describe('CookielessManager', () => {
},
})
- const response = await hub.cookielessManager.doBatch([
+ const response = await infra.cookielessManager.doBatch([
{ event: eventWithoutHost, team, message, headers: createTestEventHeaders() },
])
expect(response.length).toBe(1)
diff --git a/nodejs/src/ingestion/common/steps/event-processing/process-personless-step.test.ts b/nodejs/src/ingestion/common/steps/event-processing/process-personless-step.test.ts
index ea60f53a6f14..6affd8df984b 100644
--- a/nodejs/src/ingestion/common/steps/event-processing/process-personless-step.test.ts
+++ b/nodejs/src/ingestion/common/steps/event-processing/process-personless-step.test.ts
@@ -13,16 +13,16 @@ import { BatchBoundPersonsStore } from '~/ingestion/common/persons/persons-store
import { PipelineResultType, isOkResult } from '~/ingestion/framework/results'
import { PluginEvent, Properties } from '~/plugin-scaffold'
import { createTestEventHeaders } from '~/tests/helpers/event-headers'
+import { IngestionTestInfra, createIngestionTestInfra } from '~/tests/helpers/ingestion-e2e'
import { createOrganization, createTeam, getTeam, resetTestDatabase } from '~/tests/helpers/sql'
-import { EventHeaders, Hub, InternalPerson, PropertiesLastOperation, PropertiesLastUpdatedAt, Team } from '~/types'
-import { closeHub, createHub } from '~/utils/db/hub'
+import { EventHeaders, InternalPerson, PropertiesLastOperation, PropertiesLastUpdatedAt, Team } from '~/types'
import { UUIDT } from '~/utils/utils'
import { createNormalizeEventStep } from './normalize-event-step'
import { createNormalizeProcessPersonFlagStep } from './normalize-process-person-flag-step'
import { ProcessPersonlessInput, createProcessPersonlessStep } from './process-personless-step'
-function createPersonOutputs(_hub: Hub) {
+function createPersonOutputs(_infra: IngestionTestInfra) {
return new IngestionOutputs({
[PERSONS_OUTPUT]: new SingleIngestionOutput(PERSONS_OUTPUT, KAFKA_PERSON, mockProducer, 'test'),
[PERSON_DISTINCT_IDS_OUTPUT]: new SingleIngestionOutput(
@@ -35,7 +35,7 @@ function createPersonOutputs(_hub: Hub) {
}
async function createPerson(
- hub: Hub,
+ infra: IngestionTestInfra,
createdAt: DateTime,
properties: Properties,
propertiesLastUpdatedAt: PropertiesLastUpdatedAt,
@@ -47,7 +47,7 @@ async function createPerson(
primaryDistinctId: { distinctId: string; version?: number },
extraDistinctIds?: { distinctId: string; version?: number }[]
): Promise<InternalPerson> {
- const personRepository = new PostgresPersonRepository(hub.postgres)
+ const personRepository = new PostgresPersonRepository(infra.postgres)
const result = await personRepository.createPerson(
createdAt,
properties,
@@ -63,13 +63,13 @@ async function createPerson(
if (!result.success) {
throw new Error('Failed to create person')
}
- const personOutputs = createPersonOutputs(hub)
+ const personOutputs = createPersonOutputs(infra)
await Promise.all(result.messages.map((msg) => personOutputs.produce(msg.output, { value: msg.value, key: null })))
return result.person
}
describe('createProcessPersonlessStep', () => {
- let hub: Hub
+ let infra: IngestionTestInfra
let teamId: number
let team: Team
let pluginEvent: PluginEvent
@@ -78,12 +78,12 @@ describe('createProcessPersonlessStep', () => {
beforeEach(async () => {
await resetTestDatabase()
- hub = await createHub()
- const organizationId = await createOrganization(hub.postgres)
- teamId = await createTeam(hub.postgres, organizationId)
- team = (await getTeam(hub.postgres, teamId))!
+ infra = await createIngestionTestInfra()
+ const organizationId = await createOrganization(infra.postgres)
+ teamId = await createTeam(infra.postgres, organizationId)
+ team = (await getTeam(infra.postgres, teamId))!
- const personRepository = new PostgresPersonRepository(hub.postgres)
+ const personRepository = new PostgresPersonRepository(infra.postgres)
const storeOutputs = new IngestionOutputs({
[PERSONS_OUTPUT]: new SingleIngestionOutput(PERSONS_OUTPUT, KAFKA_PERSON, mockProducer, 'test'),
[PERSON_DISTINCT_IDS_OUTPUT]: new SingleIngestionOutput(
@@ -116,7 +116,7 @@ describe('createProcessPersonlessStep', () => {
})
afterEach(async () => {
- await closeHub(hub)
+ await infra.close()
})
const createInput = (overrides: Partial<ProcessPersonlessInput> = {}): ProcessPersonlessInput => ({
@@ -156,7 +156,7 @@ describe('createProcessPersonlessStep', () => {
it('keeps the event personful when a person already exists', async () => {
const personUuid = new UUIDT().toString()
- await createPerson(hub, timestamp, { name: 'John' }, {}, {}, teamId, null, false, personUuid, {
+ await createPerson(infra, timestamp, { name: 'John' }, {}, {}, teamId, null, false, personUuid, {
distinctId: pluginEvent.distinct_id,
})
@@ -286,7 +286,7 @@ describe('createProcessPersonlessStep', () => {
it('keeps the event personful when the distinct ID turns out to be merged', async () => {
const personUuid = new UUIDT().toString()
- const person = await createPerson(hub, timestamp, {}, {}, {}, teamId, null, false, personUuid, {
+ const person = await createPerson(infra, timestamp, {}, {}, {}, teamId, null, false, personUuid, {
distinctId: 'merge-target',
})
@@ -427,7 +427,7 @@ describe('createProcessPersonlessStep', () => {
it('returns existing person with empty properties when person exists', async () => {
const personUuid = new UUIDT().toString()
- await createPerson(hub, timestamp, { name: 'John' }, {}, {}, teamId, null, false, personUuid, {
+ await createPerson(infra, timestamp, { name: 'John' }, {}, {}, teamId, null, false, personUuid, {
distinctId: pluginEvent.distinct_id,
})
@@ -471,7 +471,7 @@ describe('createProcessPersonlessStep', () => {
const personUuid = new UUIDT().toString()
const personCreatedAt = DateTime.fromISO('2020-02-23T02:00:00Z')
- await createPerson(hub, personCreatedAt, {}, {}, {}, teamId, null, false, personUuid, {
+ await createPerson(infra, personCreatedAt, {}, {}, {}, teamId, null, false, personUuid, {
distinctId: pluginEvent.distinct_id,
})
@@ -490,7 +490,7 @@ describe('createProcessPersonlessStep', () => {
const personUuid = new UUIDT().toString()
const personCreatedAt = DateTime.fromISO('2020-02-23T02:14:30Z')
- await createPerson(hub, personCreatedAt, {}, {}, {}, teamId, null, false, personUuid, {
+ await createPerson(infra, personCreatedAt, {}, {}, {}, teamId, null, false, personUuid, {
distinctId: pluginEvent.distinct_id,
})
@@ -511,7 +511,7 @@ describe('createProcessPersonlessStep', () => {
const personUuid = new UUIDT().toString()
const personCreatedAt = DateTime.fromISO('2020-02-23T02:00:00Z')
- await createPerson(hub, personCreatedAt, {}, {}, {}, teamId, null, false, personUuid, {
+ await createPerson(infra, personCreatedAt, {}, {}, {}, teamId, null, false, personUuid, {
distinctId: pluginEvent.distinct_id,
})
@@ -533,7 +533,7 @@ describe('createProcessPersonlessStep', () => {
const personCreatedAt = DateTime.fromISO('2020-02-20T00:00:00Z')
const person = await createPerson(
- hub,
+ infra,
personCreatedAt,
{ name: 'John' },
{},
diff --git a/nodejs/src/ingestion/ingestion-consumer.test.ts b/nodejs/src/ingestion/ingestion-consumer.test.ts
index 41ffda60952c..0c8fdab5886e 100644
--- a/nodejs/src/ingestion/ingestion-consumer.test.ts
+++ b/nodejs/src/ingestion/ingestion-consumer.test.ts
@@ -18,11 +18,11 @@ import {
import { BatchWritingPersonsStore } from '~/ingestion/common/persons/batch-writing-person-store'
import { createPrepareEventStep } from '~/ingestion/common/steps/event-processing/prepare-event-step'
import { createAiEventSubpipeline } from '~/ingestion/pipelines/ai'
+import { IngestionTestInfra, createIngestionTestInfra } from '~/tests/helpers/ingestion-e2e'
import { createTestIngestionOutputs, createTestMonitoringOutputs } from '~/tests/helpers/ingestion-outputs'
import { forSnapshot } from '~/tests/helpers/snapshots'
import { createTeam, fetchPostgresPersons, getFirstTeam, getTeam, resetTestDatabase } from '~/tests/helpers/sql'
-import { CookielessServerHashMode, Hub, PipelineEvent, Team } from '~/types'
-import { closeHub, createHub } from '~/utils/db/hub'
+import { CookielessServerHashMode, PipelineEvent, Team } from '~/types'
import { PostgresUse } from '~/utils/db/postgres'
import { parseJSON } from '~/utils/json-parse'
import { logger } from '~/utils/logger'
@@ -99,25 +99,25 @@ const createKafkaMessage = (event: PipelineEvent, token: string): Message => {
describe('IngestionConsumer', () => {
let ingester: IngestionConsumer
- let hub: Hub
+ let infra: IngestionTestInfra
let team: Team
let team2: Team
let fixedTime: DateTime
const createIngestionConsumer = async (
- hub: Hub,
+ infra: IngestionTestInfra,
overrides?: ConstructorParameters<typeof IngestionConsumer>[2]
) => {
const outputs = createTestIngestionOutputs(mockProducer)
const ingester = new IngestionConsumer(
- hub,
+ infra.config,
{
- ...hub,
+ ...infra,
outputs,
clickhouseGroupRepository: new ClickhouseGroupRepository(outputs),
aiSubpipelineFactory: createAiEventSubpipeline,
- hogTransformer: createHogTransformerService(hub, {
- ...hub,
+ hogTransformer: createHogTransformerService(infra.config, {
+ ...infra,
monitoringOutputs: createTestMonitoringOutputs(mockProducer),
}),
},
@@ -177,24 +177,24 @@ describe('IngestionConsumer', () => {
offsetIncrementer = 0
await resetTestDatabase()
- hub = await createHub()
+ infra = await createIngestionTestInfra()
// mockProducer = mockProducer
- team = await getFirstTeam(hub.postgres)
- const team2Id = await createTeam(hub.postgres, team.organization_id, 'THIS IS NOT A TOKEN FOR TEAM 3')
- team2 = (await getTeam(hub.postgres, team2Id))!
+ team = await getFirstTeam(infra.postgres)
+ const team2Id = await createTeam(infra.postgres, team.organization_id, 'THIS IS NOT A TOKEN FOR TEAM 3')
+ team2 = (await getTeam(infra.postgres, team2Id))!
jest.mocked(createPrepareEventStep).mockImplementation((...args) => {
const original = jest.requireActual('~/ingestion/common/steps/event-processing/prepare-event-step')
return original.createPrepareEventStep(...args)
})
- ingester = await createIngestionConsumer(hub)
+ ingester = await createIngestionConsumer(infra)
})
afterEach(async () => {
await ingester.stop()
- await closeHub(hub)
+ await infra.close()
})
afterAll(() => {
@@ -215,7 +215,7 @@ describe('IngestionConsumer', () => {
})
it('should process a cookieless event', async () => {
- await hub.postgres.query(
+ await infra.postgres.query(
PostgresUse.COMMON_WRITE,
`UPDATE posthog_team SET cookieless_server_hash_mode = $1 WHERE id = $2`,
[CookielessServerHashMode.Stateful, team.id],
@@ -227,7 +227,7 @@ describe('IngestionConsumer', () => {
})
it('should drop a cookieless event if the team has cookieless disabled', async () => {
- await hub.postgres.query(
+ await infra.postgres.query(
PostgresUse.COMMON_WRITE,
`UPDATE posthog_team SET cookieless_server_hash_mode = $1 WHERE id = $2`,
[CookielessServerHashMode.Disabled, team.id],
@@ -283,7 +283,7 @@ describe('IngestionConsumer', () => {
const now = () => DateTime.now().toMillis()
beforeEach(() => {
// Just to make it easy to see what is configured
- expect(hub.EVENT_OVERFLOW_BUCKET_CAPACITY).toEqual(1000)
+ expect(infra.config.EVENT_OVERFLOW_BUCKET_CAPACITY).toEqual(1000)
})
it('should emit to overflow if token and distinct_id are overflowed', async () => {
@@ -309,7 +309,7 @@ describe('IngestionConsumer', () => {
it('does not overflow if it is consuming from the overflow topic', async () => {
// Create a new consumer that consumes from the overflow topic
- const overflowIngester = await createIngestionConsumer(hub, {
+ const overflowIngester = await createIngestionConsumer(infra, {
INGESTION_CONSUMER_CONSUME_TOPIC: 'events_plugin_ingestion_overflow_test',
})
@@ -333,12 +333,12 @@ describe('IngestionConsumer', () => {
describe('stateful overflow redirect', () => {
it('refreshes Redis TTL when processing events in overflow lane', async () => {
// Enable stateful overflow
- hub.INGESTION_STATEFUL_OVERFLOW_ENABLED = true
- hub.INGESTION_STATEFUL_OVERFLOW_REDIS_TTL_SECONDS = 300
- hub.INGESTION_LANE = 'overflow'
+ infra.config.INGESTION_STATEFUL_OVERFLOW_ENABLED = true
+ infra.config.INGESTION_STATEFUL_OVERFLOW_REDIS_TTL_SECONDS = 300
+ infra.config.INGESTION_LANE = 'overflow'
// Create overflow lane consumer
- const overflowIngester = await createIngestionConsumer(hub, {
+ const overflowIngester = await createIngestionConsumer(infra, {
INGESTION_CONSUMER_CONSUME_TOPIC: 'events_plugin_ingestion_overflow_test',
})
@@ -346,7 +346,7 @@ describe('IngestionConsumer', () => {
expect(overflowIngester['overflowLaneTTLRefreshService']).toBeDefined()
// Pre-seed Redis with overflow flags (simulating main lane has flagged these keys)
- const redis = await hub.redisPool.acquire()
+ const redis = await infra.redisPool.acquire()
const redisKey = `@posthog/stateful-overflow/events:${team.api_token}:overflow-user`
await redis.set(redisKey, '1', 'EX', 300)
@@ -371,22 +371,22 @@ describe('IngestionConsumer', () => {
mockProducerObserver.getProducedKafkaMessagesForTopic('clickhouse_events_json_test')
).toHaveLength(1)
- await hub.redisPool.release(redis)
+ await infra.redisPool.release(redis)
await overflowIngester.stop()
})
it('does not create keys when refreshing TTL for non-existent keys', async () => {
// Enable stateful overflow
- hub.INGESTION_STATEFUL_OVERFLOW_ENABLED = true
- hub.INGESTION_STATEFUL_OVERFLOW_REDIS_TTL_SECONDS = 300
- hub.INGESTION_LANE = 'overflow'
+ infra.config.INGESTION_STATEFUL_OVERFLOW_ENABLED = true
+ infra.config.INGESTION_STATEFUL_OVERFLOW_REDIS_TTL_SECONDS = 300
+ infra.config.INGESTION_LANE = 'overflow'
// Create overflow lane consumer
- const overflowIngester = await createIngestionConsumer(hub, {
+ const overflowIngester = await createIngestionConsumer(infra, {
INGESTION_CONSUMER_CONSUME_TOPIC: 'events_plugin_ingestion_overflow_test',
})
- const redis = await hub.redisPool.acquire()
+ const redis = await infra.redisPool.acquire()
const redisKey = `@posthog/stateful-overflow/events:${team.api_token}:new-user`
// Verify key doesn't exist initially
@@ -404,7 +404,7 @@ describe('IngestionConsumer', () => {
mockProducerObserver.getProducedKafkaMessagesForTopic('clickhouse_events_json_test')
).toHaveLength(1)
- await hub.redisPool.release(redis)
+ await infra.redisPool.release(redis)
await overflowIngester.stop()
})
})
@@ -417,8 +417,8 @@ describe('IngestionConsumer', () => {
})
it('should force events with matching token:distinct_id to overflow', async () => {
- hub.INGESTION_FORCE_OVERFLOW_BY_TOKEN_DISTINCT_ID = `${team.api_token}:team1-user`
- ingester = await createIngestionConsumer(hub)
+ infra.config.INGESTION_FORCE_OVERFLOW_BY_TOKEN_DISTINCT_ID = `${team.api_token}:team1-user`
+ ingester = await createIngestionConsumer(infra)
const messages = [
createKafkaMessage(createEvent({ distinct_id: 'team1-user' }), team.api_token), // should overflow
@@ -452,8 +452,8 @@ describe('IngestionConsumer', () => {
})
it('should handle multiple token:distinct_id pairs in force overflow setting', async () => {
- hub.INGESTION_FORCE_OVERFLOW_BY_TOKEN_DISTINCT_ID = `${team.api_token}:user1,${team2.api_token}:user2`
- ingester = await createIngestionConsumer(hub)
+ infra.config.INGESTION_FORCE_OVERFLOW_BY_TOKEN_DISTINCT_ID = `${team.api_token}:user1,${team2.api_token}:user2`
+ ingester = await createIngestionConsumer(infra)
const messages = [
createKafkaMessage(createEvent({ distinct_id: 'user1' }), team.api_token), // should overflow
@@ -498,8 +498,8 @@ describe('IngestionConsumer', () => {
describe('via headers (preprocessing)', () => {
it('forces overflow using headers even if payload token/distinct_id differ', async () => {
- hub.INGESTION_FORCE_OVERFLOW_BY_TOKEN_DISTINCT_ID = `forced-token:forced-id`
- ingester = await createIngestionConsumer(hub)
+ infra.config.INGESTION_FORCE_OVERFLOW_BY_TOKEN_DISTINCT_ID = `forced-token:forced-id`
+ ingester = await createIngestionConsumer(infra)
const event = createEvent({ distinct_id: 'not-forced' })
const [message] = createKafkaMessages([event])
@@ -523,10 +523,10 @@ describe('IngestionConsumer', () => {
it('preserves partition locality when not skipping person; drops key when skipping person', async () => {
// Not skipping person -> key preserved
- hub.INGESTION_FORCE_OVERFLOW_BY_TOKEN_DISTINCT_ID = `forced-token:forced-id`
- hub.SKIP_PERSONS_PROCESSING_BY_TOKEN_DISTINCT_ID = ''
- hub.INGESTION_OVERFLOW_PRESERVE_PARTITION_LOCALITY = true
- ingester = await createIngestionConsumer(hub)
+ infra.config.INGESTION_FORCE_OVERFLOW_BY_TOKEN_DISTINCT_ID = `forced-token:forced-id`
+ infra.config.SKIP_PERSONS_PROCESSING_BY_TOKEN_DISTINCT_ID = ''
+ infra.config.INGESTION_OVERFLOW_PRESERVE_PARTITION_LOCALITY = true
+ ingester = await createIngestionConsumer(infra)
const eventA = createEvent({ distinct_id: 'not-forced' })
const [messageA] = createKafkaMessages([eventA])
@@ -547,10 +547,10 @@ describe('IngestionConsumer', () => {
// Skipping person -> key dropped when preserve locality disabled by config
await ingester.stop()
- hub.INGESTION_FORCE_OVERFLOW_BY_TOKEN_DISTINCT_ID = `forced-token:forced-id`
- hub.SKIP_PERSONS_PROCESSING_BY_TOKEN_DISTINCT_ID = `forced-token:forced-id`
- hub.INGESTION_OVERFLOW_PRESERVE_PARTITION_LOCALITY = false
- ingester = await createIngestionConsumer(hub)
+ infra.config.INGESTION_FORCE_OVERFLOW_BY_TOKEN_DISTINCT_ID = `forced-token:forced-id`
+ infra.config.SKIP_PERSONS_PROCESSING_BY_TOKEN_DISTINCT_ID = `forced-token:forced-id`
+ infra.config.INGESTION_OVERFLOW_PRESERVE_PARTITION_LOCALITY = false
+ ingester = await createIngestionConsumer(infra)
const eventB = createEvent({ distinct_id: 'not-forced' })
const [messageB] = createKafkaMessages([eventB])
@@ -659,8 +659,8 @@ describe('IngestionConsumer', () => {
describe('with DROP_EVENTS_BY_TOKEN_DISTINCT_ID drops events with matching token:distinct_id when only event keys are listed', () => {
beforeEach(async () => {
- hub.DROP_EVENTS_BY_TOKEN_DISTINCT_ID = `${team.api_token}:distinct-id-to-ignore,phc_other:distinct-id-to-ignore`
- ingester = await createIngestionConsumer(hub)
+ infra.config.DROP_EVENTS_BY_TOKEN_DISTINCT_ID = `${team.api_token}:distinct-id-to-ignore,phc_other:distinct-id-to-ignore`
+ ingester = await createIngestionConsumer(infra)
})
it('should drop events with matching token and distinct_id', async () => {
const messages = createKafkaMessages([
@@ -708,8 +708,8 @@ describe('IngestionConsumer', () => {
describe('with DROP_EVENTS_BY_TOKEN_DISTINCT_ID drops all team events when only token is listed', () => {
beforeEach(async () => {
const distinct_id_to_drop = 'team1_user_to_drop'
- hub.DROP_EVENTS_BY_TOKEN_DISTINCT_ID = `${team.api_token}:${distinct_id_to_drop},${team2.api_token}`
- ingester = await createIngestionConsumer(hub)
+ infra.config.DROP_EVENTS_BY_TOKEN_DISTINCT_ID = `${team.api_token}:${distinct_id_to_drop},${team2.api_token}`
+ ingester = await createIngestionConsumer(infra)
})
it('should still drop events with matching token and distinct_id (event key)', async () => {
@@ -769,7 +769,7 @@ describe('IngestionConsumer', () => {
describe('event batching', () => {
beforeEach(async () => {
- ingester = await createIngestionConsumer(hub)
+ ingester = await createIngestionConsumer(infra)
})
it('should validate historical_migration flag based on timestamp age', async () => {
@@ -919,10 +919,10 @@ describe('IngestionConsumer', () => {
it('should split AI events with large properties when splitting is enabled', async () => {
await ingester.stop()
- hub.INGESTION_AI_EVENT_SPLITTING_ENABLED = true
- hub.INGESTION_AI_EVENT_SPLITTING_TEAMS = '*'
- hub.INGESTION_AI_EVENT_SPLITTING_STRIP_HEAVY_TEAMS = '*'
- ingester = await createIngestionConsumer(hub)
+ infra.config.INGESTION_AI_EVENT_SPLITTING_ENABLED = true
+ infra.config.INGESTION_AI_EVENT_SPLITTING_TEAMS = '*'
+ infra.config.INGESTION_AI_EVENT_SPLITTING_STRIP_HEAVY_TEAMS = '*'
+ ingester = await createIngestionConsumer(infra)
const events = [
createEvent({
@@ -990,7 +990,7 @@ describe('IngestionConsumer', () => {
}
})
- const ingester = await createIngestionConsumer(hub)
+ const ingester = await createIngestionConsumer(infra)
await ingester.handleKafkaBatch(messages)
expect(jest.mocked(logger.error)).toHaveBeenCalledWith('🔥', 'Error processing message', expect.any(Object))
@@ -1009,7 +1009,7 @@ describe('IngestionConsumer', () => {
}
})
- const ingester = await createIngestionConsumer(hub)
+ const ingester = await createIngestionConsumer(infra)
await expect(ingester.handleKafkaBatch(messages)).rejects.toThrow()
})
@@ -1025,7 +1025,7 @@ describe('IngestionConsumer', () => {
}
})
- const ingester = await createIngestionConsumer(hub)
+ const ingester = await createIngestionConsumer(infra)
await ingester.handleKafkaBatch(messages)
// Should not produce to clickhouse
@@ -1048,7 +1048,7 @@ describe('IngestionConsumer', () => {
*/
beforeEach(async () => {
- ingester = await createIngestionConsumer(hub)
+ ingester = await createIngestionConsumer(infra)
})
const eventTests: [string, () => PipelineEvent[]][] = [
@@ -1261,7 +1261,7 @@ describe('IngestionConsumer', () => {
const insertHogFunction = async (hogFunction: Partial<HogFunctionType>) => {
const { hog, bytecode, name } = hogFunction
- const item = await _insertHogFunction(hub.postgres, team.id, {
+ const item = await _insertHogFunction(infra.postgres, team.id, {
hog,
bytecode,
name: name || 'Test Function',
@@ -1279,15 +1279,15 @@ describe('IngestionConsumer', () => {
bytecode: hogByteCode,
})
- ingester = await createIngestionConsumer(hub)
+ ingester = await createIngestionConsumer(infra)
})
it(
'should call hogwatcher state caching methods and observe results when hogwatcher is enabled (sample rate = 1)',
async () => {
// Create a new ingester with the sample rate we want to test
- hub.CDP_HOG_WATCHER_SAMPLE_RATE = 1
- const localIngester = await createIngestionConsumer(hub)
+ infra.config.CDP_HOG_WATCHER_SAMPLE_RATE = 1
+ const localIngester = await createIngestionConsumer(infra)
// Create spies for methods after the service is configured. The consumer exposes the
// transformer via its interface, so cast to the concrete service for these internal spies.
@@ -1332,8 +1332,8 @@ describe('IngestionConsumer', () => {
'should not call hogwatcher state caching methods when hogwatcher is disabled (sample rate = 0)',
async () => {
// Create a new ingester with the sample rate we want to test
- hub.CDP_HOG_WATCHER_SAMPLE_RATE = 0
- const localIngester = await createIngestionConsumer(hub)
+ infra.config.CDP_HOG_WATCHER_SAMPLE_RATE = 0
+ const localIngester = await createIngestionConsumer(infra)
// Create spies for methods after the service is configured (cast to the concrete service)
const concreteTransformer = localIngester.hogTransformer as HogTransformerService
@@ -1588,7 +1588,7 @@ describe('IngestionConsumer', () => {
createKafkaMessages([createEvent({ properties: { $set: { name: 'Alice' } } })])
)
- const personsAfterBatch1 = await fetchPostgresPersons(hub.postgres, team.id)
+ const personsAfterBatch1 = await fetchPostgresPersons(infra.postgres, team.id)
expect(personsAfterBatch1).toHaveLength(1)
expect(personsAfterBatch1[0].properties).toMatchObject({ name: 'Alice' })
@@ -1596,7 +1596,7 @@ describe('IngestionConsumer', () => {
createKafkaMessages([createEvent({ properties: { $set: { email: '[email protected]' } } })])
)
- const personsAfterBatch2 = await fetchPostgresPersons(hub.postgres, team.id)
+ const personsAfterBatch2 = await fetchPostgresPersons(infra.postgres, team.id)
expect(personsAfterBatch2).toHaveLength(1)
expect(personsAfterBatch2[0].properties).toMatchObject({
name: 'Alice',
diff --git a/nodejs/src/ingestion/pipelines/errortracking/error-tracking-consumer.test.ts b/nodejs/src/ingestion/pipelines/errortracking/error-tracking-consumer.test.ts
index ac198265cbee..bc8cf99c32ca 100644
--- a/nodejs/src/ingestion/pipelines/errortracking/error-tracking-consumer.test.ts
+++ b/nodejs/src/ingestion/pipelines/errortracking/error-tracking-consumer.test.ts
@@ -8,9 +8,9 @@ import { IngestionOutputs } from '~/common/outputs/ingestion-outputs'
import { SingleIngestionOutput } from '~/common/outputs/single-ingestion-output'
import { PersonReadRepository } from '~/common/persons/repositories/person-repository'
import { KafkaConsumer } from '~/kafka/consumer/consumer-v1'
+import { IngestionTestInfra, createIngestionTestInfra } from '~/tests/helpers/ingestion-e2e'
import { getFirstTeam, resetTestDatabase } from '~/tests/helpers/sql'
-import { Hub, PipelineEvent, Team } from '~/types'
-import { closeHub, createHub } from '~/utils/db/hub'
+import { PipelineEvent, Team } from '~/types'
import { PostgresUse } from '~/utils/db/postgres'
import { ErrorTrackingSettingsManager } from '~/utils/error-tracking-settings-manager'
import { parseJSON } from '~/utils/json-parse'
@@ -131,41 +131,42 @@ const createKafkaMessage = (event: PipelineEvent, token: string): Message => {
describe('ErrorTrackingConsumer', () => {
let consumer: ErrorTrackingConsumer
- let hub: Hub
+ let infra: IngestionTestInfra
let team: Team
let fixedTime: DateTime
let mockHogTransformer: jest.Mocked<ErrorTrackingHogTransformer>
- const createConsumer = async (hub: Hub) => {
+ const createConsumer = async (infra: IngestionTestInfra) => {
const config = {
- groupId: hub.ERROR_TRACKING_CONSUMER_GROUP_ID,
- topic: hub.ERROR_TRACKING_CONSUMER_CONSUME_TOPIC,
- cymbalBaseUrl: hub.ERROR_TRACKING_CYMBAL_BASE_URL,
- cymbalTimeoutMs: hub.ERROR_TRACKING_CYMBAL_TIMEOUT_MS,
- cymbalMaxBodyBytes: hub.ERROR_TRACKING_CYMBAL_MAX_BODY_BYTES,
- lane: hub.INGESTION_LANE ?? ('main' as const),
+ groupId: infra.config.ERROR_TRACKING_CONSUMER_GROUP_ID,
+ topic: infra.config.ERROR_TRACKING_CONSUMER_CONSUME_TOPIC,
+ cymbalBaseUrl: infra.config.ERROR_TRACKING_CYMBAL_BASE_URL,
+ cymbalTimeoutMs: infra.config.ERROR_TRACKING_CYMBAL_TIMEOUT_MS,
+ cymbalMaxBodyBytes: infra.config.ERROR_TRACKING_CYMBAL_MAX_BODY_BYTES,
+ lane: infra.config.INGESTION_LANE ?? ('main' as const),
overflowEnabled:
- !!hub.ERROR_TRACKING_CONSUMER_OVERFLOW_TOPIC &&
- hub.ERROR_TRACKING_CONSUMER_OVERFLOW_TOPIC !== hub.ERROR_TRACKING_CONSUMER_CONSUME_TOPIC,
- overflowBucketCapacity: hub.ERROR_TRACKING_OVERFLOW_BUCKET_CAPACITY,
- overflowBucketReplenishRate: hub.ERROR_TRACKING_OVERFLOW_BUCKET_REPLENISH_RATE,
- statefulOverflowEnabled: hub.ERROR_TRACKING_STATEFUL_OVERFLOW_ENABLED,
- statefulOverflowRedisTTLSeconds: hub.ERROR_TRACKING_STATEFUL_OVERFLOW_REDIS_TTL_SECONDS,
- statefulOverflowLocalCacheTTLSeconds: hub.ERROR_TRACKING_STATEFUL_OVERFLOW_LOCAL_CACHE_TTL_SECONDS,
- preservePartitionLocality: hub.ERROR_TRACKING_OVERFLOW_PRESERVE_PARTITION_LOCALITY,
- pipeline: hub.INGESTION_PIPELINE ?? 'errortracking',
- rateLimiterEnabled: hub.ERROR_TRACKING_RATE_LIMITER_ENABLED,
- rateLimiterReportingMode: hub.ERROR_TRACKING_RATE_LIMITER_REPORTING_MODE,
- rateLimiterRedisHost: hub.ERROR_TRACKING_RATE_LIMITER_REDIS_HOST,
- rateLimiterRedisPort: hub.ERROR_TRACKING_RATE_LIMITER_REDIS_PORT,
- rateLimiterRedisTls: hub.ERROR_TRACKING_RATE_LIMITER_REDIS_TLS,
- rateLimiterTtlSeconds: hub.ERROR_TRACKING_RATE_LIMITER_TTL_SECONDS,
- perIssueGuardThreshold: hub.ERROR_TRACKING_PER_ISSUE_GUARD_THRESHOLD,
- perIssueGuardWindowTtlSeconds: hub.ERROR_TRACKING_PER_ISSUE_GUARD_WINDOW_TTL_SECONDS,
- perIssueGuardCooldownTtlSeconds: hub.ERROR_TRACKING_PER_ISSUE_GUARD_COOLDOWN_TTL_SECONDS,
- fallbackRedisUrl: hub.REDIS_URL,
- rateLimiterRedisPoolMinSize: hub.REDIS_POOL_MIN_SIZE,
- rateLimiterRedisPoolMaxSize: hub.REDIS_POOL_MAX_SIZE,
+ !!infra.config.ERROR_TRACKING_CONSUMER_OVERFLOW_TOPIC &&
+ infra.config.ERROR_TRACKING_CONSUMER_OVERFLOW_TOPIC !==
+ infra.config.ERROR_TRACKING_CONSUMER_CONSUME_TOPIC,
+ overflowBucketCapacity: infra.config.ERROR_TRACKING_OVERFLOW_BUCKET_CAPACITY,
+ overflowBucketReplenishRate: infra.config.ERROR_TRACKING_OVERFLOW_BUCKET_REPLENISH_RATE,
+ statefulOverflowEnabled: infra.config.ERROR_TRACKING_STATEFUL_OVERFLOW_ENABLED,
+ statefulOverflowRedisTTLSeconds: infra.config.ERROR_TRACKING_STATEFUL_OVERFLOW_REDIS_TTL_SECONDS,
+ statefulOverflowLocalCacheTTLSeconds: infra.config.ERROR_TRACKING_STATEFUL_OVERFLOW_LOCAL_CACHE_TTL_SECONDS,
+ preservePartitionLocality: infra.config.ERROR_TRACKING_OVERFLOW_PRESERVE_PARTITION_LOCALITY,
+ pipeline: infra.config.INGESTION_PIPELINE ?? 'errortracking',
+ rateLimiterEnabled: infra.config.ERROR_TRACKING_RATE_LIMITER_ENABLED,
+ rateLimiterReportingMode: infra.config.ERROR_TRACKING_RATE_LIMITER_REPORTING_MODE,
+ rateLimiterRedisHost: infra.config.ERROR_TRACKING_RATE_LIMITER_REDIS_HOST,
+ rateLimiterRedisPort: infra.config.ERROR_TRACKING_RATE_LIMITER_REDIS_PORT,
+ rateLimiterRedisTls: infra.config.ERROR_TRACKING_RATE_LIMITER_REDIS_TLS,
+ rateLimiterTtlSeconds: infra.config.ERROR_TRACKING_RATE_LIMITER_TTL_SECONDS,
+ perIssueGuardThreshold: infra.config.ERROR_TRACKING_PER_ISSUE_GUARD_THRESHOLD,
+ perIssueGuardWindowTtlSeconds: infra.config.ERROR_TRACKING_PER_ISSUE_GUARD_WINDOW_TTL_SECONDS,
+ perIssueGuardCooldownTtlSeconds: infra.config.ERROR_TRACKING_PER_ISSUE_GUARD_COOLDOWN_TTL_SECONDS,
+ fallbackRedisUrl: infra.config.REDIS_URL,
+ rateLimiterRedisPoolMinSize: infra.config.REDIS_POOL_MIN_SIZE,
+ rateLimiterRedisPoolMaxSize: infra.config.REDIS_POOL_MAX_SIZE,
}
// Create and store the mock so tests can configure it
mockHogTransformer = createMockHogTransformer()
@@ -173,7 +174,7 @@ describe('ErrorTrackingConsumer', () => {
outputs: new IngestionOutputs({
events: new SingleIngestionOutput(
'events',
- hub.ERROR_TRACKING_CONSUMER_OUTPUT_TOPIC,
+ infra.config.ERROR_TRACKING_CONSUMER_OUTPUT_TOPIC,
mockProducer,
'test'
),
@@ -183,10 +184,15 @@ describe('ErrorTrackingConsumer', () => {
mockProducer,
'test'
),
- dlq: new SingleIngestionOutput('dlq', hub.ERROR_TRACKING_CONSUMER_DLQ_TOPIC, mockProducer, 'test'),
+ dlq: new SingleIngestionOutput(
+ 'dlq',
+ infra.config.ERROR_TRACKING_CONSUMER_DLQ_TOPIC,
+ mockProducer,
+ 'test'
+ ),
overflow: new SingleIngestionOutput(
'overflow',
- hub.ERROR_TRACKING_CONSUMER_OVERFLOW_TOPIC || '',
+ infra.config.ERROR_TRACKING_CONSUMER_OVERFLOW_TOPIC || '',
mockProducer,
'test'
),
@@ -198,16 +204,16 @@ describe('ErrorTrackingConsumer', () => {
'test'
),
}),
- teamManager: hub.teamManager,
- errorTrackingSettingsManager: new ErrorTrackingSettingsManager(hub.postgres),
+ teamManager: infra.teamManager,
+ errorTrackingSettingsManager: new ErrorTrackingSettingsManager(infra.postgres),
hogTransformer: mockHogTransformer,
groupTypeManager: new ReadOnlyGroupTypeManager({
fetchGroupsByKeys: jest.fn().mockResolvedValue([]),
fetchGroupTypesByTeamIds: jest.fn().mockResolvedValue({}),
fetchGroupTypesByProjectIds: jest.fn().mockResolvedValue({}),
}),
- cookielessManager: hub.cookielessManager,
- redisPool: hub.redisPool,
+ cookielessManager: infra.cookielessManager,
+ redisPool: infra.redisPool,
personRepository: createMockPersonRepository(),
}
const consumer = new ErrorTrackingConsumer(config, deps)
@@ -248,15 +254,15 @@ describe('ErrorTrackingConsumer', () => {
offsetIncrementer = 0
await resetTestDatabase()
- hub = await createHub()
- team = await getFirstTeam(hub.postgres)
+ infra = await createIngestionTestInfra()
+ team = await getFirstTeam(infra.postgres)
- consumer = await createConsumer(hub)
+ consumer = await createConsumer(infra)
})
afterEach(async () => {
await consumer.stop()
- await closeHub(hub)
+ await infra.close()
mockProducerObserver.resetKafkaProducer()
})
@@ -433,7 +439,7 @@ describe('ErrorTrackingConsumer', () => {
projectRateLimit?: number | null
perIssueRateLimit?: number | null
}): Promise<void> => {
- await hub.postgres.query(
+ await infra.postgres.query(
PostgresUse.COMMON_WRITE,
`INSERT INTO posthog_errortrackingsettings
(team_id, project_rate_limit_value, project_rate_limit_bucket_size_minutes,
@@ -451,9 +457,9 @@ describe('ErrorTrackingConsumer', () => {
const enableRateLimiter = async (): Promise<void> => {
await consumer.stop()
- hub.ERROR_TRACKING_RATE_LIMITER_ENABLED = true
- hub.ERROR_TRACKING_RATE_LIMITER_REPORTING_MODE = false
- consumer = await createConsumer(hub)
+ infra.config.ERROR_TRACKING_RATE_LIMITER_ENABLED = true
+ infra.config.ERROR_TRACKING_RATE_LIMITER_REPORTING_MODE = false
+ consumer = await createConsumer(infra)
await consumer['rateLimiterRedis']!.useClient({ name: 'test-flush' }, async (client) => {
// Per-issue buckets are hash-tagged (`tokens/{teamId}/…`); the team-global
diff --git a/nodejs/src/ingestion/pipelines/errortracking/per-issue-guarded-rate-limiter.service.test.ts b/nodejs/src/ingestion/pipelines/errortracking/per-issue-guarded-rate-limiter.service.test.ts
index a37fd34e3dde..5307a05736e0 100644
--- a/nodejs/src/ingestion/pipelines/errortracking/per-issue-guarded-rate-limiter.service.test.ts
+++ b/nodejs/src/ingestion/pipelines/errortracking/per-issue-guarded-rate-limiter.service.test.ts
@@ -3,8 +3,7 @@ import { register } from 'prom-client'
import { deleteKeysWithPrefix } from '~/common/redis/_tests/redis'
import { RedisV2, createRedisV2PoolFromConfig } from '~/common/redis/redis-v2'
import { KeyedRateLimitRequest } from '~/common/services/keyed-rate-limiter.service'
-import { Hub } from '~/types'
-import { closeHub, createHub } from '~/utils/db/hub'
+import { defaultConfig } from '~/config/config'
import { logger } from '~/utils/logger'
import { PerIssueGuardedRateLimiterService } from './per-issue-guarded-rate-limiter.service'
@@ -15,7 +14,6 @@ describe('PerIssueGuardedRateLimiterService', () => {
jest.retryTimes(3)
let now: number
- let hub: Hub
let redis: RedisV2
const advanceTime = (ms: number) => {
@@ -23,25 +21,23 @@ describe('PerIssueGuardedRateLimiterService', () => {
mockNow.mockReturnValue(now)
}
- beforeEach(async () => {
- hub = await createHub()
+ beforeEach(() => {
now = 1720000000000
mockNow.mockReturnValue(now)
redis = createRedisV2PoolFromConfig({
- connection: hub.CDP_REDIS_HOST
+ connection: defaultConfig.CDP_REDIS_HOST
? {
- url: hub.CDP_REDIS_HOST,
- options: { port: hub.CDP_REDIS_PORT, password: hub.CDP_REDIS_PASSWORD },
+ url: defaultConfig.CDP_REDIS_HOST,
+ options: { port: defaultConfig.CDP_REDIS_PORT, password: defaultConfig.CDP_REDIS_PASSWORD },
}
- : { url: hub.REDIS_URL },
- poolMinSize: hub.REDIS_POOL_MIN_SIZE,
- poolMaxSize: hub.REDIS_POOL_MAX_SIZE,
+ : { url: defaultConfig.REDIS_URL },
+ poolMinSize: defaultConfig.REDIS_POOL_MIN_SIZE,
+ poolMaxSize: defaultConfig.REDIS_POOL_MAX_SIZE,
})
})
- afterEach(async () => {
- await closeHub(hub)
+ afterEach(() => {
jest.clearAllMocks()
})
diff --git a/nodejs/src/types.ts b/nodejs/src/types.ts
index 48ef2e22809e..58105ca1f05a 100644
--- a/nodejs/src/types.ts
+++ b/nodejs/src/types.ts
@@ -7,7 +7,6 @@ import { GroupTypeManager } from '~/common/groups/group-type-manager'
import { GroupRepository } from '~/common/groups/repositories/group-repository.interface'
import { PersonRepository } from '~/common/persons/repositories/person-repository'
import { QuotaLimiting } from '~/common/services/quota-limiting.service'
-import type { CookielessManager } from '~/ingestion/common/cookieless/cookieless-manager'
import type { ErrorTrackingConsumerConfig } from '~/ingestion/pipelines/errortracking/config'
import type { MetricsIngestionConsumerConfig } from '~/ingestion/pipelines/metrics/config'
import type { SessionRecordingApiConfig, SessionRecordingConfig } from '~/ingestion/pipelines/sessionreplay/config'
@@ -133,14 +132,12 @@ export interface HubServices {
postgres: PostgresRouter
redisPool: GenericPool<Redis>
posthogRedisPool: GenericPool<Redis>
- cookielessRedisPool: GenericPool<Redis>
teamManager: TeamManager
groupTypeManager: GroupTypeManager
groupRepository: GroupRepository
personRepository: PersonRepository
geoipService: GeoIPService
encryptedFields: EncryptedFields
- cookielessManager: CookielessManager
pubSub: PubSub
integrationManager: IntegrationManagerService
quotaLimiting: QuotaLimiting
diff --git a/nodejs/src/utils/db/hub.ts b/nodejs/src/utils/db/hub.ts
index 3af15e6fbe83..3e86588f2822 100644
--- a/nodejs/src/utils/db/hub.ts
+++ b/nodejs/src/utils/db/hub.ts
@@ -4,15 +4,10 @@ import { PostgresGroupRepository } from '~/common/groups/repositories/postgres-g
import { buildGroupRepository, buildPersonRepository, createPersonHogClient } from '~/common/personhog'
import { PostgresPersonRepository } from '~/common/persons/repositories/postgres-person-repository'
import { QuotaLimiting } from '~/common/services/quota-limiting.service'
-import { CookielessManager } from '~/ingestion/common/cookieless/cookieless-manager'
import { EncryptedFields } from '../../cdp/utils/encryption-utils'
import { defaultConfig } from '../../config/config'
-import {
- createCookielessRedisConnectionConfig,
- createIngestionRedisConnectionConfig,
- createPosthogRedisConnectionConfig,
-} from '../../config/redis-pools'
+import { createIngestionRedisConnectionConfig, createPosthogRedisConnectionConfig } from '../../config/redis-pools'
import { Hub, PluginsServerConfig } from '../../types'
import { isTestEnv } from '../env-utils'
import { GeoIPService } from '../geoip'
@@ -58,14 +53,6 @@ export async function createHub(config: Partial<PluginsServerConfig> = {}): Prom
})
logger.info('👍', `Ingestion Redis ready`)
- logger.info('🤔', `Connecting to cookieless Redis...`)
- const cookielessRedisPool = createRedisPoolFromConfig({
- connection: createCookielessRedisConnectionConfig(serverConfig),
- poolMinSize: serverConfig.REDIS_POOL_MIN_SIZE,
- poolMaxSize: serverConfig.REDIS_POOL_MAX_SIZE,
- })
- logger.info('👍', `Cookieless Redis ready`)
-
const teamManager = new TeamManager(postgres)
logger.info('🤔', `Connecting to PostHog Redis...`)
const posthogRedisPool = createRedisPoolFromConfig({
@@ -104,7 +91,6 @@ export async function createHub(config: Partial<PluginsServerConfig> = {}): Prom
const groupTypeManager = new GroupTypeManager(groupRepository, teamManager)
- const cookielessManager = new CookielessManager(serverConfig, cookielessRedisPool)
const geoipService = new GeoIPService(serverConfig.MMDB_FILE_LOCATION)
await geoipService.get()
const encryptedFields = new EncryptedFields(serverConfig.ENCRYPTION_SALT_KEYS)
@@ -116,14 +102,12 @@ export async function createHub(config: Partial<PluginsServerConfig> = {}): Prom
postgres,
redisPool,
posthogRedisPool,
- cookielessRedisPool,
groupTypeManager,
teamManager,
groupRepository,
personRepository,
geoipService,
encryptedFields,
- cookielessManager,
pubSub,
integrationManager,
quotaLimiting,
@@ -136,17 +120,9 @@ export const closeHub = async (hub: Hub): Promise<void> => {
logger.info('💤', 'Closing hub...')
logger.info('💤', 'Closing kafka, redis, postgres...')
await hub.pubSub.stop()
- await Promise.allSettled([
- hub.redisPool.drain(),
- hub.posthogRedisPool.drain(),
- hub.cookielessRedisPool.drain(),
- hub.postgres?.end(),
- ])
+ await Promise.allSettled([hub.redisPool.drain(), hub.posthogRedisPool.drain(), hub.postgres?.end()])
await hub.redisPool.clear()
await hub.posthogRedisPool.clear()
- await hub.cookielessRedisPool.clear()
- logger.info('💤', 'Closing cookieless manager...')
- hub.cookielessManager.shutdown()
if (isTestEnv()) {
// Break circular references to allow the hub to be GCed when running unit tests
diff --git a/nodejs/tests/helpers/ingestion-e2e.ts b/nodejs/tests/helpers/ingestion-e2e.ts
index b6d0c5d01195..9b61e4fa0bc0 100644
--- a/nodejs/tests/helpers/ingestion-e2e.ts
+++ b/nodejs/tests/helpers/ingestion-e2e.ts
@@ -332,6 +332,8 @@ export interface IngestionTestInfra {
encryptedFields: EncryptedFields
integrationManager: IntegrationManagerService
groupTypeManager: GroupTypeManager
+ /** Tears down every resource this infra owns (redis pools, postgres, pubsub, cookieless manager). */
+ close: () => Promise<void>
}
export interface TeamIngesterTestContext<T extends IngesterLike> {
@@ -353,7 +355,89 @@ export type BuildIngester<T extends IngesterLike> = (
) => T
/**
- * Builds a `test` factory that spins up an isolated team + hub + consumer per
+ * Builds the ingestion test infrastructure (postgres, redis, repos, managers) directly from
+ * primitive constructors — no hub. Mirrors how the ingestion servers wire their deps. Returns
+ * the infra plus a `close` that tears down every resource it owns.
+ */
+export async function createIngestionTestInfra(
+ configOverrides: Partial<PluginsServerConfig> = {}
+): Promise<IngestionTestInfra> {
+ const serverConfig: PluginsServerConfig = {
+ ...defaultConfig,
+ ...configOverrides,
+ }
+
+ const postgres = new PostgresRouter(serverConfig, serverConfig.PLUGIN_SERVER_MODE ?? undefined)
+ const redisPool = createRedisPoolFromConfig({
+ connection: createIngestionRedisConnectionConfig(serverConfig),
+ poolMinSize: serverConfig.REDIS_POOL_MIN_SIZE,
+ poolMaxSize: serverConfig.REDIS_POOL_MAX_SIZE,
+ })
+ const cookielessRedisPool = createRedisPoolFromConfig({
+ connection: createCookielessRedisConnectionConfig(serverConfig),
+ poolMinSize: serverConfig.REDIS_POOL_MIN_SIZE,
+ poolMaxSize: serverConfig.REDIS_POOL_MAX_SIZE,
+ })
+
+ const teamManager = new TeamManager(postgres)
+ const pubSub = new PubSub(redisPool)
+ await pubSub.start()
+
+ const personhogClient = createPersonHogClient(serverConfig)
+ const clientLabel = serverConfig.PLUGIN_SERVER_MODE ?? 'unknown'
+
+ const postgresGroupRepository = new PostgresGroupRepository(postgres)
+ const postgresPersonRepository = new PostgresPersonRepository(postgres, {
+ calculatePropertiesSize: serverConfig.PERSON_UPDATE_CALCULATE_PROPERTIES_SIZE,
+ })
+ const personRepository = buildPersonRepository(
+ personhogClient,
+ postgresPersonRepository,
+ serverConfig.PERSONHOG_PERSONS_ROLLOUT_PERCENTAGE,
+ serverConfig.PERSONHOG_PERSONS_ROLLOUT_TEAM_IDS,
+ clientLabel
+ )
+ const groupRepository = buildGroupRepository(
+ personhogClient,
+ postgresGroupRepository,
+ serverConfig.PERSONHOG_GROUPS_ROLLOUT_PERCENTAGE,
+ serverConfig.PERSONHOG_GROUPS_ROLLOUT_TEAM_IDS,
+ clientLabel
+ )
+ const groupTypeManager = new GroupTypeManager(groupRepository, teamManager)
+ const cookielessManager = new CookielessManager(serverConfig, cookielessRedisPool)
+ const geoipService = new GeoIPService(serverConfig.MMDB_FILE_LOCATION)
+ await geoipService.get()
+ const encryptedFields = new EncryptedFields(serverConfig.ENCRYPTION_SALT_KEYS)
+ const integrationManager = new IntegrationManagerService(pubSub, postgres, encryptedFields)
+
+ const close = async (): Promise<void> => {
+ await pubSub.stop()
+ await Promise.allSettled([redisPool.drain(), cookielessRedisPool.drain(), postgres.end()])
+ await redisPool.clear()
+ await cookielessRedisPool.clear()
+ cookielessManager.shutdown()
+ }
+
+ return {
+ config: serverConfig,
+ postgres,
+ redisPool,
+ teamManager,
+ groupRepository,
+ personRepository,
+ cookielessManager,
+ pubSub,
+ geoipService,
+ encryptedFields,
+ integrationManager,
+ groupTypeManager,
+ close,
+ }
+}
+
+/**
+ * Builds a `test` factory that spins up an isolated team + infra + consumer per
* test. The caller supplies the `buildIngester` function that constructs the
* consumer under test — different pipelines have different deps.
*/
@@ -367,55 +451,12 @@ export function createTestWithTeamIngester<T extends IngesterLike>(
testFn: (ctx: TeamIngesterTestContext<T>) => Promise<void>
) => {
test(name, async () => {
- const serverConfig: PluginsServerConfig = {
- ...defaultConfig,
+ const infra = await createIngestionTestInfra({
...baseConfig,
...config.pluginServerConfig,
- }
-
- const postgres = new PostgresRouter(serverConfig, serverConfig.PLUGIN_SERVER_MODE ?? undefined)
- const redisPool = createRedisPoolFromConfig({
- connection: createIngestionRedisConnectionConfig(serverConfig),
- poolMinSize: serverConfig.REDIS_POOL_MIN_SIZE,
- poolMaxSize: serverConfig.REDIS_POOL_MAX_SIZE,
- })
- const cookielessRedisPool = createRedisPoolFromConfig({
- connection: createCookielessRedisConnectionConfig(serverConfig),
- poolMinSize: serverConfig.REDIS_POOL_MIN_SIZE,
- poolMaxSize: serverConfig.REDIS_POOL_MAX_SIZE,
- })
-
- const teamManager = new TeamManager(postgres)
- const pubSub = new PubSub(redisPool)
- await pubSub.start()
-
- const personhogClient = createPersonHogClient(serverConfig)
- const clientLabel = serverConfig.PLUGIN_SERVER_MODE ?? 'unknown'
-
- const postgresGroupRepository = new PostgresGroupRepository(postgres)
- const postgresPersonRepository = new PostgresPersonRepository(postgres, {
- calculatePropertiesSize: serverConfig.PERSON_UPDATE_CALCULATE_PROPERTIES_SIZE,
})
- const personRepository = buildPersonRepository(
- personhogClient,
- postgresPersonRepository,
- serverConfig.PERSONHOG_PERSONS_ROLLOUT_PERCENTAGE,
- serverConfig.PERSONHOG_PERSONS_ROLLOUT_TEAM_IDS,
- clientLabel
- )
- const groupRepository = buildGroupRepository(
- personhogClient,
- postgresGroupRepository,
- serverConfig.PERSONHOG_GROUPS_ROLLOUT_PERCENTAGE,
- serverConfig.PERSONHOG_GROUPS_ROLLOUT_TEAM_IDS,
- clientLabel
- )
- const groupTypeManager = new GroupTypeManager(groupRepository, teamManager)
- const cookielessManager = new CookielessManager(serverConfig, cookielessRedisPool)
- const geoipService = new GeoIPService(serverConfig.MMDB_FILE_LOCATION)
- await geoipService.get()
- const encryptedFields = new EncryptedFields(serverConfig.ENCRYPTION_SALT_KEYS)
- const integrationManager = new IntegrationManagerService(pubSub, postgres, encryptedFields)
+ const { postgres, teamManager } = infra
+ const serverConfig = infra.config
const kafkaProducer = await KafkaProducerWrapper.create(serverConfig.KAFKA_CLIENT_RACK)
@@ -450,21 +491,6 @@ export function createTestWithTeamIngester<T extends IngesterLike>(
throw new Error(`Failed to fetch team ${newTeam.id} from database`)
}
- const infra: IngestionTestInfra = {
- config: serverConfig,
- postgres,
- redisPool,
- teamManager,
- groupRepository,
- personRepository,
- cookielessManager,
- pubSub,
- geoipService,
- encryptedFields,
- integrationManager,
- groupTypeManager,
- }
-
const ingester = buildIngester(infra, kafkaProducer)
// We don't actually use kafka so we skip instantiation for faster tests
;(ingester as unknown as { kafkaConsumer: unknown }).kafkaConsumer = {
@@ -479,11 +505,7 @@ export function createTestWithTeamIngester<T extends IngesterLike>(
} finally {
await ingester.stop()
await kafkaProducer.disconnect()
- await pubSub.stop()
- await Promise.allSettled([redisPool.drain(), cookielessRedisPool.drain(), postgres.end()])
- await redisPool.clear()
- await cookielessRedisPool.clear()
- cookielessManager.shutdown()
+ await infra.close()
}
})
}
diff --git a/nodejs/tests/ingestion/common/steps/event-processing/process-persons-step.integration.test.ts b/nodejs/tests/ingestion/common/steps/event-processing/process-persons-step.integration.test.ts
index 0a000c9f0650..f14b38b531c8 100644
--- a/nodejs/tests/ingestion/common/steps/event-processing/process-persons-step.integration.test.ts
+++ b/nodejs/tests/ingestion/common/steps/event-processing/process-persons-step.integration.test.ts
@@ -20,14 +20,14 @@ import {
import { parseEventTimestamp } from '~/ingestion/common/timestamps'
import { PipelineResultType, isDlqResult, isOkResult, isRedirectResult } from '~/ingestion/framework/results'
import { PluginEvent } from '~/plugin-scaffold'
+import { IngestionTestInfra, createIngestionTestInfra } from '~/tests/helpers/ingestion-e2e'
import { createOrganization, createTeam, fetchPostgresPersons, getTeam, resetTestDatabase } from '~/tests/helpers/sql'
-import { Hub, Person, Team } from '~/types'
-import { closeHub, createHub } from '~/utils/db/hub'
+import { Person, Team } from '~/types'
import { normalizeEvent, normalizeProcessPerson } from '~/utils/event'
import { UUIDT } from '~/utils/utils'
describe('createProcessPersonsStep', () => {
- let hub: Hub
+ let infra: IngestionTestInfra
let teamId: number
let team: Team
let pluginEvent: PluginEvent
@@ -48,12 +48,12 @@ describe('createProcessPersonsStep', () => {
beforeEach(async () => {
await resetTestDatabase()
- hub = await createHub()
- const organizationId = await createOrganization(hub.postgres)
- teamId = await createTeam(hub.postgres, organizationId)
- team = (await getTeam(hub.postgres, teamId))!
+ infra = await createIngestionTestInfra()
+ const organizationId = await createOrganization(infra.postgres)
+ teamId = await createTeam(infra.postgres, organizationId)
+ team = (await getTeam(infra.postgres, teamId))!
- personRepository = new PostgresPersonRepository(hub.postgres)
+ personRepository = new PostgresPersonRepository(infra.postgres)
personOutputs = new IngestionOutputs({
[PERSONS_OUTPUT]: new SingleIngestionOutput(PERSONS_OUTPUT, KAFKA_PERSON, mockProducer, 'test'),
[PERSON_DISTINCT_IDS_OUTPUT]: new SingleIngestionOutput(
@@ -90,7 +90,7 @@ describe('createProcessPersonsStep', () => {
})
afterEach(async () => {
- await closeHub(hub)
+ await infra.close()
})
const createInput = (overrides: Partial<ProcessPersonsInput> = {}): ProcessPersonsInput => ({
@@ -140,7 +140,7 @@ describe('createProcessPersonsStep', () => {
)
await personsStore.flush()
- const persons = await fetchPostgresPersons(hub.postgres, teamId)
+ const persons = await fetchPostgresPersons(infra.postgres, teamId)
expect(persons).toEqual([result.value.person])
}
})
@@ -194,7 +194,7 @@ describe('createProcessPersonsStep', () => {
)
await personsStore.flush()
- const persons = await fetchPostgresPersons(hub.postgres, teamId)
+ const persons = await fetchPostgresPersons(infra.postgres, teamId)
expect(persons).toEqual([result.value.person])
}
})
@@ -216,7 +216,7 @@ describe('createProcessPersonsStep', () => {
expect(result.sideEffects).toEqual([])
}
- const persons = await fetchPostgresPersons(hub.postgres, teamId)
+ const persons = await fetchPostgresPersons(infra.postgres, teamId)
expect(persons).toEqual([])
})
@@ -239,7 +239,7 @@ describe('createProcessPersonsStep', () => {
}
await personsStore.flush()
- const persons = await fetchPostgresPersons(hub.postgres, teamId)
+ const persons = await fetchPostgresPersons(infra.postgres, teamId)
expect(persons.length).toBe(1)
})
@@ -292,7 +292,7 @@ describe('createProcessPersonsStep', () => {
it('does not update last_seen_at when person_last_seen_at_enabled is not set', async () => {
await createPersonWithDistinctIds('my_id')
- const personsBefore = await fetchPostgresPersons(hub.postgres, teamId)
+ const personsBefore = await fetchPostgresPersons(infra.postgres, teamId)
const initialLastSeenAt = personsBefore[0].last_seen_at
const futureTimestamp = DateTime.utc().plus({ hours: 2 }).toISO()!
@@ -313,17 +313,17 @@ describe('createProcessPersonsStep', () => {
expect(result.type).toBe(PipelineResultType.OK)
await personsStore.flush()
- const persons = await fetchPostgresPersons(hub.postgres, teamId)
+ const persons = await fetchPostgresPersons(infra.postgres, teamId)
expect(persons).toHaveLength(1)
expect(persons[0].last_seen_at).toEqual(initialLastSeenAt)
})
it('updates last_seen_at when person_last_seen_at_enabled is true', async () => {
- const organizationId = await createOrganization(hub.postgres)
- const enabledTeamId = await createTeam(hub.postgres, organizationId, undefined, {
+ const organizationId = await createOrganization(infra.postgres)
+ const enabledTeamId = await createTeam(infra.postgres, organizationId, undefined, {
extra_settings: JSON.stringify({ person_last_seen_at_enabled: true }),
})
- const enabledTeam = (await getTeam(hub.postgres, enabledTeamId))!
+ const enabledTeam = (await getTeam(infra.postgres, enabledTeamId))!
await personRepository.createPerson(
DateTime.utc(),
@@ -357,7 +357,7 @@ describe('createProcessPersonsStep', () => {
expect(result.type).toBe(PipelineResultType.OK)
await personsStore.flush()
- const persons = await fetchPostgresPersons(hub.postgres, enabledTeamId)
+ const persons = await fetchPostgresPersons(infra.postgres, enabledTeamId)
expect(persons).toHaveLength(1)
expect(persons[0].last_seen_at).toEqual(futureTimestamp.startOf('hour'))
})
diff --git a/nodejs/tests/ingestion/person-properties-metadata.e2e.test.ts b/nodejs/tests/ingestion/person-properties-metadata.e2e.test.ts
index a87c62c8b608..7f0778df0e87 100644
--- a/nodejs/tests/ingestion/person-properties-metadata.e2e.test.ts
+++ b/nodejs/tests/ingestion/person-properties-metadata.e2e.test.ts
@@ -16,11 +16,11 @@ import { IngestionConsumer } from '~/ingestion/ingestion-consumer'
import { createAiEventSubpipeline } from '~/ingestion/pipelines/ai'
import { KafkaProducerWrapper } from '~/kafka/producer'
import { waitForExpect } from '~/tests/helpers/expectations'
+import { IngestionTestInfra, createIngestionTestInfra } from '~/tests/helpers/ingestion-e2e'
import { createTestIngestionOutputs, createTestMonitoringOutputs } from '~/tests/helpers/ingestion-outputs'
import { TEST_KAFKA_TOPICS, ensureKafkaTopics } from '~/tests/helpers/kafka'
import { createUserTeamAndOrganization, fetchPostgresPersons, resetTestDatabase } from '~/tests/helpers/sql'
-import { Hub, PipelineEvent, PluginsServerConfig, ProjectId, Team } from '~/types'
-import { closeHub, createHub } from '~/utils/db/hub'
+import { PipelineEvent, PluginsServerConfig, ProjectId, Team } from '~/types'
import { UUIDT } from '~/utils/utils'
jest.mock('~/utils/token-bucket', () => {
@@ -138,17 +138,17 @@ const createTestWithTeamIngester = (baseConfig: Partial<PluginsServerConfig> = {
config: { teamOverrides?: Partial<Team>; pluginServerConfig?: Partial<PluginsServerConfig> } = {},
testFn: (
ingester: IngestionConsumer,
- hub: Hub,
+ infra: IngestionTestInfra,
team: Team,
kafkaProducer: KafkaProducerWrapper
) => Promise<void>
) => {
test(name, async () => {
- const hub = await createHub({
+ const infra = await createIngestionTestInfra({
...baseConfig,
...config.pluginServerConfig,
})
- const kafkaProducer = await KafkaProducerWrapper.create(hub.KAFKA_CLIENT_RACK)
+ const kafkaProducer = await KafkaProducerWrapper.create(infra.config.KAFKA_CLIENT_RACK)
const teamId = Math.floor((Date.now() % 1000000000) + Math.random() * 1000000)
const userId = teamId
@@ -167,7 +167,7 @@ const createTestWithTeamIngester = (baseConfig: Partial<PluginsServerConfig> = {
const organizationMembershipId = new UUIDT().toString()
await createUserTeamAndOrganization(
- hub.postgres,
+ infra.postgres,
newTeam.id,
userId,
userUuid,
@@ -176,17 +176,17 @@ const createTestWithTeamIngester = (baseConfig: Partial<PluginsServerConfig> = {
config.teamOverrides
)
- const fetchedTeam = await hub.teamManager.getTeam(newTeam.id)
+ const fetchedTeam = await infra.teamManager.getTeam(newTeam.id)
if (!fetchedTeam) {
throw new Error(`Failed to fetch team ${newTeam.id} from database`)
}
const outputs = createTestIngestionOutputs(kafkaProducer)
- const ingester = new IngestionConsumer(hub, {
- ...hub,
+ const ingester = new IngestionConsumer(infra.config, {
+ ...infra,
aiSubpipelineFactory: createAiEventSubpipeline,
- hogTransformer: createHogTransformerService(hub, {
- ...hub,
+ hogTransformer: createHogTransformerService(infra.config, {
+ ...infra,
monitoringOutputs: createTestMonitoringOutputs(kafkaProducer),
}),
outputs,
@@ -200,10 +200,10 @@ const createTestWithTeamIngester = (baseConfig: Partial<PluginsServerConfig> = {
await ingester.start()
currentToken = fetchedTeam.api_token
- await testFn(ingester, hub, fetchedTeam, kafkaProducer)
+ await testFn(ingester, infra, fetchedTeam, kafkaProducer)
await ingester.stop()
await kafkaProducer.disconnect()
- await closeHub(hub)
+ await infra.close()
})
}
}
@@ -224,7 +224,7 @@ describe('Person properties_last_updated_at and properties_last_operation behavi
testWithTeamIngester(
'does set properties_last_updated_at and properties_last_operation when creating person via $set',
{},
- async (ingester, hub, team, _kafkaProducer) => {
+ async (ingester, infra, team, _kafkaProducer) => {
const distinctId = new UUIDT().toString()
const timestamp = DateTime.now().toMillis()
@@ -243,7 +243,7 @@ describe('Person properties_last_updated_at and properties_last_operation behavi
await waitForKafkaMessages(_kafkaProducer)
await waitForExpect(async () => {
- const persons = await fetchPostgresPersons(hub.postgres, team.id)
+ const persons = await fetchPostgresPersons(infra.postgres, team.id)
expect(persons.length).toBe(1)
const person = persons[0]
@@ -270,7 +270,7 @@ describe('Person properties_last_updated_at and properties_last_operation behavi
testWithTeamIngester(
'does set properties_last_updated_at and properties_last_operation when creating person via $identify',
{},
- async (ingester, hub, team, _kafkaProducer) => {
+ async (ingester, infra, team, _kafkaProducer) => {
const distinctId = new UUIDT().toString()
const timestamp = DateTime.now().toMillis()
@@ -290,7 +290,7 @@ describe('Person properties_last_updated_at and properties_last_operation behavi
await waitForKafkaMessages(_kafkaProducer)
await waitForExpect(async () => {
- const persons = await fetchPostgresPersons(hub.postgres, team.id)
+ const persons = await fetchPostgresPersons(infra.postgres, team.id)
expect(persons.length).toBe(1)
const person = persons[0]
@@ -317,7 +317,7 @@ describe('Person properties_last_updated_at and properties_last_operation behavi
testWithTeamIngester(
'DOES NOT update properties_last_updated_at when updating existing property after person creation',
{},
- async (ingester, hub, team, _kafkaProducer) => {
+ async (ingester, infra, team, _kafkaProducer) => {
const distinctId = new UUIDT().toString()
const t1 = DateTime.now().toMillis()
const t2 = t1 + 60000 // 1 minute later
@@ -339,7 +339,7 @@ describe('Person properties_last_updated_at and properties_last_operation behavi
// Wait for person to be created and capture the initial timestamp
let initialTimestamp: string | undefined
await waitForExpect(async () => {
- const persons = await fetchPostgresPersons(hub.postgres, team.id)
+ const persons = await fetchPostgresPersons(infra.postgres, team.id)
expect(persons.length).toBe(1)
expect(persons[0].properties.email).toBe('[email protected]')
initialTimestamp = persons[0].properties_last_updated_at?.email
@@ -362,7 +362,7 @@ describe('Person properties_last_updated_at and properties_last_operation behavi
// Verify property was updated but timestamp was NOT
await waitForExpect(async () => {
- const persons = await fetchPostgresPersons(hub.postgres, team.id)
+ const persons = await fetchPostgresPersons(infra.postgres, team.id)
expect(persons.length).toBe(1)
const person = persons[0]
@@ -381,7 +381,7 @@ describe('Person properties_last_updated_at and properties_last_operation behavi
testWithTeamIngester(
'DOES NOT add properties_last_updated_at entry when adding NEW property after person creation',
{},
- async (ingester, hub, team, _kafkaProducer) => {
+ async (ingester, infra, team, _kafkaProducer) => {
const distinctId = new UUIDT().toString()
const t1 = DateTime.now().toMillis()
const t2 = t1 + 60000 // 1 minute later
@@ -401,7 +401,7 @@ describe('Person properties_last_updated_at and properties_last_operation behavi
await waitForKafkaMessages(_kafkaProducer)
await waitForExpect(async () => {
- const persons = await fetchPostgresPersons(hub.postgres, team.id)
+ const persons = await fetchPostgresPersons(infra.postgres, team.id)
expect(persons.length).toBe(1)
expect(persons[0].properties_last_updated_at?.email).toBeDefined()
})
@@ -421,7 +421,7 @@ describe('Person properties_last_updated_at and properties_last_operation behavi
await waitForKafkaMessages(_kafkaProducer)
await waitForExpect(async () => {
- const persons = await fetchPostgresPersons(hub.postgres, team.id)
+ const persons = await fetchPostgresPersons(infra.postgres, team.id)
expect(persons.length).toBe(1)
const person = persons[0]
@@ -443,7 +443,7 @@ describe('Person properties_last_updated_at and properties_last_operation behavi
testWithTeamIngester(
'DOES NOT update properties_last_operation when updating existing property after person creation',
{},
- async (ingester, hub, team, _kafkaProducer) => {
+ async (ingester, infra, team, _kafkaProducer) => {
const distinctId = new UUIDT().toString()
const t1 = DateTime.now().toMillis()
const t2 = t1 + 60000 // 1 minute later
@@ -463,7 +463,7 @@ describe('Person properties_last_updated_at and properties_last_operation behavi
await waitForKafkaMessages(_kafkaProducer)
await waitForExpect(async () => {
- const persons = await fetchPostgresPersons(hub.postgres, team.id)
+ const persons = await fetchPostgresPersons(infra.postgres, team.id)
expect(persons.length).toBe(1)
expect(persons[0].properties.initial_value).toBe('first')
expect(persons[0].properties_last_operation?.initial_value).toBe('set_once')
@@ -488,7 +488,7 @@ describe('Person properties_last_updated_at and properties_last_operation behavi
await waitForKafkaMessages(_kafkaProducer)
await waitForExpect(async () => {
- const persons = await fetchPostgresPersons(hub.postgres, team.id)
+ const persons = await fetchPostgresPersons(infra.postgres, team.id)
expect(persons.length).toBe(1)
const person = persons[0]
@@ -510,7 +510,7 @@ describe('Person properties_last_updated_at and properties_last_operation behavi
testWithTeamIngester(
'DOES NOT add properties_last_operation entry when adding NEW property after person creation',
{},
- async (ingester, hub, team, _kafkaProducer) => {
+ async (ingester, infra, team, _kafkaProducer) => {
const distinctId = new UUIDT().toString()
const t1 = DateTime.now().toMillis()
const t2 = t1 + 60000 // 1 minute later
@@ -530,7 +530,7 @@ describe('Person properties_last_updated_at and properties_last_operation behavi
await waitForKafkaMessages(_kafkaProducer)
await waitForExpect(async () => {
- const persons = await fetchPostgresPersons(hub.postgres, team.id)
+ const persons = await fetchPostgresPersons(infra.postgres, team.id)
expect(persons.length).toBe(1)
expect(persons[0].properties_last_operation?.email).toBe('set')
})
@@ -550,7 +550,7 @@ describe('Person properties_last_updated_at and properties_last_operation behavi
await waitForKafkaMessages(_kafkaProducer)
await waitForExpect(async () => {
- const persons = await fetchPostgresPersons(hub.postgres, team.id)
+ const persons = await fetchPostgresPersons(infra.postgres, team.id)
expect(persons.length).toBe(1)
const person = persons[0]
@@ -572,7 +572,7 @@ describe('Person properties_last_updated_at and properties_last_operation behavi
testWithTeamIngester(
'$set can overwrite a property that was set with $set_once',
{},
- async (ingester, hub, team, _kafkaProducer) => {
+ async (ingester, infra, team, _kafkaProducer) => {
const distinctId = new UUIDT().toString()
const t1 = DateTime.now().toMillis()
const t2 = t1 + 60000 // 1 minute later
@@ -592,7 +592,7 @@ describe('Person properties_last_updated_at and properties_last_operation behavi
await waitForKafkaMessages(_kafkaProducer)
await waitForExpect(async () => {
- const persons = await fetchPostgresPersons(hub.postgres, team.id)
+ const persons = await fetchPostgresPersons(infra.postgres, team.id)
expect(persons.length).toBe(1)
expect(persons[0].properties.favorite_color).toBe('blue')
expect(persons[0].properties_last_operation?.favorite_color).toBe('set_once')
@@ -613,7 +613,7 @@ describe('Person properties_last_updated_at and properties_last_operation behavi
await waitForKafkaMessages(_kafkaProducer)
await waitForExpect(async () => {
- const persons = await fetchPostgresPersons(hub.postgres, team.id)
+ const persons = await fetchPostgresPersons(infra.postgres, team.id)
expect(persons.length).toBe(1)
const person = persons[0]
@@ -631,7 +631,7 @@ describe('Person properties_last_updated_at and properties_last_operation behavi
testWithTeamIngester(
'$unset can delete a property that was set with $set_once',
{},
- async (ingester, hub, team, _kafkaProducer) => {
+ async (ingester, infra, team, _kafkaProducer) => {
const distinctId = new UUIDT().toString()
const t1 = DateTime.now().toMillis()
const t2 = t1 + 60000 // 1 minute later
@@ -652,7 +652,7 @@ describe('Person properties_last_updated_at and properties_last_operation behavi
await waitForKafkaMessages(_kafkaProducer)
await waitForExpect(async () => {
- const persons = await fetchPostgresPersons(hub.postgres, team.id)
+ const persons = await fetchPostgresPersons(infra.postgres, team.id)
expect(persons.length).toBe(1)
expect(persons[0].properties.temp_setting).toBe('initial_value')
expect(persons[0].properties.email).toBe('[email protected]')
@@ -674,7 +674,7 @@ describe('Person properties_last_updated_at and properties_last_operation behavi
await waitForKafkaMessages(_kafkaProducer)
await waitForExpect(async () => {
- const persons = await fetchPostgresPersons(hub.postgres, team.id)
+ const persons = await fetchPostgresPersons(infra.postgres, team.id)
expect(persons.length).toBe(1)
const person = persons[0]
diff --git a/nodejs/tests/ingestion/person-updates-e2e.test.ts b/nodejs/tests/ingestion/person-updates-e2e.test.ts
index c434b4cf6443..12ee113b8756 100644
--- a/nodejs/tests/ingestion/person-updates-e2e.test.ts
+++ b/nodejs/tests/ingestion/person-updates-e2e.test.ts
@@ -22,11 +22,11 @@ import { createAiEventSubpipeline } from '~/ingestion/pipelines/ai'
import { KafkaProducerWrapper } from '~/kafka/producer'
import { Clickhouse } from '~/tests/helpers/clickhouse'
import { waitForExpect } from '~/tests/helpers/expectations'
+import { IngestionTestInfra, createIngestionTestInfra } from '~/tests/helpers/ingestion-e2e'
import { createTestIngestionOutputs, createTestMonitoringOutputs } from '~/tests/helpers/ingestion-outputs'
import { TEST_KAFKA_TOPICS, ensureKafkaTopics } from '~/tests/helpers/kafka'
import { createUserTeamAndOrganization, resetTestDatabase } from '~/tests/helpers/sql'
-import { Hub, PersonBatchWritingDbWriteMode, PipelineEvent, ProjectId, Team } from '~/types'
-import { closeHub, createHub } from '~/utils/db/hub'
+import { PersonBatchWritingDbWriteMode, PipelineEvent, ProjectId, Team } from '~/types'
import { UUIDT } from '~/utils/utils'
jest.mock('~/utils/token-bucket', () => {
@@ -171,7 +171,7 @@ const formatConfigName = (config: PersonUpdateConfig): string => {
describe.each(FLAG_COMBINATIONS)('Person Updates E2E ($#)', (config) => {
const configName = formatConfigName(config)
let clickhouse: Clickhouse
- let hub: Hub
+ let infra: IngestionTestInfra
let kafkaProducer: KafkaProducerWrapper
let ingester: IngestionConsumer
let team: Team
@@ -190,10 +190,10 @@ describe.each(FLAG_COMBINATIONS)('Person Updates E2E ($#)', (config) => {
})
beforeEach(async () => {
- hub = await createHub({
+ infra = await createIngestionTestInfra({
...config,
})
- kafkaProducer = await KafkaProducerWrapper.create(hub.KAFKA_CLIENT_RACK)
+ kafkaProducer = await KafkaProducerWrapper.create(infra.config.KAFKA_CLIENT_RACK)
const teamId = Math.floor((Date.now() % 1000000000) + Math.random() * 1000000)
const userId = teamId
@@ -211,7 +211,7 @@ describe.each(FLAG_COMBINATIONS)('Person Updates E2E ($#)', (config) => {
}
await createUserTeamAndOrganization(
- hub.postgres,
+ infra.postgres,
team.id,
userId,
userUuid,
@@ -220,7 +220,7 @@ describe.each(FLAG_COMBINATIONS)('Person Updates E2E ($#)', (config) => {
{ extra_settings: { person_last_seen_at_enabled: true } }
)
- const fetchedTeam = await hub.teamManager.getTeam(team.id)
+ const fetchedTeam = await infra.teamManager.getTeam(team.id)
if (!fetchedTeam) {
throw new Error(`Failed to fetch team ${team.id} from database`)
}
@@ -228,12 +228,23 @@ describe.each(FLAG_COMBINATIONS)('Person Updates E2E ($#)', (config) => {
currentToken = team.api_token
const outputs = createTestIngestionOutputs(kafkaProducer)
- ingester = new IngestionConsumer(hub, {
- ...hub,
+ ingester = new IngestionConsumer(infra.config, {
+ postgres: infra.postgres,
+ redisPool: infra.redisPool,
+ teamManager: infra.teamManager,
+ groupTypeManager: infra.groupTypeManager,
+ groupRepository: infra.groupRepository,
+ personRepository: infra.personRepository,
+ cookielessManager: infra.cookielessManager,
aiSubpipelineFactory: createAiEventSubpipeline,
- hogTransformer: createHogTransformerService(hub, {
- ...hub,
+ hogTransformer: createHogTransformerService(infra.config, {
+ geoipService: infra.geoipService,
+ postgres: infra.postgres,
+ pubSub: infra.pubSub,
+ encryptedFields: infra.encryptedFields,
+ integrationManager: infra.integrationManager,
monitoringOutputs: createTestMonitoringOutputs(kafkaProducer),
+ teamManager: infra.teamManager,
}),
outputs,
clickhouseGroupRepository: new ClickhouseGroupRepository(outputs),
@@ -250,7 +261,7 @@ describe.each(FLAG_COMBINATIONS)('Person Updates E2E ($#)', (config) => {
afterEach(async () => {
await ingester.stop()
await kafkaProducer.disconnect()
- await closeHub(hub)
+ await infra.close()
})
describe(configName, () => {
@@ -264,7 +275,7 @@ describe.each(FLAG_COMBINATIONS)('Person Updates E2E ($#)', (config) => {
await waitForKafkaMessages(kafkaProducer)
await waitForExpect(async () => {
- const person = await hub.personRepository.fetchPerson(team.id, distinctId)
+ const person = await infra.personRepository.fetchPerson(team.id, distinctId)
expect(person).toBeDefined()
expect(person!.team_id).toBe(team.id)
// last_seen_at should be set to an hour-rounded timestamp
@@ -296,7 +307,7 @@ describe.each(FLAG_COMBINATIONS)('Person Updates E2E ($#)', (config) => {
await waitForKafkaMessages(kafkaProducer)
await waitForExpect(async () => {
- const person = await hub.personRepository.fetchPerson(team.id, distinctId)
+ const person = await infra.personRepository.fetchPerson(team.id, distinctId)
expect(person).toBeDefined()
expect(person!.properties).toEqual(
expect.objectContaining({
@@ -337,7 +348,7 @@ describe.each(FLAG_COMBINATIONS)('Person Updates E2E ($#)', (config) => {
await waitForKafkaMessages(kafkaProducer)
await waitForExpect(async () => {
- const person = await hub.personRepository.fetchPerson(team.id, distinctId)
+ const person = await infra.personRepository.fetchPerson(team.id, distinctId)
expect(person).toBeDefined()
expect(person!.properties).toEqual(
expect.objectContaining({
@@ -369,7 +380,7 @@ describe.each(FLAG_COMBINATIONS)('Person Updates E2E ($#)', (config) => {
// Wait for person to be created
await waitForExpect(async () => {
- const person = await hub.personRepository.fetchPerson(team.id, distinctId)
+ const person = await infra.personRepository.fetchPerson(team.id, distinctId)
expect(person).toBeDefined()
expect(person!.properties).toEqual(
expect.objectContaining({
@@ -394,7 +405,7 @@ describe.each(FLAG_COMBINATIONS)('Person Updates E2E ($#)', (config) => {
await waitForKafkaMessages(kafkaProducer)
await waitForExpect(async () => {
- const person = await hub.personRepository.fetchPerson(team.id, distinctId)
+ const person = await infra.personRepository.fetchPerson(team.id, distinctId)
expect(person).toBeDefined()
expect(person!.properties).toEqual(
expect.objectContaining({
@@ -426,7 +437,7 @@ describe.each(FLAG_COMBINATIONS)('Person Updates E2E ($#)', (config) => {
await waitForKafkaMessages(kafkaProducer)
await waitForExpect(async () => {
- const person = await hub.personRepository.fetchPerson(team.id, distinctId)
+ const person = await infra.personRepository.fetchPerson(team.id, distinctId)
expect(person).toBeDefined()
expect(person!.properties).toEqual(
expect.objectContaining({
@@ -451,7 +462,7 @@ describe.each(FLAG_COMBINATIONS)('Person Updates E2E ($#)', (config) => {
await waitForKafkaMessages(kafkaProducer)
await waitForExpect(async () => {
- const person = await hub.personRepository.fetchPerson(team.id, distinctId)
+ const person = await infra.personRepository.fetchPerson(team.id, distinctId)
expect(person).toBeDefined()
// Value should remain unchanged
expect(person!.properties.first_seen).toBe('original_value')
@@ -478,7 +489,7 @@ describe.each(FLAG_COMBINATIONS)('Person Updates E2E ($#)', (config) => {
await waitForKafkaMessages(kafkaProducer)
await waitForExpect(async () => {
- const person = await hub.personRepository.fetchPerson(team.id, distinctId)
+ const person = await infra.personRepository.fetchPerson(team.id, distinctId)
expect(person).toBeDefined()
expect(person!.properties).toHaveProperty('remove_prop')
})
@@ -499,7 +510,7 @@ describe.each(FLAG_COMBINATIONS)('Person Updates E2E ($#)', (config) => {
await waitForKafkaMessages(kafkaProducer)
await waitForExpect(async () => {
- const person = await hub.personRepository.fetchPerson(team.id, distinctId)
+ const person = await infra.personRepository.fetchPerson(team.id, distinctId)
expect(person).toBeDefined()
expect(person!.properties).toEqual(
expect.objectContaining({
@@ -546,7 +557,7 @@ describe.each(FLAG_COMBINATIONS)('Person Updates E2E ($#)', (config) => {
await waitForKafkaMessages(kafkaProducer)
await waitForExpect(async () => {
- const person = await hub.personRepository.fetchPerson(team.id, distinctId)
+ const person = await infra.personRepository.fetchPerson(team.id, distinctId)
expect(person).toBeDefined()
expect(person!.properties).toEqual(
expect.objectContaining({
@@ -580,7 +591,7 @@ describe.each(FLAG_COMBINATIONS)('Person Updates E2E ($#)', (config) => {
await waitForKafkaMessages(kafkaProducer)
await waitForExpect(async () => {
- const person = await hub.personRepository.fetchPerson(team.id, distinctId)
+ const person = await infra.personRepository.fetchPerson(team.id, distinctId)
expect(person).toBeDefined()
expect(person!.last_seen_at).toBeDefined()
expect(person!.last_seen_at!.toMillis()).toBe(baseTime.toMillis())
@@ -596,7 +607,7 @@ describe.each(FLAG_COMBINATIONS)('Person Updates E2E ($#)', (config) => {
await waitForKafkaMessages(kafkaProducer)
await waitForExpect(async () => {
- const person = await hub.personRepository.fetchPerson(team.id, distinctId)
+ const person = await infra.personRepository.fetchPerson(team.id, distinctId)
expect(person).toBeDefined()
expect(person!.last_seen_at).toBeDefined()
expect(person!.last_seen_at!.toMillis()).toBe(baseTime.plus({ hours: 2 }).toMillis())
@@ -623,7 +634,7 @@ describe.each(FLAG_COMBINATIONS)('Person Updates E2E ($#)', (config) => {
await waitForKafkaMessages(kafkaProducer)
await waitForExpect(async () => {
- const person = await hub.personRepository.fetchPerson(team.id, distinctId)
+ const person = await infra.personRepository.fetchPerson(team.id, distinctId)
expect(person).toBeDefined()
expect(person!.last_seen_at!.toMillis()).toBe(baseTime.toMillis())
})
@@ -642,7 +653,7 @@ describe.each(FLAG_COMBINATIONS)('Person Updates E2E ($#)', (config) => {
await waitForKafkaMessages(kafkaProducer)
await waitForExpect(async () => {
- const person = await hub.personRepository.fetchPerson(team.id, distinctId)
+ const person = await infra.personRepository.fetchPerson(team.id, distinctId)
expect(person).toBeDefined()
// last_seen_at should remain unchanged
expect(person!.last_seen_at!.toMillis()).toBe(baseTime.toMillis())
@@ -664,7 +675,7 @@ describe.each(FLAG_COMBINATIONS)('Person Updates E2E ($#)', (config) => {
await waitForKafkaMessages(kafkaProducer)
await waitForExpect(async () => {
- const person = await hub.personRepository.fetchPerson(team.id, anonDistinctId)
+ const person = await infra.personRepository.fetchPerson(team.id, anonDistinctId)
expect(person).toBeDefined()
expect(person!.is_identified).toBe(false)
})
@@ -687,7 +698,7 @@ describe.each(FLAG_COMBINATIONS)('Person Updates E2E ($#)', (config) => {
await waitForExpect(async () => {
// After merge, the person should be identified and accessible via the identified distinct ID
- const person = await hub.personRepository.fetchPerson(team.id, identifiedDistinctId)
+ const person = await infra.personRepository.fetchPerson(team.id, identifiedDistinctId)
expect(person).toBeDefined()
expect(person!.is_identified).toBe(true)
})
@@ -703,7 +714,7 @@ describe.each(FLAG_COMBINATIONS)('Person Updates E2E ($#)', (config) => {
const disabledOrgMembershipId = new UUIDT().toString()
await createUserTeamAndOrganization(
- hub.postgres,
+ infra.postgres,
disabledTeamId,
disabledUserId,
disabledUserUuid,
@@ -711,7 +722,7 @@ describe.each(FLAG_COMBINATIONS)('Person Updates E2E ($#)', (config) => {
disabledOrgMembershipId
)
- const fetchedTeam = await hub.teamManager.getTeam(disabledTeamId)
+ const fetchedTeam = await infra.teamManager.getTeam(disabledTeamId)
if (!fetchedTeam) {
throw new Error(`Failed to fetch team ${disabledTeamId} from database`)
}
@@ -739,7 +750,7 @@ describe.each(FLAG_COMBINATIONS)('Person Updates E2E ($#)', (config) => {
let initialLastSeenAt: number | undefined
await waitForExpect(async () => {
- const person = await hub.personRepository.fetchPerson(team.id, distinctId)
+ const person = await infra.personRepository.fetchPerson(team.id, distinctId)
expect(person).toBeDefined()
initialLastSeenAt = person!.last_seen_at?.toMillis()
})
@@ -753,7 +764,7 @@ describe.each(FLAG_COMBINATIONS)('Person Updates E2E ($#)', (config) => {
await waitForKafkaMessages(kafkaProducer)
await waitForExpect(async () => {
- const person = await hub.personRepository.fetchPerson(team.id, distinctId)
+ const person = await infra.personRepository.fetchPerson(team.id, distinctId)
expect(person).toBeDefined()
expect(person!.last_seen_at?.toMillis()).toBe(initialLastSeenAt)
})
diff --git a/nodejs/tests/ingestion/pipelines/sessionreplay/consumer.e2e.test.ts b/nodejs/tests/ingestion/pipelines/sessionreplay/consumer.e2e.test.ts
index f117f9e41dc1..9ed4a7998098 100644
--- a/nodejs/tests/ingestion/pipelines/sessionreplay/consumer.e2e.test.ts
+++ b/nodejs/tests/ingestion/pipelines/sessionreplay/consumer.e2e.test.ts
@@ -30,11 +30,11 @@ import { REPLAY_EVENTS_OUTPUT, SESSION_FEATURES_OUTPUT } from '~/ingestion/pipel
import { KafkaProducerWrapper } from '~/kafka/producer'
import { Clickhouse } from '~/tests/helpers/clickhouse'
import { waitForExpect } from '~/tests/helpers/expectations'
+import { IngestionTestInfra, createIngestionTestInfra } from '~/tests/helpers/ingestion-e2e'
import { TEST_KAFKA_TOPICS, ensureKafkaTopics } from '~/tests/helpers/kafka'
import { forSnapshot } from '~/tests/helpers/snapshots'
import { createOrganization, createTeam, getFirstTeam, resetTestDatabase } from '~/tests/helpers/sql'
-import { Hub, Team } from '~/types'
-import { closeHub, createHub } from '~/utils/db/hub'
+import { Team } from '~/types'
import { PostgresRouter, PostgresUse } from '~/utils/db/postgres'
import { REDIS_KEY_PREFIX, RedisRestrictionType } from '~/utils/event-ingestion-restrictions/redis-schema'
import { parseJSON } from '~/utils/json-parse'
@@ -839,7 +839,7 @@ const testCases: TestCase[] = [
describe('Session Recording Consumer Integration', () => {
jest.setTimeout(60000)
- let hub: Hub
+ let infra: IngestionTestInfra
let team: Team
let s3Client: S3Client
let clickhouse: Clickhouse
@@ -850,8 +850,8 @@ describe('Session Recording Consumer Integration', () => {
}
async function createIngester(): Promise<IngesterWithProducers> {
- const kafkaMetadataProducer = await KafkaProducerWrapper.create(hub.KAFKA_CLIENT_RACK)
- const kafkaMessageProducer = await KafkaProducerWrapper.create(hub.KAFKA_CLIENT_RACK)
+ const kafkaMetadataProducer = await KafkaProducerWrapper.create(infra.config.KAFKA_CLIENT_RACK)
+ const kafkaMessageProducer = await KafkaProducerWrapper.create(infra.config.KAFKA_CLIENT_RACK)
const outputs = new IngestionOutputs({
[INGESTION_WARNINGS_OUTPUT]: new SingleIngestionOutput(
@@ -898,7 +898,13 @@ describe('Session Recording Consumer Integration', () => {
),
})
- const ingester = new SessionRecordingIngester(hub as any, hub.postgres, outputs, hub.redisPool, hub.redisPool)
+ const ingester = new SessionRecordingIngester(
+ infra.config as any,
+ infra.postgres,
+ outputs,
+ infra.redisPool,
+ infra.redisPool
+ )
return { ingester, kafkaMetadataProducer }
}
@@ -952,7 +958,7 @@ describe('Session Recording Consumer Integration', () => {
await ensureKafkaTopics(TEST_KAFKA_TOPICS)
await resetTestDatabase()
- hub = await createHub({
+ infra = await createIngestionTestInfra({
SESSION_RECORDING_V2_S3_BUCKET: TEST_CONFIG.S3_BUCKET,
SESSION_RECORDING_V2_S3_PREFIX: TEST_CONFIG.S3_PREFIX,
SESSION_RECORDING_V2_S3_ENDPOINT: TEST_CONFIG.S3_ENDPOINT,
@@ -964,10 +970,10 @@ describe('Session Recording Consumer Integration', () => {
SESSION_RECORDING_MAX_BATCH_AGE_MS: 1000,
})
- team = await getFirstTeam(hub.postgres)
+ team = await getFirstTeam(infra.postgres)
// Enable console log capture for the primary team so console log tests work
- await hub.postgres.query(
+ await infra.postgres.query(
PostgresUse.COMMON_WRITE,
'UPDATE posthog_team SET capture_console_log_opt_in = true WHERE id = $1',
[team.id],
@@ -975,12 +981,12 @@ describe('Session Recording Consumer Integration', () => {
)
// Create a second team with a known token that will have DROP_EVENT restriction
- const restrictedOrgId = await createOrganization(hub.postgres)
- await createTeam(hub.postgres, restrictedOrgId, RESTRICTED_TEAM_TOKEN)
+ const restrictedOrgId = await createOrganization(infra.postgres)
+ await createTeam(infra.postgres, restrictedOrgId, RESTRICTED_TEAM_TOKEN)
// Set up DROP_EVENT restriction in Redis for the restricted team
// The ingester's restriction manager will read this when it starts
- const redisClient = await hub.redisPool.acquire()
+ const redisClient = await infra.redisPool.acquire()
try {
const key = `${REDIS_KEY_PREFIX}:${RedisRestrictionType.DROP_EVENT_FROM_INGESTION}`
const restriction = [
@@ -992,24 +998,24 @@ describe('Session Recording Consumer Integration', () => {
]
await redisClient.set(key, JSON.stringify(restriction))
} finally {
- await hub.redisPool.release(redisClient)
+ await infra.redisPool.release(redisClient)
}
})
afterAll(async () => {
// Clean up the DROP_EVENT restriction from Redis
- if (hub?.redisPool) {
- const redisClient = await hub.redisPool.acquire()
+ if (infra?.redisPool) {
+ const redisClient = await infra.redisPool.acquire()
try {
const key = `${REDIS_KEY_PREFIX}:${RedisRestrictionType.DROP_EVENT_FROM_INGESTION}`
await redisClient.del(key)
} finally {
- await hub.redisPool.release(redisClient)
+ await infra.redisPool.release(redisClient)
}
}
- if (hub) {
- await closeHub(hub)
+ if (infra) {
+ await infra.close()
}
await cleanupS3TestData(s3Client)
s3Client?.destroy()
@@ -1029,8 +1035,8 @@ describe('Session Recording Consumer Integration', () => {
const expectedSessionIds =
expectedOutcome === 'written' ? new Set(payloadConfigs.map((p) => p.sessionId)) : new Set<string>()
- // Create a fresh producer for this test (not shared with hub)
- const testProducer = await KafkaProducerWrapper.create(hub.KAFKA_CLIENT_RACK)
+ // Create a fresh producer for this test (not shared with infra)
+ const testProducer = await KafkaProducerWrapper.create(infra.config.KAFKA_CLIENT_RACK)
// Create and start ingester
const { ingester, kafkaMetadataProducer } = await createIngester()
diff --git a/nodejs/tests/ingestion/utils/overflow-redirect/overflow-redis-repository.integration.test.ts b/nodejs/tests/ingestion/utils/overflow-redirect/overflow-redis-repository.integration.test.ts
index 43d50d2ec34a..84ffcc9fef47 100644
--- a/nodejs/tests/ingestion/utils/overflow-redirect/overflow-redis-repository.integration.test.ts
+++ b/nodejs/tests/ingestion/utils/overflow-redirect/overflow-redis-repository.integration.test.ts
@@ -1,26 +1,25 @@
import { RedisOverflowRepository, redisKey } from '~/ingestion/utils/overflow-redirect/overflow-redis-repository'
-import { Hub } from '~/types'
-import { closeHub, createHub } from '~/utils/db/hub'
+import { IngestionTestInfra, createIngestionTestInfra } from '~/tests/helpers/ingestion-e2e'
describe('RedisOverflowRepository (integration)', () => {
- let hub: Hub
+ let infra: IngestionTestInfra
let repository: RedisOverflowRepository
beforeEach(async () => {
- hub = await createHub()
+ infra = await createIngestionTestInfra()
- const redis = await hub.redisPool.acquire()
+ const redis = await infra.redisPool.acquire()
await redis.flushdb()
- await hub.redisPool.release(redis)
+ await infra.redisPool.release(redis)
repository = new RedisOverflowRepository({
- redisPool: hub.redisPool,
+ redisPool: infra.redisPool,
redisTTLSeconds: 300,
})
})
afterEach(async () => {
- await closeHub(hub)
+ await infra.close()
})
describe('batchCheck', () => {
@@ -31,9 +30,9 @@ describe('RedisOverflowRepository (integration)', () => {
})
it('returns true for keys that exist', async () => {
- const redis = await hub.redisPool.acquire()
+ const redis = await infra.redisPool.acquire()
await redis.set(redisKey('events', 'token1', 'user1'), '1')
- await hub.redisPool.release(redis)
+ await infra.redisPool.release(redis)
const result = await repository.batchCheck('events', [{ token: 'token1', distinctId: 'user1' }])
@@ -41,9 +40,9 @@ describe('RedisOverflowRepository (integration)', () => {
})
it('handles mixed existing and non-existing keys', async () => {
- const redis = await hub.redisPool.acquire()
+ const redis = await infra.redisPool.acquire()
await redis.set(redisKey('events', 'token1', 'user2'), '1')
- await hub.redisPool.release(redis)
+ await infra.redisPool.release(redis)
const result = await repository.batchCheck('events', [
{ token: 'token1', distinctId: 'user1' },
@@ -67,10 +66,10 @@ describe('RedisOverflowRepository (integration)', () => {
it('creates keys with TTL', async () => {
await repository.batchFlag('events', [{ token: 'token1', distinctId: 'user1' }])
- const redis = await hub.redisPool.acquire()
+ const redis = await infra.redisPool.acquire()
const value = await redis.get(redisKey('events', 'token1', 'user1'))
const ttl = await redis.ttl(redisKey('events', 'token1', 'user1'))
- await hub.redisPool.release(redis)
+ await infra.redisPool.release(redis)
expect(value).toBe('1')
expect(ttl).toBeGreaterThan(0)
@@ -83,10 +82,10 @@ describe('RedisOverflowRepository (integration)', () => {
{ token: 'token1', distinctId: 'user2' },
])
- const redis = await hub.redisPool.acquire()
+ const redis = await infra.redisPool.acquire()
const val1 = await redis.get(redisKey('events', 'token1', 'user1'))
const val2 = await redis.get(redisKey('events', 'token1', 'user2'))
- await hub.redisPool.release(redis)
+ await infra.redisPool.release(redis)
expect(val1).toBe('1')
expect(val2).toBe('1')
@@ -100,17 +99,17 @@ describe('RedisOverflowRepository (integration)', () => {
describe('batchRefreshTTL', () => {
it('refreshes TTL for existing keys', async () => {
- const redis = await hub.redisPool.acquire()
+ const redis = await infra.redisPool.acquire()
// Set key with short TTL
await redis.set(redisKey('events', 'token1', 'user1'), '1', 'EX', 10)
- await hub.redisPool.release(redis)
+ await infra.redisPool.release(redis)
// Refresh TTL to 300
await repository.batchRefreshTTL('events', [{ token: 'token1', distinctId: 'user1' }])
- const redis2 = await hub.redisPool.acquire()
+ const redis2 = await infra.redisPool.acquire()
const ttl = await redis2.ttl(redisKey('events', 'token1', 'user1'))
- await hub.redisPool.release(redis2)
+ await infra.redisPool.release(redis2)
// TTL should now be close to 300 (the configured value)
expect(ttl).toBeGreaterThan(200)
@@ -120,27 +119,27 @@ describe('RedisOverflowRepository (integration)', () => {
it('does not create keys that do not exist', async () => {
await repository.batchRefreshTTL('events', [{ token: 'token1', distinctId: 'nonexistent' }])
- const redis = await hub.redisPool.acquire()
+ const redis = await infra.redisPool.acquire()
const exists = await redis.exists(redisKey('events', 'token1', 'nonexistent'))
- await hub.redisPool.release(redis)
+ await infra.redisPool.release(redis)
expect(exists).toBe(0)
})
it('handles mixed existing and non-existing keys', async () => {
- const redis = await hub.redisPool.acquire()
+ const redis = await infra.redisPool.acquire()
await redis.set(redisKey('events', 'token1', 'existing'), '1', 'EX', 10)
- await hub.redisPool.release(redis)
+ await infra.redisPool.release(redis)
await repository.batchRefreshTTL('events', [
{ token: 'token1', distinctId: 'existing' },
{ token: 'token1', distinctId: 'nonexistent' },
])
- const redis2 = await hub.redisPool.acquire()
+ const redis2 = await infra.redisPool.acquire()
const existingTTL = await redis2.ttl(redisKey('events', 'token1', 'existing'))
const nonexistentExists = await redis2.exists(redisKey('events', 'token1', 'nonexistent'))
- await hub.redisPool.release(redis2)
+ await infra.redisPool.release(redis2)
expect(existingTTL).toBeGreaterThan(200)
expect(nonexistentExists).toBe(0)