Skip to content

OpenPanel is an open-source web and product analytics platform, an open-source alternative to Mixpanel with optional self-hosting.

8.4 KB
Raw Blame
// Job/cron-fragment wiring only; the service methods are in insight.service.test.ts.

import { expect, test } from 'bun:test';
import { testCoreConfig } from '../../../test/config-fixture';
import type { AppDeps, Buffers, JobCtx } from '../../context';
import { createRecordingProducers } from '../../jobs/testing';
import { queues } from '../../jobs.registry';
import type { Logger } from '../../logger';
import type { Services } from '../../services';
import { insightCronJobs, insightQueueJobs } from './insight.jobs';
import type { createInsightService } from './insight.service';

function stubLogger(): Logger {
  const noop = () => undefined;
  const logger: Logger = {
    fatal: noop,
    error: noop,
    warn: noop,
    info: noop,
    debug: noop,
    trace: noop,
    child: () => logger,
  };
  return logger;
}

// A plain object literal, not createCtx/extendCtx: `services` is installed
// there as a getter with no setter (the lazy-build seam), which makes it
// unassignable afterwards — exactly what a fake `services.insight` needs to be
// for a handler test.
function stubJobCtx(
  insight: Partial<ReturnType<typeof createInsightService>>,
  jobName = 'test'
): JobCtx {
  const services: Services = {
    auth: {} as Services['auth'],
    notification: {} as Services['notification'],
    insight: insight as ReturnType<typeof createInsightService>,
    gsc: {} as Services['gsc'],
    integration: {} as Services['integration'],
    cohort: {} as Services['cohort'],
    import: {} as Services['import'],
    ingest: {} as Services['ingest'],
    organization: {} as Services['organization'],
    onboarding: {} as Services['onboarding'],
    session: {} as Services['session'],
    customEvent: {} as Services['customEvent'],
    event: {} as Services['event'],
    profile: {} as Services['profile'],
    group: {} as Services['group'],
    chart: {} as Services['chart'],
    funnel: {} as Services['funnel'],
    conversion: {} as Services['conversion'],
    sankey: {} as Services['sankey'],
    retention: {} as Services['retention'],
    overview: {} as Services['overview'],
    pages: {} as Services['pages'],
    realtime: {} as Services['realtime'],
    misc: {} as Services['misc'],
    report: {} as Services['report'],
    dashboard: {} as Services['dashboard'],
    export: {} as Services['export'],
    share: {} as Services['share'],
    reference: {} as Services['reference'],
    client: {} as Services['client'],
    project: {} as Services['project'],
    user: {} as Services['user'],
    subscription: {} as Services['subscription'],
    salt: {} as Services['salt'],
    conversation: {} as Services['conversation'],
    assistant: {} as Services['assistant'],
    mcp: {} as Services['mcp'],
    ai: {} as Services['ai'],
  };
  return {
    auth: null,
    db: {} as AppDeps['db'],
    prisma: {} as AppDeps['prisma'],
    ch: {} as AppDeps['ch'],
    redis: {} as AppDeps['redis'],
    clients: {} as AppDeps['clients'],
    buffers: {} as Buffers,
    logger: stubLogger(),
    queues: createRecordingProducers(queues).queues,
    config: testCoreConfig(),
    services,
    requestId: 'req_1',
    job: { id: 'job_1', attempt: 0, queue: 'cron', name: jobName },
  };
}

test('the insight jobs registry declares insightsProject on the insights queue', () => {
  expect(queues.insights.jobs.insightsProject).toMatchObject({
    queue: 'insights',
    name: 'insightsProject',
  });
});

test('the insight cron fragment is spread into the cron queue', () => {
  // Subset, not exact equality: other modules (e.g. gsc) spread their own
  // fragments into the same cron queue. jobs.registry.test.ts owns the
  // exhaustive membership check.
  expect(Object.keys(queues.cron.jobs)).toEqual(
    expect.arrayContaining(['insightCleanup', 'insightsDaily', 'weeklyDigest'])
  );
});

test('insightsProject validates its payload', () => {
  expect(() =>
    insightQueueJobs.insightsProject.payload.parse({ projectId: 'p1' })
  ).toThrow();
  expect(
    insightQueueJobs.insightsProject.payload.parse({
      projectId: 'p1',
      date: '2026-09-03',
    })
  ).toEqual({ projectId: 'p1', date: '2026-09-03' });
});

test('insightsProject delegates to runProjectInsights', async () => {
  const calls: unknown[] = [];
  const ctx = stubJobCtx({
    runProjectInsights: async (args) => {
      calls.push(args);
    },
  });

  await insightQueueJobs.insightsProject.handler({
    payload: { projectId: 'p1', date: '2026-09-03' },
    ctx,
  });

  expect(calls).toEqual([{ projectId: 'p1', date: '2026-09-03' }]);
});

test('insightsDaily fans out one insightsProject enqueue per candidate, jobId deduped by day+project', async () => {
  const producers = createRecordingProducers(queues);
  const ctx: JobCtx = {
    auth: null,
    db: {} as AppDeps['db'],
    prisma: {} as AppDeps['prisma'],
    ch: {} as AppDeps['ch'],
    redis: {} as AppDeps['redis'],
    clients: {} as AppDeps['clients'],
    buffers: {} as Buffers,
    logger: stubLogger(),
    queues: producers.queues,
    config: testCoreConfig(),
    services: {
      auth: {} as Services['auth'],
      notification: {} as Services['notification'],
      insight: {
        listDailyInsightCandidates: async (date) => [
          { projectId: 'p1', date },
          { projectId: 'p2', date },
        ],
      } as ReturnType<typeof createInsightService>,
      gsc: {} as Services['gsc'],
      integration: {} as Services['integration'],
      cohort: {} as Services['cohort'],
      import: {} as Services['import'],
      ingest: {} as Services['ingest'],
      organization: {} as Services['organization'],
      onboarding: {} as Services['onboarding'],
      session: {} as Services['session'],
      customEvent: {} as Services['customEvent'],
      event: {} as Services['event'],
      profile: {} as Services['profile'],
      group: {} as Services['group'],
      chart: {} as Services['chart'],
      funnel: {} as Services['funnel'],
      conversion: {} as Services['conversion'],
      sankey: {} as Services['sankey'],
      retention: {} as Services['retention'],
      overview: {} as Services['overview'],
      pages: {} as Services['pages'],
      realtime: {} as Services['realtime'],
      misc: {} as Services['misc'],
      report: {} as Services['report'],
      dashboard: {} as Services['dashboard'],
      export: {} as Services['export'],
      share: {} as Services['share'],
      reference: {} as Services['reference'],
      client: {} as Services['client'],
      project: {} as Services['project'],
      user: {} as Services['user'],
      subscription: {} as Services['subscription'],
      salt: {} as Services['salt'],
      conversation: {} as Services['conversation'],
      assistant: {} as Services['assistant'],
      mcp: {} as Services['mcp'],
      ai: {} as Services['ai'],
    },
    requestId: 'req_1',
    job: { id: 'job_1', attempt: 0, queue: 'cron', name: 'insightsDaily' },
  };

  await insightCronJobs.insightsDaily.handler({ payload: null, ctx });

  expect(producers.recorded).toHaveLength(2);
  expect(producers.recorded.map((r) => r.job)).toEqual([
    'insightsProject',
    'insightsProject',
  ]);
  const today = new Date().toISOString().slice(0, 10);
  expect(producers.recorded.map((r) => r.payload)).toEqual([
    { projectId: 'p1', date: today },
    { projectId: 'p2', date: today },
  ]);
});

test('insightCleanup delegates to cleanupStaleInsights', async () => {
  let called = false;
  const ctx = stubJobCtx(
    {
      cleanupStaleInsights: async () => {
        called = true;
        return { insights: 0, events: 0 };
      },
    },
    'insightCleanup'
  );

  await insightCronJobs.insightCleanup.handler({ payload: null, ctx });
  expect(called).toBe(true);
});

test('weeklyDigest delegates to sendWeeklyDigests', async () => {
  let called = false;
  const ctx = stubJobCtx(
    {
      sendWeeklyDigests: async () => {
        called = true;
        return { projects: 0, sent: 0 };
      },
    },
    'weeklyDigest'
  );

  await insightCronJobs.weeklyDigest.handler({ payload: null, ctx });
  expect(called).toBe(true);
});

// The cadences live on the jobs themselves, so this reads them off the registry;
// schedulers.test.ts's golden snapshot pins the same ids.
test('the insight cron fragment keeps its scheduler ids and cadences', () => {
  expect(queues.cron.jobs.insightsDaily.cron).toEqual({
    pattern: '0 2 * * *',
  });
  expect(queues.cron.jobs.insightCleanup.cron).toEqual({
    pattern: '30 4 * * *',
  });
  expect(queues.cron.jobs.weeklyDigest.cron).toEqual({
    pattern: '0 8 * * 1',
  });
});