:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(cdp): drop the customer.io PluginStorage dependency (#97309)
Ben Whitef10091fe0d13
diff --git a/nodejs/src/cdp/consumers/cdp-legacy-event.consumer.test.ts b/nodejs/src/cdp/consumers/cdp-legacy-event.consumer.test.tsindex a8dca722f8aa..be50eb1acc61 100644--- a/nodejs/src/cdp/consumers/cdp-legacy-event.consumer.test.ts+++ b/nodejs/src/cdp/consumers/cdp-legacy-event.consumer.test.ts@@ -200,7 +200,6 @@ describe('CdpLegacyEventsConsumer', () => {customerioSiteId: { value: '1234567890' },customerioToken: { value: 'cio-token' },email: { value: '[email protected]' },- legacy_plugin_config_id: { value: pluginConfig.id },})})@@ -236,7 +235,6 @@ describe('CdpLegacyEventsConsumer', () => {expect(result?.inputs).toMatchObject({customerioSiteId: { value: '1234567890' },customerioToken: { value: 'cio-token' },- legacy_plugin_config_id: { value: pluginConfig.id },mappings: {value: {event1: 'action1',@@ -271,9 +269,7 @@ describe('CdpLegacyEventsConsumer', () => {const result = consumer['convertPluginConfigToHogFunction'](lightweightConfig, attachments)expect(result).toBeTruthy()- expect(result?.inputs).toMatchObject({- legacy_plugin_config_id: { value: pluginConfig.id },- })+ expect(result?.inputs).toEqual({})expect(result?.inputs?.mappings).toBeUndefined()})diff --git a/nodejs/src/cdp/consumers/cdp-legacy-event.consumer.ts b/nodejs/src/cdp/consumers/cdp-legacy-event.consumer.tsindex 1a3cd60ed5fb..fe18ee9a0b14 100644--- a/nodejs/src/cdp/consumers/cdp-legacy-event.consumer.ts+++ b/nodejs/src/cdp/consumers/cdp-legacy-event.consumer.ts@@ -244,11 +244,6 @@ export class CdpLegacyEventsConsumer extends CdpConsumerBase<CdpLegacyEventsCons}}- // Add legacy_plugin_config_id for plugins that use legacy storage- if (pluginId === 'customerio-plugin') {- inputs.legacy_plugin_config_id = { value: pluginConfig.id }- }-// Create a HogFunctionTypereturn {id: `legacy-${pluginConfig.id}`,diff --git a/nodejs/src/cdp/legacy-plugins/_destinations/customerio/customer-status.test.ts b/nodejs/src/cdp/legacy-plugins/_destinations/customerio/customer-status.test.tsnew file mode 100644index 000000000000..493dcd5d70f8--- /dev/null+++ b/nodejs/src/cdp/legacy-plugins/_destinations/customerio/customer-status.test.ts@@ -0,0 +1,76 @@+import { parseJSON } from '~/common/utils/json-parse'+import { ProcessedPluginEvent } from '~/plugin-scaffold'++import { onEvent, setupPlugin } from './index'++describe('customer.io customer status', () => {+ const run = async ({+ mode,+ person,+ event,+ }: {+ mode: string+ person?: Record<string, any>+ event?: Partial<ProcessedPluginEvent>+ }): Promise<{ sent: boolean; identifyBody: Record<string, any> | undefined }> => {+ const calls: { url: string; body: any }[] = []+ const meta: any = {+ config: { customerioSiteId: 'site', customerioToken: 'token', sendEventsFromAnonymousUsers: mode },+ global: {},+ logger: { debug: jest.fn(), warn: jest.fn(), log: jest.fn(), error: jest.fn() },+ fetch: jest.fn().mockImplementation((url: string, params: any) => {+ calls.push({ url, body: params.body ? parseJSON(params.body) : undefined })+ return Promise.resolve({ status: 200, json: () => Promise.resolve({}) })+ }),+ person: person ? { id: 'p', name: 'p', url: '', properties: person } : undefined,+ }++ await setupPlugin(meta)+ calls.length = 0++ await onEvent(+ {+ distinct_id: 'user-1',+ event: 'purchase',+ properties: {},+ team_id: 1,+ uuid: 'uuid',+ ip: null,+ ...event,+ } as ProcessedPluginEvent,+ meta+ )++ const identify = calls.find((c) => c.url.includes('/customers/') && !c.url.endsWith('/events'))+ return { sent: calls.length > 0, identifyBody: identify?.body }+ }++ const WITH_EMAIL = 'Only send events from users with emails'+ const IDENTIFIED = 'Only send events from users that have been identified'++ test.each([+ ['person carries an email the event does not', WITH_EMAIL, { email: '[email protected]' }, {}, true],+ ['neither event nor person carries an email', WITH_EMAIL, undefined, {}, false],+ ['$is_identified is true', IDENTIFIED, undefined, { properties: { $is_identified: true } }, true],+ ['$is_identified is the string true', IDENTIFIED, undefined, { properties: { $is_identified: 'true' } }, true],+ ['$is_identified is false', IDENTIFIED, undefined, { properties: { $is_identified: false } }, false],+ [+ // Cookieless events always get a device id that differs from the distinct id+ 'the event is anonymous cookieless',+ IDENTIFIED,+ undefined,+ { distinct_id: 'cookieless_a', properties: { $device_id: 'cookielessd_b' } },+ false,+ ],+ ['no gate is configured', 'Send all events', undefined, {}, true],+ ])('sends %s: %s', async (_name, mode, person, event, expected) => {+ const { sent } = await run({ mode: mode as string, person: person as any, event: event as any })+ expect(sent).toBe(expected)+ })++ it('identifies the customer by the person email when the event has none', async () => {+ const { identifyBody } = await run({ mode: WITH_EMAIL, person: { email: '[email protected]' } })++ expect(identifyBody).toMatchObject({ email: '[email protected]' })+ })+})diff --git a/nodejs/src/cdp/legacy-plugins/_destinations/customerio/index.ts b/nodejs/src/cdp/legacy-plugins/_destinations/customerio/index.tsindex 2b27284afe25..9f2160960c0e 100644--- a/nodejs/src/cdp/legacy-plugins/_destinations/customerio/index.ts+++ b/nodejs/src/cdp/legacy-plugins/_destinations/customerio/index.ts@@ -40,7 +40,6 @@ const EVENTS_CONFIG_MAP = {interface Customer {status: Set<'seen' | 'identified' | 'with_email'>- existsAlready: booleanemail: string | null}@@ -126,7 +125,8 @@ export const onEvent = async (event: ProcessedPluginEvent, meta: CustomerIoMeta)return}- const customer: Customer = await syncCustomerMetadata(meta, event)+ const customer = resolveCustomer(meta, event)+ logger.debug('Detected email', customer.email)logger.debug(customer)logger.debug(shouldCustomerBeTracked(customer, global.eventsConfig))if (!shouldCustomerBeTracked(customer, global.eventsConfig)) {@@ -143,35 +143,25 @@ export const onEvent = async (event: ProcessedPluginEvent, meta: CustomerIoMeta))}-async function syncCustomerMetadata(meta: CustomerIoMeta, event: ProcessedPluginEvent): Promise<Customer> {- const { storage, logger } = meta+function resolveCustomer(meta: CustomerIoMeta, event: ProcessedPluginEvent): Customer {+ const personProperties = meta.person?.properties ?? {}+ const personEmail = isEmail(personProperties.email) ? (personProperties.email as string) : null+ const email = getEmailFromEvent(event) ?? personEmail- const customerStatusKey = `customer-status/${event.distinct_id}`- const customerStatusArray = (await storage.get(customerStatusKey, [])) as string[]- const customerStatus = new Set(customerStatusArray) as Customer['status']- const customerExistsAlready = customerStatus.has('seen')- const email = getEmailFromEvent(event)-- logger.debug('Detected email', email)-- // Update customer status- customerStatus.add('seen')- if (event.event === '$identify') {- customerStatus.add('identified')- }+ const status = new Set(['seen']) as Customer['status']if (email) {- customerStatus.add('with_email')+ status.add('with_email')}-- if (customerStatus.size > customerStatusArray.length) {- await storage.set(customerStatusKey, Array.from(customerStatus))+ if (isIdentified(event)) {+ status.add('identified')}- return {- status: customerStatus,- existsAlready: customerExistsAlready,- email,- }+ return { status, email }+}++// The native Customer.io template gates on $is_identified, so match it rather than inventing a second rule+function isIdentified(event: ProcessedPluginEvent): boolean {+ return event.event === '$identify' || String(event.properties?.$is_identified) === 'true'}function shouldCustomerBeTracked(customer: Customer, eventsConfig: EventsConfig): boolean {@@ -203,7 +193,8 @@ async function exportSingleEvent(const customerPayload: Record<string, any> = {...(event.$set || {}),- _update: customer.existsAlready,+ // The endpoint upserts, so this flag only labels the write+ _update: true,identifier: event.distinct_id,}diff --git a/nodejs/src/cdp/legacy-plugins/_destinations/customerio/template.ts b/nodejs/src/cdp/legacy-plugins/_destinations/customerio/template.tsindex 436c8e890954..137c3337a478 100644--- a/nodejs/src/cdp/legacy-plugins/_destinations/customerio/template.ts+++ b/nodejs/src/cdp/legacy-plugins/_destinations/customerio/template.ts@@ -88,14 +88,6 @@ export const customerioPlugin: LegacyDestinationPlugin = {type: 'string',description: 'If this is set, only the specified events (comma-separated) will be sent to Customer.io.',},- {- key: 'legacy_plugin_config_id',- label: 'Legacy plugin config ID',- description: 'The ID of the legacy plugin config that this was migrated from. (DO NOT MODIFY THIS)',- type: 'string',- default: '',- required: true,- },],},}diff --git a/nodejs/src/cdp/legacy-plugins/test-utils.ts b/nodejs/src/cdp/legacy-plugins/test-utils.tsindex 0884361620c7..5d2fa77da916 100644--- a/nodejs/src/cdp/legacy-plugins/test-utils.ts+++ b/nodejs/src/cdp/legacy-plugins/test-utils.ts@@ -91,7 +91,6 @@ export function createCache(): {let testMeta: any = {config: {},cache: createCache(),- storage: createCache(),global: {},attachments: {},}@@ -100,7 +99,6 @@ export function resetMeta(meta: Record<string, any> = {}): any {testMeta = {config: {},cache: createCache(),- storage: createCache(),global: {},attachments: {},...meta,diff --git a/nodejs/src/cdp/legacy-plugins/types.ts b/nodejs/src/cdp/legacy-plugins/types.tsindex f0b78b74e4ae..f45c41168422 100644--- a/nodejs/src/cdp/legacy-plugins/types.ts+++ b/nodejs/src/cdp/legacy-plugins/types.ts@@ -1,7 +1,7 @@import { FetchOptions, FetchResponse } from '~/common/utils/request'-import { PluginEvent, ProcessedPluginEvent, StorageExtension } from '~/plugin-scaffold'+import { PluginEvent, ProcessedPluginEvent } from '~/plugin-scaffold'-import { HogFunctionTemplate } from '../types'+import { CyclotronPerson, HogFunctionTemplate } from '../types'export type LegacyPluginLogger = {debug: (...args: any[]) => void@@ -24,7 +24,7 @@ export type LegacyTransformationPluginMeta = LegacyPluginMeta & {export type LegacyDestinationPluginMeta = LegacyTransformationPluginMeta & {fetch: (url: string, fetchParams: FetchOptions) => Promise<FetchResponse>- storage: Pick<StorageExtension, 'get' | 'set'>+ person?: CyclotronPerson}export type LegacyDestinationPlugin = {diff --git a/nodejs/src/cdp/services/legacy-plugin-executor.service.test.ts b/nodejs/src/cdp/services/legacy-plugin-executor.service.test.tsindex 8a9fdbbb2f4b..55f24f637f07 100644--- a/nodejs/src/cdp/services/legacy-plugin-executor.service.test.ts+++ b/nodejs/src/cdp/services/legacy-plugin-executor.service.test.ts@@ -137,7 +137,6 @@ describe('LegacyPluginExecutorService', () => {customerioSiteId: '1234567890',customerioToken: 'cio-token',email: '[email protected]',- legacy_plugin_config_id: pluginConfigId,},}})@@ -262,7 +261,7 @@ describe('LegacyPluginExecutorService', () => {["https://track.customer.io/api/v1/customers/distinct_id",{- "body": "{"_update":false,"identifier":"distinct_id"}",+ "body": "{"_update":true,"identifier":"distinct_id","email":"[email protected]"}","headers": {"Authorization": "Basic MTIzNDU2Nzg5MDpjaW8tdG9rZW4=","Content-Type": "application/json",@@ -290,8 +289,8 @@ describe('LegacyPluginExecutorService', () => {expect(getLogMessages(res.logs)).toMatchInlineSnapshot(`["Successfully authenticated with Customer.io. Completing setupPlugin.",- "Detected email, null",- "{"status":{},"existsAlready":false,"email":null}",+ "Detected email, [email protected]",+ "{"status":{},"email":"[email protected]"}","true","Function completed in REPLACED-TIME-ms.",]@@ -318,8 +317,8 @@ describe('LegacyPluginExecutorService', () => {expect(forSnapshot(getLogMessages(res.logs))).toMatchInlineSnapshot(`["Successfully authenticated with Customer.io. Completing setupPlugin.",- "Detected email, null",- "{"status":{},"existsAlready":false,"email":null}",+ "Detected email, [email protected]",+ "{"status":{},"email":"[email protected]"}","true","Fetch called but mocked due to test function, {"url":"https://track.customer.io/api/v1/customers/distinct_id","method":"PUT"}","Fetch called but mocked due to test function, {"url":"https://track.customer.io/api/v1/customers/distinct_id/events","method":"POST"}",@@ -368,8 +367,8 @@ describe('LegacyPluginExecutorService', () => {expect(forSnapshot(getLogMessages(res.logs))).toMatchInlineSnapshot(`["Successfully authenticated with Customer.io. Completing setupPlugin.",- "Detected email, null",- "{"status":{},"existsAlready":false,"email":null}",+ "Detected email, [email protected]",+ "{"status":{},"email":"[email protected]"}","true","Plugin execution failed: Received a potentially intermittent error from the Customer.io API. Response 500: {}",]@@ -528,10 +527,6 @@ describe('LegacyPluginExecutorService', () => {const invocation = buildInvocation(plugin)invocation.hogFunction.name = nameinvocation.state.globals.event.event = '$identify' // Many plugins filter for this-- if (plugin.template.id === 'plugin-customerio-plugin') {- invocation.state.globals.inputs.legacy_plugin_config_id = pluginConfigId- }const res = await service.execute(invocation)expect(getLogMessages(res.logs)).toMatchSnapshot()})diff --git a/nodejs/src/cdp/services/legacy-plugin-executor.service.ts b/nodejs/src/cdp/services/legacy-plugin-executor.service.tsindex 3aafe3caad8e..92b48c3f1b94 100644--- a/nodejs/src/cdp/services/legacy-plugin-executor.service.ts+++ b/nodejs/src/cdp/services/legacy-plugin-executor.service.ts@@ -166,9 +166,6 @@ export class LegacyPluginExecutorService {let state = this.pluginState[invocation.hogFunction.id]- // NOTE: If this is set then we can add in the legacy storage- const legacyPluginConfigId = invocation.state.globals.inputs?.legacy_plugin_config_id-setupPromiseCacheCounter.labels({ result: state ? 'hit' : 'miss' }).inc()if (!state) {@@ -204,7 +201,6 @@ export class LegacyPluginExecutorService {...meta,// Setup receives the real fetch alwaysfetch,- storage: this.legacyStorage(invocation.hogFunction.team_id, legacyPluginConfigId),})}}@@ -299,7 +295,8 @@ export class LegacyPluginExecutorService {// NOTE: We override logger and fetch here so we can track the callslogger: pluginLogger,fetch: request,- storage: this.legacyStorage(invocation.hogFunction.team_id, legacyPluginConfigId),+ // Not on state.meta because state is cached across invocations+ person: globals.person,})addLog('info', `Function completed in ${performance.now() - start}ms.`)@@ -312,7 +309,10 @@ export class LegacyPluginExecutorService {...state.meta,logger: pluginLogger,},- this.legacyStorage(invocation.hogFunction.team_id, legacyPluginConfigId)+ this.legacyStorage(+ invocation.hogFunction.team_id,+ invocation.state.globals.inputs?.legacy_plugin_config_id+ ))result.execResult = transformedEvent} else {