: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): add Retain destination template (#79531)
Luke Belton508c81b53afd
diff --git a/frontend/public/services/retain.png b/frontend/public/services/retain.pngnew file mode 100644index 000000000000..2641b39cfab3Binary files /dev/null and b/frontend/public/services/retain.png differdiff --git a/nodejs/src/cdp/templates/_destinations/retain/retain.template.test.ts b/nodejs/src/cdp/templates/_destinations/retain/retain.template.test.tsnew file mode 100644index 000000000000..81408ba3b8e4--- /dev/null+++ b/nodejs/src/cdp/templates/_destinations/retain/retain.template.test.ts@@ -0,0 +1,140 @@+import { DateTime } from 'luxon'++import { parseJSON } from '~/common/utils/json-parse'++import { TemplateTester } from '../../test/test-helpers'+import { template } from './retain.template'++describe('retain template', () => {+ const tester = new TemplateTester(template)++ beforeEach(async () => {+ await tester.beforeEach()+ const fixedTime = DateTime.fromISO('2025-01-01T00:00:00Z').toJSDate()+ jest.spyOn(Date, 'now').mockReturnValue(fixedTime.getTime())+ })++ const baseInputs = {+ writeKey: 'rk-test-write-key',+ }++ it('should forward a custom event with the person attached', async () => {+ const response = await tester.invoke(baseInputs, {+ event: {+ uuid: 'event-uuid-1',+ event: 'report exported',+ distinct_id: 'user-123',+ timestamp: '2024-01-01T00:00:00Z',+ properties: {+ format: 'csv',+ },+ },+ person: {+ properties: {+ email: '[email protected]',+ name: 'Example User',+ },+ },+ })++ expect(response.error).toBeUndefined()+ expect(response.finished).toEqual(false)+ expect(response.invocation.queueParameters).toBeDefined()++ const queueParameters = response.invocation.queueParameters as any+ expect(queueParameters.url).toBe('https://api.retain.so/sources/posthog')+ expect(queueParameters.method).toBe('POST')+ expect(queueParameters.headers).toEqual({+ Authorization: 'Basic rk-test-write-key',+ 'Content-Type': 'application/json',+ })++ const body = parseJSON(queueParameters.body)+ expect(body).toEqual({+ event: {+ uuid: 'event-uuid-1',+ event: 'report exported',+ distinct_id: 'user-123',+ properties: {+ format: 'csv',+ },+ timestamp: '2024-01-01T00:00:00Z',+ },+ person: {+ properties: {+ email: '[email protected]',+ name: 'Example User',+ },+ },+ })++ const fetchResponse = await tester.invokeFetchResponse(response.invocation, {+ status: 201,+ body: { success: true, result: 'tracked' },+ })++ expect(fetchResponse.finished).toBe(true)+ expect(fetchResponse.error).toBeUndefined()+ })++ it.each(['$identify', '$set', '$groupidentify'])('should forward %s identity events', async (eventName) => {+ const response = await tester.invoke(baseInputs, {+ event: {+ event: eventName,+ distinct_id: 'user-123',+ properties: {+ $set: { email: '[email protected]' },+ },+ },+ person: {+ properties: { email: '[email protected]' },+ },+ })++ expect(response.error).toBeUndefined()+ expect(response.finished).toEqual(false)+ expect(response.invocation.queueParameters).toBeDefined()++ const body = parseJSON((response.invocation.queueParameters as any).body)+ expect(body.event.event).toBe(eventName)+ })++ it.each(['$pageview', '$pageleave', '$autocapture', '$feature_flag_called', '$exception'])(+ 'should skip PostHog internal event %s without making a request',+ async (eventName) => {+ const response = await tester.invoke(baseInputs, {+ event: {+ event: eventName,+ distinct_id: 'user-123',+ properties: {},+ },+ })++ expect(response.error).toBeUndefined()+ expect(response.finished).toEqual(true)+ expect(response.invocation.queueParameters).toBeUndefined()+ }+ )++ it('should throw an error when Retain responds with an error status', async () => {+ const response = await tester.invoke(baseInputs, {+ event: {+ event: 'report exported',+ distinct_id: 'user-123',+ properties: {},+ },+ })++ expect(response.error).toBeUndefined()++ const fetchResponse = await tester.invokeFetchResponse(response.invocation, {+ status: 401,+ body: { message: 'Invalid write key' },+ })++ expect(fetchResponse.finished).toBe(true)+ expect(fetchResponse.error).toMatchInlineSnapshot(+ `"Error from api.retain.so (status 401): {'message': 'Invalid write key'}"`+ )+ })+})diff --git a/nodejs/src/cdp/templates/_destinations/retain/retain.template.ts b/nodejs/src/cdp/templates/_destinations/retain/retain.template.tsnew file mode 100644index 000000000000..7992a3770167--- /dev/null+++ b/nodejs/src/cdp/templates/_destinations/retain/retain.template.ts@@ -0,0 +1,63 @@+import { HogFunctionTemplate } from '~/cdp/types'++export const template: HogFunctionTemplate = {+ status: 'beta',+ free: true,+ type: 'destination',+ id: 'template-retain',+ name: 'Retain',+ description:+ 'Send product usage and identity events to Retain for churn prediction, customer health scoring, and at-risk account alerts.',+ icon_url: '/static/services/retain.png',+ category: ['Analytics'],+ code_language: 'hog',+ code: `+// Retain only consumes product usage and identity events. Skip PostHog+// internal events ($pageview, $autocapture, $feature_flag_called, ...) to+// avoid useless requests — Retain would ignore them anyway.+let allowedSystemEvents := ['$identify', '$set', '$groupidentify']+if (startsWith(event.event, '$') and not (event.event in allowedSystemEvents)) {+ return+}++let res := fetch('https://api.retain.so/sources/posthog', {+ 'method': 'POST',+ 'headers': {+ 'Authorization': f'Basic {inputs.writeKey}',+ 'Content-Type': 'application/json'+ },+ 'body': {+ 'event': {+ 'uuid': event.uuid,+ 'event': event.event,+ 'distinct_id': event.distinct_id,+ 'properties': event.properties,+ 'timestamp': event.timestamp+ },+ 'person': {+ 'properties': person.properties+ }+ }+})++if (res.status >= 400) {+ throw Error(f'Error from api.retain.so (status {res.status}): {res.body}')+}+`,+ inputs_schema: [+ {+ key: 'writeKey',+ type: 'string',+ label: 'Retain write key',+ description:+ 'Your Retain project write key (starts with "rk-"). Find it in your Retain dashboard under Settings → Project token.',+ secret: true,+ required: true,+ },+ ],+ filters: {+ events: [],+ actions: [],+ filter_test_accounts: true,+ },+}diff --git a/nodejs/src/cdp/templates/index.ts b/nodejs/src/cdp/templates/index.tsindex e0db48213461..07790eb83060 100644--- a/nodejs/src/cdp/templates/index.ts+++ b/nodejs/src/cdp/templates/index.ts@@ -33,6 +33,7 @@ import { template as posthogUpdateAccountTemplate } from './_destinations/posthoimport { template as posthogSetHogflowVariableTemplate } from './_destinations/posthog_workflows/posthog-set-variable.template'import { template as pushTemplate } from './_destinations/push/push.template'import { template as redditAdsTemplate } from './_destinations/reddit_ads/reddit.template'+import { template as retainTemplate } from './_destinations/retain/retain.template'import { template as snapchatAdsTemplate } from './_destinations/snapchat_ads/snapchat.template'import { template as tiktokAdsTemplate } from './_destinations/tiktok_ads/tiktok.template'import { template as twilioTemplate } from './_destinations/twilio/twilio.template'@@ -98,6 +99,7 @@ export const HOG_FUNCTION_TEMPLATES_DESTINATIONS: HogFunctionTemplate[] = [klimeTemplate,unifyTemplate,closeTemplate,+ retainTemplate,]export const HOG_FUNCTION_TEMPLATES_TRANSFORMATIONS: HogFunctionTemplate[] = [