OpenPanel is an open-source web and product analytics platform, an open-source alternative to Mixpanel with optional self-hosting.
ralph(M10-003): Service factories, read path: chart (+conversion/funnel/retention/sankey), report, dashboard, export, share, reference - deps in, lazy db imports out
ralphb7760a8ceef0
diff --git a/apps/api/src/main.ts b/apps/api/src/main.tsindex a4aeb2114..51c4a5ce9 100644--- a/apps/api/src/main.ts+++ b/apps/api/src/main.ts@@ -69,10 +69,12 @@ import {sessionEndEnqueueOptions,sessionEndJobPayload,setShuttingDown,+ setV1CompatServices,startKafkaEventsConsumer,startSchedulers,startWorkers,TRPC_ENDPOINT,+ V1_COMPAT_REQUEST_ID,type WorkerHandle,} from '@openpanel/core';import { ch } from '@openpanel/db/src/clickhouse/client';@@ -464,6 +466,21 @@ async function main() {const role = config.ROLE;const deps = buildDeps();+ // The V1 compat seam (core/src/v1-compat.ts): `packages/trpc`'s routers and+ // the mcp/assistant tool runtimes reach core's modules as bare barrel+ // exports with no `Ctx`, so the deps built above are registered once here+ // for them. Everything with a `Ctx` uses `ctx.services.*`. Deleted with+ // `packages/trpc` at P10.+ setV1CompatServices({+ db: deps.db,+ ch: deps.ch,+ redis: deps.redis,+ clients: deps.clients,+ buffers: deps.buffers,+ logger: deps.logger,+ queues: deps.producers.scope({ requestId: V1_COMPAT_REQUEST_ID }),+ });+// HTTP and default metrics register everywhere (TARGET_ARCHITECTURE §18).registerDefaultMetrics();if (roleConsumes) {diff --git a/docs/TECH_DEBT.md b/docs/TECH_DEBT.mdindex d0188f51a..40baa0917 100644--- a/docs/TECH_DEBT.md+++ b/docs/TECH_DEBT.md@@ -292,3 +292,165 @@ process exited on its own. `pnpm run check:deps`:`core-uses-ctx-not-db-internals` 167, `core-no-self-barrel` 74 — unchangedfrom the M10-002 entry above; this rule only cruises `packages/core/**`, andthe revert touched nothing there.++### 2026-09-05 — M10-003, the read path (chart+4, report, dashboard, export, share, reference) onto `createXService(deps)`++Ran by: ralph (M10-003 implement task, docs/TECH_DEBT.md §4 steps 1/2/5 and+§5a).++**Shape.** Ten modules now expose exactly one+`createXService(deps: ServiceDeps): XService`, registered in `services.ts`'s+`Services` interface and `createServices`. Their implementation functions take+`deps` as the first parameter and the factory binds it; every service method+carries an explicit return type (`ReturnType<typeof fn>` /+`Parameters<typeof fn>[1]` where the shape is a Prisma payload), for the+ts7022/ts7023 reason `services.ts` documents.++**The four chart sub-services FOLD INTO `ChartService`** rather than becoming+four more `Services` members. They are sibling files of `modules/chart/`, not+modules — ADR-007's map is one service per module, `chart.service.ts` is+already the dispatcher every caller goes through (`getFunnelChart` /+`getConversionChart` / `getSankeyChart` / `getRetentionChart`), and four keys+named after files would claim four modules that do not exist.++**Loaders deleted.** In those ten modules there is now no+`import('@openpanel/db...')` at all, and `loadChClient()` / `loadDb()` /+`loadCore()` / `loadReportsService()` / `loadIdService()` /+`loadDateService()` / `loadOrganizationService()` / `loadAccessService()` /+`loadDashboardService()` are gone. ClickHouse is `deps.ch` and Postgres is+`deps.db`.++- `chart/src/run-query.ts` runs `deps.ch.query(...)` — `chQuery`'s own+ transport (`withRetry(client => client.query(...))`) — and reproduces+ `chQuery`'s Int-meta coercion, the same shape `modules/overview/src/run-query.ts`+ has shipped since M7-005. It logs `'query info'` on `deps.logger`, which is+ the request-scoped child, so the ClickHouse call now carries the requestId.+- `chart/src/table-filter-where.ts` stopped statically importing+ `@openpanel/db/src/clickhouse/client` (a module that builds a ClickHouse+ client and a pino logger at import time) for `formatClickhouseDate` and+ `TABLE_NAMES`; both are local — the module's own `./dates.formatClickhouseDate`+ (byte-identical to packages/db's non-`skipTime` branch) and+ `./field-resolution.CHART_TABLE`, which already carried all four physical+ table names (`events`, `profiles`, `groups`, `cohort_members`).+- `export/export.routes.ts`'s `/insights/:projectId/live` reads+ `ctx.buffers.event` instead of `loadDbBuffers()`.++**Section 2's duplicate is unwired.** `chart.service.ts` (and+`conversion.service.ts`, `funnel.service.ts`, `engine/normalize.ts`) reached+`mergeGlobalFilters` / `onlyReportEvents` through `import('@openpanel/core')`.+They now import them from `modules/report/src/series.ts`. The two helpers moved+there, out of `report.service.ts`, because `report.service.ts` imports the+chart engine and `chart/funnel.service.ts` imports them — a static import back+would have closed a real `report.service -> chart/funnel.service ->+report.service` cycle. `src/series.ts` imports nothing but a zod-derived type,+so both sides stay eager and neither needs a loader.++**One genuine cycle kept lazy, both ends named.**+`modules/auth/auth.service.ts`'s `loadShare()`:+`../share/share.service` statically imports this file's `hashPassword`, and+`signInToShare` needs share's three lookups — `auth.service.ts <->+share.service.ts`. It is not a `@openpanel/db` loader; the share lookups take+`deps` like everything else.++**What is still a value import of `@openpanel/db` in these modules, and why.**+Seven files in `modules/chart/src/` value-import `sql` / `SqlFragment` /+`toStatement` from `@openpanel/db/src/clickhouse/sql` (`chart.sql.ts`,+`funnel.sql.ts`, `conversion.sql.ts`, `sankey.sql.ts`, `retention.sql.ts`,+`compiled.ts`, `run-query.ts`). That is ADR-013's SQL tag, which ADR-007's+"`packages/db` — the final surface" keeps in `packages/db` by name ("**new**+`clickhouse/sql.ts`"), and `packages/db/**` is outside this task's scope globs,+so it cannot be moved here. It carries no client, no connection and no request+scope — it is a compile-time template tag — so it is not a place the requestId+chain can end. Nine more core files outside this task's modules+(`overview`, `profile`, `group`, `session`, `event`, `mcp`) import it the same+way; a decision on whether `core-uses-ctx-not-db-internals` should exempt+`clickhouse/sql.ts` (or whether the tag moves) belongs to M10-009's flip to+`error`, not here. Prisma ROW TYPES stay as `import type` (erased at runtime),+which is what keeps `bun test` offline.++**`v1-compat.ts` — the seam this wave needed and could not avoid.**+`apps/api/src/main.ts` still mounts `@openpanel/trpc`'s `appRouter`, not core's+`rpc.router.ts`, so V1's 28 routers are the LIVE `/trpc` surface; they call+core's modules as bare barrel exports and have no `Ctx` to hand a+`ServiceDeps`. `packages/trpc/**` is outside this task's scope globs (the+reviewer rejected M10-002 attempt 2 for editing it), and the mcp/assistant tool+runtimes are in the same position. So `packages/core/src/v1-compat.ts` holds+one registration point — `setV1CompatServices(deps)`, called once from+`main.ts` right after `AppDeps` is built — and the ~60 bare wrappers the barrel+exports for those callers. Everything that HAS a `Ctx` (core's own rpc files,+`export.routes.ts`, `overview.rpc.ts`) uses `ctx.services.*` and keeps the+request-scoped logger. One file, one grep, deleted whole when `packages/trpc`+dies at P10. Its `signInToShare` wrapper preserves V1's 2-argument spelling;+core's own `auth.rpc.ts` passes `ctx`.++A process that never builds `AppDeps` falls back to the same singletons the+deleted `loadDb()` / `loadChClient()` loaders reached, built lazily on first+use (so importing `@openpanel/core` still constructs no database and+`bun test` still runs offline), with packages/db's own `createLogger` — the+pino logger that already writes `chQuery`'s `query info` line — so those+callers behave exactly as they did before this wave. That fallback is not+theoretical: the root `pnpm test` run caught+`packages/trpc/src/routers/share.test.ts` calling `shareRouter` procedures+directly with no boot, and `packages/trpc/**` is outside this task's scope.+Its three lazy `import('@openpanel/db/...')` edges are the +3 in the table+below; `main.ts` always registers before `buildHttpApp`, so a running server+never reaches it.++**requestId proven through this path.** New sibling test+`packages/core/test/request-id-chart-query.test.ts` — the existing+`request-id-end-to-end.test.ts` mocks the whole `Services` container, so it+cannot show this hop. The new file uses a REAL `createServices`: an Elysia+route under `requestLogging(deps)` calls+`ctx.services.chart.getRetentionSeries({ projectId })` with a recording+`deps.ch`, and asserts++```ts+ // The query really ran through `deps.ch` — a silent miss would leave the+ // logger assertion below trivially true (AGENTS.md).+ expect(queries).toHaveLength(1);+ expect(queries[0]?.query).toContain('FROM events');++ const bindingOf = (message: string) =>+ lines.find((line) => line.message === message)?.bindings.requestId;++ // The ClickHouse call's own log line, and the route's, carry ONE requestId.+ expect(bindingOf('query info')).toBe(SUPPLIED_REQUEST_ID);+ expect(bindingOf('request done')).toBe(SUPPLIED_REQUEST_ID);+```++plus a second case proving two concurrent requests do not share one+(`expect(queryLineIds.sort()).toEqual(['req-a', 'req-b'])`).++**`pnpm run check:deps`** (`.dependency-cruiser.cjs`, both rules unchanged at+their landed `warn` severity):++| Rule | Before (M10-002) | After (M10-003) | Delta |+|---|---:|---:|---:|+| `core-uses-ctx-not-db-internals` | 167 | **160** | **−7** |+| `core-no-self-barrel` | 74 | **62** | **−12** |++The ten modules themselves shed 10 edges; `v1-compat.ts`'s lazy fallback adds+3 back, in one file with a stated death date, for a net −7. Exit `0`,+`x 222 dependency violations (0 errors, 222 warnings). 1991 modules, 8035+dependencies cruised.` (was 241.)++**Verification, all run by ralph on 2026-09-05:**++- `pnpm run typecheck` — all 25 workspaces, `Done` (`packages/trpc` included:+ the barrel's V1 spellings are unchanged).+- `cd packages/core && bun test` (bare, no `--isolate`): **1457 pass, 12 skip,+ 0 fail**, `Ran 1469 tests across 149 files. [31.02s]`.+- `pnpm test` (root vitest, what `full.sh` runs): **13 files, 205/205 passed**.+- `pnpm run check:deps` — the table above.+- `controller:verification/harness start` — api :3333, worker :9999 ready in 3s.+- `cd apps/api && timeout 900 pnpm run e2e:sessions` — **29/29 checks passed**.+- `controller:verification/golden/compare.sh`:+ `passed: 137/137` / `OK: zero diffs` (`golden: http://127.0.0.1:3333 @+ 2026-09-05T07:59:27Z`; no `stale:` skips — same UTC day as the capture).+- `controller:verification/harness stop`.+- `controller:verification/full.sh` — `FULL: green (1 documented pre-existing+ exception(s) - see BLOCKED-KNOWN above)`, exit `0`. The one exception is+ `contracts/sdk/run.sh`'s `dist-gate.sh` on the documented pre-P11 state+ (web/nextjs/react-native/express leak `@openpanel/*`, sdk is clean); every+ other stage is `OK`, including `pnpm test`, `golden/compare.sh`+ (`passed: 137/137`, zero diffs) and `contracts/auth/run.sh`.diff --git a/packages/core/src/index.ts b/packages/core/src/index.tsindex 14fcfeff1..5eaf5da4f 100644--- a/packages/core/src/index.ts+++ b/packages/core/src/index.ts@@ -316,7 +316,6 @@ export {setLastAuthProviderCookie,setSessionTokenCookie,setupTotp,- signInToShare,signInWithEmail,signInWithTotp,signOutUser,@@ -363,58 +362,37 @@ export type {ShareableReportInput,} from './modules/chart/chart.service';export {- AggregateChartEngine,buildAllCohortsLabelExpr,buildAllCohortsMembershipQuery,buildCohortMembershipQuery,buildInlineCohortJoin,CHART_TABLE,ChartCohortIdError,- ChartEngine,collectBreakdownCohortIds,collectProfilePropertyKeys,createChartService,EVENT_FIELD_ALIASES,EVENT_TOP_LEVEL_COLUMNS,evaluateFormula,- executeAggregateChart,- executeChart,extractCohortId,- fetchCohortsMetadata,- fetchProjectCohorts,- getAggregateChartSql,- getChartBucketProfiles,- getChartPropertyValues,- getChartSql,getCohortAlias,getCohortCteName,- getConversionChart,getEventFiltersWhereClause,- getFunnelChart,- getFunnelStepProfiles,getGroupPropertySelect,getGroupPropertySql,getProfilePropertySelect,- getProjectCard,- getRetentionChart,- getSankeyChart,getSelectPropertyKey,InvalidFormulaError,isAllCohortsBreakdown,isKnownEventField,isNumericColumn,isValidFormula,- listChartEvents,- listChartProperties,normalizeEventField,profilePropertiesCteSelect,resolveReportInput,rewriteProfilePropertyRefs,transformPropertyKey,} from './modules/chart/chart.service';-// Dissolved from @openpanel/db's services/conversion.service.ts (M7-004) —-// reached through the chart module's own dispatch and the db shim.-export { getConversion } from './modules/chart/conversion.service';// Dissolved from @openpanel/db's services/funnel.service.ts (M7-004) —// packages/db's reports.service, apps/api's insights controller and the// mcp/assistant tools call these. packages/db/src/services/funnel.service.ts@@ -424,13 +402,9 @@ export type {FunnelStep,} from './modules/chart/funnel.service';export {- buildFunnelBase,buildSessionsCte,EMPTY_BREAKDOWN_LABEL,- getFunnel,- getFunnelCore,getFunnelGroup,- getFunnelProfileIds,toSeries,} from './modules/chart/funnel.service';// Dissolved from @openpanel/db's services/retention.service.ts (M7-004) —@@ -443,17 +417,7 @@ export type {IRetentionInterval,IServiceRetentionRollingActiveUsers,} from './modules/chart/retention.service';-export {- getEngagementCore,- getRetentionCohort,- getRetentionCohortCore,- getRetentionLastSeenSeries,- getRetentionSeries,- getRollingActiveUsers,- getRollingActiveUsersCore,- getWeeklyRetentionSeriesCore,- processCohortData,-} from './modules/chart/retention.service';+export { processCohortData } from './modules/chart/retention.service';// Dissolved from @openpanel/db's services/sankey.service.ts (M7-004) —// apps/api's insights controller and the mcp/assistant tools call these.// packages/db/src/services/sankey.service.ts stays a re-export shim.@@ -465,8 +429,6 @@ export type {} from './modules/chart/sankey.service';export {getRawWhereClause,- getSankey,- getUserFlowCore,zGetSankeyInput,} from './modules/chart/sankey.service';// Moved from packages/db/src/services/filter-where.service.ts (M8-005) — the@@ -542,15 +504,7 @@ export type {IServiceDashboard,IServiceDashboards,} from './modules/dashboard/dashboard.service';-export {- createDashboard,- deleteDashboard,- getDashboardById,- getDashboardByIdOrThrow,- getDashboardsByProjectId,- listDashboardsCore,- updateDashboard,-} from './modules/dashboard/dashboard.service';+export { createDashboardService } from './modules/dashboard/dashboard.service';// R + C only (M6-004): the router's three bodies are three small// `db.emailUnsubscribe` calls, small enough to live inline in// `email.rpc.ts` rather than a dedicated `email.service.ts` — see that@@ -614,6 +568,8 @@ export {transformSessionToEvent,updateEventMeta,} from './modules/event/event.service';+export type { ExportService } from './modules/export/export.service';+export { createExportService } from './modules/export/export.service';export type {GetGroupListOptions,GetGroupMemberProfilesOptions,@@ -945,15 +901,7 @@ export {// way V1 reaches every other dissolved service here. packages/db keeps a// re-export shim.export type { IServiceReference } from './modules/reference/reference.service';-export {- createReference,- deleteReference,- getChartReferences,- getReferenceById,- getReferenceByIdOrThrow,- listReferences,- updateReference,-} from './modules/reference/reference.service';+export { createReferenceService } from './modules/reference/reference.service';// Moved from packages/constants/index.ts and packages/validation/src/index.ts// (M7-006, ADR-008's module map: report owns "C" for the chart/report/widget// vocabulary) — apps/start's report builder and the assistant/mcp tools@@ -1015,25 +963,16 @@ export {// packages/db/src/services/reports.service.ts stays a re-export shim.export type { IServiceReport } from './modules/report/report.service';export {- createReport,- deleteReport,- duplicateReport,- getReportById,- getReportByIdOrThrow,- getReportDataCore,- getReportLayouts,- getReportsByDashboardId,- listReportsCore,- mergeGlobalFilters,- moveReport,- onlyReportEvents,- resetReportLayouts,+ createReportService,transformFilter,transformReport,transformReportEventItem,- updateReport,- updateReportLayout,} from './modules/report/report.service';+export type { ReportEventItem } from './modules/report/src/series';+export {+ mergeGlobalFilters,+ onlyReportEvents,+} from './modules/report/src/series';// Dissolved from @openpanel/db's services/session.service.ts and// session-context.ts, plus apps/worker's session-end job, reaper and vacuum// (M7-001, ADR-008's module map: session owns "R,S,J") — packages/trpc's@@ -1093,27 +1032,7 @@ export {zShareOverview,zShareReport,} from './modules/share/share.constants';-export {- createShareDashboard,- createShareOverview,- createShareReport,- getShareByProjectId,- getShareDashboard,- getShareDashboardByDashboardId,- getShareDashboardById,- getShareDashboardReports,- getShareDashboardSettings,- getShareOverview,- getShareOverviewById,- getShareOverviewSettings,- getShareReport,- getShareReportById,- getShareReportByReportId,- getShareReportSettings,- validateOverviewShareAccess,- validateReportAccess,- validateShareAccess,-} from './modules/share/share.service';+export { createShareService } from './modules/share/share.service';// Moved from packages/trpc/src/routers/subscription.ts, plus the Polar// webhook business logic out of// apps/api/src/controllers/webhook.controller.ts (M6-006, ADR-008's module@@ -1456,3 +1375,89 @@ export {} from './shared/safe-fetch';export { getId } from './shared/slug-id';export { assertSafeUrl, createPinnedLookup } from './shared/ssrf';+// The V1 compat seam (v1-compat.ts): the bare, deps-free spellings of the+// chart / report / dashboard / share / reference functions, kept for+// `packages/trpc`'s still-live routers and the mcp/assistant tool runtimes,+// which have no `Ctx` to carry `ServiceDeps`. Everything with a `Ctx` uses+// `ctx.services.*` instead. Deleted whole with `packages/trpc` at P10.+export {+ AggregateChartEngine,+ buildFunnelBase,+ ChartEngine,+ createDashboard,+ createReference,+ createReport,+ createShareDashboard,+ createShareOverview,+ createShareReport,+ deleteDashboard,+ deleteReference,+ deleteReport,+ duplicateReport,+ executeAggregateChart,+ executeChart,+ getChartBucketProfiles,+ getChartPropertyValues,+ getChartReferences,+ getConversion,+ getConversionChart,+ getDashboardById,+ getDashboardByIdOrThrow,+ getDashboardsByProjectId,+ getEngagementCore,+ getFunnel,+ getFunnelChart,+ getFunnelCore,+ getFunnelProfileIds,+ getFunnelStepProfiles,+ getProjectCard,+ getReferenceById,+ getReferenceByIdOrThrow,+ getReportById,+ getReportByIdOrThrow,+ getReportDataCore,+ getReportLayouts,+ getReportsByDashboardId,+ getRetentionChart,+ getRetentionCohort,+ getRetentionCohortCore,+ getRetentionLastSeenSeries,+ getRetentionSeries,+ getRollingActiveUsers,+ getRollingActiveUsersCore,+ getSankey,+ getSankeyChart,+ getShareByProjectId,+ getShareDashboard,+ getShareDashboardByDashboardId,+ getShareDashboardById,+ getShareDashboardReports,+ getShareDashboardSettings,+ getShareOverview,+ getShareOverviewById,+ getShareOverviewSettings,+ getShareReport,+ getShareReportById,+ getShareReportByReportId,+ getShareReportSettings,+ getUserFlowCore,+ getWeeklyRetentionSeriesCore,+ listChartEvents,+ listChartProperties,+ listDashboardsCore,+ listReferences,+ listReportsCore,+ moveReport,+ resetReportLayouts,+ resetV1CompatServicesForTests,+ setV1CompatServices,+ signInToShare,+ updateDashboard,+ updateReference,+ updateReport,+ updateReportLayout,+ V1_COMPAT_REQUEST_ID,+ validateOverviewShareAccess,+ validateReportAccess,+ validateShareAccess,+} from './v1-compat';diff --git a/packages/core/src/modules/auth/auth.rpc.ts b/packages/core/src/modules/auth/auth.rpc.tsindex 79cc3de99..a277e5bfb 100644--- a/packages/core/src/modules/auth/auth.rpc.ts+++ b/packages/core/src/modules/auth/auth.rpc.ts@@ -125,5 +125,5 @@ export const authRouter = createTRPCRouter({signInShare: procedure.input(zSignInShare)- .mutation(({ input, ctx }) => signInToShare(input, ctx.setCookie)),+ .mutation(({ input, ctx }) => signInToShare(ctx, input, ctx.setCookie)),});diff --git a/packages/core/src/modules/auth/auth.service.ts b/packages/core/src/modules/auth/auth.service.tsindex 39f51fad7..f373b3f19 100644--- a/packages/core/src/modules/auth/auth.service.ts+++ b/packages/core/src/modules/auth/auth.service.ts@@ -271,6 +271,12 @@ function loadRegistration() {return import('@openpanel/core');}+// GENUINE CYCLE, kept lazy: `../share/share.service` statically imports this+// file's `hashPassword`, and `signInToShare` below needs share's three+// lookups. auth.service.ts <-> share.service.ts is the cycle; the dynamic+// import is what keeps it a cycle ESM can evaluate. It is NOT a+// `@openpanel/db` loader — the share lookups take `deps` like everything+// else since M10-003.function loadShare() {return import('../share/share.service');}@@ -775,6 +781,7 @@ export interface SignInShareInput {}export async function signInToShare(+ deps: ServiceDeps,input: SignInShareInput,setCookie: ISetCookie): Promise<true> {@@ -786,13 +793,13 @@ export async function signInToShare(let cookieName = '';if (shareType === 'overview') {- share = await getShareOverviewById(shareId);+ share = await getShareOverviewById(deps, shareId);cookieName = `shared-overview-${shareId}`;} else if (shareType === 'dashboard') {- share = await getShareDashboardById(shareId);+ share = await getShareDashboardById(deps, shareId);cookieName = `shared-dashboard-${shareId}`;} else if (shareType === 'report') {- share = await getShareReportById(shareId);+ share = await getShareReportById(deps, shareId);cookieName = `shared-report-${shareId}`;}diff --git a/packages/core/src/modules/chart/chart.rpc.ts b/packages/core/src/modules/chart/chart.rpc.tsindex 0909513b4..06ecf032c 100644--- a/packages/core/src/modules/chart/chart.rpc.ts+++ b/packages/core/src/modules/chart/chart.rpc.ts@@ -12,7 +12,6 @@// saved report, and the request renders that report (the caller may only move// the date window). `resolveShare` is that middleware, inlined.-import type { IServiceReport } from '@openpanel/core';import {type IReportInput,zChartEventFilter,@@ -25,22 +24,7 @@ import {import { z } from 'zod';import { createTRPCRouter, procedure, type TrpcContext } from '../../rpc/base';import { TRPCAccessError, TRPCForbiddenError } from '../../rpc/errors';-import { validateShareAccess } from '../share/share.service';-import {- executeAggregateChart,- executeChart,- getChartBucketProfiles,- getChartPropertyValues,- getConversionChart,- getFunnelChart,- getFunnelStepProfiles,- getProjectCard,- getRetentionChart,- getSankeyChart,- listChartEvents,- listChartProperties,- resolveReportInput,-} from './chart.service';+import type { IServiceReport } from '../report/report.service';const zShareable = z.object({shareId: z.string().optional(),@@ -49,10 +33,6 @@ const zShareable = z.object({const zShareableReportInput = zReportInput.and(zShareable);-function loadReportsService() {- return import('@openpanel/core');-}-function requireLogin(userId: string | null | undefined): string {if (!userId) {throw new TRPCAccessError('Not authenticated');@@ -84,16 +64,19 @@ async function resolveShare(throw new Error('reportId required with shareId');}- const shareValidation = await validateShareAccess(input.shareId, input.id, {- cookies: ctx.cookies,- session: ctx.session.userId ? { userId: ctx.session.userId } : undefined,- });+ const shareValidation = await ctx.services.share.validateShareAccess(+ input.shareId,+ input.id,+ {+ cookies: ctx.cookies,+ session: ctx.session.userId ? { userId: ctx.session.userId } : undefined,+ }+ );if (!shareValidation.isValid) {throw new TRPCForbiddenError('You do not have access to this share');}- const { getReportById } = await loadReportsService();- const report = await getReportById(input.id);+ const report = await ctx.services.report.getReportById(input.id);if (!report) {throw new TRPCAccessError('Report not found');}@@ -104,7 +87,10 @@ async function resolveShareableReport(ctx: TrpcContext,input: IReportInput & { shareId?: string; id?: string }): Promise<IReportInput> {- return resolveReportInput(await resolveShare(ctx, input), input);+ return ctx.services.chart.resolveReportInput(+ await resolveShare(ctx, input),+ input+ );}export const chartRouter = createTRPCRouter({@@ -112,21 +98,21 @@ export const chartRouter = createTRPCRouter({.input(z.object({ projectId: z.string() })).query(async ({ input, ctx }) => {await requireReadAccess(ctx, input.projectId);- return getProjectCard(input.projectId);+ return ctx.services.chart.getProjectCard(input.projectId);}),events: procedure.input(z.object({ projectId: z.string() })).query(async ({ input, ctx }) => {await requireReadAccess(ctx, input.projectId);- return listChartEvents(input.projectId);+ return ctx.services.chart.listChartEvents(input.projectId);}),properties: procedure.input(z.object({ event: z.string().optional(), projectId: z.string() })).query(async ({ input, ctx }) => {await requireReadAccess(ctx, input.projectId);- return listChartProperties(input);+ return ctx.services.chart.listChartProperties(input);}),values: procedure@@ -139,36 +125,42 @@ export const chartRouter = createTRPCRouter({).query(async ({ input, ctx }) => {await requireReadAccess(ctx, input.projectId);- return getChartPropertyValues(input);+ return ctx.services.chart.getChartPropertyValues(input);}),funnel: procedure.input(zShareableReportInput).query(async ({ input, ctx }) =>- getFunnelChart(await resolveShareableReport(ctx, input))+ ctx.services.chart.getFunnelChart(+ await resolveShareableReport(ctx, input)+ )),conversion: procedure.input(zShareableReportInput).query(async ({ input, ctx }) =>- getConversionChart(await resolveShareableReport(ctx, input))+ ctx.services.chart.getConversionChart(+ await resolveShareableReport(ctx, input)+ )),sankey: procedure.input(zReportInput).query(async ({ input, ctx }) => {await requireReadAccess(ctx, input.projectId);- return getSankeyChart(input);+ return ctx.services.chart.getSankeyChart(input);}),chart: procedure.input(zShareableReportInput).query(async ({ input, ctx }) =>- executeChart(await resolveShareableReport(ctx, input))+ ctx.services.chart.execute(await resolveShareableReport(ctx, input))),aggregate: procedure.input(zShareableReportInput).query(async ({ input, ctx }) =>- executeAggregateChart(await resolveShareableReport(ctx, input))+ ctx.services.chart.executeAggregate(+ await resolveShareableReport(ctx, input)+ )),cohort: procedure@@ -188,7 +180,10 @@ export const chartRouter = createTRPCRouter({.and(zShareable)).query(async ({ input, ctx }) =>- getRetentionChart(await resolveShare(ctx, input), input)+ ctx.services.chart.getRetentionChart(+ await resolveShare(ctx, input),+ input+ )),getProfiles: procedure@@ -203,7 +198,7 @@ export const chartRouter = createTRPCRouter({).query(async ({ input, ctx }) => {await requireReadAccess(ctx, input.projectId);- return getChartBucketProfiles(input);+ return ctx.services.chart.bucketProfiles(input);}),getFunnelProfiles: procedure@@ -230,6 +225,6 @@ export const chartRouter = createTRPCRouter({).query(async ({ input, ctx }) => {await requireReadAccess(ctx, input.projectId);- return getFunnelStepProfiles(input);+ return ctx.services.chart.funnelStepProfiles(input);}),});diff --git a/packages/core/src/modules/chart/chart.service.test.ts b/packages/core/src/modules/chart/chart.service.test.tsindex 6d7ecace8..c404073d9 100644--- a/packages/core/src/modules/chart/chart.service.test.ts+++ b/packages/core/src/modules/chart/chart.service.test.ts@@ -30,7 +30,7 @@ mock.module('@openpanel/redis', () => ({}));let FIXTURE: typeof import('../../../../../test/fixtures').FIXTURE;-let service: typeof import('./chart.service');+let service: import('./chart.service').ChartService;let ch: typeof import('@openpanel/db/src/clickhouse/client').ch;type EventSeriesItem = Extract<IChartEventItem, { type: 'event' }>;@@ -62,7 +62,9 @@ beforeAll(async () => {const fixtures = await import('../../../../../test/fixtures');FIXTURE = fixtures.FIXTURE;({ ch } = await import('@openpanel/db/src/clickhouse/client'));- service = await import('./chart.service');+ const { testServiceDeps } = await import('../../../test/service-deps');+ const { createChartService } = await import('./chart.service');+ service = createChartService(await testServiceDeps());const { bootstrapTestDatabases } = await import('../../../../../test/bootstrap-databases'@@ -120,7 +122,7 @@ function seriesNamed<TSerie extends { names: string[] }>(describe('executeChart', () => {it('counts both page views over the last 30 days', async () => {- const chart = await service.executeChart(report());+ const chart = await service.execute(report());expect(chart.series).toHaveLength(1);expect(chart.series[0]?.names).toEqual(['page_view']);@@ -131,7 +133,7 @@ describe('executeChart', () => {});it('breaks down by browser', async () => {- const chart = await service.executeChart(+ const chart = await service.execute(report({ breakdowns: [{ id: 'b', name: 'browser' }] }));@@ -143,7 +145,7 @@ describe('executeChart', () => {});it('filters on cohort membership (inCohort / notInCohort)', async () => {- const inCohort = await service.executeChart(+ const inCohort = await service.execute(report({series: [pageView({@@ -160,7 +162,7 @@ describe('executeChart', () => {],}));- const notInCohort = await service.executeChart(+ const notInCohort = await service.execute(report({series: [pageView({@@ -183,10 +185,10 @@ describe('executeChart', () => {});it('breaks down by a single cohort and by all cohorts', async () => {- const single = await service.executeChart(+ const single = await service.execute(report({ breakdowns: [{ id: 'b', name: `cohort:${COHORT_ID}` }] }));- const all = await service.executeChart(+ const all = await service.execute(report({ breakdowns: [{ id: 'b', name: 'cohort' }] }));@@ -200,7 +202,7 @@ describe('executeChart', () => {});it('narrows profile properties into the profile CTE and still matches', async () => {- const chart = await service.executeChart(+ const chart = await service.execute(report({series: [pageView({@@ -225,7 +227,7 @@ describe('executeChart', () => {describe('executeAggregateChart', () => {it('sums revenue per browser without a time axis', async () => {- const chart = await service.executeAggregateChart(+ const chart = await service.executeAggregate(report({chartType: 'bar',series: [@@ -332,14 +334,14 @@ describe('getProjectCard', () => {describe('getChartBucketProfiles', () => {it('returns the profiles behind one data point, honoring breakdowns', async () => {const twoDaysAgo = new Date(Date.now() - 2 * DAY_MS).toISOString();- const profiles = await service.getChartBucketProfiles({+ const profiles = await service.bucketProfiles({projectId: TEST_PROJECT_ID,date: twoDaysAgo,interval: 'day',series: [pageView()],breakdowns: { browser: 'Chrome' },});- const none = await service.getChartBucketProfiles({+ const none = await service.bucketProfiles({projectId: TEST_PROJECT_ID,date: twoDaysAgo,interval: 'day',@@ -355,7 +357,7 @@ describe('getChartBucketProfiles', () => {it('selects only whitelisted profile columns for profile.* references', async () => {const twoDaysAgo = new Date(Date.now() - 2 * DAY_MS).toISOString();- const profiles = await service.getChartBucketProfiles({+ const profiles = await service.bucketProfiles({projectId: TEST_PROJECT_ID,date: twoDaysAgo,interval: 'day',@@ -377,7 +379,7 @@ describe('getChartBucketProfiles', () => {FIXTURE.profiles.alice,]);await expect(- service.getChartBucketProfiles({+ service.bucketProfiles({projectId: TEST_PROJECT_ID,date: twoDaysAgo,interval: 'day',diff --git a/packages/core/src/modules/chart/chart.service.ts b/packages/core/src/modules/chart/chart.service.tsindex 7a26cc352..63fdf7657 100644--- a/packages/core/src/modules/chart/chart.service.ts+++ b/packages/core/src/modules/chart/chart.service.ts@@ -9,15 +9,15 @@// dispatches to live in the sibling `*.service.ts` files of this module// (M7-004).//-// db/ch access is lazy (`load*`), as in the sibling modules: the barrel pulls-// this module into nearly every core test file, and constructing-// @openpanel/db's clients at import time costs a pino-pretty worker per file.+// M10-003: every function takes `ServiceDeps` and reaches ClickHouse and+// Postgres as `deps.ch` / `deps.db`. The `load*` lazy loaders are gone, and+// so is the `@openpanel/core` self-barrel hop this file used to make for the+// report module's `mergeGlobalFilters` / `onlyReportEvents` — those are+// imported straight from `../report/src/series` (docs/TECH_DEBT.md §2, §4).+// The one thing still value-imported from `@openpanel/db` under `./src/` is+// ADR-013's `sql` tag, which ADR-007 keeps in `packages/db` by name: a+// compile-time template tag, no client and no request scope.-import {- getChartPrevStartEndDate,- getChartStartEndDate,-} from '@openpanel/core';-import type { IServiceReport } from '@openpanel/core';import type {FinalChart,IChartEventFilter,@@ -29,6 +29,10 @@ import type {} from '@openpanel/validation';import { flatten, map, pipe, prop, sort, uniq } from 'ramda';import type { ServiceDeps } from '../../services';+import {+ getChartPrevStartEndDate,+ getChartStartEndDate,+} from '../../shared/date';import { getEventMetasCached } from '../event/event.service';import { getSettingsForProject } from '../organization/organization.service';import {@@ -36,10 +40,34 @@ import {getProfilesCached,type IServiceProfile,} from '../profile/profile.service';+import type { IServiceReport } from '../report/report.service';+import { mergeGlobalFilters, onlyReportEvents } from '../report/src/series';import { getConversion } from './conversion.service';-import { getFunnel, getFunnelProfileIds } from './funnel.service';-import { getRetentionCohort } from './retention.service';-import { getSankey } from './sankey.service';+import {+ buildFunnelBase,+ buildSessionsCte,+ getFunnel,+ getFunnelCore,+ getFunnelGroup,+ getFunnelProfileIds,+ toSeries as toFunnelSeries,+} from './funnel.service';+import {+ getEngagementCore,+ getRetentionCohort,+ getRetentionCohortCore,+ getRetentionLastSeenSeries,+ getRetentionSeries,+ getRollingActiveUsers,+ getRollingActiveUsersCore,+ getWeeklyRetentionSeriesCore,+ processCohortData,+} from './retention.service';+import {+ getRawWhereClause,+ getSankey,+ getUserFlowCore,+} from './sankey.service';import {chartBucketProfilesQuery,eventFieldValuesQuery,@@ -74,12 +102,7 @@ export {getAggregateChartSql,getChartSql,} from './src/chart-statement';-export {- AggregateChartEngine,- ChartEngine,- executeAggregateChart,- executeChart,-} from './src/engine/execute';+export { executeAggregateChart, executeChart } from './src/engine/execute';export {evaluateFormula,InvalidFormulaError,@@ -174,10 +197,6 @@ const FIXED_FILTER_PROPERTIES = ['profile.last_seen_at',];-function loadReportsService() {- return import('@openpanel/core');-}-async function getProfilesInBatches(ids: string[],projectId: string,@@ -263,15 +282,26 @@ function projectCardTrend(return { direction: 'neutral', percentage: 0 };}-export async function getProjectCard(projectId: string): Promise<{+export async function getProjectCard(+ deps: ServiceDeps,+ projectId: string+): Promise<{chart: ProjectCardChartRow[];metrics: ProjectCardMetrics | undefined;trend: ProjectCardTrend;}> {const { timezone } = await getSettingsForProject(projectId);const [chart, [metrics]] = await Promise.all([- runQuery<ProjectCardChartRow>(projectCardChartQuery(projectId), timezone),- runQuery<ProjectCardMetrics>(projectCardMetricsQuery(projectId), timezone),+ runQuery<ProjectCardChartRow>(+ deps,+ projectCardChartQuery(projectId),+ timezone+ ),+ runQuery<ProjectCardMetrics>(+ deps,+ projectCardMetricsQuery(projectId),+ timezone+ ),]);return {@@ -290,10 +320,12 @@ export interface ChartEventOption {}export async function listChartEvents(+ deps: ServiceDeps,projectId: string): Promise<ChartEventOption[]> {const [events, meta] = await Promise.all([runQuery<{ name: string; count: number }>(+ deps,eventNamesWithCountQuery(projectId)),getEventMetasCached(projectId),@@ -318,14 +350,18 @@ function toWildcardPropertyKey(key: string): string {return key.replace(/\.([0-9]+)\./g, '.*.').replace(/\.([0-9]+)/g, '[*]');}-export async function listChartProperties(input: {- projectId: string;- event?: string;-}): Promise<string[]> {+export async function listChartProperties(+ deps: ServiceDeps,+ input: {+ projectId: string;+ event?: string;+ }+): Promise<string[]> {const { projectId, event } = input;const [profileKeys, eventKeys] = await Promise.all([getProfilePropertyKeysCached(projectId),runQuery<{ property_key: string; created_at: string }>(+ deps,eventPropertyKeysQuery(projectId, event, EVENT_PROPERTY_KEY_LIMIT)),]);@@ -349,11 +385,14 @@ function nonEmptyValues(rows: { values: string }[]): string[] {return rows.map((row) => String(row.values)).filter(Boolean);}-export async function getChartPropertyValues(input: {- projectId: string;- event: string;- property: string;-}): Promise<{ values: string[] }> {+export async function getChartPropertyValues(+ deps: ServiceDeps,+ input: {+ projectId: string;+ event: string;+ property: string;+ }+): Promise<{ values: string[] }> {const { projectId, event, property } = input;if (property === 'has_profile') {@@ -362,6 +401,7 @@ export async function getChartPropertyValues(input: {if (property.startsWith('properties.')) {const rows = await runQuery<{ property_value: string; created_at: string }>(+ deps,eventPropertyValuesQuery(projectId,property.replace(/^properties\./, ''),@@ -374,6 +414,7 @@ export async function getChartPropertyValues(input: {if (property.startsWith('profile.')) {const rows = await runQuery<{ values: string }>(+ deps,profilePropertyValuesQuery(projectId, getProfilePropertySelect(property)));return { values: nonEmptyValues(rows) };@@ -381,6 +422,7 @@ export async function getChartPropertyValues(input: {if (property.startsWith('group.')) {const rows = await runQuery<{ values: string }>(+ deps,groupPropertyValuesQuery(projectId, getGroupPropertySelect(property)));return { values: nonEmptyValues(rows) };@@ -399,6 +441,7 @@ export async function getChartPropertyValues(input: {return { values: [] };}const rows = await runQuery<{ values: string[] }>(+ deps,eventFieldValuesQuery(projectId,getSelectPropertyKey(resolvedProperty),@@ -424,34 +467,40 @@ async function currentAndPreviousPeriod(chartInput: IReportInput) {return { timezone, currentPeriod, previousPeriod };}-export async function getFunnelChart(chartInput: IReportInput) {+export async function getFunnelChart(+ deps: ServiceDeps,+ chartInput: IReportInput+) {const { timezone, currentPeriod, previousPeriod } =await currentAndPreviousPeriod(chartInput);const [current, previous] = await Promise.all([- getFunnel({ ...chartInput, ...currentPeriod, timezone }),+ getFunnel(deps, { ...chartInput, ...currentPeriod, timezone }),chartInput.previous- ? getFunnel({ ...chartInput, ...previousPeriod, timezone })+ ? getFunnel(deps, { ...chartInput, ...previousPeriod, timezone }): Promise.resolve(null),]);return { current, previous };}-export async function getConversionChart(chartInput: IReportInput) {+export async function getConversionChart(+ deps: ServiceDeps,+ chartInput: IReportInput+) {const { timezone, currentPeriod, previousPeriod } =await currentAndPreviousPeriod(chartInput);const interval = chartInput.interval;const [current, previous] = await Promise.all([- getConversion({+ getConversion(deps, {...chartInput,...currentPeriod,interval,timezone,}),chartInput.previous- ? getConversion({+ ? getConversion(deps, {...chartInput,...previousPeriod,interval,@@ -472,8 +521,7 @@ export async function getConversionChart(chartInput: IReportInput) {};}-export async function getSankeyChart(input: IReportInput) {- const { mergeGlobalFilters, onlyReportEvents } = await loadReportsService();+export async function getSankeyChart(deps: ServiceDeps, input: IReportInput) {const { timezone } = await getSettingsForProject(input.projectId);const currentPeriod = getChartStartEndDate(input, timezone);@@ -489,7 +537,7 @@ export async function getSankeyChart(input: IReportInput) {throw new Error('Start and end events are required');}- return getSankey({+ return getSankey(deps, {projectId: input.projectId,startDate: currentPeriod.startDate,endDate: currentPeriod.endDate,@@ -556,6 +604,7 @@ function onlyEventSeries(series: NonNullable<IServiceReport>['series']) {}export async function getRetentionChart(+ deps: ServiceDeps,report: NonNullable<IServiceReport> | null,input: RetentionChartInput) {@@ -571,7 +620,7 @@ export async function getRetentionChart(timezone);- return getRetentionCohort({+ return getRetentionCohort(deps, {projectId: resolved.projectId,firstEvent: resolved.firstEvent,secondEvent: resolved.secondEvent,@@ -596,6 +645,7 @@ export interface ChartBucketProfilesRequest {/** Profiles behind one data point of a time-series chart (V1 `getProfiles`). */export async function getChartBucketProfiles(+ deps: ServiceDeps,input: ChartBucketProfilesRequest): Promise<IServiceProfile[]> {const serie = input.series[0];@@ -607,6 +657,7 @@ export async function getChartBucketProfiles(}const rows = await runQuery<{ profile_id: string }>(+ deps,chartBucketProfilesQuery({projectId: input.projectId,bucketDate: formatClickhouseDate(new Date(input.date)),@@ -645,6 +696,7 @@ export interface FunnelStepProfilesRequest {* joined fail with UNKNOWN_IDENTIFIER.*/export async function getFunnelStepProfiles(+ deps: ServiceDeps,input: FunnelStepProfilesRequest): Promise<IServiceProfile[]> {const { timezone } = await getSettingsForProject(input.projectId);@@ -660,7 +712,7 @@ export async function getFunnelStepProfiles(} = input;const { startDate, endDate } = getChartStartEndDate(input, timezone);- const ids = await getFunnelProfileIds({+ const ids = await getFunnelProfileIds(deps, {projectId,startDate,endDate,@@ -683,16 +735,146 @@ export async function getFunnelStepProfiles(// --- service -----------------------------------------------------------------+// The funnel, conversion, sankey and retention services live in this module's+// own sibling files, not in modules of their own (ADR-007 gives one service+// per module), so they FOLD INTO `ChartService` rather than becoming four+// more `Services` members: chart.service.ts is already the dispatcher every+// caller goes through (`getFunnelChart` / `getConversionChart` /+// `getSankeyChart` / `getRetentionChart`), and a `Services` key per file+// would name four things that are not modules.+export interface ChartService {+ // chartexecute(input: IReportInput): Promise<FinalChart>;executeAggregate(input: IReportInput): Promise<FinalChart>;+ resolveReportInput(+ report: NonNullable<IServiceReport> | null,+ input: ShareableReportInput+ ): IReportInput;+ getProjectCard(projectId: string): ReturnType<typeof getProjectCard>;+ listChartEvents(projectId: string): Promise<ChartEventOption[]>;+ listChartProperties(+ input: Parameters<typeof listChartProperties>[1]+ ): Promise<string[]>;+ getChartPropertyValues(+ input: Parameters<typeof getChartPropertyValues>[1]+ ): Promise<{ values: string[] }>;bucketProfiles(input: ChartBucketProfilesRequest): Promise<IServiceProfile[]>;+ funnelStepProfiles(+ input: FunnelStepProfilesRequest+ ): Promise<IServiceProfile[]>;+ // funnel+ getFunnelGroup(group?: string): ReturnType<typeof getFunnelGroup>;+ /** The funnel row -> serie grouping (funnel.service.ts's `toSeries`). */+ toFunnelSeries(+ ...args: Parameters<typeof toFunnelSeries>+ ): ReturnType<typeof toFunnelSeries>;+ buildSessionsCte(+ input: Parameters<typeof buildSessionsCte>[0]+ ): ReturnType<typeof buildSessionsCte>;+ getFunnelChart(chartInput: IReportInput): ReturnType<typeof getFunnelChart>;+ getFunnel(+ input: Parameters<typeof getFunnel>[1]+ ): ReturnType<typeof getFunnel>;+ getFunnelCore(+ input: Parameters<typeof getFunnelCore>[1]+ ): ReturnType<typeof getFunnelCore>;+ buildFunnelBase(+ input: Parameters<typeof buildFunnelBase>[1]+ ): ReturnType<typeof buildFunnelBase>;+ getFunnelProfileIds(+ input: Parameters<typeof getFunnelProfileIds>[1]+ ): Promise<string[]>;+ // conversion+ getConversionChart(+ chartInput: IReportInput+ ): ReturnType<typeof getConversionChart>;+ getConversion(+ input: Parameters<typeof getConversion>[1]+ ): ReturnType<typeof getConversion>;+ // sankey+ getRawWhereClause(+ type: 'events' | 'sessions',+ filters: IChartEventFilter[]+ ): string;+ getSankeyChart(input: IReportInput): ReturnType<typeof getSankeyChart>;+ getSankey(+ input: Parameters<typeof getSankey>[1]+ ): ReturnType<typeof getSankey>;+ getUserFlowCore(+ input: Parameters<typeof getUserFlowCore>[1]+ ): ReturnType<typeof getUserFlowCore>;+ // retention+ processCohortData(+ ...args: Parameters<typeof processCohortData>+ ): ReturnType<typeof processCohortData>;+ getRetentionChart(+ report: NonNullable<IServiceReport> | null,+ input: RetentionChartInput+ ): ReturnType<typeof getRetentionChart>;+ getRetentionCohort(+ input: Parameters<typeof getRetentionCohort>[1]+ ): ReturnType<typeof getRetentionCohort>;+ getRetentionCohortCore(+ projectId: string+ ): ReturnType<typeof getRetentionCohortCore>;+ getRetentionSeries(+ input: Parameters<typeof getRetentionSeries>[1]+ ): ReturnType<typeof getRetentionSeries>;+ getRetentionLastSeenSeries(+ input: Parameters<typeof getRetentionLastSeenSeries>[1]+ ): ReturnType<typeof getRetentionLastSeenSeries>;+ getRollingActiveUsers(+ input: Parameters<typeof getRollingActiveUsers>[1]+ ): ReturnType<typeof getRollingActiveUsers>;+ getRollingActiveUsersCore(+ input: Parameters<typeof getRollingActiveUsersCore>[1]+ ): ReturnType<typeof getRollingActiveUsersCore>;+ getWeeklyRetentionSeriesCore(+ projectId: string+ ): ReturnType<typeof getWeeklyRetentionSeriesCore>;+ getEngagementCore(projectId: string): ReturnType<typeof getEngagementCore>;}-export function createChartService(_deps: ServiceDeps): ChartService {+export function createChartService(deps: ServiceDeps): ChartService {return {- execute: executeChart,- executeAggregate: executeAggregateChart,- bucketProfiles: getChartBucketProfiles,+ execute: (input) => executeChart(deps, input),+ executeAggregate: (input) => executeAggregateChart(deps, input),+ resolveReportInput,+ getProjectCard: (projectId) => getProjectCard(deps, projectId),+ listChartEvents: (projectId) => listChartEvents(deps, projectId),+ listChartProperties: (input) => listChartProperties(deps, input),+ getChartPropertyValues: (input) => getChartPropertyValues(deps, input),+ bucketProfiles: (input) => getChartBucketProfiles(deps, input),+ funnelStepProfiles: (input) => getFunnelStepProfiles(deps, input),+ getFunnelGroup,+ toFunnelSeries,+ buildSessionsCte,+ getFunnelChart: (chartInput) => getFunnelChart(deps, chartInput),+ getFunnel: (input) => getFunnel(deps, input),+ getFunnelCore: (input) => getFunnelCore(deps, input),+ buildFunnelBase: (input) => buildFunnelBase(deps, input),+ getFunnelProfileIds: (input) => getFunnelProfileIds(deps, input),+ getConversionChart: (chartInput) => getConversionChart(deps, chartInput),+ getConversion: (input) => getConversion(deps, input),+ getRawWhereClause,+ getSankeyChart: (input) => getSankeyChart(deps, input),+ getSankey: (input) => getSankey(deps, input),+ getUserFlowCore: (input) => getUserFlowCore(deps, input),+ processCohortData,+ getRetentionChart: (report, input) =>+ getRetentionChart(deps, report, input),+ getRetentionCohort: (input) => getRetentionCohort(deps, input),+ getRetentionCohortCore: (projectId) =>+ getRetentionCohortCore(deps, projectId),+ getRetentionSeries: (input) => getRetentionSeries(deps, input),+ getRetentionLastSeenSeries: (input) =>+ getRetentionLastSeenSeries(deps, input),+ getRollingActiveUsers: (input) => getRollingActiveUsers(deps, input),+ getRollingActiveUsersCore: (input) =>+ getRollingActiveUsersCore(deps, input),+ getWeeklyRetentionSeriesCore: (projectId) =>+ getWeeklyRetentionSeriesCore(deps, projectId),+ getEngagementCore: (projectId) => getEngagementCore(deps, projectId),};}diff --git a/packages/core/src/modules/chart/conversion.service.ts b/packages/core/src/modules/chart/conversion.service.tsindex 6505efe29..abb6d8284 100644--- a/packages/core/src/modules/chart/conversion.service.ts+++ b/packages/core/src/modules/chart/conversion.service.ts@@ -6,6 +6,8 @@import { NOT_SET_VALUE } from '@openpanel/constants';import type { IReportInput } from '@openpanel/validation';import { omit } from 'ramda';+import type { ServiceDeps } from '../../services';+import { mergeGlobalFilters, onlyReportEvents } from '../report/src/series';import { fetchCohortsMetadata } from './src/chart-statement';import { type ConversionGroup, conversionQuery } from './src/conversion.sql';import {@@ -18,12 +20,6 @@ import {import { getEventFiltersWhereClause } from './src/filter-where';import { runQuery } from './src/run-query';-// Lazy: packages/db's reports.service imports the funnel shim, which points-// back here — a static import would close the cycle at module load.-function loadReportsService() {- return import('@openpanel/core');-}-/** Default funnel window, in hours, when the report does not set one. */const DEFAULT_FUNNEL_WINDOW_HOURS = 24;const SECONDS_PER_HOUR = 3600;@@ -85,19 +81,21 @@ function profileJoinFields(profileBreakdowns: { name: string }[]): string[] {return Array.from(fields);}-export async function getConversion({- projectId,- startDate,- endDate,- options,- series,- globalFilters,- breakdowns = [],- limit,- interval,- timezone,-}: ConversionChartInput) {- const { mergeGlobalFilters, onlyReportEvents } = await loadReportsService();+export async function getConversion(+ deps: ServiceDeps,+ {+ projectId,+ startDate,+ endDate,+ options,+ series,+ globalFilters,+ breakdowns = [],+ limit,+ interval,+ timezone,+ }: ConversionChartInput+) {const mergedSeries = mergeGlobalFilters(series, globalFilters);const funnelOptions = options?.type === 'funnel' ? options : undefined;const funnelGroup = funnelOptions?.funnelGroup;@@ -113,7 +111,7 @@ export async function getConversion({);const cohortIds = collectBreakdownCohortIds(knownBreakdowns);- const cohortMetadata = await fetchCohortsMetadata(cohortIds);+ const cohortMetadata = await fetchCohortsMetadata(deps, cohortIds);const cohortJoins = cohortIds.map((id) =>buildInlineCohortJoin(id, projectId, 'events'));@@ -167,6 +165,7 @@ export async function getConversion({).join(' AND ');const results = await runQuery<ConversionRow>(+ deps,conversionQuery({projectId,startDate,diff --git a/packages/core/src/modules/chart/funnel.service.ts b/packages/core/src/modules/chart/funnel.service.tsindex 4529567a8..c9ed2977c 100644--- a/packages/core/src/modules/chart/funnel.service.ts+++ b/packages/core/src/modules/chart/funnel.service.ts@@ -10,7 +10,9 @@ import type {IReportInput,} from '@openpanel/validation';import { last, reverse } from 'ramda';+import type { ServiceDeps } from '../../services';import { getSettingsForProject } from '../organization/organization.service';+import { mergeGlobalFilters, onlyReportEvents } from '../report/src/series';import { fetchCohortsMetadata } from './src/chart-statement';import { collectBreakdownCohortIds } from './src/field-resolution';import {@@ -26,12 +28,6 @@ import {} from './src/funnel.sql';import { runQuery } from './src/run-query';-// Lazy: packages/db's reports.service imports the funnel shim, which points-// back here — a static import would close the cycle at module load.-function loadReportsService() {- return import('@openpanel/core');-}-export {EMPTY_BREAKDOWN_LABEL,type FunnelBase,@@ -104,23 +100,26 @@ export interface BuildFunnelBaseInput {* normalized event series and breakdowns, and the `session_funnel` / `funnel`* CTEs with all of their joins wired up. Callers add their own projection.*/-export async function buildFunnelBase({- projectId,- startDate,- endDate,- series,- globalFilters,- breakdowns: initialBreakdowns = [],- funnelWindow = DEFAULT_FUNNEL_WINDOW_HOURS,- funnelGroup,- timezone,-}: BuildFunnelBaseInput): Promise<FunnelBase> {- const { mergeGlobalFilters, onlyReportEvents } = await loadReportsService();+export async function buildFunnelBase(+ deps: ServiceDeps,+ {+ projectId,+ startDate,+ endDate,+ series,+ globalFilters,+ breakdowns: initialBreakdowns = [],+ funnelWindow = DEFAULT_FUNNEL_WINDOW_HOURS,+ funnelGroup,+ timezone,+ }: BuildFunnelBaseInput+): Promise<FunnelBase> {const breakdowns = knownFunnelBreakdowns(initialBreakdowns);const eventSeries = onlyReportEvents(mergeGlobalFilters(series, globalFilters));const cohortMetadata = await fetchCohortsMetadata(+ deps,collectBreakdownCohortIds(breakdowns));@@ -273,23 +272,26 @@ function toFunnelSteps(return { steps, totalSessions };}-export async function getFunnel({- projectId,- startDate,- endDate,- series,- globalFilters,- options,- breakdowns: initialBreakdowns = [],- limit,- timezone = 'UTC',-}: IReportInput & { timezone: string; events?: IChartEvent[] }) {+export async function getFunnel(+ deps: ServiceDeps,+ {+ projectId,+ startDate,+ endDate,+ series,+ globalFilters,+ options,+ breakdowns: initialBreakdowns = [],+ limit,+ timezone = 'UTC',+ }: IReportInput & { timezone: string; events?: IChartEvent[] }+) {if (!(startDate && endDate)) {throw new Error('startDate and endDate are required');}const funnelOptions = options?.type === 'funnel' ? options : undefined;- const base = await buildFunnelBase({+ const base = await buildFunnelBase(deps, {projectId,startDate,endDate,@@ -302,6 +304,7 @@ export async function getFunnel({});const funnelData = await runQuery<FunnelRow>(+ deps,funnelChartQuery(base),base.timezone);@@ -327,14 +330,17 @@ export async function getFunnel({});}-export async function getFunnelCore(input: {- projectId: string;- startDate: string;- endDate: string;- steps: string[];- windowHours?: number;- groupBy?: FunnelGroup;-}) {+export async function getFunnelCore(+ deps: ServiceDeps,+ input: {+ projectId: string;+ startDate: string;+ endDate: string;+ steps: string[];+ windowHours?: number;+ groupBy?: FunnelGroup;+ }+) {const { timezone } = await getSettingsForProject(input.projectId);const eventSeries = input.steps.map((name, index) => ({id: String(index + 1),@@ -345,7 +351,7 @@ export async function getFunnelCore(input: {filters: [],}));- const result = await getFunnel({+ const result = await getFunnel(deps, {projectId: input.projectId,startDate: input.startDate,endDate: input.endDate,@@ -405,13 +411,15 @@ export async function getFunnelCore(input: {}export async function getFunnelProfileIds(+ deps: ServiceDeps,input: BuildFunnelBaseInput &Omit<FunnelProfilesInput, 'breakdownValues'> & {breakdownValues: (string | undefined)[];}): Promise<string[]> {- const base = await buildFunnelBase(input);+ const base = await buildFunnelBase(deps, input);const rows = await runQuery<{ profile_id: string }>(+ deps,funnelProfilesQuery(base, {targetLevel: input.targetLevel,showDropoffs: input.showDropoffs,diff --git a/packages/core/src/modules/chart/retention.service.test.ts b/packages/core/src/modules/chart/retention.service.test.tsindex 23eec756d..7669d54af 100644--- a/packages/core/src/modules/chart/retention.service.test.ts+++ b/packages/core/src/modules/chart/retention.service.test.ts@@ -7,6 +7,8 @@ import {setupRetentionFixtures,teardownRetentionFixtures,} from '../../../../../test/retention-fixtures';+import { testServiceDeps } from '../../../test/service-deps';+import type { ServiceDeps } from '../../services';import {getRetentionCohort,getRetentionSeries,@@ -15,6 +17,10 @@ import {} from './retention.service';const PROJECT_ID = 'test-retention-cohort';++// M10-003: retention reaches ClickHouse as `deps.ch`, so the suite builds the+// same `ServiceDeps` main.ts does (pointed at `openpanel_test` by preload.ts).+let deps: ServiceDeps;const { day, week } = RETENTION_FIXTURE;// bun:test's `toEqual` overloads (unlike vitest's) reject a `readonly` actual@@ -43,6 +49,7 @@ function cohortsOnly(rows: IRetentionCohortRow[]) {describe('getRetentionCohort', () => {beforeAll(async () => {+ deps = await testServiceDeps();await setupRetentionFixtures(PROJECT_ID);});@@ -51,7 +58,7 @@ describe('getRetentionCohort', () => {});it('matches the blueprint for day interval, criteria "on"', async () => {- const rows = await getRetentionCohort({+ const rows = await getRetentionCohort(deps, {projectId: PROJECT_ID,firstEvent: ['app_open'],secondEvent: ['app_open'],@@ -65,7 +72,7 @@ describe('getRetentionCohort', () => {});it('matches the blueprint for day interval, criteria "on_or_after"', async () => {- const rows = await getRetentionCohort({+ const rows = await getRetentionCohort(deps, {projectId: PROJECT_ID,firstEvent: ['app_open'],secondEvent: ['app_open'],@@ -84,7 +91,7 @@ describe('getRetentionCohort', () => {// The old toWeek() implementation returned week-of-year (resets each Jan),// so a 2024-W52 -> 2025-W01 return produced a negative diff and was dropped.// This locks the year-aware behavior.- const rows = await getRetentionCohort({+ const rows = await getRetentionCohort(deps, {projectId: PROJECT_ID,firstEvent: ['app_open'],secondEvent: ['app_open'],@@ -98,7 +105,7 @@ describe('getRetentionCohort', () => {});it('prepends a weighted-average row that is 100% retained at interval 0', async () => {- const rows = await getRetentionCohort({+ const rows = await getRetentionCohort(deps, {projectId: PROJECT_ID,firstEvent: ['app_open'],secondEvent: ['app_open'],@@ -114,7 +121,7 @@ describe('getRetentionCohort', () => {it('assigns each user to a single first-touch cohort (no double-counting)', async () => {const rows = cohortsOnly(- await getRetentionCohort({+ await getRetentionCohort(deps, {projectId: PROJECT_ID,firstEvent: ['app_open'],secondEvent: ['app_open'],@@ -150,7 +157,7 @@ describe('getRetentionCohort', () => {});it('supports any-event (active-user) retention when no event names given', async () => {- const named = await getRetentionCohort({+ const named = await getRetentionCohort(deps, {projectId: PROJECT_ID,firstEvent: ['app_open'],secondEvent: ['app_open'],@@ -159,7 +166,7 @@ describe('getRetentionCohort', () => {startDate: day.start,endDate: day.end,});- const anyEvent = await getRetentionCohort({+ const anyEvent = await getRetentionCohort(deps, {projectId: PROJECT_ID,criteria: 'on',interval: 'day',@@ -179,7 +186,7 @@ describe('getRetentionCohort', () => {// country = US drops RU3 (SE) from the D0 cohort. This filter references an// event column not present in cohort_events_mv, so the engine must fall// back to the raw events table.- const rows = await getRetentionCohort({+ const rows = await getRetentionCohort(deps, {projectId: PROJECT_ID,firstEvent: ['app_open'],secondEvent: ['app_open'],@@ -196,7 +203,7 @@ describe('getRetentionCohort', () => {it('scopes to a saved cohort via the fast MV path (inCohort)', async () => {// inCohort only needs profile_id, so this stays on cohort_events_mv. The// cohort contains RU1 and RU4, leaving one user in each of D0 and D1.- const rows = await getRetentionCohort({+ const rows = await getRetentionCohort(deps, {projectId: PROJECT_ID,firstEvent: ['app_open'],secondEvent: ['app_open'],@@ -220,6 +227,7 @@ describe('getRetentionCohort', () => {describe('getRetentionSeries', () => {beforeAll(async () => {+ deps = await testServiceDeps();await setupRetentionFixtures(PROJECT_ID);});@@ -228,7 +236,7 @@ describe('getRetentionSeries', () => {});it('computes week-over-week active-user retention', async () => {- const rows = await getRetentionSeries({ projectId: PROJECT_ID });+ const rows = await getRetentionSeries(deps, { projectId: PROJECT_ID });expect(rows).toEqual(mutable(RETENTION_BLUEPRINT.weeklySeries));});});diff --git a/packages/core/src/modules/chart/retention.service.ts b/packages/core/src/modules/chart/retention.service.tsindex f9c72e7c7..363bf256f 100644--- a/packages/core/src/modules/chart/retention.service.ts+++ b/packages/core/src/modules/chart/retention.service.ts@@ -10,6 +10,7 @@import { DateTime, round } from '@openpanel/common';import type { IChartEventFilter } from '@openpanel/validation';import { range } from 'ramda';+import type { ServiceDeps } from '../../services';import {type IRetentionCriteria,type IRetentionInterval,@@ -85,40 +86,48 @@ export interface IGetRetentionCohortInput {// Instead of self-joining the raw events table (O(events²) per profile), the// statement first collapses events to one row per (profile, week), then// self-joins that much smaller set to its next week.-export function getRetentionSeries({ projectId }: IGetWeekRetentionInput) {+export function getRetentionSeries(+ deps: ServiceDeps,+ { projectId }: IGetWeekRetentionInput+) {return runQuery<{date: string;active_users: number;retained_users: number;retention: number;- }>(retentionSeriesQuery(projectId));+ }>(deps, retentionSeriesQuery(projectId));}// https://medium.com/@andre_bodro/how-to-fast-calculating-mau-in-clickhouse-fd793559b229// Rolling active users-export function getRollingActiveUsers({- projectId,- days,-}: IGetWeekRetentionInput & { days: number }) {+export function getRollingActiveUsers(+ deps: ServiceDeps,+ { projectId, days }: IGetWeekRetentionInput & { days: number }+) {return runQuery<IServiceRetentionRollingActiveUsers>(+ deps,rollingActiveUsersQuery(projectId, days));}-export function getRetentionLastSeenSeries({- projectId,-}: IGetWeekRetentionInput) {+export function getRetentionLastSeenSeries(+ deps: ServiceDeps,+ { projectId }: IGetWeekRetentionInput+) {return runQuery<{days: number;users: number;- }>(retentionLastSeenSeriesQuery(projectId));+ }>(deps, retentionLastSeenSeriesQuery(projectId));}-export async function getRollingActiveUsersCore(input: {- projectId: string;- days: number;-}) {- const data = await getRollingActiveUsers(input);+export async function getRollingActiveUsersCore(+ deps: ServiceDeps,+ input: {+ projectId: string;+ days: number;+ }+) {+ const data = await getRollingActiveUsers(deps, input);return {window_days: input.days,label: ROLLING_ACTIVE_USER_LABELS[input.days] ?? `${input.days}d active`,@@ -126,17 +135,23 @@ export async function getRollingActiveUsersCore(input: {};}-export async function getWeeklyRetentionSeriesCore(projectId: string) {- return getRetentionSeries({ projectId });+export async function getWeeklyRetentionSeriesCore(+ deps: ServiceDeps,+ projectId: string+) {+ return getRetentionSeries(deps, { projectId });}// Weekly active-user retention cohort over the last 12 weeks, computed by the// unified getRetentionCohort engine. firstEvent/secondEvent are omitted so any// identified activity counts toward the cohort.-export async function getRetentionCohortCore(projectId: string) {+export async function getRetentionCohortCore(+ deps: ServiceDeps,+ projectId: string+) {const end = DateTime.now();const start = end.minus({ weeks: RETENTION_COHORT_WEEKS });- return getRetentionCohort({+ return getRetentionCohort(deps, {projectId,interval: 'week',startDate: start.toFormat('yyyy-MM-dd HH:mm:ss'),@@ -144,8 +159,8 @@ export async function getRetentionCohortCore(projectId: string) {});}-export async function getEngagementCore(projectId: string) {- const raw = await getRetentionLastSeenSeries({ projectId });+export async function getEngagementCore(deps: ServiceDeps, projectId: string) {+ const raw = await getRetentionLastSeenSeries(deps, { projectId });let active_0_7 = 0;let active_8_14 = 0;@@ -228,7 +243,10 @@ function diffIntervalCount(return Math.max(0, Math.floor(end.diff(start, unit).as(unit)));}-export async function getRetentionCohort(input: IGetRetentionCohortInput) {+export async function getRetentionCohort(+ deps: ServiceDeps,+ input: IGetRetentionCohortInput+) {const {projectId,firstEvent,@@ -247,6 +265,7 @@ export async function getRetentionCohort(input: IGetRetentionCohortInput) {total_first_event_count: number;[key: string]: number | string;}>(+ deps,retentionCohortQuery({projectId,firstEvent,diff --git a/packages/core/src/modules/chart/sankey.service.ts b/packages/core/src/modules/chart/sankey.service.tsindex 77b84c3b4..7a47f58b4 100644--- a/packages/core/src/modules/chart/sankey.service.ts+++ b/packages/core/src/modules/chart/sankey.service.ts@@ -6,6 +6,7 @@import { chartColors } from '@openpanel/constants';import { type IChartEventFilter, zChartEvent } from '@openpanel/validation';import { z } from 'zod';+import type { ServiceDeps } from '../../services';import { getSettingsForProject } from '../organization/organization.service';import { getEventFiltersWhereClause } from './src/filter-where';import { runQuery } from './src/run-query';@@ -133,18 +134,21 @@ function toSankeyEvent(: undefined;}-export async function getSankey({- projectId,- startDate,- endDate,- steps = DEFAULT_SANKEY_STEPS,- mode,- startEvent,- endEvent,- exclude = [],- include,- timezone,-}: IGetSankeyInput): Promise<SankeyResult> {+export async function getSankey(+ deps: ServiceDeps,+ {+ projectId,+ startDate,+ endDate,+ steps = DEFAULT_SANKEY_STEPS,+ mode,+ startEvent,+ endEvent,+ exclude = [],+ include,+ timezone,+ }: IGetSankeyInput+): Promise<SankeyResult> {const colors = chartColors.map((color) => color.main);const pathsInput: SankeyPathsInput = {projectId,@@ -162,6 +166,7 @@ export async function getSankey({const end = pathsInput.endEvent as SankeyEvent;const topEntries = await runQuery<TopEntry>(+ deps,isBetween? sankeyBetweenTopEntriesQuery(pathsInput, start, end): sankeyTopEntriesQuery(pathsInput),@@ -176,6 +181,7 @@ export async function getSankey({const totalSessions = topEntries.reduce((sum, entry) => sum + entry.count, 0);const transitions = await runQuery<Transition>(+ deps,isBetween? sankeyBetweenTransitionsQuery(pathsInput, start, end, topEntryEvents): sankeyTransitionsQuery(pathsInput, topEntryEvents),@@ -463,23 +469,26 @@ function toChartEvent(name: string) {};}-export async function getUserFlowCore(input: {- projectId: string;- startDate: string;- endDate: string;- startEvent: string;- endEvent?: string;- mode: 'after' | 'before' | 'between';- steps?: number;- exclude?: string[];- include?: string[];-}) {+export async function getUserFlowCore(+ deps: ServiceDeps,+ input: {+ projectId: string;+ startDate: string;+ endDate: string;+ startEvent: string;+ endEvent?: string;+ mode: 'after' | 'before' | 'between';+ steps?: number;+ exclude?: string[];+ include?: string[];+ }+) {if (input.mode === 'between' && !input.endEvent) {throw new Error('endEvent is required when mode is "between"');}const { timezone } = await getSettingsForProject(input.projectId);- const result = await getSankey({+ const result = await getSankey(deps, {projectId: input.projectId,startDate: input.startDate,endDate: input.endDate,diff --git a/packages/core/src/modules/chart/src/chart-statement.ts b/packages/core/src/modules/chart/src/chart-statement.tsindex 5a4e81f99..8cc16d1a2 100644--- a/packages/core/src/modules/chart/src/chart-statement.ts+++ b/packages/core/src/modules/chart/src/chart-statement.ts@@ -5,6 +5,7 @@import type { SqlFragment } from '@openpanel/db/src/clickhouse/sql';import type { IGetChartDataInput } from '@openpanel/validation';+import type { ServiceDeps } from '../../../services';import {aggregateChartQuery,chartSeriesQuery,@@ -22,51 +23,53 @@ export type AggregateChartSqlInput = Omit<'interval' | 'chartType'> & { timezone: string };-function loadDb() {- return import('@openpanel/db/src/prisma-client').then((m) => m.db);-}-export async function fetchCohortsMetadata(+ deps: ServiceDeps,cohortIds: string[]): Promise<Map<string, CohortMetadata>> {if (cohortIds.length === 0) {return new Map();}- const db = await loadDb();- const cohorts = await db.cohort.findMany({+ const cohorts = await deps.db.cohort.findMany({where: { id: { in: cohortIds } },select: { id: true, name: true },});return new Map(cohorts.map((c) => [c.id, { id: c.id, name: c.name }]));}-export async function fetchProjectCohorts(+export function fetchProjectCohorts(+ deps: ServiceDeps,projectId: string): Promise<CohortMetadata[]> {- const db = await loadDb();- return db.cohort.findMany({+ return deps.db.cohort.findMany({where: { projectId },select: { id: true, name: true },});}export async function resolveChartBreakdowns(+ deps: ServiceDeps,projectId: string,requested: IGetChartDataInput['breakdowns']): Promise<ResolvedChartBreakdowns> {const known = knownBreakdowns(requested);const allCohorts = requestsAllCohortsBreakdown(known)- ? await fetchProjectCohorts(projectId)+ ? await fetchProjectCohorts(deps, projectId): [];const breakdowns = withoutEmptyAllCohortsBreakdown(known, allCohorts);const cohortMetadata = await fetchCohortsMetadata(+ deps,collectBreakdownCohortIds(breakdowns));return { breakdowns, allCohorts, cohortMetadata };}-export async function getChartSql(input: ChartSqlInput): Promise<SqlFragment> {+export async function getChartSql(+ deps: ServiceDeps,+ input: ChartSqlInput+): Promise<SqlFragment> {const resolved = await resolveChartBreakdowns(+ deps,input.projectId,input.breakdowns);@@ -82,9 +85,11 @@ export async function getChartSql(input: ChartSqlInput): Promise<SqlFragment> {}export async function getAggregateChartSql(+ deps: ServiceDeps,input: AggregateChartSqlInput): Promise<SqlFragment> {const resolved = await resolveChartBreakdowns(+ deps,input.projectId,input.breakdowns);diff --git a/packages/core/src/modules/chart/src/chart.sql.test.ts b/packages/core/src/modules/chart/src/chart.sql.test.tsindex 5183742b5..870cbca10 100644--- a/packages/core/src/modules/chart/src/chart.sql.test.ts+++ b/packages/core/src/modules/chart/src/chart.sql.test.ts@@ -42,6 +42,7 @@ afterAll(() => {});let ch: typeof import('@openpanel/db/src/clickhouse/client').ch;+let deps: import('../../../services').ServiceDeps;let buildChartSql: typeof import('./chart-statement').getChartSql;let buildAggregateChartSql: typeof import('./chart-statement').getAggregateChartSql;@@ -53,11 +54,13 @@ type LooseAggregateInput = Partial<AggregateChartSqlInput> &Pick<AggregateChartSqlInput, 'event' | 'projectId' | 'timezone'>;async function getChartSql(input: LooseChartInput) {- return render(await buildChartSql(input as ChartSqlInput));+ return render(await buildChartSql(deps, input as ChartSqlInput));}async function getAggregateChartSql(input: LooseAggregateInput) {- return render(await buildAggregateChartSql(input as AggregateChartSqlInput));+ return render(+ await buildAggregateChartSql(deps, input as AggregateChartSqlInput)+ );}interface Rendered {@@ -98,6 +101,8 @@ const base = {beforeAll(async () => {({ ch } = await import('@openpanel/db/src/clickhouse/client'));+ const { testServiceDeps } = await import('../../../../test/service-deps');+ deps = await testServiceDeps();({getChartSql: buildChartSql,getAggregateChartSql: buildAggregateChartSql,diff --git a/packages/core/src/modules/chart/src/engine/execute.ts b/packages/core/src/modules/chart/src/engine/execute.tsindex 738bc25a5..2a015d07f 100644--- a/packages/core/src/modules/chart/src/engine/execute.ts+++ b/packages/core/src/modules/chart/src/engine/execute.ts@@ -1,5 +1,6 @@-import { getChartPrevStartEndDate } from '@openpanel/core';import type { FinalChart, IReportInput } from '@openpanel/validation';+import type { ServiceDeps } from '../../../../services';+import { getChartPrevStartEndDate } from '../../../../shared/date';import {getOrganizationSubscriptionChartEndDate,getSettingsForProject,@@ -27,11 +28,14 @@ async function normalizeWithinSubscription(}/** Time-series chart: normalize -> plan -> fetch -> compute -> format. */-export async function executeChart(input: IReportInput): Promise<FinalChart> {+export async function executeChart(+ deps: ServiceDeps,+ input: IReportInput+): Promise<FinalChart> {const normalized = await normalizeWithinSubscription(input);const executionPlan = await plan(normalized);const computedSeries = compute(- await fetch(executionPlan),+ await fetch(deps, executionPlan),executionPlan.definitions);@@ -45,7 +49,7 @@ export async function executeChart(input: IReportInput): Promise<FinalChart> {}),});previousSeries = compute(- await fetch(previousPlan),+ await fetch(deps, previousPlan),previousPlan.definitions);}@@ -61,6 +65,7 @@ export async function executeChart(input: IReportInput): Promise<FinalChart> {/** Bar/pie chart without a time axis: normalize -> fetch aggregate -> format. */export async function executeAggregateChart(+ deps: ServiceDeps,input: IReportInput): Promise<FinalChart> {const normalized = await normalizeWithinSubscription(input);@@ -70,7 +75,7 @@ export async function executeAggregateChart(endDate: normalized.endDate,};const computedSeries = compute(- await fetchAggregate(normalized, currentPeriod, timezone),+ await fetchAggregate(deps, normalized, currentPeriod, timezone),normalized.series);@@ -78,6 +83,7 @@ export async function executeAggregateChart(if (input.previous) {previousSeries = compute(await fetchAggregate(+ deps,normalized,getChartPrevStartEndDate(currentPeriod),timezone@@ -94,11 +100,3 @@ export async function executeAggregateChart(normalized.limit);}--export const ChartEngine = {- execute: executeChart,-};--export const AggregateChartEngine = {- execute: executeAggregateChart,-};diff --git a/packages/core/src/modules/chart/src/engine/fetch.ts b/packages/core/src/modules/chart/src/engine/fetch.tsindex ed304c799..0054b0d2e 100644--- a/packages/core/src/modules/chart/src/engine/fetch.ts+++ b/packages/core/src/modules/chart/src/engine/fetch.ts@@ -7,22 +7,20 @@ import type {IChartEventItem,IGetChartDataInput,} from '@openpanel/validation';+import type { ServiceDeps } from '../../../../services';import { getAggregateChartSql, getChartSql } from '../chart-statement';+import { runQuery } from '../run-query';import type { NormalizedInput } from './normalize';import type { ConcreteSeries, Plan, SeriesDefinition } from './types';type EventDefinition = IChartEventItem & { type: 'event' };-function loadChClient() {- return import('@openpanel/db/src/clickhouse/client');-}--async function runChartQuery(+function runChartQuery(+ deps: ServiceDeps,statement: Awaited<ReturnType<typeof getChartSql>>,timezone: string): Promise<ISerieDataItem[]> {- const { chQuery } = await loadChClient();- return chQuery<ISerieDataItem>(statement, { session_timezone: timezone });+ return runQuery<ISerieDataItem>(deps, statement, timezone);}function breakdownFilters(@@ -122,7 +120,10 @@ function queryEvent(event: EventDefinition): IGetChartDataInput['event'] {}/** Fetch every event series of the plan; breakdown expansion included. */-export async function fetch(plan: Plan): Promise<ConcreteSeries[]> {+export async function fetch(+ deps: ServiceDeps,+ plan: Plan+): Promise<ConcreteSeries[]> {const results: ConcreteSeries[] = [];for (const [index, definition] of plan.definitions.entries()) {@@ -152,13 +153,15 @@ export async function fetch(plan: Plan): Promise<ConcreteSeries[]> {};let rows = await runChartQuery(- await getChartSql({ ...queryInput, timezone: plan.timezone }),+ deps,+ await getChartSql(deps, { ...queryInput, timezone: plan.timezone }),plan.timezone);// Nothing matched the breakdown: fall back to the plain series.if (rows.length === 0 && plan.input.breakdowns.length > 0) {rows = await runChartQuery(- await getChartSql({+ deps,+ await getChartSql(deps, {...queryInput,breakdowns: [],timezone: plan.timezone,@@ -187,6 +190,7 @@ export async function fetch(plan: Plan): Promise<ConcreteSeries[]> {* constant date, for the given period.*/export async function fetchAggregate(+ deps: ServiceDeps,normalized: NormalizedInput,period: { startDate: string; endDate: string },timezone: string@@ -212,12 +216,14 @@ export async function fetchAggregate(};let rows = await runChartQuery(- await getAggregateChartSql(queryInput),+ deps,+ await getAggregateChartSql(deps, queryInput),timezone);if (rows.length === 0 && normalized.breakdowns.length > 0) {rows = await runChartQuery(- await getAggregateChartSql({ ...queryInput, breakdowns: [] }),+ deps,+ await getAggregateChartSql(deps, { ...queryInput, breakdowns: [] }),timezone);}diff --git a/packages/core/src/modules/chart/src/engine/normalize.ts b/packages/core/src/modules/chart/src/engine/normalize.tsindex 28b3c6bc1..78d663613 100644--- a/packages/core/src/modules/chart/src/engine/normalize.ts+++ b/packages/core/src/modules/chart/src/engine/normalize.ts@@ -1,25 +1,18 @@import { alphabetIds } from '@openpanel/constants';-import { getChartStartEndDate } from '@openpanel/core';import type {IChartEvent,IReportInput,IReportInputWithDates,} from '@openpanel/validation';+import { getChartStartEndDate } from '../../../../shared/date';import { getSettingsForProject } from '../../../organization/organization.service';+import { mergeGlobalFilters } from '../../../report/src/series';import type { SeriesDefinition } from './types';export type NormalizedInput = IReportInputWithDates & {series: SeriesDefinition[];};-// `mergeGlobalFilters` belongs to the report module (its own task); until it-// moves, reach V1's copy lazily — reports.service imports prisma at load.-function loadGlobalFilterMerge() {- return import('@openpanel/core').then(- (m) => m.mergeGlobalFilters- );-}-type LegacySeriesItem = Partial<IChartEvent> & { type?: string };function toSeriesDefinition(@@ -59,8 +52,6 @@ export async function normalize(input: IReportInput): Promise<NormalizedInput> {(input as { series?: LegacySeriesItem[] }).series ??(input as { events?: LegacySeriesItem[] }).events ??[];- const mergeGlobalFilters = await loadGlobalFilterMerge();-return {...input,series: mergeGlobalFilters(diff --git a/packages/core/src/modules/chart/src/funnel.sql.test.ts b/packages/core/src/modules/chart/src/funnel.sql.test.tsindex b25faf1e1..e1cacd618 100644--- a/packages/core/src/modules/chart/src/funnel.sql.test.ts+++ b/packages/core/src/modules/chart/src/funnel.sql.test.ts@@ -46,7 +46,8 @@ let buildFunnelBase: typeof import('../funnel.service').buildFunnelBase;let funnelChartQuery: typeof import('./funnel.sql').funnelChartQuery;let funnelProfilesQuery: typeof import('./funnel.sql').funnelProfilesQuery;let funnelStepConditions: typeof import('./funnel.sql').funnelStepConditions;-let onlyReportEvents: typeof import('@openpanel/core').onlyReportEvents;+let onlyReportEvents: typeof import('../../report/src/series').onlyReportEvents;+let deps: import('../../../services').ServiceDeps;const PROJECT_ID = 'test-sql-validation';const START = '2026-04-14 00:00:00';@@ -113,7 +114,7 @@ function baseInput(overrides: BaseOverrides = {}) {/** Mirrors what getFunnelStepProfiles builds on top of the shared base. */async function profilesStatement(overrides: BaseOverrides = {}) {- const base = await buildFunnelBase(baseInput(overrides));+ const base = await buildFunnelBase(deps, baseInput(overrides));return funnelProfilesQuery(base, {targetLevel: TARGET_LEVEL,showDropoffs: false,@@ -124,7 +125,7 @@ async function profilesStatement(overrides: BaseOverrides = {}) {/** Mirrors what the funnel chart builds on top of the shared base. */async function chartStatement(overrides: BaseOverrides = {}) {- const base = await buildFunnelBase(baseInput(overrides));+ const base = await buildFunnelBase(deps, baseInput(overrides));return funnelChartQuery(base);}@@ -146,9 +147,9 @@ beforeAll(async () => {({ buildFunnelBase } = await import('../funnel.service'));({ funnelChartQuery, funnelProfilesQuery, funnelStepConditions } =await import('./funnel.sql'));- ({ onlyReportEvents } = await import(- '@openpanel/core'- ));+ ({ onlyReportEvents } = await import('../../report/src/series'));+ const { testServiceDeps } = await import('../../../../test/service-deps');+ deps = await testServiceDeps();});describe('funnel.sql / buildFunnelBase — profile breakdowns', () => {diff --git a/packages/core/src/modules/chart/src/run-query.ts b/packages/core/src/modules/chart/src/run-query.tsindex a623f4474..67c4963c3 100644--- a/packages/core/src/modules/chart/src/run-query.ts+++ b/packages/core/src/modules/chart/src/run-query.ts@@ -1,23 +1,68 @@-// The one place the chart module reaches @openpanel/db's ClickHouse client.+// The chart module's one ClickHouse entry point.//-// The import is lazy on purpose: the core barrel pulls this module into nearly-// every test file, and constructing @openpanel/db's clients at import time-// costs a pino-pretty worker per file.--import type { SqlFragment } from '@openpanel/db/src/clickhouse/sql';+// M10-003: the client is `deps.ch` — the same round-robin/retry proxy+// `main.ts` builds and hands to every scope — instead of a lazy+// `import('@openpanel/db/src/clickhouse/client')`. Reaching it through the+// scope is what puts the request's `requestId` on the query's log line+// (ADR-018 R1); the lazy loader had no request scope to carry.+//+// `deps.ch.query` is `chQuery`'s own transport (`withRetry(client =>+// client.query(...))`), and the Int-meta coercion below is the same one+// `chQuery` applies — ClickHouse's JSON format returns every Int*/UInt*+// column as a string, so a caller's `count: number` only holds if it is+// parsed back out here. Same shape as the overview module's run-query.ts.-export function loadChClient() {- return import('@openpanel/db/src/clickhouse/client');-}+import {+ type SqlFragment,+ toStatement,+} from '@openpanel/db/src/clickhouse/sql';+import type { ServiceDeps } from '../../../services';/** `timezone` travels as `session_timezone`, exactly as clix sent it. */export async function runQuery<T extends object>(+ deps: ServiceDeps,statement: SqlFragment,timezone?: string): Promise<T[]> {- const { chQuery } = await loadChClient();- return chQuery<T>(- statement,- timezone ? { session_timezone: timezone } : undefined+ const start = Date.now();+ const { query, query_params } = toStatement(statement);+ const paramNames = Object.keys(query_params);+ const result = await deps.ch.query({+ query,+ query_params: paramNames.length > 0 ? query_params : undefined,+ clickhouse_settings: timezone ? { session_timezone: timezone } : undefined,+ });+ const json = await result.json<T>();++ deps.logger.info(+ {+ query: cleanQuery(query),+ // Names only: bound values are user data and must not reach the logs.+ queryParams: paramNames.length > 0 ? paramNames : undefined,+ rows: json.rows,+ stats: json.statistics,+ elapsed: Date.now() - start,+ },+ 'query info');++ const keys = Object.keys(json.data[0] ?? {});+ return json.data.map((item) =>+ keys.reduce((acc, key) => {+ const meta = json.meta?.find((m) => m.name === key);+ const value = item[key as keyof T];+ acc[key as keyof T] =+ value && meta?.type.includes('Int')+ ? (Number.parseFloat(value as string) as T[keyof T])+ : value;+ return acc;+ }, {} as T)+ );+}++const NEWLINES = /\n/g;+const WHITESPACE_RUNS = /\s+/g;++function cleanQuery(query: string): string {+ return query.replace(NEWLINES, '').replace(WHITESPACE_RUNS, ' ').trim();}diff --git a/packages/core/src/modules/chart/src/table-filter-where.ts b/packages/core/src/modules/chart/src/table-filter-where.tsindex 96276445a..b96493b06 100644--- a/packages/core/src/modules/chart/src/table-filter-where.ts+++ b/packages/core/src/modules/chart/src/table-filter-where.ts@@ -5,28 +5,22 @@// filters). Still sqlstring-escaped text, not the `sql` tag: ADR-013 keeps// the two filter compilers as they are ("two behaviours, not two builders")// until every caller that splices their output stops using text builders.-// packages/db/src/services/filter-where.service.ts stays a re-export shim;-// event/profile/session/cohort services reach this module through the-// existing lazy `loadFilterCompiler()` dynamic import, now pointed here-// instead of at packages/db — the dynamic import is what keeps-// clickhouse/client.ts's module-scope logger construction out of those-// services' eager import chain.+// M10-003: the two symbols this file used to take from+// `@openpanel/db/src/clickhouse/client` (a module that constructs a+// ClickHouse client and a pino logger at import time) are now local — the+// module's own `./dates.formatClickhouseDate`, byte-identical to+// packages/db's non-`skipTime` branch, and `./field-resolution.CHART_TABLE`,+// which already carried all four physical table names used below.import {getCohortIds,type IChartEventFilter,type IChartFilterValueType,} from '@openpanel/validation';-import {- formatClickhouseDate,- TABLE_NAMES,-} from '@openpanel/db/src/clickhouse/client';import sqlstring from 'sqlstring';-import {- buildTypedClause,- hasTypedCast,- isTypedOperator,-} from './filter-cast';+import { formatClickhouseDate } from './dates';+import { CHART_TABLE } from './field-resolution';+import { buildTypedClause, hasTypedCast, isTypedOperator } from './filter-cast';export interface FilterTableContext {/** Outer query's primary table. */@@ -78,11 +72,7 @@ function compileScalarClause(value: IChartEventFilter['value'],options: { numeric?: boolean; type?: IChartFilterValueType } = {}): string | null {- if (- value.length === 0 &&- operator !== 'isNull' &&- operator !== 'isNotNull'- ) {+ if (value.length === 0 && operator !== 'isNull' && operator !== 'isNotNull') {return null;}@@ -242,8 +232,12 @@ function groupColumnSql(name: string): string {/** Translate `session.<field>` to the underlying sessions column. */function sessionColumnSql(name: string): string | null {const withoutPrefix = name.replace(/^session\./, '');- if (withoutPrefix === 'is_bounce') return 'is_bounce';- if (SESSION_NUMERIC_COLUMNS.has(withoutPrefix)) return withoutPrefix;+ if (withoutPrefix === 'is_bounce') {+ return 'is_bounce';+ }+ if (SESSION_NUMERIC_COLUMNS.has(withoutPrefix)) {+ return withoutPrefix;+ }// performed_event is handled as a subselect, not a columnreturn null;}@@ -261,11 +255,13 @@ function buildCohortClause(if (cohortIds.length === 0 && filter.name.startsWith('cohort:')) {cohortIds = [filter.name.slice('cohort:'.length)];}- if (cohortIds.length === 0) return null;+ if (cohortIds.length === 0) {+ return null;+ }const negate = filter.operator === 'notInCohort';const op = negate ? 'NOT IN' : 'IN';const escapedIds = cohortIds.map((id) => sqlstring.escape(id)).join(', ');- return `${ctx.profileIdExpr} ${op} (SELECT profile_id FROM ${TABLE_NAMES.cohort_members} FINAL WHERE cohort_id IN (${escapedIds}) AND project_id = ${sqlstring.escape(projectId)})`;+ return `${ctx.profileIdExpr} ${op} (SELECT profile_id FROM ${CHART_TABLE.cohortMembers} FINAL WHERE cohort_id IN (${escapedIds}) AND project_id = ${sqlstring.escape(projectId)})`;}function buildGroupClause(@@ -273,14 +269,18 @@ function buildGroupClause(projectId: string,ctx: FilterTableContext): string | null {- if (!ctx.groupsExpr) return null;+ if (!ctx.groupsExpr) {+ return null;+ }const column = groupColumnSql(filter.name);const inner = compileScalarClause(column, filter.operator, filter.value, {type: filter.type,});- if (!inner) return null;+ if (!inner) {+ return null;+ }const projectClause = `project_id = ${sqlstring.escape(projectId)}`;- return `arrayExists(g -> g IN (SELECT id FROM ${TABLE_NAMES.groups} FINAL WHERE ${projectClause} AND ${inner}), ${ctx.groupsExpr})`;+ return `arrayExists(g -> g IN (SELECT id FROM ${CHART_TABLE.groups} FINAL WHERE ${projectClause} AND ${inner}), ${ctx.groupsExpr})`;}function buildProfileClause(@@ -289,17 +289,21 @@ function buildProfileClause(ctx: FilterTableContext): string | null {const column = profileColumnSql(filter.name);- if (!column) return null;+ if (!column) {+ return null;+ }const numeric = column === 'created_at' || column === 'last_seen_at';const inner = compileScalarClause(column, filter.operator, filter.value, {numeric,type: filter.type,});- if (!inner) return null;+ if (!inner) {+ return null;+ }if (ctx.selfTable === 'profiles') {return inner;}- return `${ctx.profileIdExpr} IN (SELECT id FROM ${TABLE_NAMES.profiles} FINAL WHERE project_id = ${sqlstring.escape(projectId)} AND ${inner})`;+ return `${ctx.profileIdExpr} IN (SELECT id FROM ${CHART_TABLE.profiles} FINAL WHERE project_id = ${sqlstring.escape(projectId)} AND ${inner})`;}function buildSessionClause(@@ -307,11 +311,15 @@ function buildSessionClause(projectId: string,ctx: FilterTableContext): string | null {- if (ctx.selfTable !== 'sessions') return null;+ if (ctx.selfTable !== 'sessions') {+ return null;+ }const fieldName = filter.name.replace(/^session\./, '');if (fieldName === 'performed_event') {- if (filter.value.length === 0) return null;+ if (filter.value.length === 0) {+ return null;+ }const inClause =filter.value.length === 1? `= ${escape(filter.value[0]!)}`@@ -324,11 +332,13 @@ function buildSessionClause();}const scopeSql = dateScope.length ? `AND ${dateScope.join(' AND ')} ` : '';- return `id ${op} (SELECT DISTINCT session_id FROM ${TABLE_NAMES.events} WHERE project_id = ${sqlstring.escape(projectId)} ${scopeSql}AND name ${inClause})`;+ return `id ${op} (SELECT DISTINCT session_id FROM ${CHART_TABLE.events} WHERE project_id = ${sqlstring.escape(projectId)} ${scopeSql}AND name ${inClause})`;}if (fieldName === 'is_bounce') {- if (filter.value.length === 0) return null;+ if (filter.value.length === 0) {+ return null;+ }const wants = filter.value.some((v) =>typeof v === 'boolean' ? v : String(v).toLowerCase() === 'true');@@ -337,7 +347,9 @@ function buildSessionClause(}const column = sessionColumnSql(filter.name);- if (!column) return null;+ if (!column) {+ return null;+ }return compileScalarClause(column, filter.operator, filter.value, {numeric: SESSION_NUMERIC_COLUMNS.has(column),type: filter.type,@@ -363,7 +375,9 @@ export function buildFilterWhere(// fragment is parenthesized here to keep a top-level OR inside it from// rebinding the surrounding conditions.const set = (clause: string | null) => {- if (clause) where[id] = `(${clause})`;+ if (clause) {+ where[id] = `(${clause})`;+ }};if (filter.operator === 'inCohort' || filter.operator === 'notInCohort') {diff --git a/packages/core/src/modules/cohort/cohort.jobs.test.ts b/packages/core/src/modules/cohort/cohort.jobs.test.tsindex 915a61196..bb4ac2bc0 100644--- a/packages/core/src/modules/cohort/cohort.jobs.test.ts+++ b/packages/core/src/modules/cohort/cohort.jobs.test.ts@@ -45,6 +45,11 @@ function stubJobCtx(cohort: Partial<CohortService>, jobName = 'test'): JobCtx {group: {} as Services['group'],chart: {} as Services['chart'],misc: {} as Services['misc'],+ report: {} as Services['report'],+ dashboard: {} as Services['dashboard'],+ export: {} as Services['export'],+ share: {} as Services['share'],+ reference: {} as Services['reference'],};return {db: {} as AppDeps['db'],diff --git a/packages/core/src/modules/dashboard/dashboard.rpc.ts b/packages/core/src/modules/dashboard/dashboard.rpc.tsindex 2a5612336..5bc8cc5f9 100644--- a/packages/core/src/modules/dashboard/dashboard.rpc.ts+++ b/packages/core/src/modules/dashboard/dashboard.rpc.ts@@ -12,14 +12,6 @@import { z } from 'zod';import { createTRPCRouter, procedure, type TrpcContext } from '../../rpc/base';import { TRPCAccessError, TRPCNotFoundError } from '../../rpc/errors';-import {- createDashboard,- deleteDashboard,- getDashboardById,- getDashboardByIdOrThrow,- getDashboardsByProjectId,- updateDashboard,-} from './dashboard.service';function requireLogin(userId: string | null | undefined): string {if (!userId) {@@ -53,7 +45,7 @@ export const dashboardRouter = createTRPCRouter({).query(({ input, ctx }) => {requireLogin(ctx.session.userId);- return getDashboardsByProjectId(input.projectId);+ return ctx.services.dashboard.getDashboardsByProjectId(input.projectId);}),byId: procedure@@ -66,7 +58,10 @@ export const dashboardRouter = createTRPCRouter({.query(async ({ input, ctx }) => {await requireReadAccess(ctx, input.projectId);- const dashboard = await getDashboardById(input.id, input.projectId);+ const dashboard = await ctx.services.dashboard.getDashboardById(+ input.id,+ input.projectId+ );if (!dashboard) {throw new TRPCNotFoundError('Dashboard not found');@@ -84,7 +79,7 @@ export const dashboardRouter = createTRPCRouter({).mutation(async ({ input, ctx }) => {await requireWriteAccess(ctx, input.projectId);- return createDashboard(input);+ return ctx.services.dashboard.createDashboard(input);}),update: procedure@@ -95,9 +90,11 @@ export const dashboardRouter = createTRPCRouter({})).mutation(async ({ input, ctx }) => {- const dashboard = await getDashboardByIdOrThrow(input.id);+ const dashboard = await ctx.services.dashboard.getDashboardByIdOrThrow(+ input.id+ );await requireWriteAccess(ctx, dashboard.projectId);- return updateDashboard(input);+ return ctx.services.dashboard.updateDashboard(input);}),delete: procedure@@ -108,8 +105,10 @@ export const dashboardRouter = createTRPCRouter({})).mutation(async ({ input, ctx }) => {- const dashboard = await getDashboardByIdOrThrow(input.id);+ const dashboard = await ctx.services.dashboard.getDashboardByIdOrThrow(+ input.id+ );await requireWriteAccess(ctx, dashboard.projectId);- return deleteDashboard(input);+ return ctx.services.dashboard.deleteDashboard(input);}),});diff --git a/packages/core/src/modules/dashboard/dashboard.service.ts b/packages/core/src/modules/dashboard/dashboard.service.tsindex e87bc3523..1f7eee291 100644--- a/packages/core/src/modules/dashboard/dashboard.service.ts+++ b/packages/core/src/modules/dashboard/dashboard.service.ts@@ -1,18 +1,18 @@// Moved from packages/db/src/services/dashboard.service.ts, plus the// create/update/delete mutation bodies packages/trpc/src/routers/dashboard.ts// held inline (M7-006, ADR-008's module map: dashboard owns "R,S").-// packages/db/src/services/dashboard.service.ts stays a re-export shim-// (DELEGATE PATTERN), same shape as project.service.ts since M6-002.//-// db access is LAZY, not a static top-level import — dashboard.rpc.ts lands-// in the eager rpc.router.ts barrel chain nearly every core test file-// reaches, and constructing @openpanel/db's clients at import time would-// spawn a pino-pretty transport worker thread per test file (see-// insight.service.ts's header / project.service.ts's header).+// M10-003: every function takes `ServiceDeps` and reaches Postgres as+// `deps.db`; the `loadDb()` / `loadIdService()` lazy loaders are gone, so+// this module value-imports neither `@openpanel/db` nor its own package+// barrel — the Prisma row types below are `import type`, erased at runtime+// (docs/TECH_DEBT.md §4).import type { Dashboard, Prisma } from '@openpanel/db/src/prisma-client';import { PrismaError } from 'prisma-error-enum';import { TRPCNotFoundError } from '../../rpc/errors';+import type { ServiceDeps } from '../../services';+import { getId } from '../../shared/slug-id';import { getProjectById } from '../project/project.service';export type IServiceDashboard = Dashboard;@@ -23,17 +23,22 @@ export type IServiceDashboards = Prisma.DashboardGetPayload<{};}>[];-function loadDb() {- return import('@openpanel/db/src/prisma-client').then((m) => m.db);-}+export type DashboardWithProject = Prisma.DashboardGetPayload<{+ include: { project: true };+}>;-function loadIdService() {- return import('@openpanel/core').then((m) => m.getId);+export interface DashboardListItem {+ id: string;+ name: string;+ projectId: string;}-export async function getDashboardById(id: string, projectId: string) {- const db = await loadDb();- const dashboard = await db.dashboard.findUnique({+export function getDashboardById(+ deps: ServiceDeps,+ id: string,+ projectId: string+): Promise<DashboardWithProject | null> {+ return deps.db.dashboard.findUnique({where: {id,projectId,@@ -42,62 +47,61 @@ export async function getDashboardById(id: string, projectId: string) {project: true,},});-- if (!dashboard) {- return null;- }-- return dashboard;}/** Unscoped lookup for mutation handlers that only receive a dashboard id and* need its `projectId` to run the access check — same shape as V1's inline* `db.dashboard.findUniqueOrThrow`. */-export async function getDashboardByIdOrThrow(id: string) {- const db = await loadDb();- return db.dashboard.findUniqueOrThrow({ where: { id } });+export function getDashboardByIdOrThrow(+ deps: ServiceDeps,+ id: string+): Promise<Dashboard> {+ return deps.db.dashboard.findUniqueOrThrow({ where: { id } });}-export function getDashboardsByProjectId(projectId: string) {- return loadDb().then((db) =>- db.dashboard.findMany({- where: {- projectId,- },- include: {- project: true,- reports: true,- },- })- );+export function getDashboardsByProjectId(+ deps: ServiceDeps,+ projectId: string+): Promise<IServiceDashboards> {+ return deps.db.dashboard.findMany({+ where: {+ projectId,+ },+ include: {+ project: true,+ reports: true,+ },+ });}-export async function listDashboardsCore(input: {- projectId: string;- organizationId: string;-}) {- const db = await loadDb();- return db.dashboard.findMany({+export function listDashboardsCore(+ deps: ServiceDeps,+ input: {+ projectId: string;+ organizationId: string;+ }+): Promise<DashboardListItem[]> {+ return deps.db.dashboard.findMany({where: { projectId: input.projectId },orderBy: { createdAt: 'desc' },select: { id: true, name: true, projectId: true },});}-export async function createDashboard(input: {- name: string;- projectId: string;-}) {- const db = await loadDb();+export async function createDashboard(+ deps: ServiceDeps,+ input: {+ name: string;+ projectId: string;+ }+): Promise<Dashboard> {const project = await getProjectById(input.projectId);if (!project) {throw new TRPCNotFoundError('Project not found');}- const getId = await loadIdService();-- return db.dashboard.create({+ return deps.db.dashboard.create({data: {id: await getId('dashboard', input.name),projectId: input.projectId,@@ -107,9 +111,11 @@ export async function createDashboard(input: {});}-export async function updateDashboard(input: { id: string; name: string }) {- const db = await loadDb();- return db.dashboard.update({+export function updateDashboard(+ deps: ServiceDeps,+ input: { id: string; name: string }+): Promise<Dashboard> {+ return deps.db.dashboard.update({where: {id: input.id,},@@ -119,20 +125,22 @@ export async function updateDashboard(input: { id: string; name: string }) {});}-export async function deleteDashboard(input: {- id: string;- forceDelete?: boolean;-}) {- const db = await loadDb();+export async function deleteDashboard(+ deps: ServiceDeps,+ input: {+ id: string;+ forceDelete?: boolean;+ }+): Promise<void> {try {if (input.forceDelete) {- await db.report.deleteMany({+ await deps.db.report.deleteMany({where: {dashboardId: input.id,},});}- await db.dashboard.delete({+ await deps.db.dashboard.delete({where: {id: input.id,},@@ -151,3 +159,35 @@ export async function deleteDashboard(input: {}}}++export interface DashboardService {+ getDashboardById(+ id: string,+ projectId: string+ ): Promise<DashboardWithProject | null>;+ getDashboardByIdOrThrow(id: string): Promise<Dashboard>;+ getDashboardsByProjectId(projectId: string): Promise<IServiceDashboards>;+ listDashboardsCore(input: {+ projectId: string;+ organizationId: string;+ }): Promise<DashboardListItem[]>;+ createDashboard(input: {+ name: string;+ projectId: string;+ }): Promise<Dashboard>;+ updateDashboard(input: { id: string; name: string }): Promise<Dashboard>;+ deleteDashboard(input: { id: string; forceDelete?: boolean }): Promise<void>;+}++export function createDashboardService(deps: ServiceDeps): DashboardService {+ return {+ getDashboardById: (id, projectId) => getDashboardById(deps, id, projectId),+ getDashboardByIdOrThrow: (id) => getDashboardByIdOrThrow(deps, id),+ getDashboardsByProjectId: (projectId) =>+ getDashboardsByProjectId(deps, projectId),+ listDashboardsCore: (input) => listDashboardsCore(deps, input),+ createDashboard: (input) => createDashboard(deps, input),+ updateDashboard: (input) => updateDashboard(deps, input),+ deleteDashboard: (input) => deleteDashboard(deps, input),+ };+}diff --git a/packages/core/src/modules/export/export.routes.ts b/packages/core/src/modules/export/export.routes.tsindex 4b3212684..f0b6f8287 100644--- a/packages/core/src/modules/export/export.routes.ts+++ b/packages/core/src/modules/export/export.routes.ts@@ -28,11 +28,6 @@import { DateTime } from '@openpanel/common';import { getDefaultIntervalByDates } from '@openpanel/constants';-import type {- GetEventListOptions,- IGetTopGenericInput,- TrafficColumn,-} from '@openpanel/core';import {zChartEvent,zChartEventFilter,@@ -43,10 +38,54 @@ import { z } from 'zod';import type { ClientType } from '../../http/client-auth';import { defineRoutes } from '../../http/define';import { parseQueryStringTransform } from '../../http/query';-import { loadDbBuffers } from '../../buffers/lazy-db-buffers';+import { getChartStartEndDate } from '../../shared/date';import { HttpError } from '../../shared/errors';+import type { GetEventListOptions } from '../event/event.service';+import {+ getEventList,+ getEventPropertyValuesCore,+ getEventsCount,+ listEventNamesCore,+ listEventPropertiesCore,+ queryEventsCore,+} from '../event/event.service';+import {+ findGroupsCore,+ getGroupCore,+ listGroupTypesCore,+} from '../group/group.service';+import {+ gscGetCannibalizationCore,+ gscGetOverviewCore,+ gscGetPageDetailsCore,+ gscGetQueryDetailsCore,+ gscGetQueryOpportunitiesCore,+ gscGetTopPagesCore,+ gscGetTopQueriesCore,+} from '../gsc/gsc.service';+import { getSettingsForProject } from '../organization/organization.service';+import type {+ IGetTopGenericInput,+ TrafficColumn,+} from '../overview/overview.service';+import {+ getAnalyticsOverviewCore,+ getTrafficBreakdownCore,+ overviewService,+} from '../overview/overview.service';+import {+ getEntryExitPagesCore,+ getPagePerformanceCore,+ getTopPagesCore,+} from '../overview/pages.service';+import {+ findProfilesCore,+ getProfileMetricsCore,+ getProfileSessionsCore,+ getProfileWithEvents,+} from '../profile/profile.service';+import { querySessionsCore } from '../session/session.service';import {- loadCore,resolveExportProjectId,resolveInsightsDateRange,resolveInsightsProjectId,@@ -167,15 +206,14 @@ export const exportRoutes = defineRoutes((app) =>.onTransform(parseQueryStringTransform).get('/export/events',- async ({ query, client }) => {- const resolved = await resolveExportProjectId(client, query);+ async ({ query, client, ctx }) => {+ const resolved = await resolveExportProjectId(ctx, client, query);if (!resolved.ok) {// V1's controller threw an `HttpError` and let the error handler// shape it; the body is `{status, message}` because `HttpError.error`// is undefined and JSON drops it.throw new HttpError(resolved.message, { status: resolved.status });}- const { getEventList, getEventsCount } = await loadCore();const {limit,page: rawPage,@@ -233,15 +271,14 @@ export const exportRoutes = defineRoutes((app) =>).get('/export/charts',- async ({ query, client }) => {- const resolved = await resolveExportProjectId(client, query);+ async ({ query, client, ctx }) => {+ const resolved = await resolveExportProjectId(ctx, client, query);if (!resolved.ok) {// V1's controller threw an `HttpError` and let the error handler// shape it; the body is `{status, message}` because `HttpError.error`// is undefined and JSON drops it.throw new HttpError(resolved.message, { status: resolved.status });}- const { ChartEngine, getSettingsForProject } = await loadCore();const { timezone } = await getSettingsForProject(resolved.projectId);const { events, series, ...rest } = query;@@ -252,7 +289,7 @@ export const exportRoutes = defineRoutes((app) =>filters: event.filters ?? [],}));- return ChartEngine.execute({+ return ctx.services.chart.execute({...rest,startDate: rest.startDate? DateTime.fromISO(rest.startDate)@@ -324,8 +361,6 @@ async function getOverviewGeneric(client: InsightsClient) {const projectId = await resolveInsightsProjectId(client, params);- const { getChartStartEndDate, getSettingsForProject, overviewService } =- await loadCore();const { timezone } = await getSettingsForProject(projectId);const { startDate, endDate } = getChartStartEndDate(query, timezone);return overviewService.getTopGeneric({@@ -509,7 +544,6 @@ export const insightsRoutes = defineRoutes((app) =>projectId,query);- const { getAnalyticsOverviewCore } = await loadCore();return getAnalyticsOverviewCore({projectId,startDate,@@ -530,10 +564,12 @@ export const insightsRoutes = defineRoutes((app) =>).get('/insights/:projectId/active_users',- async ({ params, query, client }) => {+ async ({ params, query, client, ctx }) => {const projectId = await resolveInsightsProjectId(client, params);- const { getRollingActiveUsersCore } = await loadCore();- return getRollingActiveUsersCore({ projectId, days: query.days });+ return ctx.services.chart.getRollingActiveUsersCore({+ projectId,+ days: query.days,+ });},{clientAuth: CLIENT_ALLOW,@@ -547,10 +583,9 @@ export const insightsRoutes = defineRoutes((app) =>).get('/insights/:projectId/retention',- async ({ params, client }) => {+ async ({ params, client, ctx }) => {const projectId = await resolveInsightsProjectId(client, params);- const { getWeeklyRetentionSeriesCore } = await loadCore();- return getWeeklyRetentionSeriesCore(projectId);+ return ctx.services.chart.getWeeklyRetentionSeriesCore(projectId);},{clientAuth: CLIENT_ALLOW,@@ -563,10 +598,9 @@ export const insightsRoutes = defineRoutes((app) =>).get('/insights/:projectId/retention/cohort',- async ({ params, client }) => {+ async ({ params, client, ctx }) => {const projectId = await resolveInsightsProjectId(client, params);- const { getRetentionCohortCore } = await loadCore();- return getRetentionCohortCore(projectId);+ return ctx.services.chart.getRetentionCohortCore(projectId);},{clientAuth: CLIENT_ALLOW,@@ -585,7 +619,6 @@ export const insightsRoutes = defineRoutes((app) =>projectId,query);- const { getTopPagesCore } = await loadCore();return getTopPagesCore({ projectId, startDate, endDate });},{@@ -607,7 +640,6 @@ export const insightsRoutes = defineRoutes((app) =>projectId,query);- const { getEntryExitPagesCore } = await loadCore();return getEntryExitPagesCore({projectId,startDate,@@ -633,7 +665,6 @@ export const insightsRoutes = defineRoutes((app) =>projectId,query);- const { getPagePerformanceCore } = await loadCore();return getPagePerformanceCore({projectId,startDate,@@ -656,8 +687,6 @@ export const insightsRoutes = defineRoutes((app) =>'/insights/:projectId/metrics',async ({ params, query, client }) => {const projectId = await resolveInsightsProjectId(client, params);- const { getChartStartEndDate, getSettingsForProject, overviewService } =- await loadCore();const { timezone } = await getSettingsForProject(projectId);const { startDate, endDate } = getChartStartEndDate(query, timezone);return overviewService.getMetrics({@@ -682,10 +711,11 @@ export const insightsRoutes = defineRoutes((app) =>).get('/insights/:projectId/live',- async ({ params, client }) => {+ async ({ params, client, ctx }) => {const projectId = await resolveInsightsProjectId(client, params);- const { eventBuffer } = await loadDbBuffers();- return { visitors: await eventBuffer.getActiveVisitorCount(projectId) };+ return {+ visitors: await ctx.buffers.event.getActiveVisitorCount(projectId),+ };},{clientAuth: CLIENT_ALLOW,@@ -700,8 +730,6 @@ export const insightsRoutes = defineRoutes((app) =>'/insights/:projectId/pages',async ({ params, query, client }) => {const projectId = await resolveInsightsProjectId(client, params);- const { getChartStartEndDate, getSettingsForProject, overviewService } =- await loadCore();const { timezone } = await getSettingsForProject(projectId);const { startDate, endDate } = getChartStartEndDate(query, timezone);return overviewService.getTopPages({@@ -977,14 +1005,13 @@ export const insightsRoutes = defineRoutes((app) =>).get('/insights/:projectId/funnel',- async ({ params, query, client }) => {+ async ({ params, query, client, ctx }) => {const projectId = await resolveInsightsProjectId(client, params);const { startDate, endDate } = await resolveInsightsDateRange(projectId,query);- const { getFunnelCore } = await loadCore();- return getFunnelCore({+ return ctx.services.chart.getFunnelCore({projectId,startDate,endDate,@@ -1011,7 +1038,6 @@ export const insightsRoutes = defineRoutes((app) =>projectId,query);- const { getTrafficBreakdownCore } = await loadCore();return getTrafficBreakdownCore({projectId,startDate,@@ -1037,7 +1063,6 @@ export const insightsRoutes = defineRoutes((app) =>projectId,query);- const { getTrafficBreakdownCore } = await loadCore();return getTrafficBreakdownCore({projectId,startDate,@@ -1064,7 +1089,6 @@ export const insightsRoutes = defineRoutes((app) =>projectId,query);- const { getTrafficBreakdownCore } = await loadCore();return getTrafficBreakdownCore({projectId,startDate,@@ -1084,14 +1108,18 @@ export const insightsRoutes = defineRoutes((app) =>).get('/insights/:projectId/user_flow',- async ({ params, query, client }) => {+ async ({ params, query, client, ctx }) => {const projectId = await resolveInsightsProjectId(client, params);const { startDate, endDate } = await resolveInsightsDateRange(projectId,query);- const { getUserFlowCore } = await loadCore();- return getUserFlowCore({ projectId, startDate, endDate, ...query });+ return ctx.services.chart.getUserFlowCore({+ projectId,+ startDate,+ endDate,+ ...query,+ });},{clientAuth: CLIENT_ALLOW,@@ -1106,10 +1134,9 @@ export const insightsRoutes = defineRoutes((app) =>).get('/insights/:projectId/engagement',- async ({ params, client }) => {+ async ({ params, client, ctx }) => {const projectId = await resolveInsightsProjectId(client, params);- const { getEngagementCore } = await loadCore();- return getEngagementCore(projectId);+ return ctx.services.chart.getEngagementCore(projectId);},{clientAuth: CLIENT_ALLOW,@@ -1124,7 +1151,6 @@ export const insightsRoutes = defineRoutes((app) =>'/insights/:projectId/events',async ({ params, query, client }) => {const projectId = await resolveInsightsProjectId(client, params);- const { queryEventsCore } = await loadCore();return queryEventsCore({ projectId, ...query });},{@@ -1142,7 +1168,6 @@ export const insightsRoutes = defineRoutes((app) =>'/insights/:projectId/events/names',async ({ params, client }) => {const projectId = await resolveInsightsProjectId(client, params);- const { listEventNamesCore } = await loadCore();return listEventNamesCore(projectId);},{@@ -1158,7 +1183,6 @@ export const insightsRoutes = defineRoutes((app) =>'/insights/:projectId/events/properties',async ({ params, query, client }) => {const projectId = await resolveInsightsProjectId(client, params);- const { listEventPropertiesCore } = await loadCore();return listEventPropertiesCore({projectId,eventName: query.eventName,@@ -1178,7 +1202,6 @@ export const insightsRoutes = defineRoutes((app) =>'/insights/:projectId/events/property_values',async ({ params, query, client }) => {const projectId = await resolveInsightsProjectId(client, params);- const { getEventPropertyValuesCore } = await loadCore();return getEventPropertyValuesCore({ projectId, ...query });},{@@ -1195,7 +1218,6 @@ export const insightsRoutes = defineRoutes((app) =>'/insights/:projectId/profiles',async ({ params, query, client }) => {const projectId = await resolveInsightsProjectId(client, params);- const { findProfilesCore } = await loadCore();return findProfilesCore({ projectId, ...query });},{@@ -1212,7 +1234,6 @@ export const insightsRoutes = defineRoutes((app) =>'/insights/:projectId/profiles/:profileId',async ({ params, query, client, status }) => {const projectId = await resolveInsightsProjectId(client, params);- const { getProfileWithEvents } = await loadCore();const result = await getProfileWithEvents(projectId,params.profileId,@@ -1240,7 +1261,6 @@ export const insightsRoutes = defineRoutes((app) =>'/insights/:projectId/profiles/:profileId/sessions',async ({ params, query, client }) => {const projectId = await resolveInsightsProjectId(client, params);- const { getProfileSessionsCore } = await loadCore();return getProfileSessionsCore(projectId, params.profileId, query.limit);},{@@ -1257,7 +1277,6 @@ export const insightsRoutes = defineRoutes((app) =>'/insights/:projectId/profiles/:profileId/metrics',async ({ params, client }) => {const projectId = await resolveInsightsProjectId(client, params);- const { getProfileMetricsCore } = await loadCore();return getProfileMetricsCore({projectId,profileId: params.profileId,@@ -1276,7 +1295,6 @@ export const insightsRoutes = defineRoutes((app) =>'/insights/:projectId/sessions',async ({ params, query, client }) => {const projectId = await resolveInsightsProjectId(client, params);- const { querySessionsCore } = await loadCore();return querySessionsCore({ projectId, ...query });},{@@ -1293,7 +1311,6 @@ export const insightsRoutes = defineRoutes((app) =>'/insights/:projectId/groups/types',async ({ params, client }) => {const projectId = await resolveInsightsProjectId(client, params);- const { listGroupTypesCore } = await loadCore();return listGroupTypesCore(projectId);},{@@ -1309,7 +1326,6 @@ export const insightsRoutes = defineRoutes((app) =>'/insights/:projectId/groups',async ({ params, query, client }) => {const projectId = await resolveInsightsProjectId(client, params);- const { findGroupsCore } = await loadCore();return findGroupsCore({ projectId, ...query });},{@@ -1326,7 +1342,6 @@ export const insightsRoutes = defineRoutes((app) =>'/insights/:projectId/groups/:groupId',async ({ params, query, client }) => {const projectId = await resolveInsightsProjectId(client, params);- const { getGroupCore } = await loadCore();return getGroupCore({projectId,groupId: params.groupId,@@ -1345,10 +1360,9 @@ export const insightsRoutes = defineRoutes((app) =>).get('/insights/:projectId/reports/:reportId/data',- async ({ params, client }) => {+ async ({ params, client, ctx }) => {const projectId = await resolveInsightsProjectId(client, params);- const { getReportDataCore } = await loadCore();- return getReportDataCore({+ return ctx.services.report.getReportDataCore({projectId,reportId: params.reportId,organizationId: client.organizationId,@@ -1371,7 +1385,6 @@ export const insightsRoutes = defineRoutes((app) =>projectId,query);- const { gscGetOverviewCore } = await loadCore();return gscGetOverviewCore({projectId,startDate,@@ -1398,7 +1411,6 @@ export const insightsRoutes = defineRoutes((app) =>projectId,query);- const { gscGetTopPagesCore } = await loadCore();return gscGetTopPagesCore({projectId,startDate,@@ -1424,7 +1436,6 @@ export const insightsRoutes = defineRoutes((app) =>projectId,query);- const { gscGetPageDetailsCore } = await loadCore();return gscGetPageDetailsCore({projectId,startDate,@@ -1450,7 +1461,6 @@ export const insightsRoutes = defineRoutes((app) =>projectId,query);- const { gscGetTopQueriesCore } = await loadCore();return gscGetTopQueriesCore({projectId,startDate,@@ -1476,7 +1486,6 @@ export const insightsRoutes = defineRoutes((app) =>projectId,query);- const { gscGetQueryDetailsCore } = await loadCore();return gscGetQueryDetailsCore({projectId,startDate,@@ -1502,7 +1511,6 @@ export const insightsRoutes = defineRoutes((app) =>projectId,query);- const { gscGetQueryOpportunitiesCore } = await loadCore();return gscGetQueryOpportunitiesCore({projectId,startDate,@@ -1529,7 +1537,6 @@ export const insightsRoutes = defineRoutes((app) =>projectId,query);- const { gscGetCannibalizationCore } = await loadCore();return gscGetCannibalizationCore({ projectId, startDate, endDate });},{diff --git a/packages/core/src/modules/export/export.service.ts b/packages/core/src/modules/export/export.service.tsindex 8f5fea665..66a2e3146 100644--- a/packages/core/src/modules/export/export.service.ts+++ b/packages/core/src/modules/export/export.service.ts@@ -7,28 +7,18 @@// apps/api/src/controllers/{export,insights}.controller.ts. No new query// logic: every resolution here already existed in V1's controllers.//-// This barrel (`@openpanel/core`) is reached through `loadCore()`, not a-// static import: `export.routes.ts` mounts into `rest.routes.ts`, which-// `index.ts` — this package's curated barrel — imports. A static import here-// would make importing `@openpanel/core` from ANYWHERE eagerly re-enter this-// same barrel mid-evaluation — the "core imports itself" hazard-// session.service.ts and event.service.ts already document for their own-// lazy loaders — just reached via a different, much more central, file this-// time. A route body only pays for it when it actually runs, same reason-// `event.rpc.ts`'s `loadPagesRuntime()` exists. `@openpanel/db` (just the-// Prisma client) is cheap enough to load the same way, kept separate so a-// caller that only needs `db` doesn't pull in the rest.+// M10-003: `loadDb()` and `loadCore()` are gone. Postgres is `deps.db`, and+// the sibling services these routes delegate to are imported by RELATIVE+// path — the hazard the old `loadCore()` guarded against was re-entering+// this package's own barrel (`@openpanel/core`) mid-evaluation, which a+// relative import cannot do (docs/TECH_DEBT.md §4).import type { IChartRange } from '@openpanel/validation';import type { AuthenticatedClient } from '../../http/client-auth';--export function loadDb() {- return import('@openpanel/db');-}--export function loadCore() {- return import('@openpanel/core');-}+import type { ServiceDeps } from '../../services';+import { getChartStartEndDate, resolveDateRange } from '../../shared/date';+import { getSettingsForProject } from '../organization/organization.service';+import { resolveClientProjectId } from '../project/project.service';export type ProjectIdResolution =| { ok: true; projectId: string }@@ -43,6 +33,7 @@ export type ProjectIdResolution =* being folded into `resolveClientProjectId`.*/export async function resolveExportProjectId(+ deps: ServiceDeps,client: AuthenticatedClient,query: { project_id?: string; projectId?: string }): Promise<ProjectIdResolution> {@@ -57,8 +48,7 @@ export async function resolveExportProjectId(};}- const { db } = await loadDb();- const project = await db.project.findUnique({+ const project = await deps.db.project.findUnique({where: { organizationId: client.organizationId, id: projectId },});@@ -85,11 +75,10 @@ export async function resolveExportProjectId(* is the single client->project resolution point (ADR-011 A-iii invariant* 12), already what apps/api's insights.controller.ts `getProjectId` calls.*/-export async function resolveInsightsProjectId(+export function resolveInsightsProjectId(client: AuthenticatedClient,params: { projectId?: string }): Promise<string> {- const { resolveClientProjectId } = await loadCore();return resolveClientProjectId({clientType: client.type === 'root' ? 'root' : 'read',clientProjectId: client.projectId,@@ -106,8 +95,6 @@ export async function resolveInsightsDateRange(projectId: string,data: { startDate?: string; endDate?: string; range?: IChartRange }): Promise<{ startDate: string; endDate: string }> {- const { getChartStartEndDate, getSettingsForProject, resolveDateRange } =- await loadCore();if (!data.range || data.startDate) {return resolveDateRange(data.startDate, data.endDate);}@@ -117,3 +104,29 @@ export async function resolveInsightsDateRange(timezone);}++// --- service ------------------------------------------------------------++export interface ExportService {+ resolveExportProjectId(+ client: AuthenticatedClient,+ query: { project_id?: string; projectId?: string }+ ): Promise<ProjectIdResolution>;+ resolveInsightsProjectId(+ client: AuthenticatedClient,+ params: { projectId?: string }+ ): Promise<string>;+ resolveInsightsDateRange(+ projectId: string,+ data: { startDate?: string; endDate?: string; range?: IChartRange }+ ): Promise<{ startDate: string; endDate: string }>;+}++export function createExportService(deps: ServiceDeps): ExportService {+ return {+ resolveExportProjectId: (client, query) =>+ resolveExportProjectId(deps, client, query),+ resolveInsightsProjectId,+ resolveInsightsDateRange,+ };+}diff --git a/packages/core/src/modules/gsc/gsc.jobs.test.ts b/packages/core/src/modules/gsc/gsc.jobs.test.tsindex 58aa9a72a..f01757cba 100644--- a/packages/core/src/modules/gsc/gsc.jobs.test.ts+++ b/packages/core/src/modules/gsc/gsc.jobs.test.ts@@ -41,6 +41,11 @@ function stubJobCtx(gsc: Partial<GscService>, jobName = 'test'): JobCtx {group: {} as Services['group'],chart: {} as Services['chart'],misc: {} as Services['misc'],+ report: {} as Services['report'],+ dashboard: {} as Services['dashboard'],+ export: {} as Services['export'],+ share: {} as Services['share'],+ reference: {} as Services['reference'],};return {db: {} as AppDeps['db'],@@ -148,6 +153,11 @@ test('gscSync fans out one gscProjectSync enqueue per connected project', asyncgroup: {} as Services['group'],chart: {} as Services['chart'],misc: {} as Services['misc'],+ report: {} as Services['report'],+ dashboard: {} as Services['dashboard'],+ export: {} as Services['export'],+ share: {} as Services['share'],+ reference: {} as Services['reference'],},requestId: 'req_1',job: { id: 'job_1', attempt: 0, queue: 'cron', name: 'gscSync' },diff --git a/packages/core/src/modules/import/import.jobs.test.ts b/packages/core/src/modules/import/import.jobs.test.tsindex 6ff83e71f..201eb78b3 100644--- a/packages/core/src/modules/import/import.jobs.test.ts+++ b/packages/core/src/modules/import/import.jobs.test.ts@@ -41,6 +41,11 @@ function stubJobCtx(importService: Partial<ImportService>): JobCtx {group: {} as Services['group'],chart: {} as Services['chart'],misc: {} as Services['misc'],+ report: {} as Services['report'],+ dashboard: {} as Services['dashboard'],+ export: {} as Services['export'],+ share: {} as Services['share'],+ reference: {} as Services['reference'],};return {db: {} as AppDeps['db'],diff --git a/packages/core/src/modules/insight/insight.jobs.test.ts b/packages/core/src/modules/insight/insight.jobs.test.tsindex 578b0d9d8..2c0f76b3c 100644--- a/packages/core/src/modules/insight/insight.jobs.test.ts+++ b/packages/core/src/modules/insight/insight.jobs.test.ts@@ -52,6 +52,11 @@ function stubJobCtx(group: {} as Services['group'],chart: {} as Services['chart'],misc: {} as Services['misc'],+ report: {} as Services['report'],+ dashboard: {} as Services['dashboard'],+ export: {} as Services['export'],+ share: {} as Services['share'],+ reference: {} as Services['reference'],};return {db: {} as AppDeps['db'],@@ -142,6 +147,11 @@ test('insightsDaily fans out one insightsProject enqueue per candidate, jobId degroup: {} as Services['group'],chart: {} as Services['chart'],misc: {} as Services['misc'],+ report: {} as Services['report'],+ dashboard: {} as Services['dashboard'],+ export: {} as Services['export'],+ share: {} as Services['share'],+ reference: {} as Services['reference'],},requestId: 'req_1',job: { id: 'job_1', attempt: 0, queue: 'cron', name: 'insightsDaily' },diff --git a/packages/core/src/modules/mcp/src/integration/tools.test.ts b/packages/core/src/modules/mcp/src/integration/tools.test.tsindex 6c171786f..a624f694e 100644--- a/packages/core/src/modules/mcp/src/integration/tools.test.ts+++ b/packages/core/src/modules/mcp/src/integration/tools.test.ts@@ -90,10 +90,21 @@ beforeAll(async () => {await bootstrapTestDatabases();await fixtures.setupPostgresFixtures(TEST_PROJECT_ID, TEST_ORG_ID);await fixtures.setupFixtures(TEST_PROJECT_ID);++ // The mcp tools call core's chart/report functions as bare barrel exports+ // (they have no `Ctx`), so they go through the V1 compat seam, which+ // `main.ts` registers at boot and a test must register itself (M10-003).+ const { setV1CompatServices } = await import('../../../../v1-compat');+ const { testServiceDeps } = await import('../../../../../test/service-deps');+ setV1CompatServices(await testServiceDeps());}, 30_000);afterAll(async () => {const fixtures = await import('../../../../../../../test/fixtures');+ const { resetV1CompatServicesForTests } = await import(+ '../../../../v1-compat'+ );+ resetV1CompatServicesForTests();await fixtures.teardownFixtures(TEST_PROJECT_ID);await fixtures.teardownPostgresFixtures(TEST_PROJECT_ID, TEST_ORG_ID);});diff --git a/packages/core/src/modules/notification/notification.jobs.test.ts b/packages/core/src/modules/notification/notification.jobs.test.tsindex 425be01a9..1e503625c 100644--- a/packages/core/src/modules/notification/notification.jobs.test.ts+++ b/packages/core/src/modules/notification/notification.jobs.test.ts@@ -41,6 +41,11 @@ function stubJobCtx(notification: Partial<NotificationService>): JobCtx {group: {} as Services['group'],chart: {} as Services['chart'],misc: {} as Services['misc'],+ report: {} as Services['report'],+ dashboard: {} as Services['dashboard'],+ export: {} as Services['export'],+ share: {} as Services['share'],+ reference: {} as Services['reference'],};return {db: {} as AppDeps['db'],diff --git a/packages/core/src/modules/onboarding/onboarding.jobs.test.ts b/packages/core/src/modules/onboarding/onboarding.jobs.test.tsindex 48bb8abcd..f866a8632 100644--- a/packages/core/src/modules/onboarding/onboarding.jobs.test.ts+++ b/packages/core/src/modules/onboarding/onboarding.jobs.test.ts@@ -44,6 +44,11 @@ function stubJobCtx(group: {} as Services['group'],chart: {} as Services['chart'],misc: {} as Services['misc'],+ report: {} as Services['report'],+ dashboard: {} as Services['dashboard'],+ export: {} as Services['export'],+ share: {} as Services['share'],+ reference: {} as Services['reference'],};return {db: {} as AppDeps['db'],diff --git a/packages/core/src/modules/organization/organization.jobs.test.ts b/packages/core/src/modules/organization/organization.jobs.test.tsindex 94282b8c8..8a11e5b4d 100644--- a/packages/core/src/modules/organization/organization.jobs.test.ts+++ b/packages/core/src/modules/organization/organization.jobs.test.ts@@ -47,6 +47,11 @@ function stubJobCtx(group: {} as Services['group'],chart: {} as Services['chart'],misc: {} as Services['misc'],+ report: {} as Services['report'],+ dashboard: {} as Services['dashboard'],+ export: {} as Services['export'],+ share: {} as Services['share'],+ reference: {} as Services['reference'],};return {db: {} as AppDeps['db'],diff --git a/packages/core/src/modules/overview/overview.rpc.ts b/packages/core/src/modules/overview/overview.rpc.tsindex 8d71e09c6..4ce7082fb 100644--- a/packages/core/src/modules/overview/overview.rpc.ts+++ b/packages/core/src/modules/overview/overview.rpc.ts@@ -31,7 +31,6 @@ import {getSettingsForProject,} from '../organization/organization.service';import { getActiveVisitorCount } from '../realtime/realtime.service';-import { validateOverviewShareAccess } from '../share/share.service';import {overviewService,zGetMapDataInput,@@ -80,16 +79,17 @@ async function resolveOverviewAccess(input: { projectId: string; shareId?: string }): Promise<void> {if (input.shareId) {- const shareValidation = await validateOverviewShareAccess(- input.shareId,- input.projectId,- {- cookies: ctx.cookies,- session: ctx.session.userId- ? { userId: ctx.session.userId }- : undefined,- }- );+ const shareValidation =+ await ctx.services.share.validateOverviewShareAccess(+ input.shareId,+ input.projectId,+ {+ cookies: ctx.cookies,+ session: ctx.session.userId+ ? { userId: ctx.session.userId }+ : undefined,+ }+ );if (!shareValidation.isValid) {throw new TRPCForbiddenError('You do not have access to this share');}diff --git a/packages/core/src/modules/reference/reference.rpc.ts b/packages/core/src/modules/reference/reference.rpc.tsindex 7288a0c4f..06afc6a14 100644--- a/packages/core/src/modules/reference/reference.rpc.ts+++ b/packages/core/src/modules/reference/reference.rpc.ts@@ -7,8 +7,11 @@// exactly like V1's `enforceUserIsAuthed`. V1 keeps serving the live route// through packages/trpc's own `protectedProcedure` (full stack included) and// delegates its handler bodies to core's reference functions (DELEGATE-// PATTERN) — this module has no queue/cron of its own, so there is no-// `ctx.services.reference`, same as `user`/`conversation`.+// PATTERN).+//+// M10-003: the handler bodies reach the module through+// `ctx.services.reference`, so the requestId minted at the edge reaches the+// Postgres call (ADR-018).//// The permission ladder itself is bound once, in auth.service.ts (M10-002);// every procedure here reaches it through `ctx.services.auth`. `create` has@@ -19,14 +22,6 @@ import { zCreateReference, zRange } from '@openpanel/validation';import { z } from 'zod';import { createTRPCRouter, procedure } from '../../rpc/base';import { TRPCAccessError, TRPCForbiddenError } from '../../rpc/errors';-import {- createReference,- deleteReference,- getChartReferences,- getReferenceByIdOrThrow,- listReferences,- updateReference,-} from './reference.service';function requireLogin(userId: string | null | undefined): string {if (!userId) {@@ -47,12 +42,12 @@ export const referenceRouter = createTRPCRouter({if (!access) {throw new TRPCForbiddenError('You do not have access to this project');}- return listReferences(input);+ return ctx.services.reference.listReferences(input);}),create: procedure.input(zCreateReference).mutation(({ input, ctx }) => {requireLogin(ctx.session.userId);- return createReference(input);+ return ctx.services.reference.createReference(input);}),update: procedure@@ -66,26 +61,30 @@ export const referenceRouter = createTRPCRouter({).mutation(async ({ input, ctx }) => {const userId = requireLogin(ctx.session.userId);- const existing = await getReferenceByIdOrThrow(input.id);+ const existing = await ctx.services.reference.getReferenceByIdOrThrow(+ input.id+ );await ctx.services.auth.requireProjectAccess({userId,projectId: existing.projectId,level: 'write',});- return updateReference(input);+ return ctx.services.reference.updateReference(input);}),delete: procedure.input(z.object({ id: z.string() })).mutation(async ({ input, ctx }) => {const userId = requireLogin(ctx.session.userId);- const existing = await getReferenceByIdOrThrow(input.id);+ const existing = await ctx.services.reference.getReferenceByIdOrThrow(+ input.id+ );await ctx.services.auth.requireProjectAccess({userId,projectId: existing.projectId,level: 'write',});- return deleteReference(input.id);+ return ctx.services.reference.deleteReference(input.id);}),getChartReferences: procedure@@ -97,5 +96,7 @@ export const referenceRouter = createTRPCRouter({range: zRange,}))- .query(({ input }) => getChartReferences(input)),+ .query(({ input, ctx }) =>+ ctx.services.reference.getChartReferences(input)+ ),});diff --git a/packages/core/src/modules/reference/reference.service.test.ts b/packages/core/src/modules/reference/reference.service.test.tsindex 7704817a7..6cdbde826 100644--- a/packages/core/src/modules/reference/reference.service.test.ts+++ b/packages/core/src/modules/reference/reference.service.test.ts@@ -1,10 +1,9 @@-// reference.service.ts's db access is lazy (`await import(...)` inside each-// function — see the file's header), which is exactly what makes-// `mock.module` work here with no import-time side effects to race: every-// mock below is registered before the subject's first call, not before its-// (side-effect-free) import.+// The subject is built by its factory over a fake `ServiceDeps` (M10-003), so+// Postgres needs no module mock at all — `deps.db` IS the fake below. Only the+// two sibling modules the service still calls as plain functions are mocked,+// at the specifier the source resolves through.-import { beforeAll, beforeEach, expect, mock, test } from 'bun:test';+import { afterAll, beforeAll, beforeEach, expect, mock, test } from 'bun:test';interface FakeReference {id: string;@@ -67,7 +66,10 @@ const reference = {}),create: mock(async ({ data }: { data: Omit<FakeReference, 'id'> }) => {- const row = makeReference({ id: `ref_${referenceStore.size + 1}`, ...data });+ const row = makeReference({+ id: `ref_${referenceStore.size + 1}`,+ ...data,+ });referenceStore.set(row.id, row);return row;}),@@ -95,28 +97,40 @@ const reference = {}),};-const actualPrismaClient = await import('@openpanel/db/src/prisma-client');-mock.module('@openpanel/db/src/prisma-client', () => ({- ...actualPrismaClient,- db: { reference },-}));-const getSettingsForProject = mock(async () => ({ timezone: 'UTC' }));const getChartStartEndDate = mock(() => ({startDate: '2026-08-25 00:00:00',endDate: '2026-09-01 23:59:59',}));-// Both loaders (date.service + organization.service) resolve through the-// same @openpanel/core specifier now (M9-CLEANUP-001) — one mock.module call,-// not two, or the second silently drops the first's override.-mock.module('@openpanel/core', () => ({+// M10-003: the module no longer reaches either through a lazy+// `@openpanel/core` hop — Postgres arrives as `deps.db` and these two are+// plain relative imports, so each is mocked at the specifier the source+// actually resolves through. Snapshot-before-mock so `afterAll` restores the+// real module rather than re-applying the mock.+const actualOrganization = await import('../organization/organization.service');+const realOrganization = { ...actualOrganization };+mock.module('../organization/organization.service', () => ({+ ...realOrganization,getSettingsForProject,+}));+const actualDate = await import('../../shared/date');+const realDate = { ...actualDate };+mock.module('../../shared/date', () => ({+ ...realDate,getChartStartEndDate,}));-let subject: typeof import('./reference.service');+afterAll(() => {+ mock.module('../organization/organization.service', () => realOrganization);+ mock.module('../../shared/date', () => realDate);+});++let subject: import('./reference.service').ReferenceService;beforeAll(async () => {- subject = await import('./reference.service');+ const { createReferenceService } = await import('./reference.service');+ subject = createReferenceService({+ db: { reference },+ } as unknown as import('../../services').ServiceDeps);});beforeEach(() => {@@ -160,7 +174,10 @@ test('createReference stores the date as a Date, not a string', async () => {});test('updateReference normalizes a nullish description to null', async () => {- referenceStore.set('ref_1', makeReference({ id: 'ref_1', description: 'old' }));+ referenceStore.set(+ 'ref_1',+ makeReference({ id: 'ref_1', description: 'old' })+ );const result = await subject.updateReference({id: 'ref_1',title: 'Renamed',diff --git a/packages/core/src/modules/reference/reference.service.ts b/packages/core/src/modules/reference/reference.service.tsindex 374cbed28..cfe08e80a 100644--- a/packages/core/src/modules/reference/reference.service.ts+++ b/packages/core/src/modules/reference/reference.service.ts@@ -2,69 +2,84 @@// query/mutation bodies packages/trpc/src/routers/reference.ts held inline// (M6-004, DELEGATE PATTERN: V1's router and this package's own// reference.rpc.ts share one implementation, same as-// conversation.service.ts since M5-006). packages/db keeps a re-export shim:-// nothing outside this module's own routers reached it directly, but the-// shape stays for any future @openpanel/db importer, same as-// packages/db/src/services/organization.service.ts since M6-001.+// conversation.service.ts since M5-006).//-// db access is LAZY, not a static top-level import — see insight.service.ts's-// header for the full reasoning (jobs.registry.ts and services.ts pull this-// module into the eager barrel chain nearly every core test file reaches, and-// constructing @openpanel/db's clients at import time would spawn a-// pino-pretty transport worker thread per test file).+// M10-003: every function takes `ServiceDeps` and reaches Postgres as+// `deps.db`. The `loadDb()` / `loadDateService()` / `loadOrganizationService()`+// lazy loaders are gone: nothing here value-imports `@openpanel/db` or this+// package's own barrel any more (the Prisma row type below is `import type`,+// erased at runtime), so there is no import-time client — and no pino-pretty+// worker per test file — left to defer (docs/TECH_DEBT.md §4).import type { Reference } from '@openpanel/db/src/prisma-client';import type { IChartRange } from '@openpanel/validation';+import type { ServiceDeps } from '../../services';+import { getChartStartEndDate } from '../../shared/date';+import { getSettingsForProject } from '../organization/organization.service';export type IServiceReference = Reference;const REFERENCES_PAGE_SIZE = 50;-function loadDb() {- return import('@openpanel/db/src/prisma-client').then((m) => m.db);+export interface ListReferencesInput {+ projectId: string;+ cursor?: number;}-function loadDateService() {- return import('@openpanel/core');+export interface CreateReferenceInput {+ title: string;+ description?: string | null;+ datetime: string;+ projectId: string;+}++export interface UpdateReferenceInput {+ id: string;+ title: string;+ description?: string | null;+ datetime: string;}-function loadOrganizationService() {- return import('@openpanel/core');+export interface ChartReferencesInput {+ projectId: string;+ startDate?: string | null;+ endDate?: string | null;+ range: IChartRange;}-export async function getReferenceById(id: string): Promise<Reference | null> {- const db = await loadDb();- return db.reference.findUnique({ where: { id } });+export function getReferenceById(+ deps: ServiceDeps,+ id: string+): Promise<Reference | null> {+ return deps.db.reference.findUnique({ where: { id } });}/** Throws Prisma's own not-found error, same as V1's inline* `findUniqueOrThrow` call sites — used by both routers' ownership lookup* ahead of their own access check. */-export async function getReferenceByIdOrThrow(id: string): Promise<Reference> {- const db = await loadDb();- return db.reference.findUniqueOrThrow({ where: { id } });+export function getReferenceByIdOrThrow(+ deps: ServiceDeps,+ id: string+): Promise<Reference> {+ return deps.db.reference.findUniqueOrThrow({ where: { id } });}-export async function listReferences(input: {- projectId: string;- cursor?: number;-}): Promise<Reference[]> {- const db = await loadDb();- return db.reference.findMany({+export function listReferences(+ deps: ServiceDeps,+ input: ListReferencesInput+): Promise<Reference[]> {+ return deps.db.reference.findMany({where: { projectId: input.projectId },take: REFERENCES_PAGE_SIZE,skip: input.cursor ? input.cursor * REFERENCES_PAGE_SIZE : 0,});}-export async function createReference(input: {- title: string;- description?: string | null;- datetime: string;- projectId: string;-}): Promise<Reference> {- const db = await loadDb();- return db.reference.create({+export function createReference(+ deps: ServiceDeps,+ input: CreateReferenceInput+): Promise<Reference> {+ return deps.db.reference.create({data: {title: input.title,description: input.description,@@ -74,14 +89,11 @@ export async function createReference(input: {});}-export async function updateReference(input: {- id: string;- title: string;- description?: string | null;- datetime: string;-}): Promise<Reference> {- const db = await loadDb();- return db.reference.update({+export function updateReference(+ deps: ServiceDeps,+ input: UpdateReferenceInput+): Promise<Reference> {+ return deps.db.reference.update({where: { id: input.id },data: {title: input.title,@@ -91,21 +103,18 @@ export async function updateReference(input: {});}-export async function deleteReference(id: string): Promise<Reference> {- const db = await loadDb();- return db.reference.delete({ where: { id } });+export function deleteReference(+ deps: ServiceDeps,+ id: string+): Promise<Reference> {+ return deps.db.reference.delete({ where: { id } });}-export async function getChartReferences(input: {- projectId: string;- startDate?: string | null;- endDate?: string | null;- range: IChartRange;-}): Promise<Reference[]> {- const { getSettingsForProject } = await loadOrganizationService();+export async function getChartReferences(+ deps: ServiceDeps,+ input: ChartReferencesInput+): Promise<Reference[]> {const { timezone } = await getSettingsForProject(input.projectId);-- const { getChartStartEndDate } = await loadDateService();const { startDate, endDate } = getChartStartEndDate({startDate: input.startDate,@@ -115,8 +124,7 @@ export async function getChartReferences(input: {timezone);- const db = await loadDb();- return db.reference.findMany({+ return deps.db.reference.findMany({where: {projectId: input.projectId,date: {@@ -126,3 +134,25 @@ export async function getChartReferences(input: {},});}++export interface ReferenceService {+ getReferenceById(id: string): Promise<Reference | null>;+ getReferenceByIdOrThrow(id: string): Promise<Reference>;+ listReferences(input: ListReferencesInput): Promise<Reference[]>;+ createReference(input: CreateReferenceInput): Promise<Reference>;+ updateReference(input: UpdateReferenceInput): Promise<Reference>;+ deleteReference(id: string): Promise<Reference>;+ getChartReferences(input: ChartReferencesInput): Promise<Reference[]>;+}++export function createReferenceService(deps: ServiceDeps): ReferenceService {+ return {+ getReferenceById: (id) => getReferenceById(deps, id),+ getReferenceByIdOrThrow: (id) => getReferenceByIdOrThrow(deps, id),+ listReferences: (input) => listReferences(deps, input),+ createReference: (input) => createReference(deps, input),+ updateReference: (input) => updateReference(deps, input),+ deleteReference: (id) => deleteReference(deps, id),+ getChartReferences: (input) => getChartReferences(deps, input),+ };+}diff --git a/packages/core/src/modules/report/report.rpc.ts b/packages/core/src/modules/report/report.rpc.tsindex e64a7b512..8d26ebd6c 100644--- a/packages/core/src/modules/report/report.rpc.ts+++ b/packages/core/src/modules/report/report.rpc.ts@@ -12,24 +12,7 @@import { z } from 'zod';import { createTRPCRouter, procedure, type TrpcContext } from '../../rpc/base';import { TRPCAccessError, TRPCNotFoundError } from '../../rpc/errors';-import {- getDashboardById,- getDashboardByIdOrThrow,-} from '../dashboard/dashboard.service';import { zReport } from './report.constants';-import {- createReport,- deleteReport,- duplicateReport,- getReportById,- getReportByIdOrThrow,- getReportLayouts,- getReportsByDashboardId,- moveReport,- resetReportLayouts,- updateReport,- updateReportLayout,-} from './report.service';const zReportLayout = z.object({x: z.number(),@@ -75,11 +58,14 @@ export const reportRouter = createTRPCRouter({).query(async ({ input: { dashboardId, projectId }, ctx }) => {requireLogin(ctx.session.userId);- const dashboard = await getDashboardById(dashboardId, projectId);+ const dashboard = await ctx.services.dashboard.getDashboardById(+ dashboardId,+ projectId+ );if (!dashboard) {throw new TRPCNotFoundError('Dashboard not found');}- return getReportsByDashboardId(dashboardId);+ return ctx.services.report.getReportsByDashboardId(dashboardId);}),create: procedure@@ -90,9 +76,10 @@ export const reportRouter = createTRPCRouter({})).mutation(async ({ input: { report, dashboardId }, ctx }) => {- const dbDashboard = await getDashboardByIdOrThrow(dashboardId);+ const dbDashboard =+ await ctx.services.dashboard.getDashboardByIdOrThrow(dashboardId);await requireWriteAccess(ctx, dbDashboard.projectId);- return createReport({+ return ctx.services.report.createReport({dashboardId,projectId: dbDashboard.projectId,report,@@ -107,9 +94,9 @@ export const reportRouter = createTRPCRouter({})).mutation(async ({ input: { report, reportId }, ctx }) => {- const dbReport = await getReportByIdOrThrow(reportId);+ const dbReport = await ctx.services.report.getReportByIdOrThrow(reportId);await requireWriteAccess(ctx, dbReport.projectId);- return updateReport({ reportId, report });+ return ctx.services.report.updateReport({ reportId, report });}),move: procedure@@ -120,9 +107,9 @@ export const reportRouter = createTRPCRouter({})).mutation(async ({ input: { reportId, dashboardId }, ctx }) => {- const dbReport = await getReportByIdOrThrow(reportId);+ const dbReport = await ctx.services.report.getReportByIdOrThrow(reportId);await requireWriteAccess(ctx, dbReport.projectId);- return moveReport({ report: dbReport, dashboardId });+ return ctx.services.report.moveReport({ report: dbReport, dashboardId });}),delete: procedure@@ -132,9 +119,9 @@ export const reportRouter = createTRPCRouter({})).mutation(async ({ input: { reportId }, ctx }) => {- const dbReport = await getReportByIdOrThrow(reportId);+ const dbReport = await ctx.services.report.getReportByIdOrThrow(reportId);await requireWriteAccess(ctx, dbReport.projectId);- return deleteReport(reportId);+ return ctx.services.report.deleteReport(reportId);}),duplicate: procedure@@ -144,9 +131,9 @@ export const reportRouter = createTRPCRouter({})).mutation(async ({ input: { reportId }, ctx }) => {- const dbReport = await getReportByIdOrThrow(reportId);+ const dbReport = await ctx.services.report.getReportByIdOrThrow(reportId);await requireWriteAccess(ctx, dbReport.projectId);- return duplicateReport(dbReport);+ return ctx.services.report.duplicateReport(dbReport);}),get: procedure@@ -156,7 +143,7 @@ export const reportRouter = createTRPCRouter({})).query(async ({ input: { reportId }, ctx }) => {- const report = await getReportById(reportId);+ const report = await ctx.services.report.getReportById(reportId);if (!report) {throw new TRPCNotFoundError('Report not found');}@@ -172,9 +159,9 @@ export const reportRouter = createTRPCRouter({})).mutation(async ({ input: { reportId, layout }, ctx }) => {- const dbReport = await getReportByIdOrThrow(reportId);+ const dbReport = await ctx.services.report.getReportByIdOrThrow(reportId);await requireWriteAccess(ctx, dbReport.projectId);- return updateReportLayout({ reportId, layout });+ return ctx.services.report.updateReportLayout({ reportId, layout });}),getLayouts: procedure@@ -190,12 +177,15 @@ export const reportRouter = createTRPCRouter({// The access check above only proves the caller owns `projectId`. Bind// the caller-supplied `dashboardId` to that project as well, otherwise a// dashboard from another organization can be read through this handler.- const dashboard = await getDashboardById(dashboardId, projectId);+ const dashboard = await ctx.services.dashboard.getDashboardById(+ dashboardId,+ projectId+ );if (!dashboard) {throw new TRPCNotFoundError('Dashboard not found');}- return getReportLayouts({ dashboardId, projectId });+ return ctx.services.report.getReportLayouts({ dashboardId, projectId });}),resetLayout: procedure@@ -210,11 +200,17 @@ export const reportRouter = createTRPCRouter({// Same as `getLayouts`: bind the dashboard to the access-checked project// before deleting anything, so a foreign dashboard cannot be wiped.- const dashboard = await getDashboardById(dashboardId, projectId);+ const dashboard = await ctx.services.dashboard.getDashboardById(+ dashboardId,+ projectId+ );if (!dashboard) {throw new TRPCNotFoundError('Dashboard not found');}- return resetReportLayouts({ dashboardId, projectId });+ return ctx.services.report.resetReportLayouts({+ dashboardId,+ projectId,+ });}),});diff --git a/packages/core/src/modules/report/report.service.test.ts b/packages/core/src/modules/report/report.service.test.tsindex 412e10a85..e794a4808 100644--- a/packages/core/src/modules/report/report.service.test.ts+++ b/packages/core/src/modules/report/report.service.test.ts@@ -3,10 +3,11 @@* global filters with each event series' own filters (AND semantics). Pure* function, no ClickHouse/Postgres needed. Ported from* packages/db/src/services/reports.service.test.ts (M7-006), vitest -> bun:test.+ * M10-003 moved the helper to ./src/series.ts — see that file for why.*/import { describe, expect, it } from 'bun:test';import type { IChartEventFilter, IChartEventItem } from '@openpanel/validation';-import { mergeGlobalFilters } from './report.service';+import { mergeGlobalFilters } from './src/series';const globalFilter: IChartEventFilter = {id: 'g1',diff --git a/packages/core/src/modules/report/report.service.ts b/packages/core/src/modules/report/report.service.tsindex abf149313..7ef689b42 100644--- a/packages/core/src/modules/report/report.service.ts+++ b/packages/core/src/modules/report/report.service.ts@@ -1,15 +1,18 @@// Moved from packages/db/src/services/reports.service.ts, plus the// create/update/move/delete/duplicate/layout mutation bodies// packages/trpc/src/routers/report.ts held inline (M7-006, ADR-008's module-// map: report owns "R,S,C"). packages/db/src/services/reports.service.ts-// stays a re-export shim (DELEGATE PATTERN), same shape as-// project.service.ts since M6-002.+// map: report owns "R,S,C").+//+// M10-003: every function takes `ServiceDeps` and reaches Postgres as+// `deps.db`; `loadDb()` and the `@openpanel/core` self-barrel import are+// gone — the Prisma row types below are `import type`, erased at runtime+// (docs/TECH_DEBT.md §4). `onlyReportEvents`/`mergeGlobalFilters` moved to+// ./src/series.ts — see that file for why.import type {Report as DbReport,ReportLayout,} from '@openpanel/db/src/prisma-client';-import { getChartStartEndDate } from '@openpanel/core';import type {IChartBreakdown,IChartEventFilter,@@ -20,51 +23,20 @@ import type {IReportOptions,} from '@openpanel/validation';import { TRPCBadRequestError } from '../../rpc/errors';+import type { ServiceDeps } from '../../services';+import { getChartStartEndDate } from '../../shared/date';import { getFunnel } from '../chart/funnel.service';-import { AggregateChartEngine, ChartEngine } from '../chart/src/engine/execute';+import {+ executeAggregateChart,+ executeChart,+} from '../chart/src/engine/execute';import { getDashboardById } from '../dashboard/dashboard.service';import { getSettingsForProject } from '../organization/organization.service';import { alphabetIds, lineTypes } from './report.constants';+import { mergeGlobalFilters, onlyReportEvents } from './src/series';export type IServiceReport = Awaited<ReturnType<typeof getReportById>>;-// Only the Postgres client stays lazy: report.rpc.ts lands in the eager-// rpc.router.ts barrel chain nearly every core test file reaches, and-// constructing @openpanel/db's prisma-client at import time would spawn a-// pino-pretty transport worker thread per test file (see-// insight.service.ts's header / project.service.ts's header). date.service-// and the chart engine carry no db construction of their own, and the chart-// engine is already eager via chart.rpc.ts, so both stay static imports.-function loadDb() {- return import('@openpanel/db/src/prisma-client').then((m) => m.db);-}--export const onlyReportEvents = (- series: NonNullable<IServiceReport>['series']-) => {- return series.filter((item) => item.type === 'event');-};--/**- * Prepend report-level global filters to every event series' own filters.- * Combining is AND (filters already combine with AND in getEventFiltersWhereClause).- * Formulas reference other series, so they inherit the global filters transitively- * and are left untouched here.- */-export function mergeGlobalFilters(- series: IChartEventItem[],- globalFilters: IChartEventFilter[] = []-): IChartEventItem[] {- if (!globalFilters.length) {- return series;- }- return series.map((item) =>- item.type === 'event'- ? { ...item, filters: [...globalFilters, ...item.filters] }- : item- );-}-export function transformFilter(filter: Partial<IChartEventFilter>,index: number@@ -140,8 +112,11 @@ export function transformReport(};}-export async function getReportsByDashboardId(dashboardId: string) {- const db = await loadDb();+export async function getReportsByDashboardId(+ deps: ServiceDeps,+ dashboardId: string+) {+ const db = deps.db;const reports = await db.report.findMany({where: {dashboardId,@@ -153,8 +128,8 @@ export async function getReportsByDashboardId(dashboardId: string) {return reports.map(transformReport);}-export async function getReportById(id: string) {- const db = await loadDb();+export async function getReportById(deps: ServiceDeps, id: string) {+ const db = deps.db;const report = await db.report.findUnique({where: {id,@@ -174,21 +149,27 @@ export async function getReportById(id: string) {/** Unscoped lookup for mutation handlers that only receive a report id and* need its `projectId`/`dashboardId` to run the access check — same shape as* V1's inline `db.report.findUniqueOrThrow`. */-export async function getReportByIdOrThrow(id: string) {- const db = await loadDb();- return db.report.findUniqueOrThrow({ where: { id } });+export async function getReportByIdOrThrow(deps: ServiceDeps, id: string) {+ return deps.db.report.findUniqueOrThrow({ where: { id } });}-export async function listReportsCore(input: {- projectId: string;- dashboardId: string;- organizationId: string;-}) {- const dashboard = await getDashboardById(input.dashboardId, input.projectId);+export async function listReportsCore(+ deps: ServiceDeps,+ input: {+ projectId: string;+ dashboardId: string;+ organizationId: string;+ }+) {+ const dashboard = await getDashboardById(+ deps,+ input.dashboardId,+ input.projectId+ );if (!dashboard) {return [];}- const reports = await getReportsByDashboardId(input.dashboardId);+ const reports = await getReportsByDashboardId(deps, input.dashboardId);return reports.map((r) => ({id: r.id,name: r.name,@@ -211,13 +192,15 @@ export async function listReportsCore(input: {}));}-export async function getReportDataCore(input: {- projectId: string;- reportId: string;- organizationId: string;-}) {- const db = await loadDb();- const rawReport = await db.report.findUnique({+export async function getReportDataCore(+ deps: ServiceDeps,+ input: {+ projectId: string;+ reportId: string;+ organizationId: string;+ }+) {+ const rawReport = await deps.db.report.findUnique({where: { id: input.reportId, projectId: input.projectId },include: { layout: true },});@@ -242,16 +225,16 @@ export async function getReportDataCore(input: {};if (report.chartType === 'funnel') {- const result = await getFunnel(chartInput);+ const result = await getFunnel(deps, chartInput);return { ...meta, data: result };}if (report.chartType === 'metric') {- const result = await AggregateChartEngine.execute(chartInput);+ const result = await executeAggregateChart(deps, chartInput);return { ...meta, data: result };}- const result = await ChartEngine.execute(chartInput);+ const result = await executeChart(deps, chartInput);return { ...meta, data: result };}@@ -284,12 +267,15 @@ function reportWriteData(report: IReportInputForWrite) {};}-export async function createReport(input: {- dashboardId: string;- projectId: string;- report: IReportInputForWrite;-}) {- const db = await loadDb();+export async function createReport(+ deps: ServiceDeps,+ input: {+ dashboardId: string;+ projectId: string;+ report: IReportInputForWrite;+ }+) {+ const db = deps.db;return db.report.create({data: {projectId: input.projectId,@@ -299,11 +285,14 @@ export async function createReport(input: {});}-export async function updateReport(input: {- reportId: string;- report: IReportInputForWrite;-}) {- const db = await loadDb();+export async function updateReport(+ deps: ServiceDeps,+ input: {+ reportId: string;+ report: IReportInputForWrite;+ }+) {+ const db = deps.db;return db.report.update({where: {id: input.reportId,@@ -312,11 +301,14 @@ export async function updateReport(input: {});}-export async function moveReport(input: {- report: DbReport;- dashboardId: string;-}) {- const db = await loadDb();+export async function moveReport(+ deps: ServiceDeps,+ input: {+ report: DbReport;+ dashboardId: string;+ }+) {+ const db = deps.db;const { report, dashboardId } = input;if (report.dashboardId === dashboardId) {@@ -360,8 +352,8 @@ export async function moveReport(input: {return moved;}-export async function deleteReport(reportId: string) {- const db = await loadDb();+export async function deleteReport(deps: ServiceDeps, reportId: string) {+ const db = deps.db;return db.report.delete({where: {id: reportId,@@ -369,8 +361,8 @@ export async function deleteReport(reportId: string) {});}-export async function duplicateReport(report: DbReport) {- const db = await loadDb();+export async function duplicateReport(deps: ServiceDeps, report: DbReport) {+ const db = deps.db;return db.report.create({data: {projectId: report.projectId,@@ -406,11 +398,14 @@ interface ReportLayoutInput {maxH?: number;}-export async function updateReportLayout(input: {- reportId: string;- layout: ReportLayoutInput;-}) {- const db = await loadDb();+export async function updateReportLayout(+ deps: ServiceDeps,+ input: {+ reportId: string;+ layout: ReportLayoutInput;+ }+) {+ const db = deps.db;const { reportId, layout } = input;// Upsert the layout (create if doesn't exist, update if it does)@@ -426,11 +421,14 @@ export async function updateReportLayout(input: {});}-export async function getReportLayouts(input: {- dashboardId: string;- projectId: string;-}) {- const db = await loadDb();+export async function getReportLayouts(+ deps: ServiceDeps,+ input: {+ dashboardId: string;+ projectId: string;+ }+) {+ const db = deps.db;return db.reportLayout.findMany({where: {report: {@@ -444,11 +442,14 @@ export async function getReportLayouts(input: {});}-export async function resetReportLayouts(input: {- dashboardId: string;- projectId: string;-}) {- const db = await loadDb();+export async function resetReportLayouts(+ deps: ServiceDeps,+ input: {+ dashboardId: string;+ projectId: string;+ }+) {+ const db = deps.db;return db.reportLayout.deleteMany({where: {report: {@@ -458,3 +459,79 @@ export async function resetReportLayouts(input: {},});}++// --- service ------------------------------------------------------------++export interface ReportService {+ transformFilter(+ filter: Partial<IChartEventFilter>,+ index: number+ ): IChartEventFilter;+ transformReportEventItem(+ item: IChartEventItem,+ index: number+ ): IChartEventItem;+ transformReport(+ report: DbReport & { layout?: ReportLayout | null }+ ): ReturnType<typeof transformReport>;+ mergeGlobalFilters(+ series: IChartEventItem[],+ globalFilters?: IChartEventFilter[]+ ): IChartEventItem[];+ onlyReportEvents(series: IChartEventItem[]): IChartEventItem[];+ getReportsByDashboardId(+ dashboardId: string+ ): ReturnType<typeof getReportsByDashboardId>;+ getReportById(id: string): ReturnType<typeof getReportById>;+ getReportByIdOrThrow(id: string): ReturnType<typeof getReportByIdOrThrow>;+ listReportsCore(+ input: Parameters<typeof listReportsCore>[1]+ ): ReturnType<typeof listReportsCore>;+ getReportDataCore(+ input: Parameters<typeof getReportDataCore>[1]+ ): ReturnType<typeof getReportDataCore>;+ createReport(+ input: Parameters<typeof createReport>[1]+ ): ReturnType<typeof createReport>;+ updateReport(+ input: Parameters<typeof updateReport>[1]+ ): ReturnType<typeof updateReport>;+ moveReport(+ input: Parameters<typeof moveReport>[1]+ ): ReturnType<typeof moveReport>;+ deleteReport(reportId: string): ReturnType<typeof deleteReport>;+ duplicateReport(report: DbReport): ReturnType<typeof duplicateReport>;+ updateReportLayout(+ input: Parameters<typeof updateReportLayout>[1]+ ): ReturnType<typeof updateReportLayout>;+ getReportLayouts(+ input: Parameters<typeof getReportLayouts>[1]+ ): ReturnType<typeof getReportLayouts>;+ resetReportLayouts(+ input: Parameters<typeof resetReportLayouts>[1]+ ): ReturnType<typeof resetReportLayouts>;+}++export function createReportService(deps: ServiceDeps): ReportService {+ return {+ transformFilter,+ transformReportEventItem,+ transformReport,+ mergeGlobalFilters,+ onlyReportEvents,+ getReportsByDashboardId: (dashboardId) =>+ getReportsByDashboardId(deps, dashboardId),+ getReportById: (id) => getReportById(deps, id),+ getReportByIdOrThrow: (id) => getReportByIdOrThrow(deps, id),+ listReportsCore: (input) => listReportsCore(deps, input),+ getReportDataCore: (input) => getReportDataCore(deps, input),+ createReport: (input) => createReport(deps, input),+ updateReport: (input) => updateReport(deps, input),+ moveReport: (input) => moveReport(deps, input),+ deleteReport: (reportId) => deleteReport(deps, reportId),+ duplicateReport: (report) => duplicateReport(deps, report),+ updateReportLayout: (input) => updateReportLayout(deps, input),+ getReportLayouts: (input) => getReportLayouts(deps, input),+ resetReportLayouts: (input) => resetReportLayouts(deps, input),+ };+}diff --git a/packages/core/src/modules/report/src/series.ts b/packages/core/src/modules/report/src/series.tsnew file mode 100644index 000000000..7df120014--- /dev/null+++ b/packages/core/src/modules/report/src/series.ts@@ -0,0 +1,38 @@+// The two pure series helpers V1 kept on `reports.service`. They live here,+// not on report.service.ts, because the chart module needs them and+// report.service.ts imports the chart engine — a static import back would+// close a real cycle (report.service -> chart/funnel.service ->+// report.service). Nothing here touches a database, so both sides stay+// eager and neither needs a lazy loader (docs/TECH_DEBT.md §4 step 2).++import type { IChartEventFilter, IChartEventItem } from '@openpanel/validation';++/** The event half of the discriminated series union — what every caller then+ * reads `.name` / `.filters` off. */+export type ReportEventItem = Extract<IChartEventItem, { type: 'event' }>;++export function onlyReportEvents(series: IChartEventItem[]): ReportEventItem[] {+ return series.filter(+ (item): item is ReportEventItem => item.type === 'event'+ );+}++/**+ * Prepend report-level global filters to every event series' own filters.+ * Combining is AND (filters already combine with AND in getEventFiltersWhereClause).+ * Formulas reference other series, so they inherit the global filters transitively+ * and are left untouched here.+ */+export function mergeGlobalFilters(+ series: IChartEventItem[],+ globalFilters: IChartEventFilter[] = []+): IChartEventItem[] {+ if (!globalFilters.length) {+ return series;+ }+ return series.map((item) =>+ item.type === 'event'+ ? { ...item, filters: [...globalFilters, ...item.filters] }+ : item+ );+}diff --git a/packages/core/src/modules/share/share.rpc.ts b/packages/core/src/modules/share/share.rpc.tsindex 70b6cabcb..ae6ba5055 100644--- a/packages/core/src/modules/share/share.rpc.ts+++ b/packages/core/src/modules/share/share.rpc.ts@@ -7,8 +7,10 @@// exactly like V1's `enforceUserIsAuthed`. V1 keeps serving the live route// through packages/trpc's own `protectedProcedure` (full stack included) and// delegates its handler bodies to core's share functions (DELEGATE-// PATTERN) — this module has no queue/cron of its own, so there is no-// `ctx.services.share`, same as `user`/`project`.+// PATTERN).+//+// M10-003: the handler bodies reach the module through `ctx.services.share`,+// so the requestId minted at the edge reaches the Postgres call (ADR-018).//// The permission ladder itself is bound once, in auth.service.ts// (M10-002); every procedure here reaches it through `ctx.services.auth`. `createOverview` has no access@@ -22,18 +24,6 @@ import {zShareOverview,zShareReport,} from './share.constants';-import {- createShareDashboard,- createShareOverview,- createShareReport,- getShareDashboard,- getShareDashboardReports,- getShareDashboardSettings,- getShareOverview,- getShareOverviewSettings,- getShareReport,- getShareReportSettings,-} from './share.service';function requireLogin(userId: string | null | undefined): string {if (!userId) {@@ -45,29 +35,36 @@ function requireLogin(userId: string | null | undefined): string {export const shareRouter = createTRPCRouter({overview: procedure.input(z.object({ shareId: z.string() }))- .query(({ input, ctx }) => getShareOverview(input.shareId, ctx.cookies)),+ .query(({ input, ctx }) =>+ ctx.services.share.getShareOverview(input.shareId, ctx.cookies)+ ),overviewSettings: procedure.input(z.object({ projectId: z.string() })).query(({ input, ctx }) => {requireLogin(ctx.session.userId);- return getShareOverviewSettings(input.projectId);+ return ctx.services.share.getShareOverviewSettings(input.projectId);}),createOverview: procedure.input(zShareOverview).mutation(({ input, ctx }) => {requireLogin(ctx.session.userId);- return createShareOverview(input);+ return ctx.services.share.createShareOverview(input);}),dashboard: procedure.input(z.object({ shareId: z.string() }))- .query(({ input, ctx }) => getShareDashboard(input.shareId, ctx.cookies)),+ .query(({ input, ctx }) =>+ ctx.services.share.getShareDashboard(input.shareId, ctx.cookies)+ ),dashboardSettings: procedure.input(z.object({ projectId: z.string(), dashboardId: z.string() })).query(({ input, ctx }) => {requireLogin(ctx.session.userId);- return getShareDashboardSettings(input.projectId, input.dashboardId);+ return ctx.services.share.getShareDashboardSettings(+ input.projectId,+ input.dashboardId+ );}),createDashboard: procedure@@ -79,24 +76,29 @@ export const shareRouter = createTRPCRouter({projectId: input.projectId,level: 'write',});- return createShareDashboard(input);+ return ctx.services.share.createShareDashboard(input);}),dashboardReports: procedure.input(z.object({ shareId: z.string() })).query(({ input, ctx }) =>- getShareDashboardReports(input.shareId, ctx.cookies)+ ctx.services.share.getShareDashboardReports(input.shareId, ctx.cookies)),report: procedure.input(z.object({ shareId: z.string() }))- .query(({ input, ctx }) => getShareReport(input.shareId, ctx.cookies)),+ .query(({ input, ctx }) =>+ ctx.services.share.getShareReport(input.shareId, ctx.cookies)+ ),reportSettings: procedure.input(z.object({ projectId: z.string(), reportId: z.string() })).query(({ input, ctx }) => {requireLogin(ctx.session.userId);- return getShareReportSettings(input.projectId, input.reportId);+ return ctx.services.share.getShareReportSettings(+ input.projectId,+ input.reportId+ );}),createReport: procedure@@ -108,6 +110,6 @@ export const shareRouter = createTRPCRouter({projectId: input.projectId,level: 'write',});- return createShareReport(input);+ return ctx.services.share.createShareReport(input);}),});diff --git a/packages/core/src/modules/share/share.service.test.ts b/packages/core/src/modules/share/share.service.test.tsindex 5f64ccb6e..8302bdf7e 100644--- a/packages/core/src/modules/share/share.service.test.ts+++ b/packages/core/src/modules/share/share.service.test.ts@@ -1,10 +1,10 @@-// share.service.ts's db access is lazy (`await import(...)` inside each-// function — see the file's header), which is exactly what makes-// `mock.module` work here with no import-time side effects to race: every-// mock below is registered before the subject's first call, not before its-// (side-effect-free) import.+// The subject is built by its factory over a fake `ServiceDeps` (M10-003), so+// Postgres needs no module mock at all — `deps.db` IS the fake below. Only the+// three sibling modules the service calls as plain functions are mocked, each+// at the specifier the source resolves through, snapshot-before-mock so+// `afterAll` restores the real module instead of re-applying the mock.-import { beforeAll, beforeEach, expect, mock, test } from 'bun:test';+import { afterAll, beforeAll, beforeEach, expect, mock, test } from 'bun:test';interface FakeShare {id: string;@@ -72,9 +72,7 @@ const shareOverview = {update: { public: boolean; password: string | null };}) => {const existing = findOverviewByProjectId(projectId);- const next = existing- ? { ...existing, ...update }- : { ...create };+ const next = existing ? { ...existing, ...update } : { ...create };overviewStore.set(next.id, next);return next;}@@ -92,7 +90,12 @@ const shareDashboard = {if (!share) {return null;}- return { ...share, organization: ORG, project: PROJECT, dashboard: { name: 'Main' } };+ return {+ ...share,+ organization: ORG,+ project: PROJECT,+ dashboard: { name: 'Main' },+ };}),findFirst: mock(async ({ where: { id } }: { where: { id: string } }) => {@@ -164,17 +167,12 @@ const shareReport = {),};-const actualPrismaClient = await import('@openpanel/db/src/prisma-client');-mock.module('@openpanel/db/src/prisma-client', () => ({- ...actualPrismaClient,- db: { shareOverview, shareDashboard, shareReport },-}));--const getDashboardById = mock(async (id: string, projectId: string) =>- id === 'dash_missing' ? null : { id, projectId, name: 'Main' }+const getDashboardById = mock(+ async (_deps: unknown, id: string, projectId: string) =>+ id === 'dash_missing' ? null : { id, projectId, name: 'Main' });-const getReportById = mock(async (id: string) =>+const getReportById = mock(async (_deps: unknown, id: string) =>id === 'report_missing'? null: { id, projectId: 'proj_1', name: 'Weekly report' }@@ -183,27 +181,48 @@ const transformReport = mock((report: unknown) => ({...(report as Record<string, unknown>),transformed: true,}));-const getReportsByDashboardId = mock(async () => [{ id: 'report_1' }]);+const getReportsByDashboardId = mock(async (_deps: unknown) => [+ { id: 'report_1' },+]);const getProjectAccess = mock(async ({ userId }: { userId: string; projectId: string }) =>userId === 'member' ? { level: 'read' } : null);-// The access/dashboard/reports loaders all resolve through the same-// @openpanel/core specifier now (M9-CLEANUP-001) — one mock.module call, not-// three, or each later call silently drops the earlier ones' overrides.-mock.module('@openpanel/core', () => ({+const actualDashboard = await import('../dashboard/dashboard.service');+const realDashboard = { ...actualDashboard };+mock.module('../dashboard/dashboard.service', () => ({+ ...realDashboard,getDashboardById,+}));+const actualReport = await import('../report/report.service');+const realReport = { ...actualReport };+mock.module('../report/report.service', () => ({+ ...realReport,getReportById,transformReport,getReportsByDashboardId,+}));+const actualAccessLookups = await import('../../shared/access-lookups');+const realAccessLookups = { ...actualAccessLookups };+mock.module('../../shared/access-lookups', () => ({+ ...realAccessLookups,getProjectAccess,}));-let subject: typeof import('./share.service');+afterAll(() => {+ mock.module('../dashboard/dashboard.service', () => realDashboard);+ mock.module('../report/report.service', () => realReport);+ mock.module('../../shared/access-lookups', () => realAccessLookups);+});++let subject: import('./share.service').ShareService;beforeAll(async () => {- subject = await import('./share.service');+ const { createShareService } = await import('./share.service');+ subject = createShareService({+ db: { shareOverview, shareDashboard, shareReport },+ } as unknown as import('../../services').ServiceDeps);});beforeEach(() => {@@ -222,9 +241,9 @@ function cookies(values: Record<string, string> = {}) {}test('getShareOverview throws NOT_FOUND when the share is missing or not public', async () => {- await expect(subject.getShareOverview('missing', cookies())).rejects.toMatchObject(- { code: 'NOT_FOUND' }- );+ await expect(+ subject.getShareOverview('missing', cookies())+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });overviewStore.set('share_1', {id: 'share_1',@@ -233,9 +252,9 @@ test('getShareOverview throws NOT_FOUND when the share is missing or not public'public: false,password: null,});- await expect(subject.getShareOverview('share_1', cookies())).rejects.toMatchObject(- { code: 'NOT_FOUND' }- );+ await expect(+ subject.getShareOverview('share_1', cookies())+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });});test('getShareOverview returns a locked shape when password-protected without the unlock cookie', async () => {@@ -346,7 +365,10 @@ test('getShareDashboardReports returns the dashboard reports once unlocked', asyconst result = await subject.getShareDashboardReports('share_1', cookies());expect(result).toMatchObject([{ id: 'report_1' }]);- expect(getReportsByDashboardId).toHaveBeenCalledWith('dash_1');+ expect(getReportsByDashboardId).toHaveBeenCalledWith(+ expect.anything(),+ 'dash_1'+ );});test('createShareReport throws NOT_FOUND when the report belongs to a different project', async () => {@@ -391,9 +413,13 @@ test('validateOverviewShareAccess requires membership when no shareId is given',})).rejects.toThrow('You do not have access to this project');- const result = await subject.validateOverviewShareAccess(undefined, 'proj_1', {- cookies: cookies(),- session: { userId: 'member' },- });+ const result = await subject.validateOverviewShareAccess(+ undefined,+ 'proj_1',+ {+ cookies: cookies(),+ session: { userId: 'member' },+ }+ );expect(result).toEqual({ isValid: true });});diff --git a/packages/core/src/modules/share/share.service.ts b/packages/core/src/modules/share/share.service.tsindex 98dd76bc1..10067cae0 100644--- a/packages/core/src/modules/share/share.service.ts+++ b/packages/core/src/modules/share/share.service.ts@@ -6,15 +6,23 @@// (M6-003) and packages/trpc's chart/overview routers still reach// validateShareAccess/validateOverviewShareAccess through it.//-// db access is LAZY, not a static top-level import — see insight.service.ts's-// header for the full reasoning (jobs.registry.ts and services.ts pull this-// module into the eager barrel chain nearly every core test file reaches, and-// constructing @openpanel/db's clients at import time would spawn a-// pino-pretty transport worker thread per test file).+// M10-003: every function takes `ServiceDeps` and reaches Postgres as+// `deps.db`; the `loadDb()` / `loadAccessService()` / `loadDashboardService()`+// / `loadReportsService()` lazy loaders are gone, so this module+// value-imports neither `@openpanel/db` nor its own package barrel+// (docs/TECH_DEBT.md §4).import ShortUniqueId from 'short-unique-id';import { TRPCAccessError, TRPCNotFoundError } from '../../rpc/errors';+import type { ServiceDeps } from '../../services';+import { getProjectAccess } from '../../shared/access-lookups';import { hashPassword } from '../auth/auth.service';+import { getDashboardById } from '../dashboard/dashboard.service';+import {+ getReportById,+ getReportsByDashboardId,+ transformReport,+} from '../report/report.service';const SHARE_ID_LENGTH = 6;const uid = new ShortUniqueId({ length: SHARE_ID_LENGTH });@@ -25,61 +33,54 @@ interface CookieReader {get(name: string): string | undefined;}-function loadDb() {- return import('@openpanel/db/src/prisma-client').then((m) => m.db);-}--function loadAccessService() {- return import('@openpanel/core');-}--function loadDashboardService() {- return import('@openpanel/core');-}--function loadReportsService() {- return import('@openpanel/core');-}-// -----------------------------------------------------------------------// Raw lookups (ported verbatim from packages/db/src/services/share.service.ts).-export async function getShareOverviewById(id: string) {- const db = await loadDb();+export async function getShareOverviewById(deps: ServiceDeps, id: string) {+ const db = deps.db;return db.shareOverview.findFirst({where: { id },include: { project: true },});}-export async function getShareByProjectId(projectId: string) {- const db = await loadDb();+export async function getShareByProjectId(+ deps: ServiceDeps,+ projectId: string+) {+ const db = deps.db;return db.shareOverview.findUnique({ where: { projectId } });}-export async function getShareDashboardById(id: string) {- const db = await loadDb();+export async function getShareDashboardById(deps: ServiceDeps, id: string) {+ const db = deps.db;return db.shareDashboard.findFirst({where: { id },include: { dashboard: { include: { project: true } } },});}-export async function getShareDashboardByDashboardId(dashboardId: string) {- const db = await loadDb();+export async function getShareDashboardByDashboardId(+ deps: ServiceDeps,+ dashboardId: string+) {+ const db = deps.db;return db.shareDashboard.findUnique({ where: { dashboardId } });}-export async function getShareReportById(id: string) {- const db = await loadDb();+export async function getShareReportById(deps: ServiceDeps, id: string) {+ const db = deps.db;return db.shareReport.findFirst({where: { id },include: { report: { include: { project: true } } },});}-export async function getShareReportByReportId(reportId: string) {- const db = await loadDb();+export async function getShareReportByReportId(+ deps: ServiceDeps,+ reportId: string+) {+ const db = deps.db;return db.shareReport.findUnique({ where: { reportId } });}@@ -88,11 +89,12 @@ export async function getShareReportByReportId(reportId: string) {* Ported as-is — removal is a separate P6/P7 task, not this one's.*/export async function validateReportAccess(+ deps: ServiceDeps,reportId: string,shareId: string,shareType: 'dashboard' | 'report') {- const db = await loadDb();+ const db = deps.db;if (shareType === 'dashboard') {const share = await db.shareDashboard.findUnique({@@ -106,7 +108,7 @@ export async function validateReportAccess(},});- if (!share || !share.public) {+ if (!(share && share.public)) {throw new Error('Share not found or not public');}@@ -122,7 +124,7 @@ export async function validateReportAccess(include: { report: true },});- if (!share || !share.public) {+ if (!(share && share.public)) {throw new Error('Share not found or not public');}@@ -134,6 +136,7 @@ export async function validateReportAccess(}export async function validateShareAccess(+ deps: ServiceDeps,shareId: string,reportId: string,ctx: {@@ -141,8 +144,7 @@ export async function validateShareAccess(session?: { userId?: string | null };}): Promise<{ projectId: string; isValid: boolean }> {- const db = await loadDb();- const { getProjectAccess } = await loadAccessService();+ const db = deps.db;const dashboardShare = await db.shareDashboard.findUnique({where: { id: shareId },@@ -205,6 +207,7 @@ export async function validateShareAccess(}export async function validateOverviewShareAccess(+ deps: ServiceDeps,shareId: string | undefined,projectId: string,ctx: {@@ -212,15 +215,14 @@ export async function validateOverviewShareAccess(session?: { userId?: string | null };}): Promise<{ isValid: boolean }> {- const db = await loadDb();- const { getProjectAccess } = await loadAccessService();+ const db = deps.db;if (shareId) {const share = await db.shareOverview.findUnique({where: { id: shareId },});- if (!share || !share.public) {+ if (!(share && share.public)) {throw new Error('Share not found or not public');}@@ -283,8 +285,12 @@ function lockedShare(};}-export async function getShareOverview(shareId: string, cookies: CookieReader) {- const db = await loadDb();+export async function getShareOverview(+ deps: ServiceDeps,+ shareId: string,+ cookies: CookieReader+) {+ const db = deps.db;const share = await db.shareOverview.findUnique({where: { id: shareId },select: {@@ -315,8 +321,11 @@ export async function getShareOverview(shareId: string, cookies: CookieReader) {};}-export async function getShareOverviewSettings(projectId: string) {- const db = await loadDb();+export async function getShareOverviewSettings(+ deps: ServiceDeps,+ projectId: string+) {+ const db = deps.db;const share = await db.shareOverview.findUnique({where: { projectId },select: { id: true, public: true, password: true },@@ -329,14 +338,21 @@ export async function getShareOverviewSettings(projectId: string) {return { id: share.id, public: share.public, hasPassword: !!share.password };}-export async function createShareOverview(input: {+export interface CreateShareOverviewInput {organizationId: string;projectId: string;public: boolean;password: string | null;-}) {- const db = await loadDb();- const passwordHash = input.password ? await hashPassword(input.password) : null;+}++export async function createShareOverview(+ deps: ServiceDeps,+ input: CreateShareOverviewInput+) {+ const db = deps.db;+ const passwordHash = input.password+ ? await hashPassword(input.password)+ : null;const share = await db.shareOverview.upsert({where: { projectId: input.projectId },@@ -354,8 +370,12 @@ export async function createShareOverview(input: {return { id: share.id, public: share.public, hasPassword: !!share.password };}-export async function getShareDashboard(shareId: string, cookies: CookieReader) {- const db = await loadDb();+export async function getShareDashboard(+ deps: ServiceDeps,+ shareId: string,+ cookies: CookieReader+) {+ const db = deps.db;const share = await db.shareDashboard.findUnique({where: { id: shareId },select: {@@ -387,10 +407,11 @@ export async function getShareDashboard(shareId: string, cookies: CookieReader)}export async function getShareDashboardSettings(+ deps: ServiceDeps,projectId: string,dashboardId: string) {- const db = await loadDb();+ const db = deps.db;const share = await db.shareDashboard.findUnique({where: { dashboardId },select: { id: true, public: true, password: true, projectId: true },@@ -405,22 +426,32 @@ export async function getShareDashboardSettings(/** The caller must already have write access to `input.projectId` — the RPC* layer's job (each transport still owns its own access-check plumbing). */-export async function createShareDashboard(input: {+export interface CreateShareDashboardInput {organizationId: string;projectId: string;dashboardId: string;public: boolean;password: string | null;-}) {- const { getDashboardById } = await loadDashboardService();- const dashboard = await getDashboardById(input.dashboardId, input.projectId);+}++export async function createShareDashboard(+ deps: ServiceDeps,+ input: CreateShareDashboardInput+) {+ const dashboard = await getDashboardById(+ deps,+ input.dashboardId,+ input.projectId+ );if (!dashboard) {throw new TRPCNotFoundError('Dashboard not found');}- const passwordHash = input.password ? await hashPassword(input.password) : null;+ const passwordHash = input.password+ ? await hashPassword(input.password)+ : null;- const db = await loadDb();+ const db = deps.db;const share = await db.shareDashboard.upsert({where: { dashboardId: input.dashboardId },create: {@@ -439,10 +470,11 @@ export async function createShareDashboard(input: {}export async function getShareDashboardReports(+ deps: ServiceDeps,shareId: string,cookies: CookieReader) {- const share = await getShareDashboardById(shareId);+ const share = await getShareDashboardById(deps, shareId);if (!(share && share.public)) {throw new TRPCNotFoundError('Dashboard share not found');@@ -453,12 +485,15 @@ export async function getShareDashboardReports(throw new TRPCAccessError('Password required');}- const { getReportsByDashboardId } = await loadReportsService();- return getReportsByDashboardId(share.dashboardId);+ return getReportsByDashboardId(deps, share.dashboardId);}-export async function getShareReport(shareId: string, cookies: CookieReader) {- const db = await loadDb();+export async function getShareReport(+ deps: ServiceDeps,+ shareId: string,+ cookies: CookieReader+) {+ const db = deps.db;const share = await db.shareReport.findUnique({where: { id: shareId },select: {@@ -481,7 +516,6 @@ export async function getShareReport(shareId: string, cookies: CookieReader) {return lockedShare(share.id, share.organization, share.project);}- const { transformReport } = await loadReportsService();return {id: share.id,requiresPassword: false as const,@@ -493,10 +527,11 @@ export async function getShareReport(shareId: string, cookies: CookieReader) {}export async function getShareReportSettings(+ deps: ServiceDeps,projectId: string,reportId: string) {- const db = await loadDb();+ const db = deps.db;const share = await db.shareReport.findUnique({where: { reportId },select: { id: true, public: true, password: true, projectId: true },@@ -511,22 +546,28 @@ export async function getShareReportSettings(/** The caller must already have write access to `input.projectId` — the RPC* layer's job (each transport still owns its own access-check plumbing). */-export async function createShareReport(input: {+export interface CreateShareReportInput {organizationId: string;projectId: string;reportId: string;public: boolean;password: string | null;-}) {- const { getReportById } = await loadReportsService();- const report = await getReportById(input.reportId);+}++export async function createShareReport(+ deps: ServiceDeps,+ input: CreateShareReportInput+) {+ const report = await getReportById(deps, input.reportId);if (!report || report.projectId !== input.projectId) {throw new TRPCNotFoundError('Report not found');}- const passwordHash = input.password ? await hashPassword(input.password) : null;+ const passwordHash = input.password+ ? await hashPassword(input.password)+ : null;- const db = await loadDb();+ const db = deps.db;const share = await db.shareReport.upsert({where: { reportId: input.reportId },create: {@@ -543,3 +584,113 @@ export async function createShareReport(input: {return { id: share.id, public: share.public, hasPassword: !!share.password };}++// --- service ------------------------------------------------------------++/** What the RPC layer passes to the two share validators. */+export interface ShareAccessContext {+ cookies: CookieReader;+ session?: { userId?: string | null };+}++export interface ShareService {+ getShareOverviewById(id: string): ReturnType<typeof getShareOverviewById>;+ getShareByProjectId(+ projectId: string+ ): ReturnType<typeof getShareByProjectId>;+ getShareDashboardById(id: string): ReturnType<typeof getShareDashboardById>;+ getShareDashboardByDashboardId(+ dashboardId: string+ ): ReturnType<typeof getShareDashboardByDashboardId>;+ getShareReportById(id: string): ReturnType<typeof getShareReportById>;+ getShareReportByReportId(+ reportId: string+ ): ReturnType<typeof getShareReportByReportId>;+ validateReportAccess(+ reportId: string,+ shareId: string,+ shareType: 'dashboard' | 'report'+ ): ReturnType<typeof validateReportAccess>;+ validateShareAccess(+ shareId: string,+ reportId: string,+ accessContext: ShareAccessContext+ ): Promise<{ projectId: string; isValid: boolean }>;+ validateOverviewShareAccess(+ shareId: string | undefined,+ projectId: string,+ accessContext: ShareAccessContext+ ): Promise<{ isValid: boolean }>;+ getShareOverview(+ shareId: string,+ cookies: CookieReader+ ): ReturnType<typeof getShareOverview>;+ getShareOverviewSettings(+ projectId: string+ ): ReturnType<typeof getShareOverviewSettings>;+ createShareOverview(+ input: CreateShareOverviewInput+ ): ReturnType<typeof createShareOverview>;+ getShareDashboard(+ shareId: string,+ cookies: CookieReader+ ): ReturnType<typeof getShareDashboard>;+ getShareDashboardSettings(+ projectId: string,+ dashboardId: string+ ): ReturnType<typeof getShareDashboardSettings>;+ createShareDashboard(+ input: CreateShareDashboardInput+ ): ReturnType<typeof createShareDashboard>;+ getShareDashboardReports(+ shareId: string,+ cookies: CookieReader+ ): ReturnType<typeof getShareDashboardReports>;+ getShareReport(+ shareId: string,+ cookies: CookieReader+ ): ReturnType<typeof getShareReport>;+ getShareReportSettings(+ projectId: string,+ reportId: string+ ): ReturnType<typeof getShareReportSettings>;+ createShareReport(+ input: CreateShareReportInput+ ): ReturnType<typeof createShareReport>;+}++export function createShareService(deps: ServiceDeps): ShareService {+ return {+ getShareOverviewById: (id) => getShareOverviewById(deps, id),+ getShareByProjectId: (projectId) => getShareByProjectId(deps, projectId),+ getShareDashboardById: (id) => getShareDashboardById(deps, id),+ getShareDashboardByDashboardId: (dashboardId) =>+ getShareDashboardByDashboardId(deps, dashboardId),+ getShareReportById: (id) => getShareReportById(deps, id),+ getShareReportByReportId: (reportId) =>+ getShareReportByReportId(deps, reportId),+ validateReportAccess: (reportId, shareId, shareType) =>+ validateReportAccess(deps, reportId, shareId, shareType),+ validateShareAccess: (shareId, reportId, accessContext) =>+ validateShareAccess(deps, shareId, reportId, accessContext),+ validateOverviewShareAccess: (shareId, projectId, accessContext) =>+ validateOverviewShareAccess(deps, shareId, projectId, accessContext),+ getShareOverview: (shareId, cookies) =>+ getShareOverview(deps, shareId, cookies),+ getShareOverviewSettings: (projectId) =>+ getShareOverviewSettings(deps, projectId),+ createShareOverview: (input) => createShareOverview(deps, input),+ getShareDashboard: (shareId, cookies) =>+ getShareDashboard(deps, shareId, cookies),+ getShareDashboardSettings: (projectId, dashboardId) =>+ getShareDashboardSettings(deps, projectId, dashboardId),+ createShareDashboard: (input) => createShareDashboard(deps, input),+ getShareDashboardReports: (shareId, cookies) =>+ getShareDashboardReports(deps, shareId, cookies),+ getShareReport: (shareId, cookies) =>+ getShareReport(deps, shareId, cookies),+ getShareReportSettings: (projectId, reportId) =>+ getShareReportSettings(deps, projectId, reportId),+ createShareReport: (input) => createShareReport(deps, input),+ };+}diff --git a/packages/core/src/services.ts b/packages/core/src/services.tsindex 4e9fcc43b..3aeabe04f 100644--- a/packages/core/src/services.ts+++ b/packages/core/src/services.ts@@ -15,10 +15,18 @@ import {type CohortService,createCohortService,} from './modules/cohort/cohort.service';+import {+ createDashboardService,+ type DashboardService,+} from './modules/dashboard/dashboard.service';import {createEventService,type EventService,} from './modules/event/event.service';+import {+ createExportService,+ type ExportService,+} from './modules/export/export.service';import {createGroupService,type GroupService,@@ -56,10 +64,22 @@ import {createProfileService,type ProfileService,} from './modules/profile/profile.service';+import {+ createReferenceService,+ type ReferenceService,+} from './modules/reference/reference.service';+import {+ createReportService,+ type ReportService,+} from './modules/report/report.service';import {createSessionService,type SessionService,} from './modules/session/session.service';+import {+ createShareService,+ type ShareService,+} from './modules/share/share.service';/** What every service factory receives — derived from Ctx, so it cannot drift. */export type ServiceDeps = Pick<@@ -92,6 +112,11 @@ export interface Services {group: GroupService;chart: ChartService;misc: MiscService;+ report: ReportService;+ dashboard: DashboardService;+ export: ExportService;+ share: ShareService;+ reference: ReferenceService;}export function createServices(deps: ServiceDeps): Services {@@ -114,5 +139,10 @@ export function createServices(deps: ServiceDeps): Services {group: createGroupService(deps),chart: createChartService(deps),misc: createMiscService(deps),+ report: createReportService(deps),+ dashboard: createDashboardService(deps),+ export: createExportService(deps),+ share: createShareService(deps),+ reference: createReferenceService(deps),};}diff --git a/packages/core/src/v1-compat.ts b/packages/core/src/v1-compat.tsnew file mode 100644index 000000000..824fe1572--- /dev/null+++ b/packages/core/src/v1-compat.ts@@ -0,0 +1,413 @@+// V1 COMPAT SEAM — one file, deleted whole when `packages/trpc` dies at P10.+//+// `apps/api/src/main.ts` still mounts `@openpanel/trpc`'s `appRouter`, not+// this package's `rpc.router.ts`, so V1's 28 routers are the live `/trpc`+// surface; the mcp and assistant tool runtimes call this package the same+// way. All of them reach a module through a BARE barrel export and have no+// `ServiceDeps` to hand it — `packages/trpc` is outside this wave's scope,+// so its call sites cannot change here.+//+// The alternative was to leave every module its own+// `import('@openpanel/db/...')` loader, which is exactly the drift+// docs/TECH_DEBT.md §4 exists to remove. Instead the boot scope registers+// the deps it has ALREADY built, once, here, and the barrel's V1 wrappers+// read them from this one place.+//+// Nothing that has a `Ctx` comes through here. HTTP routes, core's own+// procedures and job handlers all use `ctx.services.*`, built from the+// request-scoped ctx, so the requestId minted at the edge still reaches the+// query (ADR-018). What comes through this file gets the boot logger —+// exactly what those callers got before this wave, no worse.+//+// A process that never builds `AppDeps` — `packages/trpc`'s own vitest+// suites, which exercise a router directly — falls back to the singletons+// the deleted module-level `loadDb()` / `loadChClient()` loaders reached, so+// those callers behave exactly as they did before this wave. The fallback is+// LAZY: importing `@openpanel/core` still constructs no database, which is+// what keeps `bun test` runnable offline.++import {+ type SignInShareInput,+ signInToShare as signInToShareWithDeps,+} from './modules/auth/auth.service';+import { createServices, type ServiceDeps, type Services } from './services';+import type { ISetCookie } from './shared/cookie';++let registered: Services | undefined;+let registeredDeps: ServiceDeps | undefined;++/** Called once from `main.ts`, right after `AppDeps` is built. */+export function setV1CompatServices(deps: ServiceDeps): void {+ registeredDeps = deps;+ registered = createServices(deps);+}++/** Test-only: drop the registration so one suite cannot answer the next. */+export function resetV1CompatServicesForTests(): void {+ registered = undefined;+ registeredDeps = undefined;+ fallback = undefined;+}++/** What the boot scope stamps on jobs enqueued through this seam — there is+ * no request to correlate with, and saying so beats a random id. */+export const V1_COMPAT_REQUEST_ID = 'v1-compat';++function unbuilt(field: string): never {+ throw new Error(+ `ServiceDeps.${field} is only available once main.ts has called setV1CompatServices(deps)`+ );+}++let fallback: Promise<ServiceDeps> | undefined;++function fallbackServiceDeps(): Promise<ServiceDeps> {+ fallback ??= (async () => {+ // `createLogger` is packages/db's own pino factory — the one that already+ // writes `chQuery`'s `query info` line today — so a caller that reaches+ // this fallback logs exactly what it logged before M10-003.+ const [{ db }, { ch }, { getRedisCache }, { createLogger }] =+ await Promise.all([+ import('@openpanel/db/src/prisma-client'),+ import('@openpanel/db/src/clickhouse/client'),+ import('@openpanel/redis'),+ import('@openpanel/db/src/logger'),+ ]);+ return {+ db,+ ch,+ redis: getRedisCache(),+ logger: createLogger({ name: 'v1-compat' }),+ get clients(): never {+ return unbuilt('clients');+ },+ get buffers(): never {+ return unbuilt('buffers');+ },+ get queues(): never {+ return unbuilt('queues');+ },+ };+ })();+ return fallback;+}++function compatServiceDeps(): Promise<ServiceDeps> {+ return registeredDeps+ ? Promise.resolve(registeredDeps)+ : fallbackServiceDeps();+}++function services(): Promise<Services> {+ return registered+ ? Promise.resolve(registered)+ : fallbackServiceDeps().then(createServices);+}++// --- chart -----------------------------------------------------------------++export const getProjectCard: Services['chart']['getProjectCard'] = (...args) =>+ services().then((container) => container.chart.getProjectCard(...args));+export const listChartEvents: Services['chart']['listChartEvents'] = (+ ...args+) => services().then((container) => container.chart.listChartEvents(...args));+export const listChartProperties: Services['chart']['listChartProperties'] = (+ ...args+) =>+ services().then((container) => container.chart.listChartProperties(...args));+export const getChartPropertyValues: Services['chart']['getChartPropertyValues'] =+ (...args) =>+ services().then((container) =>+ container.chart.getChartPropertyValues(...args)+ );+export const getChartBucketProfiles: Services['chart']['bucketProfiles'] = (+ ...args+) => services().then((container) => container.chart.bucketProfiles(...args));+export const getFunnelStepProfiles: Services['chart']['funnelStepProfiles'] = (+ ...args+) =>+ services().then((container) => container.chart.funnelStepProfiles(...args));+export const executeChart: Services['chart']['execute'] = (...args) =>+ services().then((container) => container.chart.execute(...args));+export const executeAggregateChart: Services['chart']['executeAggregate'] = (+ ...args+) => services().then((container) => container.chart.executeAggregate(...args));+export const ChartEngine = { execute: executeChart };+export const AggregateChartEngine = { execute: executeAggregateChart };++// --- funnel / conversion / sankey / retention ------------------------------++export const getFunnelChart: Services['chart']['getFunnelChart'] = (...args) =>+ services().then((container) => container.chart.getFunnelChart(...args));+export const getFunnel: Services['chart']['getFunnel'] = (...args) =>+ services().then((container) => container.chart.getFunnel(...args));+export const getFunnelCore: Services['chart']['getFunnelCore'] = (...args) =>+ services().then((container) => container.chart.getFunnelCore(...args));+export const buildFunnelBase: Services['chart']['buildFunnelBase'] = (+ ...args+) => services().then((container) => container.chart.buildFunnelBase(...args));+export const getFunnelProfileIds: Services['chart']['getFunnelProfileIds'] = (+ ...args+) =>+ services().then((container) => container.chart.getFunnelProfileIds(...args));+export const getConversionChart: Services['chart']['getConversionChart'] = (+ ...args+) =>+ services().then((container) => container.chart.getConversionChart(...args));+export const getConversion: Services['chart']['getConversion'] = (...args) =>+ services().then((container) => container.chart.getConversion(...args));+export const getSankeyChart: Services['chart']['getSankeyChart'] = (...args) =>+ services().then((container) => container.chart.getSankeyChart(...args));+export const getSankey: Services['chart']['getSankey'] = (...args) =>+ services().then((container) => container.chart.getSankey(...args));+export const getUserFlowCore: Services['chart']['getUserFlowCore'] = (+ ...args+) => services().then((container) => container.chart.getUserFlowCore(...args));+export const getRetentionChart: Services['chart']['getRetentionChart'] = (+ ...args+) => services().then((container) => container.chart.getRetentionChart(...args));+export const getRetentionCohort: Services['chart']['getRetentionCohort'] = (+ ...args+) =>+ services().then((container) => container.chart.getRetentionCohort(...args));+export const getRetentionCohortCore: Services['chart']['getRetentionCohortCore'] =+ (...args) =>+ services().then((container) =>+ container.chart.getRetentionCohortCore(...args)+ );+export const getRetentionSeries: Services['chart']['getRetentionSeries'] = (+ ...args+) =>+ services().then((container) => container.chart.getRetentionSeries(...args));+export const getRetentionLastSeenSeries: Services['chart']['getRetentionLastSeenSeries'] =+ (...args) =>+ services().then((container) =>+ container.chart.getRetentionLastSeenSeries(...args)+ );+export const getRollingActiveUsers: Services['chart']['getRollingActiveUsers'] =+ (...args) =>+ services().then((container) =>+ container.chart.getRollingActiveUsers(...args)+ );+export const getRollingActiveUsersCore: Services['chart']['getRollingActiveUsersCore'] =+ (...args) =>+ services().then((container) =>+ container.chart.getRollingActiveUsersCore(...args)+ );+export const getWeeklyRetentionSeriesCore: Services['chart']['getWeeklyRetentionSeriesCore'] =+ (...args) =>+ services().then((container) =>+ container.chart.getWeeklyRetentionSeriesCore(...args)+ );+export const getEngagementCore: Services['chart']['getEngagementCore'] = (+ ...args+) => services().then((container) => container.chart.getEngagementCore(...args));++// --- report ----------------------------------------------------------------++export const getReportsByDashboardId: Services['report']['getReportsByDashboardId'] =+ (...args) =>+ services().then((container) =>+ container.report.getReportsByDashboardId(...args)+ );+export const getReportById: Services['report']['getReportById'] = (...args) =>+ services().then((container) => container.report.getReportById(...args));+export const getReportByIdOrThrow: Services['report']['getReportByIdOrThrow'] =+ (...args) =>+ services().then((container) =>+ container.report.getReportByIdOrThrow(...args)+ );+export const listReportsCore: Services['report']['listReportsCore'] = (+ ...args+) => services().then((container) => container.report.listReportsCore(...args));+export const getReportDataCore: Services['report']['getReportDataCore'] = (+ ...args+) =>+ services().then((container) => container.report.getReportDataCore(...args));+export const createReport: Services['report']['createReport'] = (...args) =>+ services().then((container) => container.report.createReport(...args));+export const updateReport: Services['report']['updateReport'] = (...args) =>+ services().then((container) => container.report.updateReport(...args));+export const moveReport: Services['report']['moveReport'] = (...args) =>+ services().then((container) => container.report.moveReport(...args));+export const deleteReport: Services['report']['deleteReport'] = (...args) =>+ services().then((container) => container.report.deleteReport(...args));+export const duplicateReport: Services['report']['duplicateReport'] = (+ ...args+) => services().then((container) => container.report.duplicateReport(...args));+export const updateReportLayout: Services['report']['updateReportLayout'] = (+ ...args+) =>+ services().then((container) => container.report.updateReportLayout(...args));+export const getReportLayouts: Services['report']['getReportLayouts'] = (+ ...args+) => services().then((container) => container.report.getReportLayouts(...args));+export const resetReportLayouts: Services['report']['resetReportLayouts'] = (+ ...args+) =>+ services().then((container) => container.report.resetReportLayouts(...args));++// --- dashboard -------------------------------------------------------------++export const getDashboardById: Services['dashboard']['getDashboardById'] = (+ ...args+) =>+ services().then((container) => container.dashboard.getDashboardById(...args));+export const getDashboardByIdOrThrow: Services['dashboard']['getDashboardByIdOrThrow'] =+ (...args) =>+ services().then((container) =>+ container.dashboard.getDashboardByIdOrThrow(...args)+ );+export const getDashboardsByProjectId: Services['dashboard']['getDashboardsByProjectId'] =+ (...args) =>+ services().then((container) =>+ container.dashboard.getDashboardsByProjectId(...args)+ );+export const listDashboardsCore: Services['dashboard']['listDashboardsCore'] = (+ ...args+) =>+ services().then((container) =>+ container.dashboard.listDashboardsCore(...args)+ );+export const createDashboard: Services['dashboard']['createDashboard'] = (+ ...args+) =>+ services().then((container) => container.dashboard.createDashboard(...args));+export const updateDashboard: Services['dashboard']['updateDashboard'] = (+ ...args+) =>+ services().then((container) => container.dashboard.updateDashboard(...args));+export const deleteDashboard: Services['dashboard']['deleteDashboard'] = (+ ...args+) =>+ services().then((container) => container.dashboard.deleteDashboard(...args));++// --- share -----------------------------------------------------------------++export const getShareOverviewById: Services['share']['getShareOverviewById'] = (+ ...args+) =>+ services().then((container) => container.share.getShareOverviewById(...args));+export const getShareByProjectId: Services['share']['getShareByProjectId'] = (+ ...args+) =>+ services().then((container) => container.share.getShareByProjectId(...args));+export const getShareDashboardById: Services['share']['getShareDashboardById'] =+ (...args) =>+ services().then((container) =>+ container.share.getShareDashboardById(...args)+ );+export const getShareDashboardByDashboardId: Services['share']['getShareDashboardByDashboardId'] =+ (...args) =>+ services().then((container) =>+ container.share.getShareDashboardByDashboardId(...args)+ );+export const getShareReportById: Services['share']['getShareReportById'] = (+ ...args+) =>+ services().then((container) => container.share.getShareReportById(...args));+export const getShareReportByReportId: Services['share']['getShareReportByReportId'] =+ (...args) =>+ services().then((container) =>+ container.share.getShareReportByReportId(...args)+ );+export const validateReportAccess: Services['share']['validateReportAccess'] = (+ ...args+) =>+ services().then((container) => container.share.validateReportAccess(...args));+export const validateShareAccess: Services['share']['validateShareAccess'] = (+ ...args+) =>+ services().then((container) => container.share.validateShareAccess(...args));+export const validateOverviewShareAccess: Services['share']['validateOverviewShareAccess'] =+ (...args) =>+ services().then((container) =>+ container.share.validateOverviewShareAccess(...args)+ );+export const getShareOverview: Services['share']['getShareOverview'] = (+ ...args+) => services().then((container) => container.share.getShareOverview(...args));+export const getShareOverviewSettings: Services['share']['getShareOverviewSettings'] =+ (...args) =>+ services().then((container) =>+ container.share.getShareOverviewSettings(...args)+ );+export const createShareOverview: Services['share']['createShareOverview'] = (+ ...args+) =>+ services().then((container) => container.share.createShareOverview(...args));+export const getShareDashboard: Services['share']['getShareDashboard'] = (+ ...args+) => services().then((container) => container.share.getShareDashboard(...args));+export const getShareDashboardSettings: Services['share']['getShareDashboardSettings'] =+ (...args) =>+ services().then((container) =>+ container.share.getShareDashboardSettings(...args)+ );+export const createShareDashboard: Services['share']['createShareDashboard'] = (+ ...args+) =>+ services().then((container) => container.share.createShareDashboard(...args));+export const getShareDashboardReports: Services['share']['getShareDashboardReports'] =+ (...args) =>+ services().then((container) =>+ container.share.getShareDashboardReports(...args)+ );+export const getShareReport: Services['share']['getShareReport'] = (...args) =>+ services().then((container) => container.share.getShareReport(...args));+export const getShareReportSettings: Services['share']['getShareReportSettings'] =+ (...args) =>+ services().then((container) =>+ container.share.getShareReportSettings(...args)+ );+export const createShareReport: Services['share']['createShareReport'] = (+ ...args+) => services().then((container) => container.share.createShareReport(...args));++// --- reference -------------------------------------------------------------++export const getReferenceById: Services['reference']['getReferenceById'] = (+ ...args+) =>+ services().then((container) => container.reference.getReferenceById(...args));+export const getReferenceByIdOrThrow: Services['reference']['getReferenceByIdOrThrow'] =+ (...args) =>+ services().then((container) =>+ container.reference.getReferenceByIdOrThrow(...args)+ );+export const listReferences: Services['reference']['listReferences'] = (+ ...args+) =>+ services().then((container) => container.reference.listReferences(...args));+export const createReference: Services['reference']['createReference'] = (+ ...args+) =>+ services().then((container) => container.reference.createReference(...args));+export const updateReference: Services['reference']['updateReference'] = (+ ...args+) =>+ services().then((container) => container.reference.updateReference(...args));+export const deleteReference: Services['reference']['deleteReference'] = (+ ...args+) =>+ services().then((container) => container.reference.deleteReference(...args));+export const getChartReferences: Services['reference']['getChartReferences'] = (+ ...args+) =>+ services().then((container) =>+ container.reference.getChartReferences(...args)+ );++// --- auth ------------------------------------------------------------------++// `signInToShare` lives in the auth module, but it reads the share module's+// three lookups, so it took `ServiceDeps` in M10-003 too. V1's auth router+// calls it with two arguments.+export function signInToShare(+ input: SignInShareInput,+ setCookie: ISetCookie+): Promise<true> {+ return compatServiceDeps().then((deps) =>+ signInToShareWithDeps(deps, input, setCookie)+ );+}diff --git a/packages/core/test/request-id-chart-query.test.ts b/packages/core/test/request-id-chart-query.test.tsnew file mode 100644index 000000000..1caf26008--- /dev/null+++ b/packages/core/test/request-id-chart-query.test.ts@@ -0,0 +1,149 @@+// ADR-018 R1, through the analytics read path (M10-003).+//+// The sibling `request-id-end-to-end.test.ts` proves the chain across the+// route, the enqueue and the job — with the whole `Services` container+// mocked. This file proves the hop that mock replaces: a REAL+// `createServices`, a real `ctx.services.chart`, and the ClickHouse call the+// chart query makes, observed on the request's own logger.+//+// It is the criterion the `loadChClient()` loaders failed silently: a+// module that reached `@openpanel/db`'s client itself got a connection with+// no request scope, so the requestId stopped at the service boundary.++import { beforeEach, expect, test } from 'bun:test';+import { Elysia } from 'elysia';+import type { AppDeps, Buffers } from '../src/context';+import { requestLogging } from '../src/http/context';+import { defineRoutes } from '../src/http/define';+import { createRecordingProducers } from '../src/jobs/testing';+import type { QueueProducerHandle } from '../src/jobs.registry';+import { type LogFn, type Logger, REQUEST_ID_HEADER } from '../src/logger';++const SUPPLIED_REQUEST_ID = 'm10-003-chart-query';+const PROJECT_ID = 'requestid-chart-project';++interface CapturedLine {+ message: unknown;+ bindings: Record<string, unknown>;+ payload: Record<string, unknown>;+}++function bindingLogger(+ lines: CapturedLine[],+ bindings: Record<string, unknown> = {}+): Logger {+ const write: LogFn = (first: unknown, second?: unknown) => {+ lines.push({+ message: typeof first === 'string' ? first : second,+ bindings,+ payload:+ typeof first === 'string' ? {} : (first as CapturedLine['payload']),+ });+ };+ return {+ fatal: write,+ error: write,+ warn: write,+ info: write,+ debug: write,+ trace: write,+ child: (extra) => bindingLogger(lines, { ...bindings, ...extra }),+ };+}++const queries: Array<{ query: string }> = [];++/** Just enough of the ClickHouse client for `runQuery`: one `query` that+ * answers with an empty JSONEachRow result. */+function recordingClickHouse(): AppDeps['ch'] {+ return {+ query: (params: { query: string }) => {+ queries.push({ query: params.query });+ return Promise.resolve({+ json: () => Promise.resolve({ data: [], rows: 0, meta: [] }),+ });+ },+ } as unknown as AppDeps['ch'];+}++function stubDeps() {+ const lines: CapturedLine[] = [];+ const producers = createRecordingProducers({});+ const deps: AppDeps = {+ db: {} as AppDeps['db'],+ ch: recordingClickHouse(),+ redis: {} as AppDeps['redis'],+ clients: {} as AppDeps['clients'],+ buffers: {} as Buffers,+ producers: producers as unknown as QueueProducerHandle,+ produceIncomingEvent: () => Promise.resolve(),+ logger: bindingLogger(lines),+ config: { selfHosted: false },+ };+ return { deps, lines };+}++// `getRetentionSeries` is the narrowest real chart query: one ClickHouse+// statement, no Postgres and no project-settings lookup, so what the test+// observes is the transport hop and nothing else.+function buildApp(deps: AppDeps) {+ const routes = defineRoutes((app) =>+ app.post('/proof/chart', async ({ ctx }) => ({+ rows: await ctx.services.chart.getRetentionSeries({+ projectId: PROJECT_ID,+ }),+ }))+ );+ return new Elysia().use(requestLogging(deps)).use(routes(deps));+}++beforeEach(() => {+ queries.length = 0;+});++test("a chart query made through a request-scoped ctx logs the request's own requestId", async () => {+ const { deps, lines } = stubDeps();+ const response = await buildApp(deps).handle(+ new Request('http://localhost/proof/chart', {+ method: 'POST',+ headers: { [REQUEST_ID_HEADER]: SUPPLIED_REQUEST_ID },+ })+ );+ // onAfterResponse writes `request done` after `handle` resolves.+ await new Promise((resolve) => setTimeout(resolve, 0));++ expect(response.status).toBe(200);++ // The query really ran through `deps.ch` — a silent miss would leave the+ // logger assertion below trivially true (AGENTS.md).+ expect(queries).toHaveLength(1);+ expect(queries[0]?.query).toContain('FROM events');++ const bindingOf = (message: string) =>+ lines.find((line) => line.message === message)?.bindings.requestId;++ // The ClickHouse call's own log line, and the route's, carry ONE requestId.+ expect(bindingOf('query info')).toBe(SUPPLIED_REQUEST_ID);+ expect(bindingOf('request done')).toBe(SUPPLIED_REQUEST_ID);+});++test('two concurrent requests do not share a requestId on their ClickHouse calls', async () => {+ const { deps, lines } = stubDeps();+ const app = buildApp(deps);++ const call = (requestId: string) =>+ app.handle(+ new Request('http://localhost/proof/chart', {+ method: 'POST',+ headers: { [REQUEST_ID_HEADER]: requestId },+ })+ );++ await Promise.all([call('req-a'), call('req-b')]);+ await new Promise((resolve) => setTimeout(resolve, 0));++ const queryLineIds = lines+ .filter((line) => line.message === 'query info')+ .map((line) => line.bindings.requestId);+ expect(queryLineIds.sort()).toEqual(['req-a', 'req-b']);+});diff --git a/packages/core/test/service-deps.ts b/packages/core/test/service-deps.tsnew file mode 100644index 000000000..660115cb7--- /dev/null+++ b/packages/core/test/service-deps.ts@@ -0,0 +1,66 @@+// A real `ServiceDeps` for integration tests: the same singletons `main.ts`+// hands to `AppDeps`, pointed at the isolated `openpanel_test` databases by+// preload.ts. `clients`, `buffers` and `queues` are unused by the read-path+// services these tests exercise, so they stay unbuilt and a test that reaches+// one gets a named error rather than silently working against a half-built+// container.++import type { Logger } from '../src/logger';+import type { ServiceDeps } from '../src/services';++/** Records what the ClickHouse/Postgres call was logged with — the requestId+ * chain's observation point. */+export function recordingLogger(+ bindings: Record<string, unknown> = {},+ lines: Array<{ bindings: Record<string, unknown>; message: string }> = []+): Logger & { lines: typeof lines; bindings: Record<string, unknown> } {+ const noop = () => undefined;+ const logger = {+ bindings,+ lines,+ fatal: noop,+ error: noop,+ warn: noop,+ info: (_obj: unknown, message?: string) => {+ lines.push({ bindings, message: message ?? '' });+ },+ debug: noop,+ trace: noop,+ child: (extra: Record<string, unknown>) =>+ recordingLogger({ ...bindings, ...extra }, lines),+ };+ return logger as unknown as Logger & {+ lines: typeof lines;+ bindings: Record<string, unknown>;+ };+}++function unavailable(name: string): never {+ throw new Error(`ServiceDeps.${name} is not built in this test`);+}++export async function testServiceDeps(+ overrides: Partial<ServiceDeps> = {}+): Promise<ServiceDeps> {+ const [{ db }, { ch }, redis] = await Promise.all([+ import('@openpanel/db/src/prisma-client'),+ import('@openpanel/db/src/clickhouse/client'),+ import('@openpanel/redis').then((m) => m.getRedisCache()),+ ]);+ return {+ db,+ ch,+ redis,+ logger: recordingLogger(),+ get clients(): never {+ return unavailable('clients');+ },+ get buffers(): never {+ return unavailable('buffers');+ },+ get queues(): never {+ return unavailable('queues');+ },+ ...overrides,+ };+}