Skip to content

The micro-VM for AI agents — light enough to embed on your laptop, elastic enough to power an agentic cloud.

7.5 KB
Raw Blame
/* Copyright 2026 BoxLite AI. SPDX-License-Identifier: AGPL-3.0 */
import { AsyncLocalStorage } from 'node:async_hooks'
import { createServer, ServerResponse } from 'node:http'
import type { AddressInfo } from 'node:net'
import { Logger } from '@nestjs/common'
import type Redis from 'ioredis'
import type { DataSource } from 'typeorm'
import type { TypedConfigService } from '../../config/typed-config.service'
import { signupAttributionEvent } from '../signup-attribution-log'
import { AnalyticsConsentService } from './analytics-consent.service'
import { AnalyticsService } from './analytics.service'

function consentWithCache(status: string, get: (key: string) => Promise<string>) {
  return new AnalyticsConsentService(
    { options: {} } as DataSource,
    { status, get } as Redis,
    { getOrThrow: () => 10 } as unknown as TypedConfigService,
  )
}

describe('Signup attribution logging', () => {
  const eventTime = new Date('2025-01-01T00:00:00Z')
  const users = { users: ['user'], organizations: [] }
  const nobody = { users: [], organizations: [] }

  it.each([
    ['invalid_event_time', new Date(NaN), 'ready', users, ''],
    ['invalid_event_time', new Date('2999-01-01T00:00:00Z'), 'ready', users, ''],
    ['redis_unavailable', eventTime, 'end', users, ''],
    ['organization_creator_unavailable', eventTime, 'ready', { ...users, organizations: ['org'] }, ''],
    ['no_subjects', eventTime, 'ready', nobody, ''],
    ['consent_grant_unavailable', eventTime, 'ready', users, ''],
    ['consent_after_event', eventTime, 'ready', users, String(eventTime.getTime() + 1)],
  ])('reports %s from consent dispatch without sending', async (reason, time, status, subjects, cached) => {
    const consent = consentWithCache(status, async () => cached)
    const send = jest.fn(async () => {})
    const onSkip = jest.fn()

    await expect(consent.dispatch(subjects, time, send, onSkip)).resolves.toBe(false)
    expect(send).not.toHaveBeenCalled()
    expect(onSkip.mock.calls).toEqual([[reason]])
  })

  it('logs signup attempts before the response and acknowledges only the matching 2xx', async () => {
    const context = new AsyncLocalStorage<string>()
    const logged: Array<{ scope?: string; fields: object }> = []
    const warnings: Array<{ scope?: string; message: unknown }> = []
    const requests: Array<{ distinct_id: string; event: string }> = []
    let observeHeld!: () => void
    let observeRejection!: () => void
    let heldResponse: ServerResponse | undefined
    const held = new Promise<void>((resolve) => (observeHeld = resolve))
    const rejected = new Promise<void>((resolve) => (observeRejection = resolve))
    const info = jest.spyOn(Logger.prototype, 'log').mockImplementation((message, fields) => {
      if (typeof message === 'string' && message.startsWith('signup.attribution ')) {
        logged.push({ scope: context.getStore(), fields })
      }
    })
    const warn = jest.spyOn(Logger.prototype, 'warn').mockImplementation((message) => {
      const scope = context.getStore()
      warnings.push({ scope, message })
      if (scope === 'rejected') observeRejection()
    })
    const server = createServer((request, response) => {
      const chunks: Buffer[] = []
      request.on('data', (chunk: Buffer) => chunks.push(chunk))
      request.on('end', () => {
        const [event] = JSON.parse(Buffer.concat(chunks).toString()).batch
        requests.push(event)
        if (event.distinct_id === 'accepted') {
          heldResponse = response
          observeHeld()
        } else if (event.distinct_id === 'disconnected') {
          request.socket.destroy()
        } else {
          response.writeHead(event.distinct_id === 'rejected' ? 429 : 200).end('{"status":1}')
        }
      })
    })

    let analytics: AnalyticsService | undefined
    let shutdown: Promise<void> | undefined
    try {
      await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve))
      const consent = consentWithCache('ready', async (key) => {
        if (key.endsWith(':lookup-failed')) throw new Error('Redis lookup failed')
        return key.endsWith(':denied') ? '' : '0'
      })
      const config = {
        'posthog.apiKey': 'phc_test',
        'posthog.host': 'http://127.0.0.1:' + (server.address() as AddressInfo).port,
        'posthog.environment': 'test',
      }
      analytics = new AnalyticsService(
        { get: (key: keyof typeof config) => config[key] } as TypedConfigService,
        consent,
      )
      const disabled = new AnalyticsService({ get: () => undefined } as unknown as TypedConfigService, consent)
      const event = {
        event: signupAttributionEvent,
        uuid: '2dfd7b11-7b07-4efb-ad36-16afd0db4cd1',
        properties: { 'signup.source': 'example.com' },
        groups: { organization: 'org' },
      }
      const capture = (scope: string, name = signupAttributionEvent) =>
        context.run(scope, () => {
          analytics!.capture({ ...event, event: name, distinctId: scope }, { users: [scope], organizations: [] })
        })
      context.run('disabled', () => disabled.capture({ ...event, distinctId: 'disabled' }, users))
      context.run('empty', () => analytics!.capture({ ...event, distinctId: 'empty' }, nobody))
      capture('accepted')
      await held
      capture('rejected')
      capture('disconnected')
      capture('other', 'user.login')
      capture('denied')
      capture('lookup-failed')

      let drained = false
      shutdown = analytics.onApplicationShutdown().then(() => {
        drained = true
      })
      capture('closing')
      await rejected
      expect(drained).toBe(false)
      const outcomes = (scope: string) =>
        logged.filter((record) => record.scope === scope).map((record) => record.fields)
      const fields = { 'event.name': 'signup.attribution' }
      const sending = { ...fields, outcome: 'sending' }
      expect(outcomes('accepted')).toEqual([sending])
      heldResponse!.writeHead(202).end('{"status":1}')
      await shutdown

      expect(requests.map((request) => request.distinct_id).sort()).toEqual([
        'accepted',
        'disconnected',
        'other',
        'rejected',
      ])
      expect(requests.find((request) => request.distinct_id === 'accepted')).toMatchObject({
        event: signupAttributionEvent,
        uuid: event.uuid,
        properties: { 'signup.source': 'example.com', $groups: { organization: 'org' }, environment: 'test' },
      })
      expect(outcomes('accepted')).toEqual([sending, { ...fields, outcome: 'delivered', http_status: 202 }])
      expect(outcomes('rejected')).toEqual([sending])
      expect(outcomes('disconnected')).toEqual([sending])
      expect(outcomes('other')).toEqual([])
      expect(outcomes('lookup-failed')).toEqual([])
      for (const [scope, reason] of [
        ['disabled', 'analytics_disabled'],
        ['empty', 'no_subjects'],
        ['closing', 'shutdown_in_progress'],
        ['denied', 'consent_grant_unavailable'],
      ]) {
        expect(outcomes(scope)).toEqual([{ ...fields, outcome: 'skipped', reason }])
      }
      expect(warnings).toHaveLength(3)
      expect(warnings).toEqual(
        expect.arrayContaining([
          { scope: 'rejected', message: 'PostHog analytics delivery failed' },
          { scope: 'disconnected', message: 'PostHog analytics delivery failed' },
          { scope: 'lookup-failed', message: 'PostHog analytics capture failed' },
        ]),
      )
    } finally {
      heldResponse?.end()
      await (shutdown ?? analytics?.onApplicationShutdown())
      await new Promise<void>((resolve) => server.close(() => resolve()))
      warn.mockRestore()
      info.mockRestore()
    }
  })
})