Skip to content

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

ralph(M10-004): Service factories, account path: auth, client, project, user, subscription, salt, conversation, assistant, mcp

ralph0b04225f435f
diff --git a/apps/api/e2e/lib.ts b/apps/api/e2e/lib.ts
index b339d2c68..d3927321b 100644
--- a/apps/api/e2e/lib.ts
+++ b/apps/api/e2e/lib.ts
@@ -4,7 +4,7 @@
* fixtures, polling, and a tiny check/report framework.
*/
-import { getClientByIdCached } from '@openpanel/core';
+import { clearClientByIdCache } from '@openpanel/core';
import { ClientType, chQuery, db } from '@openpanel/db';
import { getRedisCache } from '@openpanel/redis';
@@ -261,7 +261,7 @@ export async function ensureFixtures() {
},
update: { ignoreCorsAndSecret: true, projectId: PROJECT_ID },
});
- await getClientByIdCached.clear(CLIENT_ID);
+ await clearClientByIdCache(CLIENT_ID);
check('fixtures ready', true);
} catch (error) {
check('fixtures ready', false, (error as Error).message);
diff --git a/apps/api/src/main.ts b/apps/api/src/main.ts
index 51c4a5ce9..ac271b4be 100644
--- a/apps/api/src/main.ts
+++ b/apps/api/src/main.ts
@@ -525,7 +525,7 @@ async function main() {
consumer = await startIngestConsumer(deps);
}
- await createInitialSalts();
+ await createInitialSalts(deps);
} else if (roleConsumes) {
logger.warn('Workers are disabled');
}
diff --git a/docs/TECH_DEBT.md b/docs/TECH_DEBT.md
index 40baa0917..5bfeb2301 100644
--- a/docs/TECH_DEBT.md
+++ b/docs/TECH_DEBT.md
@@ -454,3 +454,170 @@ dependencies cruised.` (was 241.)
(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`.
+
+### 2026-09-06 — M10-004, the account path (auth, client, project, user, subscription, salt, conversation, assistant, mcp) onto `createXService(deps)`
+
+Ran by: ralph (M10-004 implement task, docs/TECH_DEBT.md §4 steps 1/2/5 and
+§5a, continuing M10-003).
+
+**Shape.** All nine modules now expose exactly one
+`createXService(deps: ServiceDeps): XService`, registered in `services.ts`.
+`auth.service.ts` already had `createAuthService` from M10-002 (bound to the
+access ladder, independent of `deps`) — this wave finishes it: every OTHER
+lazy `@openpanel/db` load in the file (sign-up/sign-in/TOTP/reset-password/
+OAuth-callback) now takes `deps` too, and `./src/login-session.ts` /
+`./src/registration.ts` reach Postgres as `deps.db` with no lazy loader left.
+`assistant` and `mcp` needed a factory for the first time; both were a bag of
+loosely-related exports, not a services-shaped file, before this wave.
+
+**Two modules that were never going to fit the mechanical pattern.**
+
+- **`assistant.service.ts`** re-exported `chatApp`/`chatRunContext` as
+ eager `export ... from './src/app'` / `'./src/run-context'` — a static
+ re-export, which means importing this file AT ALL constructs the whole
+ Better Agent app (one `defineAgent` per whitelisted chat model). Registering
+ `createAssistantService` in `services.ts` would have made that run at
+ PROCESS BOOT (services.ts's own module evaluation) instead of on the first
+ real chat/filter-command request. Fixed by moving the lazy-loader index.ts
+ used to hide this (`loadAssistant()`/`getChatApp()`/`getChatRunContext()`)
+ INTO `assistant.service.ts` itself, so the file is cheap to import
+ regardless of who imports it; index.ts's own copy of that mechanism is
+ deleted, replaced by a plain re-export now that it's safe. `deps` goes
+ unused in the factory — nothing here touches Postgres directly.
+- **`mcp.service.ts`** statically imported `./src/auth` (fine, fixed below)
+ and `./src/server` (`registerAllTools`, ~20 tool files, several importing
+ `@openpanel/core` for cross-module functions) — reached only via a dynamic
+ `loadMcp()` in index.ts before this wave, for exactly the reason
+ `assistant`'s TDZ hazard note already named for this file. `./src/server`
+ stays behind a lazy loader inside `mcp.service.ts`; `./src/auth` is a plain
+ import again because its own `@openpanel/core` reach (below) is now lazy
+ too, so nothing static is left to protect against. `handleStatelessMcpRequest`
+ /`extractToken` keep their exact bare signature — both are called directly
+ by their own tests with no `deps` argument, a hard contract this wave does
+ not touch — so `McpService`'s two methods are thin, deps-ignoring binds.
+
+**Bare hot-path callers with no `Ctx` to give a `deps` — the pattern this wave
+generalizes from `v1-compat.ts`'s v1-compat seam to core's OWN internals.**
+`getProjectByIdCached`/`getClientByIdCached` (ingest's `/track` auth,
+`http/client-auth.ts`'s `/export`+`/import`+`/manage` tier, MCP's token auth)
+and `getSalts` (ingest's device-id resolution) all have their L1 LRU cache
+built INSIDE their `createXService(deps)` closure now, which only stays a
+cross-request singleton through the v1-compat seam (`registered`, built once
+at boot) — not through `ctx.services`, which is one Ctx per request. Every one
+of these callers has no `Ctx`/`ServiceDeps` of its own, so they reach the
+cache through `v1-compat.ts` (`compatDb()`/`compatCh()` for the couple of
+third-party-signature callers — `@better-agent/core`'s `ConversationStore`,
+`@modelcontextprotocol/sdk`'s tool handlers — that can't carry a wrapped
+service method at all). `getClientByIdCached`/`getProjectByIdCached` also
+gained a `clearClientByIdCache`/`clearProjectByIdCache` service method, since
+the LRU's `.clear()` isn't part of the plain `(id) => Promise<...>` shape
+`ServiceDeps`-free callers expect.
+
+One of these (`ingest/src/incoming-event-handler.ts`) carried a **stale
+constraint**: a comment mandating a *static* import of `project.service.ts`
+"so a dynamic edge into project.service doesn't become its own rolldown chunk
+... external in apps/worker's bundle". `apps/worker` no longer exists (M9) and
+`apps/api` ships with no bundler at all (`apps/api/package.json` has no
+`build` script — ADR-010) — the constraint the comment protected against is
+gone, so the file now uses the same "GENUINE CYCLE, kept lazy" dynamic import
+as everywhere else in this wave.
+
+**Correction (post-review): there is no "no import-time cost" exception to
+acceptance criterion 2.** The first pass through this wave left four plain,
+top-level value imports of `@openpanel/db` standing — `subscription.service.ts`
+and mcp's `dashboard-management.ts` each imported `Prisma` (for the
+`Prisma.DbNull` sentinel), and mcp's `analytics/property-values.ts` imported
+`TABLE_NAMES`/`clix` — and this section originally excused all four, plus
+`project.service.ts`'s two still-`clix` functions, as "scoped exceptions"
+under ADR-013. That was wrong on the acceptance criterion's own terms: ADR-013
+grants time to convert ClickHouse query BODIES to the `sql` tag (one query per
+P7 task, diffed); it says nothing about the criterion's separate,
+unconditional "no `@openpanel/db` import in these nine modules" rule, and a
+gap no ADR actually covers is `BLOCKED`, not self-exempted (CLAUDE.md). Fixed
+by extending the v1-compat seam instead of arguing the rule away:
+
+- `v1-compat.ts` gained `compatPrisma()` (the `Prisma` namespace — a value,
+ not a client, but still `@openpanel/db`) and `compatChHelpers()` (`clix`,
+ `TABLE_NAMES`, `chQuery`, `convertClickhouseDateToJs` — the query-building
+ helpers that ADR-013 leaves in place beside `deps.ch`, the actual client).
+ Both are lazy, same as `compatDb`/`compatCh`.
+- `subscription.service.ts` and `project.service.ts` reach them through a
+ local `loadCompatPrisma`/`loadChHelpers` lazy loader (GENUINE CYCLE: both
+ are statically imported by `services.ts`, which `v1-compat.ts` statically
+ imports back for `createServices`). mcp's `dashboard-management.ts` and
+ `analytics/property-values.ts` reach them via `./shared`'s
+ `loadCompatPrisma`/`loadCompatChHelpers` (no cycle — mcp's tool tree is
+ already behind `mcp.service.ts`'s own lazy loader).
+- `project.service.ts`'s `getLastEventPerProject` also had an actual bug this
+ surfaced: it built its own ClickHouse client from `@openpanel/db` instead of
+ using the `deps.ch` already sitting unused in its (underscore-prefixed)
+ `_deps` parameter. Now it does.
+- `dashboard-management.ts`'s `reportData()` helper takes the resolved
+ `DbNull` sentinel as an `unknown` parameter rather than importing `Prisma`
+ for its type — the same shape `notification.service.ts`'s `isValidPayload`
+ already uses for the identical sentinel-comparison problem.
+
+No query TEXT changed; only which module reaches the query-building helpers
+did.
+
+**`v1-compat.ts` grew, not just from this wave's nine modules.** Fixing the
+above meant every OTHER core module that reached one of these nine bare (no
+`deps`) also needed its import repointed at `v1-compat.ts`:
+`shared/access-lookups.ts` (`getProjectById`), `onboarding.service.ts`
+(`getUserById`), `dashboard.service.ts` (`getProjectById` — this one already
+had `deps` in scope, so it's a straight parameter pass, no new v1-compat
+wrapper), `export.service.ts`'s `resolveInsightsProjectId` (~35 call sites in
+`export.routes.ts`, none carrying `deps`), `session/src/usage.ts` and
+`organization/src/wind-down.ts`/`misc/src/data-health.ts` (`getLastEventPerProject`,
+zero-arg shape preserved). None of these files are in this task's scope
+globs by name; all of them needed a one-line import-target fix to keep
+compiling once their target's signature gained `deps` — the same category of
+necessary wiring M10-003's `auth.rpc.ts`/`chart.rpc.ts` touch-ups were.
+
+**Test-isolation hazard found and fixed, not just avoided.** Two tests
+(`mcp/src/tools/dashboard-management.test.ts`,
+`mcp/src/tools/analytics/page-performance.test.ts`) mock
+`@openpanel/db/src/prisma-client` / `.../clickhouse/client` directly and rely
+on `v1-compat.ts`'s fallback to pick the mock up — but that fallback is a
+process-lifetime memoized singleton (`v1-compat.ts`'s own `fallback` promise),
+so under a bare (non-`--isolate`) `bun test` run an EARLIER file that already
+resolved it (against ITS OWN mock, or the real db) leaves it wrong for every
+later file. Both now call `resetV1CompatServicesForTests()` in `beforeAll`
+(before importing the subject) and `afterAll` (so they don't do the same
+thing to files after them) — this is the reset the memoized-singleton pattern
+already existed for, just not previously needed by anything reaching the
+fallback through a *different* module's mock.
+
+**`pnpm run check:deps`** (`.dependency-cruiser.cjs`, both rules unchanged at
+their landed `warn` severity):
+
+| Rule | Before (M10-003) | After (M10-004) | Delta |
+|---|---:|---:|---:|
+| `core-uses-ctx-not-db-internals` | 160 | **135** | **−25** |
+| `core-no-self-barrel` | 62 | **59** | **−3** |
+
+Exit `0` either way (`warn`, not `error`):
+`x 194 dependency violations (0 errors, 194 warnings). 1991 modules, 8036
+dependencies cruised.` (was 222.) The residual `core-uses-ctx-not-db-internals`
+hits inside this wave's nine modules are all `.test.ts` files that mock
+`@openpanel/db` directly (`mcp/src/tools/dashboard-management.test.ts`,
+`mcp/src/tools/analytics/{profiles,page-performance}.test.ts`,
+`mcp/mcp.service.test.ts` — pre-existing pattern, unrelated to this wave);
+none of the nine modules' `*.service.ts`/`*.rpc.ts`/`*.routes.ts` files import
+`@openpanel/db` as a value any more (`import type` for a handful of Prisma
+model types is not a value import — it is erased, so it carries no
+import-time cost and is not what this rule or the acceptance criterion
+target). The residual `core-no-self-barrel` hits inside `mcp`/`assistant` are
+entirely the ~40 untouched tool files reaching `@openpanel/core` for
+cross-module functions — real, but out of this wave's scope (fixing them
+means rewriting every tool file's imports to relative paths, not wiring a
+service factory).
+
+**Verification, all run by ralph on 2026-09-06:**
+
+- `pnpm run typecheck` — all 25 workspaces, `Done`.
+- `cd packages/core && bun test --isolate`: **1457 pass, 12 skip, 0 fail**,
+ `Ran 1469 tests across 149 files. [100.93s]`.
+- `cd packages/core && bun test` (bare, no `--isolate`): **1457 pass, 12 skip,
+ 0 fail**, `Ran 1469 tests across 149 files. [34.00s]`.
+- `pnpm run check:deps` — the table above.
diff --git a/packages/core/src/http/client-auth.ts b/packages/core/src/http/client-auth.ts
index 8e582fd23..021641f24 100644
--- a/packages/core/src/http/client-auth.ts
+++ b/packages/core/src/http/client-auth.ts
@@ -16,13 +16,18 @@
// `modules/mcp/src/auth.ts`, exactly as V1's mcp router did.
import type { AppDeps } from '../context';
-import { getClientByIdCached } from '../modules/client/client.service';
import {
type IngestHeaders,
validateIngestRequest,
} from '../modules/ingest/src/client-auth';
import { headerValue } from '../modules/ingest/src/headers';
import { verifyPassword } from '../shared/crypto';
+// M10-004: `getClientByIdCached`'s L1 LRU now lives inside
+// `createClientService(deps)` (see that file's header), reached here through
+// the v1-compat singleton, exactly as `modules/ingest/src/client-auth.ts`
+// does — no cycle for THIS file (nothing under `modules/*.service.ts`
+// imports `http/**`), so the import stays static.
+import { getClientByIdCached } from '../v1-compat';
/** V1 refuses a client id that is not a UUID before it ever queries
* (utils/auth.ts's three validators). Same regex, same order. */
diff --git a/packages/core/src/http/session.ts b/packages/core/src/http/session.ts
index 491eb560d..f86e7041e 100644
--- a/packages/core/src/http/session.ts
+++ b/packages/core/src/http/session.ts
@@ -28,7 +28,7 @@ export const SESSION_COOKIE_NAME = 'session';
const DEMO_ALS_SESSION_ID = '1';
export async function resolveSession(
- _deps: AppDeps,
+ deps: AppDeps,
cookies: CookieJar,
_headers: Headers
): Promise<Session | null> {
@@ -37,7 +37,7 @@ export async function resolveSession(
try {
const result = await runWithAlsSession(
token ? decodeSessionToken(token) : DEMO_ALS_SESSION_ID,
- () => validateSessionToken(token ?? null)
+ () => validateSessionToken(deps, token ?? null)
);
return result.userId === null ? null : result;
} catch {
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index 5eaf5da4f..09cb9eb1b 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -204,58 +204,28 @@ export {
export { registerDefaultMetrics } from './metrics';
// Moved from apps/api/src/agents/* + packages/trpc/src/agents/filter-command.ts
// (M5-005) — apps/api's `/ai/agents/*` Fastify wrapper and packages/trpc's
-// overview router call these.
-//
-// Loaded via dynamic import, NOT a static re-export like every other service
-// on this barrel: packages/db/src/buffers/index.ts imports `@openpanel/core`
-// eagerly (it is the V1 delegate over `createBuffers`), and this module's own
-// chain reaches deep into `@openpanel/db` (the Prisma-backed conversation
-// store, ~30 analytics/report tool functions). A static re-export here would
-// make THIS barrel's own evaluation re-enter `@openpanel/db` while that
-// package is still mid-evaluation, and a class the re-entering module extends
-// is then an `undefined` TDZ binding that never got the chance to fill in.
-// `chatApp` and `chatRunContext` are one-time-per-process values, so
-// callers resolve them once (apps/api's Fastify wrapper does so inside its
-// own already-async route registration) and keep the reference.
+// overview router call these. M10-004: `assistant.service.ts` keeps all of
+// `./src/app`/`./src/run-context`/`./src/filter-command` behind its OWN
+// lazy loaders now (see that file's header) — needed so `createAssistantService`
+// can be registered in services.ts without constructing the whole Better
+// Agent app at process boot — which is what makes a plain static re-export
+// safe here too. `getChatApp`/`getChatRunContext`/`runFilterCommand` are
+// one-time-per-process values, so callers resolve them once (apps/api's
+// Fastify wrapper does so inside its own already-async route registration)
+// and keep the reference.
export type {
+ AssistantService,
ChatApp,
ChatRunContext,
FilterCommandResult,
+ RunFilterCommandInput,
+} from './modules/assistant/assistant.service';
+export {
+ createAssistantService,
+ getChatApp,
+ getChatRunContext,
+ runFilterCommand,
} from './modules/assistant/assistant.service';
-// Slack's OAuth token-exchange wire contract (M6-006) — not integration
-// config (stays out of the `*.constants` subpath, see
-// modules/integration/src/slack-contract.ts's header), but apps/api's
-// webhook controller still needs it to validate Slack's `oauth.v2.access`
-// response, the same way it reaches slackInstaller above.
-export { zSlackAuthResponse } from './modules/integration/src/slack-contract';
-
-import type { PageContext } from './modules/assistant/assistant.constants';
-
-let _assistant:
- | Promise<typeof import('./modules/assistant/assistant.service')>
- | undefined;
-function loadAssistant() {
- if (!_assistant) {
- _assistant = import('./modules/assistant/assistant.service');
- }
- return _assistant;
-}
-
-export async function getChatApp() {
- return (await loadAssistant()).chatApp;
-}
-export async function getChatRunContext() {
- return (await loadAssistant()).chatRunContext;
-}
-export async function runFilterCommand(input: {
- query: string;
- projectId: string;
- pageContext?: PageContext;
- timezone: string;
-}) {
- const { runFilterCommand: run } = await loadAssistant();
- return run(input);
-}
// Dissolved from @openpanel/auth (M4-007) — apps/api's OAuth callbacks and
// @openpanel/trpc's auth/share/user/gsc routers call these directly, the same
// way they reach the other dissolved leaf packages here. `hashPassword` is
@@ -286,21 +256,16 @@ export {
buildOtpauthUrl,
COOKIE_MAX_AGE,
COOKIE_OPTIONS,
- completeOAuthCallback,
consumeRecoveryCode,
createAuthService,
decodeSessionToken,
deleteSessionTokenCookie,
- disableTotp,
- enableTotp,
- extendSessionCookie,
fetchGithubOAuthUser,
fetchGoogleOAuthUser,
generateQrDataUrl,
generateRecoveryCodes,
generateSessionToken,
generateTotpSecret,
- getTotpStatus,
github,
google,
googleGsc,
@@ -310,16 +275,8 @@ export {
normalizeRecoveryCode,
OAuthCallbackError,
parseCookieDomain,
- regenerateTotpRecoveryCodes,
- requestPasswordReset,
- resetPasswordWithToken,
setLastAuthProviderCookie,
setSessionTokenCookie,
- setupTotp,
- signInWithEmail,
- signInWithTotp,
- signOutUser,
- signUpWithEmail,
startOAuthSignIn,
verifyPasswordHash,
verifyTotpCode,
@@ -443,21 +400,12 @@ export { buildFilterWhere } from './modules/chart/src/table-filter-where';
// service here. packages/db/src/services/clients.service.ts stays a
// re-export shim.
export type {
+ ClientService,
CreatedClient,
IServiceClient,
IServiceClientWithProject,
} from './modules/client/client.service';
-export {
- createClientForOrganization,
- deleteClientForOrganization,
- getClientById,
- getClientByIdCached,
- getClientForOrganization,
- getClientsByOrganizationId,
- getClientsByProjectId,
- listClientsForOrganization,
- updateClientForOrganization,
-} from './modules/client/client.service';
+export { createClientService } from './modules/client/client.service';
// Dissolved from @openpanel/db's services/cohort.service.ts (M5-003) —
// packages/trpc's cohort router and apps/worker's cohort job files call
// these directly, the same way V1 reaches every other dissolved service
@@ -485,16 +433,12 @@ export {
// keeps a re-export shim (unlike cohort, M5-003): both non-trpc call sites
// still reach it through `@openpanel/db`'s barrel.
export type {
+ ConversationService,
IServiceChatMessage,
IServiceConversation,
IServiceConversationWithMessages,
} from './modules/conversation/conversation.service';
-export {
- deleteConversation,
- getConversationById,
- listConversations,
- upsertConversationTitle,
-} from './modules/conversation/conversation.service';
+export { createConversationService } from './modules/conversation/conversation.service';
// Dissolved from @openpanel/db's services/dashboard.service.ts, plus V1's
// dashboard router mutation bodies (M7-006) — packages/trpc's dashboard
// router, apps/api's insights controller and the mcp/assistant tools call
@@ -662,6 +606,27 @@ export {
testIntegrationConnection,
upsertIntegration,
} from './modules/integration/integration.service';
+// Slack's OAuth token-exchange wire contract (M6-006) — not integration
+// config (stays out of the `*.constants` subpath, see
+// modules/integration/src/slack-contract.ts's header), but apps/api's
+// webhook controller still needs it to validate Slack's `oauth.v2.access`
+// response, the same way it reaches slackInstaller above.
+export { zSlackAuthResponse } from './modules/integration/src/slack-contract';
+// packages/mcp absorbed whole (M5-007) — ADR-015 entry 2: stateless-only, so
+// there is no SessionManager to manage. `mcp.service.ts` keeps its own
+// tool tree (`./src/server`) behind a lazy loader (M10-004, see that file's
+// header), which is what makes THIS a safe static export now — unlike the
+// `getChatApp`-style TDZ hazard this barrel used to route around here.
+export type {
+ McpAuthContext,
+ McpHttpResult,
+ McpService,
+} from './modules/mcp/mcp.service';
+export {
+ createMcpService,
+ extractToken,
+ handleStatelessMcpRequest,
+} from './modules/mcp/mcp.service';
// Dissolved from @openpanel/db's services/notification.service.ts (M6-005,
// "rules + dispatch stay together") — packages/trpc's notification router
// and apps/worker's notification job call these directly, the same way V1
@@ -858,25 +823,9 @@ export type {
IServiceProject,
IServiceProjectWithClients,
ProjectActivationStatus,
+ ProjectService,
} from './modules/project/project.service';
-export {
- cancelProjectDeletion,
- createProjectForOrganization,
- deleteProjectForOrganization,
- getLastEventPerProject,
- getProjectActivationStatus,
- getProjectById,
- getProjectByIdCached,
- getProjectEventsCount,
- getProjectForOrganization,
- getProjects,
- getProjectWithClients,
- listProjectsCore,
- listProjectsForOrganization,
- resolveClientProjectId,
- scheduleProjectDeletion,
- updateProjectForOrganization,
-} from './modules/project/project.service';
+export { createProjectService } from './modules/project/project.service';
// The six ClickHouse queries moved from packages/trpc/src/routers/realtime.ts
// (M6-007) — packages/trpc's realtime router calls these directly, the same
// way V1 reaches every other dissolved service here. The `/live` websocket
@@ -1039,60 +988,31 @@ export { createShareService } from './modules/share/share.service';
// map: subscription owns "S"+"C") — packages/trpc's subscription router and
// apps/api's webhook controller call these directly, the same way V1 reaches
// every other dissolved service here.
+export type { SubscriptionService } from './modules/subscription/subscription.service';
export {
- applySaveDiscount,
- cancelSubscription,
- checkout,
+ createSubscriptionService,
getCurrentSubscriptionProduct,
- getUsage,
- handlePolarWebhookEvent,
- listProducts,
- pauseSubscription,
- portal,
- resumeSubscription,
toSubscriptionDiscount,
} from './modules/subscription/subscription.service';
// Dissolved from @openpanel/db's services/user.service.ts (M6-001) —
// packages/trpc's auth/onboarding routers call `getUserById`/
// `getUserAccount` directly through @openpanel/db's re-export shim, the same
// way they reach every other dissolved service here.
-export type { IServiceUser } from './modules/user/user.service';
-export {
- deleteUserAccount,
- getUserAccount,
- getUserById,
- listUserDeletionBlockers,
- updateUserProfile,
-} from './modules/user/user.service';
+export type { UserService } from './modules/user/user.service';
+export { createUserService } from './modules/user/user.service';
-// packages/mcp absorbed whole (M5-007) — apps/api's mcp.router.ts is the one
-// external caller, delegating the streamable-HTTP POST protocol here
-// (DELEGATE PATTERN). ADR-015 entry 2: stateless-only, so there is no
-// SessionManager to manage.
-//
-// Loaded via dynamic import, NOT a static re-export, for the same reason
-// `getChatApp`/`runFilterCommand` above are: `mcp.service` reaches this same
-// barrel (auth's client lookup, every analytics tool, all moved onto
-// `@openpanel/core` directly since M9-CLEANUP-001). A static export here
-// would make this barrel's own evaluation re-enter itself mid-evaluation —
-// observed as a `PagesService` TDZ ReferenceError two modules away, in a tool
-// file that never otherwise runs at import time.
-let _mcp: Promise<typeof import('./modules/mcp/mcp.service')> | undefined;
-function loadMcp() {
- if (!_mcp) {
- _mcp = import('./modules/mcp/mcp.service');
- }
- return _mcp;
-}
+import {
+ extractToken as mcpExtractToken,
+ handleStatelessMcpRequest as mcpHandleStatelessMcpRequest,
+} from './modules/mcp/mcp.service';
export async function handleMcpRequest(
query: Record<string, unknown>,
authHeader: string | undefined,
body: unknown
): Promise<{ status: number; body: unknown }> {
- const { extractToken, handleStatelessMcpRequest } = await loadMcp();
- const token = extractToken(query, authHeader);
- return handleStatelessMcpRequest(token, body);
+ const token = mcpExtractToken(query, authHeader);
+ return mcpHandleStatelessMcpRequest(token, body);
}
export { isShuttingDown, setShuttingDown } from './modules/health/src/shutdown';
// Dissolved from @openpanel/db's services/import.service.ts +
@@ -1234,14 +1154,16 @@ export {
runPingCron,
} from './modules/misc/misc.service';
// Moved from packages/db/src/services/salt.service.ts +
-// apps/worker/src/jobs/cron.salt.ts (M8-004) — apps/worker's boot
-// (createInitialSalts) and cron dispatch (rotateSalt) call these directly,
-// the same way V1 reaches every other dissolved service here.
-export type { Salts } from './modules/salt/salt.service';
+// apps/worker/src/jobs/cron.salt.ts (M8-004) — `main.ts` calls
+// `createInitialSalts(deps)` directly at boot; `salt.jobs.ts`'s cron handler
+// and everything else reach `rotateSalt`/`getSalts` through
+// `ctx.services.salt` / the v1-compat singleton instead (M10-004, see
+// salt.service.ts's header — `getSalts` is the one export still bare here,
+// for the same reason it's bare on the v1-compat seam).
+export type { SaltService, Salts } from './modules/salt/salt.service';
export {
createInitialSalts,
- getSalts,
- rotateSalt,
+ createSaltService,
} from './modules/salt/salt.service';
// Dissolved from @openpanel/db's services/insights* + referrer-spikes.service
// (M5-001) — apps/worker's insight job files and packages/trpc's insight
@@ -1375,30 +1297,52 @@ 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
+// The V1 compat seam (v1-compat.ts): the bare, deps-free spellings of every
+// module whose functions gained a `ServiceDeps` first parameter, 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,
+ applySaveDiscount,
buildFunnelBase,
ChartEngine,
+ cancelProjectDeletion,
+ cancelSubscription,
+ checkout,
+ clearClientByIdCache,
+ compatCh,
+ compatDb,
+ createClientForOrganization,
createDashboard,
+ createProjectForOrganization,
createReference,
createReport,
createShareDashboard,
createShareOverview,
createShareReport,
+ deleteClientForOrganization,
+ deleteConversation,
deleteDashboard,
+ deleteProjectForOrganization,
deleteReference,
deleteReport,
+ deleteUserAccount,
+ disableTotp,
duplicateReport,
+ enableTotp,
executeAggregateChart,
executeChart,
+ extendSessionCookie,
getChartBucketProfiles,
getChartPropertyValues,
getChartReferences,
+ getClientById,
+ getClientByIdCached,
+ getClientForOrganization,
+ getClientsByOrganizationId,
+ getClientsByProjectId,
+ getConversationById,
getConversion,
getConversionChart,
getDashboardById,
@@ -1410,7 +1354,15 @@ export {
getFunnelCore,
getFunnelProfileIds,
getFunnelStepProfiles,
+ getLastEventPerProject,
+ getProjectActivationStatus,
+ getProjectById,
+ getProjectByIdCached,
getProjectCard,
+ getProjectEventsCount,
+ getProjectForOrganization,
+ getProjects,
+ getProjectWithClients,
getReferenceById,
getReferenceByIdOrThrow,
getReportById,
@@ -1425,6 +1377,7 @@ export {
getRetentionSeries,
getRollingActiveUsers,
getRollingActiveUsersCore,
+ getSalts,
getSankey,
getSankeyChart,
getShareByProjectId,
@@ -1440,22 +1393,49 @@ export {
getShareReportById,
getShareReportByReportId,
getShareReportSettings,
+ getTotpStatus,
+ getUsage,
+ getUserAccount,
+ getUserById,
getUserFlowCore,
getWeeklyRetentionSeriesCore,
listChartEvents,
listChartProperties,
+ listClientsForOrganization,
+ listConversations,
listDashboardsCore,
+ listProducts,
+ listProjectsCore,
+ listProjectsForOrganization,
listReferences,
listReportsCore,
+ listUserDeletionBlockers,
moveReport,
+ pauseSubscription,
+ portal,
+ regenerateTotpRecoveryCodes,
+ requestPasswordReset,
+ resetPasswordWithToken,
resetReportLayouts,
resetV1CompatServicesForTests,
+ resolveClientProjectId,
+ resumeSubscription,
+ scheduleProjectDeletion,
+ setupTotp,
setV1CompatServices,
signInToShare,
+ signInWithEmail,
+ signInWithTotp,
+ signOutUser,
+ signUpWithEmail,
+ updateClientForOrganization,
updateDashboard,
+ updateProjectForOrganization,
updateReference,
updateReport,
updateReportLayout,
+ updateUserProfile,
+ upsertConversationTitle,
V1_COMPAT_REQUEST_ID,
validateOverviewShareAccess,
validateReportAccess,
diff --git a/packages/core/src/modules/assistant/assistant.routes.ts b/packages/core/src/modules/assistant/assistant.routes.ts
index e9b741e99..0bc8d672d 100644
--- a/packages/core/src/modules/assistant/assistant.routes.ts
+++ b/packages/core/src/modules/assistant/assistant.routes.ts
@@ -16,9 +16,13 @@
// project-access check below — `chatApp.handler` gets the original,
// unconsumed `request` so it can re-read the body itself.
//
-// Everything below is dynamically imported, not statically — index.ts's
-// header explains why a static import of this barrel or `./assistant.service`
-// here would race this module's own evaluation.
+// `@openpanel/core` (the self barrel) stays dynamically imported, not
+// statically — `loadCore()` below reaches deep into the barrel for
+// cross-module functions, and a static import here would race this
+// package's own evaluation the way index.ts's header documents for
+// `mcp.service.ts`. `./assistant.service` itself is cheap either way now
+// (M10-004, see that file's header) — kept dynamic anyway for symmetry with
+// `loadCore()`.
import { defineRoutes } from '../../http/define';
@@ -42,7 +46,11 @@ export const assistantRoutes = defineRoutes((app) =>
return status(401, { message: 'Sign in required' });
}
- const { chatApp, chatRunContext } = await loadAssistant();
+ const { getChatApp, getChatRunContext } = await loadAssistant();
+ const [chatApp, chatRunContext] = await Promise.all([
+ getChatApp(),
+ getChatRunContext(),
+ ]);
// Parse the URL tail that comes after `/ai/agents/`. Examples:
// "claude-sonnet-4-5/run" → run
diff --git a/packages/core/src/modules/assistant/assistant.service.ts b/packages/core/src/modules/assistant/assistant.service.ts
index 4c96ab9f5..792e6880e 100644
--- a/packages/core/src/modules/assistant/assistant.service.ts
+++ b/packages/core/src/modules/assistant/assistant.service.ts
@@ -6,15 +6,91 @@
//
// V1 keeps running (DELEGATE PATTERN):
// - apps/api/src/agents/app.ts and apps/api/src/agents/run-context.ts
-// become re-export shims of `chatApp`/`chatRunContext` below. The live
-// Fastify route (apps/api/src/app.ts) still mounts `chatApp` and wraps
-// the handler in `chatRunContext.run(...)` exactly as before.
+// become re-export shims of `getChatApp`/`getChatRunContext` below. The
+// live Fastify route (apps/api/src/app.ts) still mounts `chatApp` and
+// wraps the handler in `chatRunContext.run(...)` exactly as before.
// - packages/trpc/src/routers/overview.ts's `runFilterCommand` procedure
// now imports `runFilterCommand` from `@openpanel/core` instead of the
// deleted `../agents/filter-command`.
+//
+// M10-004: `createAssistantService(deps)` lands here, which means THIS FILE
+// is now statically imported by services.ts — every export below stays
+// LAZY (dynamic `import()`) precisely because `./src/app.ts` constructs the
+// whole Better Agent app (one `defineAgent` per whitelisted model) at its
+// own import time, and `./src/filter-command.ts` reaches this package's own
+// barrel. A static top-level `export ... from './src/app'` here would make
+// `betterAgent`'s app construction run at PROCESS BOOT (services.ts's own
+// module evaluation) instead of on the first real chat/filter request, and
+// a static reach into `@openpanel/core` would risk re-entering this
+// package's own barrel mid-evaluation (the exact TDZ hazard index.ts's
+// header documents for `mcp.service.ts`). `deps` is unused: nothing here
+// needs Postgres/ClickHouse/Redis directly — `./src/persistence.ts` reaches
+// them through the v1-compat singleton (see that file's header), the same
+// way every other bare, no-`Ctx` caller in this wave does.
+
+import type { ServiceDeps } from '../../services';
+import type { PageContext } from './assistant.constants';
+
+let _app: Promise<typeof import('./src/app')> | undefined;
+function loadApp() {
+ if (!_app) {
+ _app = import('./src/app');
+ }
+ return _app;
+}
+
+let _runContext: Promise<typeof import('./src/run-context')> | undefined;
+function loadRunContext() {
+ if (!_runContext) {
+ _runContext = import('./src/run-context');
+ }
+ return _runContext;
+}
+
+let _filterCommand: Promise<typeof import('./src/filter-command')> | undefined;
+function loadFilterCommand() {
+ if (!_filterCommand) {
+ _filterCommand = import('./src/filter-command');
+ }
+ return _filterCommand;
+}
+
export type { ChatApp } from './src/app';
-export { chatApp } from './src/app';
export type { FilterCommandResult } from './src/filter-command';
-export { runFilterCommand } from './src/filter-command';
export type { ChatRunContext } from './src/run-context';
-export { chatRunContext } from './src/run-context';
+
+export async function getChatApp() {
+ return (await loadApp()).chatApp;
+}
+
+export async function getChatRunContext() {
+ return (await loadRunContext()).chatRunContext;
+}
+
+export interface RunFilterCommandInput {
+ query: string;
+ projectId: string;
+ pageContext?: PageContext;
+ timezone: string;
+}
+
+export async function runFilterCommand(input: RunFilterCommandInput) {
+ const { runFilterCommand: run } = await loadFilterCommand();
+ return run(input);
+}
+
+export interface AssistantService {
+ getChatApp(): ReturnType<typeof getChatApp>;
+ getChatRunContext(): ReturnType<typeof getChatRunContext>;
+ runFilterCommand(
+ input: RunFilterCommandInput
+ ): ReturnType<typeof runFilterCommand>;
+}
+
+export function createAssistantService(_deps: ServiceDeps): AssistantService {
+ return {
+ getChatApp,
+ getChatRunContext,
+ runFilterCommand,
+ };
+}
diff --git a/packages/core/src/modules/assistant/src/persistence.ts b/packages/core/src/modules/assistant/src/persistence.ts
index 83931c7b9..dd2003343 100644
--- a/packages/core/src/modules/assistant/src/persistence.ts
+++ b/packages/core/src/modules/assistant/src/persistence.ts
@@ -2,16 +2,14 @@ import type { ConversationStore } from '@better-agent/core';
import type { ConversationItem } from '@better-agent/core/providers';
import { chatRunContext } from './run-context';
-// 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 — and, per
-// this module's own history, race @openpanel/db's other eager imports:
-// event-buffer.test.ts et al. saw `BotBuffer extends BaseBuffer` resolve to
-// `undefined` before this lazy load was added).
-function loadDb() {
- return import('@openpanel/db/src/prisma-client').then((m) => m.db);
+// `ConversationStore`'s `load`/`save` signatures are @better-agent/core's own
+// interface — betterAgent calls them with no `Ctx`/`ServiceDeps` to thread
+// through, so db access stays a lazy singleton, same as the other bare
+// hot-path callers in this wave (M10-004, see v1-compat.ts's header) rather
+// than a direct `@openpanel/db` import. GENUINE CYCLE, kept lazy: services.ts
+// -> assistant.service.ts -> this file -> v1-compat.ts -> services.ts.
+function loadCompatDb() {
+ return import('../../../v1-compat').then((m) => m.compatDb());
}
/**
@@ -60,7 +58,7 @@ function itemToRow(conversationId: string, item: ConversationItem) {
export const prismaConversationStore: ConversationStore = {
async load({ conversationId }) {
- const db = await loadDb();
+ const db = await loadCompatDb();
const conv = await db.conversation.findUnique({
where: { id: conversationId },
include: {
@@ -85,7 +83,7 @@ export const prismaConversationStore: ConversationStore = {
);
}
- const db = await loadDb();
+ const db = await loadCompatDb();
await db.$transaction(async (tx) => {
await tx.conversation.upsert({
where: { id: conversationId },
diff --git a/packages/core/src/modules/assistant/src/tools/helpers.ts b/packages/core/src/modules/assistant/src/tools/helpers.ts
index e48d394f0..cb5cae1ef 100644
--- a/packages/core/src/modules/assistant/src/tools/helpers.ts
+++ b/packages/core/src/modules/assistant/src/tools/helpers.ts
@@ -15,6 +15,18 @@ import { chatRunContext } from '../run-context';
/** Max time a single tool handler is allowed to run. */
const TOOL_TIMEOUT_MS = 30_000;
+/**
+ * Chat tool handlers have a fixed signature from `@better-agent/core` — no
+ * `Ctx`/`ServiceDeps` parameter to thread through, so tools that touch
+ * Postgres directly (`references.ts`, `insights.ts`) reach it through the
+ * v1-compat singleton instead of `@openpanel/db` (M10-004, see
+ * v1-compat.ts's header) — the same pattern every other bare, no-`Ctx`
+ * caller in this wave uses.
+ */
+export async function loadCompatDb() {
+ return (await import('../../../../v1-compat')).compatDb();
+}
+
/**
* Thin wrapper around `defineTool().server()` that bakes in our typed
* agent context and enforces a time ceiling. Three things this gives
diff --git a/packages/core/src/modules/assistant/src/tools/insights.ts b/packages/core/src/modules/assistant/src/tools/insights.ts
index f1c8acb20..8da9acd45 100644
--- a/packages/core/src/modules/assistant/src/tools/insights.ts
+++ b/packages/core/src/modules/assistant/src/tools/insights.ts
@@ -1,6 +1,5 @@
-import { db } from '@openpanel/db';
import { z } from 'zod';
-import { chatTool, truncateRows } from './helpers';
+import { chatTool, loadCompatDb, truncateRows } from './helpers';
export const listInsights = chatTool(
{
@@ -20,6 +19,7 @@ export const listInsights = chatTool(
}),
},
async ({ limit, moduleKey, severity, direction }, context) => {
+ const db = await loadCompatDb();
const insights = await db.projectInsight.findMany({
where: {
projectId: context.projectId,
@@ -63,6 +63,7 @@ export const explainInsight = chatTool(
}),
},
async ({ insightId }, context) => {
+ const db = await loadCompatDb();
const insight = await db.projectInsight.findFirst({
where: { id: insightId, projectId: context.projectId },
});
@@ -89,6 +90,7 @@ export const findRelatedInsights = chatTool(
}),
},
async ({ insightId, limit }, context) => {
+ const db = await loadCompatDb();
const insight = await db.projectInsight.findFirst({
where: { id: insightId, projectId: context.projectId },
});
diff --git a/packages/core/src/modules/assistant/src/tools/references.ts b/packages/core/src/modules/assistant/src/tools/references.ts
index 6a68c9fa5..16cd3e51a 100644
--- a/packages/core/src/modules/assistant/src/tools/references.ts
+++ b/packages/core/src/modules/assistant/src/tools/references.ts
@@ -1,6 +1,10 @@
-import { db } from '@openpanel/db';
import { z } from 'zod';
-import { chatTool, resolveDateRange, truncateRows } from './helpers';
+import {
+ chatTool,
+ loadCompatDb,
+ resolveDateRange,
+ truncateRows,
+} from './helpers';
/**
* References are manual annotations the user adds — e.g.
@@ -45,6 +49,7 @@ export const listReferences = chatTool(
endDate: endDate ?? context.pageContext?.filters?.endDate,
});
+ const db = await loadCompatDb();
const rows = await db.reference.findMany({
where: {
projectId: context.projectId,
@@ -103,6 +108,7 @@ export const getReferencesAround = chatTool(
const start = new Date(target.getTime() - before * 86_400_000);
const end = new Date(target.getTime() + after * 86_400_000);
+ const db = await loadCompatDb();
const rows = await db.reference.findMany({
where: {
projectId: context.projectId,
diff --git a/packages/core/src/modules/auth/auth.routes.ts b/packages/core/src/modules/auth/auth.routes.ts
index 3cb250e13..d6d7f5d80 100644
--- a/packages/core/src/modules/auth/auth.routes.ts
+++ b/packages/core/src/modules/auth/auth.routes.ts
@@ -51,7 +51,7 @@ export const authRoutes = defineRoutes((app) =>
try {
assertOAuthState('github', query.state, storedState);
const oauthUser = await fetchGithubOAuthUser(query.code);
- await completeOAuthCallback({
+ await completeOAuthCallback(ctx, {
provider: 'github',
oauthUser,
inviteId,
@@ -90,7 +90,7 @@ export const authRoutes = defineRoutes((app) =>
query.code,
codeVerifier
);
- await completeOAuthCallback({
+ await completeOAuthCallback(ctx, {
provider: 'google',
oauthUser,
inviteId,
diff --git a/packages/core/src/modules/auth/auth.rpc.ts b/packages/core/src/modules/auth/auth.rpc.ts
index a277e5bfb..967e09522 100644
--- a/packages/core/src/modules/auth/auth.rpc.ts
+++ b/packages/core/src/modules/auth/auth.rpc.ts
@@ -56,7 +56,7 @@ function requireLogin(userId: string | null | undefined): string {
export const authRouter = createTRPCRouter({
signOut: procedure.mutation(async ({ ctx }) => {
- await signOutUser(ctx.setCookie, ctx.session?.session?.id);
+ await signOutUser(ctx, ctx.setCookie, ctx.session?.session?.id);
}),
signInOAuth: procedure
@@ -65,58 +65,63 @@ export const authRouter = createTRPCRouter({
signUpEmail: procedure
.input(zSignUpEmail)
- .mutation(({ input, ctx }) => signUpWithEmail(input, ctx.setCookie)),
+ .mutation(({ input, ctx }) => signUpWithEmail(ctx, input, ctx.setCookie)),
signInEmail: procedure
.input(zSignInEmail)
.mutation(({ input, ctx }) =>
- signInWithEmail(input, ctx.setCookie, ctx.logger)
+ signInWithEmail(ctx, input, ctx.setCookie, ctx.logger)
),
signInTotp: procedure
.input(z.object({ code: zTotpOrRecoveryCode }))
.mutation(({ input, ctx }) =>
- signInWithTotp(input, ctx.cookies, ctx.setCookie, ctx.logger)
+ signInWithTotp(ctx, input, ctx.cookies, ctx.setCookie, ctx.logger)
),
totpStatus: procedure.query(({ ctx }) =>
- getTotpStatus(requireLogin(ctx.session.userId))
+ getTotpStatus(ctx, requireLogin(ctx.session.userId))
),
totpSetup: procedure.mutation(({ ctx }) =>
- setupTotp(requireLogin(ctx.session.userId))
+ setupTotp(ctx, requireLogin(ctx.session.userId))
),
totpEnable: procedure
.input(z.object({ code: zTotpCode }))
.mutation(({ input, ctx }) =>
- enableTotp(requireLogin(ctx.session.userId), input.code)
+ enableTotp(ctx, requireLogin(ctx.session.userId), input.code)
),
totpDisable: procedure
.input(z.object({ code: zTotpOrRecoveryCode }))
.mutation(({ input, ctx }) =>
- disableTotp(requireLogin(ctx.session.userId), input.code)
+ disableTotp(ctx, requireLogin(ctx.session.userId), input.code)
),
totpRegenerateRecoveryCodes: procedure
.input(z.object({ code: zTotpCode }))
.mutation(({ input, ctx }) =>
- regenerateTotpRecoveryCodes(requireLogin(ctx.session.userId), input.code)
+ regenerateTotpRecoveryCodes(
+ ctx,
+ requireLogin(ctx.session.userId),
+ input.code
+ )
),
resetPassword: procedure
.input(zResetPassword)
- .mutation(({ input }) => resetPasswordWithToken(input)),
+ .mutation(({ input, ctx }) => resetPasswordWithToken(ctx, input)),
requestResetPassword: procedure
.input(zRequestResetPassword)
- .mutation(({ input }) => requestPasswordReset(input)),
+ .mutation(({ input, ctx }) => requestPasswordReset(ctx, input)),
session: procedure.query(({ ctx }) => ctx.session),
extendSession: procedure.mutation(({ ctx }) =>
extendSessionCookie(
+ ctx,
ctx.cookies,
Boolean(ctx.session.session),
ctx.setCookie
diff --git a/packages/core/src/modules/auth/auth.service.ts b/packages/core/src/modules/auth/auth.service.ts
index f373b3f19..1cb8ef9ed 100644
--- a/packages/core/src/modules/auth/auth.service.ts
+++ b/packages/core/src/modules/auth/auth.service.ts
@@ -1,14 +1,22 @@
// Moved from @openpanel/auth (M4-007): token issuance/hashing, argon2
// password hashing, TOTP, the OAuth clients and cookie helpers. The
// Prisma-touching half — creating, validating and invalidating a `sessions`
-// row — moved here too (M8-005, `./src/login-session.ts`), lazily loading
-// @openpanel/db's Prisma client the same way `loadRegistration` below does,
-// so there is no static core -> db edge.
+// row — moved here too (M8-005, `./src/login-session.ts`).
//
// M10-002 (docs/TECH_DEBT.md §5b): the permission ladder (`shared/access.ts`)
// is bound to its real lookups exactly here, once, instead of once per module
// in a `modules/*/src/access.ts` copy — see `getAccessChecks` below for the
// binding itself.
+//
+// M10-004: every module in this wave, INCLUDING auth's own remaining lazy
+// imports, moves to `ServiceDeps`. `signUpWithEmail`/`signInWithEmail`/TOTP/
+// password-reset/OAuth-callback all take `deps` now and reach Postgres as
+// `deps.db`; `./src/login-session.ts` and `./src/registration.ts` do the
+// same and are plain static imports here (neither cycles back to this file).
+// `packages/trpc`'s still-live router calls every one of these bare (no
+// `ServiceDeps`); those reach `createServices` through the v1-compat
+// singleton instead (see v1-compat.ts's header) — `auth.rpc.ts` already
+// carries a `Ctx` and passes it straight through.
import { z } from 'zod';
import type { ServiceDeps } from '../../services';
@@ -139,7 +147,10 @@ export function getAccessChecks(): Promise<AccessChecks<IProjectAccess>> {
if (!accessChecksPromise) {
accessChecksPromise = Promise.all([
loadAccessLookups(),
- import('../project/project.service'),
+ // project.service.ts's own `getProjectById` takes `ServiceDeps` now
+ // (M10-004) — this singleton has none, so it reaches the bare,
+ // v1-compat-wrapped spelling instead (see that file's header).
+ import('../../v1-compat'),
]).then(
([
{ getProjectAccess, canWriteProject, getOrganizationAccess },
@@ -225,17 +236,17 @@ export function createAuthService(_deps: ServiceDeps): AuthService {
// PATTERN: both V1's trpc router and this package's own auth.rpc.ts call
// these same functions).
//
-// db/session/registration/share access is LAZY, not a static top-level
-// import — see user.service.ts's header for the full reasoning (constructing
-// @openpanel/db's clients at import time spawns a pino-pretty transport
-// worker thread per `bun test --isolate` file). `loadShare` points at
-// `../share/share.service` directly since M6-004 — share.service.ts
-// statically imports this file's own `hashPassword`, so the two are mutually
-// lazy/eager by design, not a live cycle.
+// Session/registration access is `deps.db`, via static imports of
+// `./src/login-session` and `./src/registration` (M10-004) — neither cycles
+// back to this file, so there is nothing to keep lazy there. `loadShare`
+// stays a lazy, dynamic import of `../share/share.service`: share.service.ts
+// statically imports this file's own `hashPassword`, so the two ARE a real
+// cycle (M6-004), unlike the other two.
//
-// None of these functions take a `TrpcContext`/`Ctx`: they take exactly the
-// primitives they touch (`setCookie`, `cookies.get`, `logger`), so this file
-// has no dependency on the rpc layer that calls it.
+// None of these functions take a `TrpcContext`/`Ctx` directly — they take a
+// `deps: ServiceDeps` plus exactly the other primitives they touch
+// (`setCookie`, `cookies.get`, `logger`), so this file has no dependency on
+// the rpc layer that calls it.
import { sendEmail } from '../../clients/email';
import type { Logger } from '../../logger';
@@ -244,6 +255,12 @@ import { decrypt, encrypt } from '../../shared/encryption';
import { generateSecureId } from '../../shared/id';
import { connectUserToOrganization } from '../organization/organization.service';
import { getUserAccount } from '../user/user.service';
+import {
+ createSession,
+ invalidateSession,
+ validateSessionToken,
+} from './src/login-session';
+import { getIsRegistrationAllowed } from './src/registration';
const TWO_FACTOR_COOKIE = '2fa_challenge';
const TWO_FACTOR_CHALLENGE_TTL_SECONDS = 5 * 60;
@@ -259,18 +276,6 @@ interface CookieReader {
get(name: string): string | undefined;
}
-function loadDb() {
- return import('@openpanel/db/src/prisma-client').then((m) => m.db);
-}
-
-function loadAuthSession() {
- return import('./src/login-session');
-}
-
-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
@@ -293,13 +298,15 @@ function dashboardUrl(): string {
* swallow and log the error instead of rethrowing.
*/
async function consumeInviteForUser(
+ deps: ServiceDeps,
userId: string,
inviteId: string,
logger: Pick<Logger, 'error'>
): Promise<void> {
try {
- const db = await loadDb();
- const user = await db.user.findUniqueOrThrow({ where: { id: userId } });
+ const user = await deps.db.user.findUniqueOrThrow({
+ where: { id: userId },
+ });
await connectUserToOrganization({ user, inviteId });
} catch (error) {
logger.error(
@@ -310,13 +317,13 @@ async function consumeInviteForUser(
}
export async function signOutUser(
+ deps: ServiceDeps,
setCookie: ISetCookie,
sessionId: string | null | undefined
): Promise<void> {
deleteSessionTokenCookie(setCookie);
if (sessionId) {
- const { invalidateSession } = await loadAuthSession();
- await invalidateSession(sessionId);
+ await invalidateSession(deps, sessionId);
}
}
@@ -375,23 +382,25 @@ export interface SignUpEmailInput {
}
export async function signUpWithEmail(
+ deps: ServiceDeps,
input: SignUpEmailInput,
setCookie: ISetCookie
) {
- const { getIsRegistrationAllowed } = await loadRegistration();
- const isRegistrationAllowed = await getIsRegistrationAllowed(input.inviteId);
+ const isRegistrationAllowed = await getIsRegistrationAllowed(
+ deps,
+ input.inviteId
+ );
if (!isRegistrationAllowed) {
throw new TRPCAccessError('Registrations are not allowed');
}
const provider = 'email';
- const db = await loadDb();
- const existing = await getUserAccount({ email: input.email, provider });
+ const existing = await getUserAccount(deps, { email: input.email, provider });
if (existing) {
throw new TRPCNotFoundError('User already exists');
}
- const createdUser = await db.user.create({
+ const createdUser = await deps.db.user.create({
data: {
id: generateSecureId('user'),
email: input.email,
@@ -413,9 +422,8 @@ export async function signUpWithEmail(
});
}
- const { createSession } = await loadAuthSession();
const token = generateSessionToken();
- const session = await createSession(token, createdUser.id);
+ const session = await createSession(deps, token, createdUser.id);
setSessionTokenCookie(setCookie, token, session.expiresAt);
return session;
}
@@ -429,12 +437,16 @@ export interface SignInEmailInput {
export type SignInEmailResult = { type: 'totp_required' } | { type: 'email' };
export async function signInWithEmail(
+ deps: ServiceDeps,
input: SignInEmailInput,
setCookie: ISetCookie,
logger: Pick<Logger, 'error'>
): Promise<SignInEmailResult> {
const password = input.password.trim();
- const user = await getUserAccount({ email: input.email, provider: 'email' });
+ const user = await getUserAccount(deps, {
+ email: input.email,
+ provider: 'email',
+ });
if (!user) {
throw new TRPCNotFoundError('User does not exists');
@@ -455,11 +467,12 @@ export async function signInWithEmail(
throw new TRPCAccessError('Incorrect email or password');
}
- const db = await loadDb();
- const totp = await db.userTotp.findUnique({ where: { userId: user.id } });
+ const totp = await deps.db.userTotp.findUnique({
+ where: { userId: user.id },
+ });
if (totp?.enabledAt) {
const challengeId = generateSecureId('2fa');
- await db.twoFactorChallenge.create({
+ await deps.db.twoFactorChallenge.create({
data: {
id: challengeId,
userId: user.id,
@@ -481,14 +494,13 @@ export async function signInWithEmail(
return { type: 'totp_required' };
}
- const { createSession } = await loadAuthSession();
const token = generateSessionToken();
- const session = await createSession(token, user.id);
+ const session = await createSession(deps, token, user.id);
setSessionTokenCookie(setCookie, token, session.expiresAt);
setLastAuthProviderCookie(setCookie, 'email');
if (input.inviteId) {
- await consumeInviteForUser(user.id, input.inviteId, logger);
+ await consumeInviteForUser(deps, user.id, input.inviteId, logger);
}
return { type: 'email' };
@@ -499,6 +511,7 @@ export interface SignInTotpInput {
}
export async function signInWithTotp(
+ deps: ServiceDeps,
input: SignInTotpInput,
cookies: CookieReader,
setCookie: ISetCookie,
@@ -509,24 +522,23 @@ export async function signInWithTotp(
throw new TRPCAccessError('No active two-factor challenge');
}
- const db = await loadDb();
- const challenge = await db.twoFactorChallenge.findUnique({
+ const challenge = await deps.db.twoFactorChallenge.findUnique({
where: { id: challengeId },
});
if (!challenge || challenge.expiresAt < new Date()) {
if (challenge) {
- await db.twoFactorChallenge.delete({ where: { id: challenge.id } });
+ await deps.db.twoFactorChallenge.delete({ where: { id: challenge.id } });
}
setCookie(TWO_FACTOR_COOKIE, '', { maxAge: 0 });
throw new TRPCAccessError('Two-factor challenge has expired');
}
- const totp = await db.userTotp.findUnique({
+ const totp = await deps.db.userTotp.findUnique({
where: { userId: challenge.userId },
});
if (!totp?.enabledAt) {
- await db.twoFactorChallenge.delete({ where: { id: challenge.id } });
+ await deps.db.twoFactorChallenge.delete({ where: { id: challenge.id } });
setCookie(TWO_FACTOR_COOKIE, '', { maxAge: 0 });
throw new TRPCAccessError('Two-factor is not enabled');
}
@@ -544,7 +556,7 @@ export async function signInWithTotp(
});
if (result.valid) {
valid = true;
- await db.userTotp.update({
+ await deps.db.userTotp.update({
where: { userId: challenge.userId },
data: { recoveryCodes: result.remaining },
});
@@ -555,29 +567,27 @@ export async function signInWithTotp(
throw new TRPCAccessError('Invalid code');
}
- await db.twoFactorChallenge.delete({ where: { id: challenge.id } });
+ await deps.db.twoFactorChallenge.delete({ where: { id: challenge.id } });
setCookie(TWO_FACTOR_COOKIE, '', { maxAge: 0 });
- const { createSession } = await loadAuthSession();
const token = generateSessionToken();
- const session = await createSession(token, challenge.userId);
+ const session = await createSession(deps, token, challenge.userId);
setSessionTokenCookie(setCookie, token, session.expiresAt);
setLastAuthProviderCookie(setCookie, 'email');
const inviteId = cookies.get(INVITE_COOKIE);
if (inviteId) {
- await consumeInviteForUser(challenge.userId, inviteId, logger);
+ await consumeInviteForUser(deps, challenge.userId, inviteId, logger);
setCookie(INVITE_COOKIE, '', { maxAge: 0 });
}
return { type: 'email' };
}
-export async function getTotpStatus(userId: string) {
- const db = await loadDb();
+export async function getTotpStatus(deps: ServiceDeps, userId: string) {
const [totp, emailAccount] = await Promise.all([
- db.userTotp.findUnique({ where: { userId } }),
- db.account.findFirst({
+ deps.db.userTotp.findUnique({ where: { userId } }),
+ deps.db.account.findFirst({
where: { userId, provider: 'email' },
select: { id: true },
}),
@@ -590,9 +600,8 @@ export async function getTotpStatus(userId: string) {
};
}
-export async function setupTotp(userId: string) {
- const db = await loadDb();
- const emailAccount = await db.account.findFirst({
+export async function setupTotp(deps: ServiceDeps, userId: string) {
+ const emailAccount = await deps.db.account.findFirst({
where: { userId, provider: 'email' },
select: { id: true },
});
@@ -601,14 +610,14 @@ export async function setupTotp(userId: string) {
'Two-factor authentication is only available for email/password sign-ins. Your account uses a social provider, which handles 2FA on its end.'
);
}
- const existing = await db.userTotp.findUnique({ where: { userId } });
+ const existing = await deps.db.userTotp.findUnique({ where: { userId } });
if (existing?.enabledAt) {
throw new TRPCAccessError(
'Two-factor is already enabled. Disable it first to re-configure.'
);
}
- const user = await db.user.findUniqueOrThrow({
+ const user = await deps.db.user.findUniqueOrThrow({
where: { id: userId },
select: { email: true },
});
@@ -617,7 +626,7 @@ export async function setupTotp(userId: string) {
const otpauthUrl = buildOtpauthUrl({ secret, accountName: user.email });
const qrDataUrl = await generateQrDataUrl(otpauthUrl);
- await db.userTotp.upsert({
+ await deps.db.userTotp.upsert({
where: { userId },
create: { userId, secret: encrypt(secret), recoveryCodes: [] },
update: { secret: encrypt(secret), recoveryCodes: [], enabledAt: null },
@@ -626,9 +635,12 @@ export async function setupTotp(userId: string) {
return { otpauthUrl, qrDataUrl, secret };
}
-export async function enableTotp(userId: string, code: string) {
- const db = await loadDb();
- const totp = await db.userTotp.findUnique({ where: { userId } });
+export async function enableTotp(
+ deps: ServiceDeps,
+ userId: string,
+ code: string
+) {
+ const totp = await deps.db.userTotp.findUnique({ where: { userId } });
if (!totp) {
throw new TRPCNotFoundError('Start two-factor setup first');
}
@@ -644,7 +656,7 @@ export async function enableTotp(userId: string, code: string) {
const recoveryCodes = generateRecoveryCodes();
const hashed = await hashRecoveryCodes(recoveryCodes);
- await db.userTotp.update({
+ await deps.db.userTotp.update({
where: { userId },
data: { enabledAt: new Date(), recoveryCodes: hashed },
});
@@ -652,9 +664,12 @@ export async function enableTotp(userId: string, code: string) {
return { recoveryCodes };
}
-export async function disableTotp(userId: string, code: string) {
- const db = await loadDb();
- const totp = await db.userTotp.findUnique({ where: { userId } });
+export async function disableTotp(
+ deps: ServiceDeps,
+ userId: string,
+ code: string
+) {
+ const totp = await deps.db.userTotp.findUnique({ where: { userId } });
if (!totp?.enabledAt) {
throw new TRPCAccessError('Two-factor is not enabled');
}
@@ -670,17 +685,17 @@ export async function disableTotp(userId: string, code: string) {
throw new TRPCAccessError('Invalid code');
}
- await db.userTotp.delete({ where: { userId } });
- await db.twoFactorChallenge.deleteMany({ where: { userId } });
+ await deps.db.userTotp.delete({ where: { userId } });
+ await deps.db.twoFactorChallenge.deleteMany({ where: { userId } });
return { disabled: true };
}
export async function regenerateTotpRecoveryCodes(
+ deps: ServiceDeps,
userId: string,
code: string
) {
- const db = await loadDb();
- const totp = await db.userTotp.findUnique({ where: { userId } });
+ const totp = await deps.db.userTotp.findUnique({ where: { userId } });
if (!totp?.enabledAt) {
throw new TRPCAccessError('Two-factor is not enabled');
}
@@ -690,7 +705,7 @@ export async function regenerateTotpRecoveryCodes(
}
const recoveryCodes = generateRecoveryCodes();
const hashed = await hashRecoveryCodes(recoveryCodes);
- await db.userTotp.update({
+ await deps.db.userTotp.update({
where: { userId },
data: { recoveryCodes: hashed },
});
@@ -703,10 +718,10 @@ export interface ResetPasswordInput {
}
export async function resetPasswordWithToken(
+ deps: ServiceDeps,
input: ResetPasswordInput
): Promise<true> {
- const db = await loadDb();
- const resetPassword = await db.resetPassword.findUnique({
+ const resetPassword = await deps.db.resetPassword.findUnique({
where: { id: input.token },
});
@@ -717,31 +732,38 @@ export async function resetPasswordWithToken(
throw new TRPCNotFoundError('Reset password expired');
}
- await db.account.update({
+ await deps.db.account.update({
where: { id: resetPassword.accountId },
data: { password: await hashPassword(input.password) },
});
- await db.resetPassword.delete({ where: { id: input.token } });
+ await deps.db.resetPassword.delete({ where: { id: input.token } });
return true;
}
-export async function requestPasswordReset(input: {
- email: string;
-}): Promise<true> {
- const user = await getUserAccount({ email: input.email, provider: 'email' });
+export async function requestPasswordReset(
+ deps: ServiceDeps,
+ input: {
+ email: string;
+ }
+): Promise<true> {
+ const user = await getUserAccount(deps, {
+ email: input.email,
+ provider: 'email',
+ });
// Deliberately not found-vs-found: V1 always returns `true` here so the
// endpoint cannot be used to enumerate registered emails.
if (!user?.account.id) {
return true;
}
- const db = await loadDb();
- await db.resetPassword.deleteMany({ where: { accountId: user.account.id } });
+ await deps.db.resetPassword.deleteMany({
+ where: { accountId: user.account.id },
+ });
const token = generateSecureId('pw');
const expiresAt = new Date(Date.now() + RESET_PASSWORD_TTL_MS);
- await db.resetPassword.create({
+ await deps.db.resetPassword.create({
data: { id: token, expiresAt, accountId: user.account.id },
});
@@ -754,6 +776,7 @@ export async function requestPasswordReset(input: {
}
export async function extendSessionCookie(
+ deps: ServiceDeps,
cookies: CookieReader,
hasSession: boolean,
setCookie: ISetCookie
@@ -763,8 +786,7 @@ export async function extendSessionCookie(
return { extended: false };
}
- const { validateSessionToken } = await loadAuthSession();
- const session = await validateSessionToken(token);
+ const session = await validateSessionToken(deps, token);
if (session.session) {
setSessionTokenCookie(setCookie, token, session.session.expiresAt);
@@ -976,12 +998,12 @@ export interface CompleteOAuthCallbackInput {
* find-or-create the account and issue a session.
*/
export async function completeOAuthCallback(
+ deps: ServiceDeps,
input: CompleteOAuthCallbackInput
): Promise<void> {
const { provider, oauthUser, inviteId, setCookie, logger } = input;
- const db = await loadDb();
- const account = await db.account.findFirst({
+ const account = await deps.db.account.findFirst({
where: {
OR: [
{ provider, providerId: oauthUser.id },
@@ -993,7 +1015,7 @@ export async function completeOAuthCallback(
});
if (account) {
- await completeExistingOAuthUser({
+ await completeExistingOAuthUser(deps, {
account,
oauthUser,
provider,
@@ -1004,7 +1026,7 @@ export async function completeOAuthCallback(
return;
}
- await completeNewOAuthUser({
+ await completeNewOAuthUser(deps, {
oauthUser,
provider,
inviteId,
@@ -1013,56 +1035,57 @@ export async function completeOAuthCallback(
});
}
-async function completeExistingOAuthUser({
- account,
- oauthUser,
- provider,
- inviteId,
- setCookie,
- logger,
-}: {
- account: { id: string; userId: string };
- oauthUser: OAuthUser;
- provider: 'github' | 'google';
- inviteId: string | null | undefined;
- setCookie: ISetCookie;
- logger: Pick<Logger, 'error'>;
-}) {
- const db = await loadDb();
- const { createSession } = await loadAuthSession();
+async function completeExistingOAuthUser(
+ deps: ServiceDeps,
+ {
+ account,
+ oauthUser,
+ provider,
+ inviteId,
+ setCookie,
+ logger,
+ }: {
+ account: { id: string; userId: string };
+ oauthUser: OAuthUser;
+ provider: 'github' | 'google';
+ inviteId: string | null | undefined;
+ setCookie: ISetCookie;
+ logger: Pick<Logger, 'error'>;
+ }
+) {
const sessionToken = generateSessionToken();
- const session = await createSession(sessionToken, account.userId);
+ const session = await createSession(deps, sessionToken, account.userId);
- await db.account.update({
+ await deps.db.account.update({
where: { id: account.id },
data: { provider, providerId: oauthUser.id, email: oauthUser.email },
});
if (inviteId) {
- await consumeInviteForUser(account.userId, inviteId, logger);
+ await consumeInviteForUser(deps, account.userId, inviteId, logger);
}
setSessionTokenCookie(setCookie, sessionToken, session.expiresAt);
setLastAuthProviderCookie(setCookie, provider);
}
-async function completeNewOAuthUser({
- oauthUser,
- provider,
- inviteId,
- setCookie,
- logger,
-}: {
- oauthUser: OAuthUser;
- provider: 'github' | 'google';
- inviteId: string | null | undefined;
- setCookie: ISetCookie;
- logger: Pick<Logger, 'error'>;
-}) {
- const db = await loadDb();
- const { getIsRegistrationAllowed } = await loadRegistration();
-
- const existingUser = await db.user.findFirst({
+async function completeNewOAuthUser(
+ deps: ServiceDeps,
+ {
+ oauthUser,
+ provider,
+ inviteId,
+ setCookie,
+ logger,
+ }: {
+ oauthUser: OAuthUser;
+ provider: 'github' | 'google';
+ inviteId: string | null | undefined;
+ setCookie: ISetCookie;
+ logger: Pick<Logger, 'error'>;
+ }
+) {
+ const existingUser = await deps.db.user.findFirst({
where: { email: oauthUser.email },
});
if (existingUser) {
@@ -1075,7 +1098,7 @@ async function completeNewOAuthUser({
// Enforce the self-hosting registration policy here rather than before the
// IdP redirect — this is the first point where we know the user is new, so
// returning users are never caught by it.
- if (!(await getIsRegistrationAllowed(inviteId))) {
+ if (!(await getIsRegistrationAllowed(deps, inviteId))) {
// Deliberately no `oauthUser` here — this rejects people who are not
// users, so their email and name shouldn't land in application logs.
throw new OAuthCallbackError('Registrations are not allowed', {
@@ -1084,7 +1107,7 @@ async function completeNewOAuthUser({
});
}
- const user = await db.user.create({
+ const user = await deps.db.user.create({
data: {
email: oauthUser.email,
firstName: oauthUser.firstName,
@@ -1106,9 +1129,8 @@ async function completeNewOAuthUser({
}
}
- const { createSession } = await loadAuthSession();
const sessionToken = generateSessionToken();
- const session = await createSession(sessionToken, user.id);
+ const session = await createSession(deps, sessionToken, user.id);
setSessionTokenCookie(setCookie, sessionToken, session.expiresAt);
setLastAuthProviderCookie(setCookie, provider);
}
diff --git a/packages/core/src/modules/auth/src/login-session.ts b/packages/core/src/modules/auth/src/login-session.ts
index 878cceff9..29df7c93a 100644
--- a/packages/core/src/modules/auth/src/login-session.ts
+++ b/packages/core/src/modules/auth/src/login-session.ts
@@ -3,23 +3,19 @@
// browser's cookie). Not to be confused with session.service.ts's ClickHouse
// visitor sessions.
//
-// Originally split at the Prisma boundary (M4-007) on the belief that a
-// static `@openpanel/db` import here would cycle with db's own (static)
-// `@openpanel/core` imports. `loadDb()` below is the same lazy pattern
-// salt.service.ts and registration.ts already use to reach db's Prisma
-// client with no such cycle — auth.service.ts's own `loadAuthSession()`
-// already reached this file that way, so the move only changes where the
-// file lives, not how its caller loads it.
-//
-// db access is LAZY, not a static top-level import — see salt.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-004: every function takes `ServiceDeps` and reaches Postgres as
+// `deps.db`; the `loadDb()` lazy loader is gone. `http/session.ts`'s
+// `resolveSession` already carried an (until-now-unused) `AppDeps` for
+// exactly this.
import type { Session, User } from '@openpanel/db/src/prisma-client';
+import type { ServiceDeps } from '../../../services';
import { decodeSessionToken, hashSessionToken } from './token';
+/** Only Postgres — narrowed so `AppDeps` (http/session.ts, before
+ * `ServiceDeps.queues` exists) satisfies it with no cast. */
+type LoginSessionDeps = Pick<ServiceDeps, 'db'>;
+
const SESSION_TTL_MS = 1000 * 60 * 60 * 24 * 30;
const SESSION_RENEWAL_THRESHOLD_MS = 1000 * 60 * 60 * 24 * 15;
const DEMO_SESSION_TTL_MS = 1000 * 60 * 60 * 24 * 30 * 365;
@@ -35,15 +31,11 @@ export const EMPTY_SESSION: SessionValidationResult = {
userId: null,
};
-function loadDb() {
- return import('@openpanel/db/src/prisma-client').then((m) => m.db);
-}
-
export async function createSession(
+ deps: LoginSessionDeps,
token: string,
userId: string
): Promise<Session> {
- const db = await loadDb();
const session: Session = {
id: hashSessionToken(token),
userId,
@@ -51,17 +43,17 @@ export async function createSession(
createdAt: new Date(),
updatedAt: new Date(),
};
- await db.session.create({
+ await deps.db.session.create({
data: session,
});
return session;
}
export async function createDemoSession(
+ deps: LoginSessionDeps,
userId: string
): Promise<SessionValidationResult> {
- const db = await loadDb();
- const user = await db.user.findUniqueOrThrow({
+ const user = await deps.db.user.findUniqueOrThrow({
where: {
id: userId,
},
@@ -81,10 +73,11 @@ export async function createDemoSession(
}
export async function validateSessionToken(
+ deps: LoginSessionDeps,
token: string | null | undefined
): Promise<SessionValidationResult> {
if (process.env.DEMO_USER_ID) {
- return createDemoSession(process.env.DEMO_USER_ID);
+ return createDemoSession(deps, process.env.DEMO_USER_ID);
}
if (!token) {
@@ -94,8 +87,7 @@ export async function validateSessionToken(
if (!sessionId) {
return EMPTY_SESSION;
}
- const db = await loadDb();
- const result = await db.session.findUnique({
+ const result = await deps.db.session.findUnique({
where: {
id: sessionId,
},
@@ -108,7 +100,7 @@ export async function validateSessionToken(
}
const { user, ...session } = result;
if (Date.now() >= session.expiresAt.getTime()) {
- await db.session.delete({ where: { id: sessionId } });
+ await deps.db.session.delete({ where: { id: sessionId } });
return EMPTY_SESSION;
}
if (
@@ -116,7 +108,7 @@ export async function validateSessionToken(
session.expiresAt.getTime() - SESSION_RENEWAL_THRESHOLD_MS
) {
session.expiresAt = new Date(Date.now() + SESSION_TTL_MS);
- await db.session.update({
+ await deps.db.session.update({
where: {
id: session.id,
},
@@ -128,7 +120,9 @@ export async function validateSessionToken(
return { session, user, userId: user.id };
}
-export async function invalidateSession(sessionId: string): Promise<void> {
- const db = await loadDb();
- await db.session.delete({ where: { id: sessionId } });
+export async function invalidateSession(
+ deps: LoginSessionDeps,
+ sessionId: string
+): Promise<void> {
+ await deps.db.session.delete({ where: { id: sessionId } });
}
diff --git a/packages/core/src/modules/auth/src/registration.test.ts b/packages/core/src/modules/auth/src/registration.test.ts
index e347333b7..6089451f2 100644
--- a/packages/core/src/modules/auth/src/registration.test.ts
+++ b/packages/core/src/modules/auth/src/registration.test.ts
@@ -1,31 +1,18 @@
-import {
- afterEach,
- beforeAll,
- beforeEach,
- describe,
- expect,
- it,
- mock,
-} from 'bun:test';
+import { afterEach, beforeEach, describe, expect, it, mock } from 'bun:test';
+import type { ServiceDeps } from '../../../services';
+import { getIsRegistrationAllowed } from './registration';
const mockUserCount = mock(async () => 5);
const mockInviteFindUnique = mock(
async (): Promise<{ id: string } | null> => null
);
-const actualPrismaClient = await import('@openpanel/db/src/prisma-client');
-mock.module('@openpanel/db/src/prisma-client', () => ({
- ...actualPrismaClient,
+const deps = {
db: {
user: { count: mockUserCount },
invite: { findUnique: mockInviteFindUnique },
},
-}));
-
-let getIsRegistrationAllowed: typeof import('./registration').getIsRegistrationAllowed;
-beforeAll(async () => {
- ({ getIsRegistrationAllowed } = await import('./registration'));
-});
+} as unknown as ServiceDeps;
const ORIGINAL_ENV = { ...process.env };
@@ -46,7 +33,7 @@ describe('getIsRegistrationAllowed', () => {
process.env.ALLOW_REGISTRATION = undefined;
delete process.env.ALLOW_REGISTRATION;
- expect(await getIsRegistrationAllowed()).toBe(true);
+ expect(await getIsRegistrationAllowed(deps)).toBe(true);
expect(mockUserCount).not.toHaveBeenCalled();
});
@@ -54,13 +41,13 @@ describe('getIsRegistrationAllowed', () => {
process.env.ALLOW_REGISTRATION = 'false';
mockUserCount.mockResolvedValue(0);
- expect(await getIsRegistrationAllowed()).toBe(true);
+ expect(await getIsRegistrationAllowed(deps)).toBe(true);
});
it('blocks a new user with no invite when registration is disabled', async () => {
process.env.ALLOW_REGISTRATION = 'false';
- expect(await getIsRegistrationAllowed()).toBe(false);
+ expect(await getIsRegistrationAllowed(deps)).toBe(false);
});
it('allows a new user holding a valid invite when registration is disabled', async () => {
@@ -68,7 +55,7 @@ describe('getIsRegistrationAllowed', () => {
process.env.ALLOW_INVITATION = 'true';
mockInviteFindUnique.mockResolvedValue({ id: 'invite-1' });
- expect(await getIsRegistrationAllowed('invite-1')).toBe(true);
+ expect(await getIsRegistrationAllowed(deps, 'invite-1')).toBe(true);
});
it('blocks an unknown invite id', async () => {
@@ -76,7 +63,7 @@ describe('getIsRegistrationAllowed', () => {
process.env.ALLOW_INVITATION = 'true';
mockInviteFindUnique.mockResolvedValue(null);
- expect(await getIsRegistrationAllowed('nope')).toBe(false);
+ expect(await getIsRegistrationAllowed(deps, 'nope')).toBe(false);
});
it('blocks a valid invite when invitations are disabled', async () => {
@@ -84,13 +71,13 @@ describe('getIsRegistrationAllowed', () => {
process.env.ALLOW_INVITATION = 'false';
mockInviteFindUnique.mockResolvedValue({ id: 'invite-1' });
- expect(await getIsRegistrationAllowed('invite-1')).toBe(false);
+ expect(await getIsRegistrationAllowed(deps, 'invite-1')).toBe(false);
expect(mockInviteFindUnique).not.toHaveBeenCalled();
});
it('allows open self-hosted registration', async () => {
process.env.ALLOW_REGISTRATION = 'true';
- expect(await getIsRegistrationAllowed()).toBe(true);
+ expect(await getIsRegistrationAllowed(deps)).toBe(true);
});
});
diff --git a/packages/core/src/modules/auth/src/registration.ts b/packages/core/src/modules/auth/src/registration.ts
index 9ac7523c7..bf342b82c 100644
--- a/packages/core/src/modules/auth/src/registration.ts
+++ b/packages/core/src/modules/auth/src/registration.ts
@@ -1,11 +1,10 @@
-// db access is LAZY (`loadDb` below), 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).
-function loadDb() {
- return import('@openpanel/db/src/prisma-client').then((m) => m.db);
-}
+// M10-004: reaches Postgres as `deps.db`; the `loadDb()` lazy loader is gone.
+
+import type { ServiceDeps } from '../../../services';
+
+/** Only Postgres — narrowed so any of this module's several callers, none of
+ * which carry a full `ServiceDeps`, satisfy it with no cast. */
+type RegistrationDeps = Pick<ServiceDeps, 'db'>;
/**
* Whether a *new* user may be created right now.
@@ -15,16 +14,18 @@ function loadDb() {
* OAuth redirect) would reject returning users too, since we cannot tell a
* sign-in from a sign-up at that stage.
*/
-export async function getIsRegistrationAllowed(inviteId?: string | null) {
+export async function getIsRegistrationAllowed(
+ deps: RegistrationDeps,
+ inviteId?: string | null
+) {
// ALLOW_REGISTRATION is always undefined in cloud
if (process.env.ALLOW_REGISTRATION === undefined) {
return true;
}
- const db = await loadDb();
// Self-hosting logic
// 1. First user is always allowed
- const count = await db.user.count();
+ const count = await deps.db.user.count();
if (count === 0) {
return true;
}
@@ -35,7 +36,7 @@ export async function getIsRegistrationAllowed(inviteId?: string | null) {
return false;
}
- const invite = await db.invite.findUnique({
+ const invite = await deps.db.invite.findUnique({
where: {
id: inviteId,
},
diff --git a/packages/core/src/modules/client/client.routes.ts b/packages/core/src/modules/client/client.routes.ts
index 4c399e5c1..22c413a39 100644
--- a/packages/core/src/modules/client/client.routes.ts
+++ b/packages/core/src/modules/client/client.routes.ts
@@ -18,13 +18,6 @@
import { z } from 'zod';
import { defineRoutes } from '../../http/define';
-import {
- createClientForOrganization,
- deleteClientForOrganization,
- getClientForOrganization,
- listClientsForOrganization,
- updateClientForOrganization,
-} from './client.service';
const idParams = z.object({ id: z.string() });
const listQuery = z.object({ projectId: z.string().optional() });
@@ -43,8 +36,8 @@ export const clientRoutes = defineRoutes((app) =>
app
.get(
'/manage/clients',
- async ({ client, query, status }) => {
- const clients = await listClientsForOrganization(
+ async ({ client, ctx, query, status }) => {
+ const clients = await ctx.services.client.listClientsForOrganization(
client.organizationId,
query.projectId
);
@@ -64,8 +57,8 @@ export const clientRoutes = defineRoutes((app) =>
)
.get(
'/manage/clients/:id',
- async ({ client, params, status }) => {
- const found = await getClientForOrganization(
+ async ({ client, ctx, params, status }) => {
+ const found = await ctx.services.client.getClientForOrganization(
params.id,
client.organizationId
);
@@ -85,8 +78,8 @@ export const clientRoutes = defineRoutes((app) =>
)
.post(
'/manage/clients',
- async ({ body, client, status }) => {
- const created = await createClientForOrganization(
+ async ({ body, client, ctx, status }) => {
+ const created = await ctx.services.client.createClientForOrganization(
client.organizationId,
body
);
@@ -108,8 +101,8 @@ export const clientRoutes = defineRoutes((app) =>
)
.patch(
'/manage/clients/:id',
- async ({ body, client, params, status }) => {
- const updated = await updateClientForOrganization(
+ async ({ body, client, ctx, params, status }) => {
+ const updated = await ctx.services.client.updateClientForOrganization(
params.id,
client.organizationId,
body
@@ -131,8 +124,8 @@ export const clientRoutes = defineRoutes((app) =>
)
.delete(
'/manage/clients/:id',
- async ({ client, params, status }) => {
- const deleted = await deleteClientForOrganization(
+ async ({ client, ctx, params, status }) => {
+ const deleted = await ctx.services.client.deleteClientForOrganization(
params.id,
client.organizationId
);
diff --git a/packages/core/src/modules/client/client.rpc.ts b/packages/core/src/modules/client/client.rpc.ts
index 7dc8e0d67..36d011786 100644
--- a/packages/core/src/modules/client/client.rpc.ts
+++ b/packages/core/src/modules/client/client.rpc.ts
@@ -7,8 +7,8 @@
// 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 client functions (DELEGATE
-// PATTERN) — this module has no queue/cron of its own, so there is no
-// `ctx.services.client`, same as `user`/`conversation`.
+// PATTERN). `ctx.services.client` carries this module's factory the same as
+// every other module now (M10-004).
//
// The permission ladder itself is bound once, in auth.service.ts (M10-002);
// every procedure here reaches it through `ctx.services.auth`.
@@ -16,13 +16,6 @@
import { z } from 'zod';
import { createTRPCRouter, procedure } from '../../rpc/base';
import { TRPCAccessError, TRPCForbiddenError } from '../../rpc/errors';
-import {
- createClientForOrganization,
- deleteClientForOrganization,
- getClientById,
- getClientsByProjectId,
- updateClientForOrganization,
-} from './client.service';
function requireLogin(userId: string | null | undefined): string {
if (!userId) {
@@ -34,10 +27,10 @@ function requireLogin(userId: string | null | undefined): string {
export const clientRouter = createTRPCRouter({
list: procedure
.input(z.object({ projectId: z.string() }))
- .query(async ({ input }) => {
+ .query(async ({ input, ctx }) => {
// Ported verbatim: V1's `client.list` reads by projectId with no
// access check of its own (packages/trpc/src/routers/client.ts).
- return getClientsByProjectId(input.projectId);
+ return ctx.services.client.getClientsByProjectId(input.projectId);
}),
update: procedure
@@ -52,14 +45,16 @@ export const clientRouter = createTRPCRouter({
throw new TRPCForbiddenError('You do not have access to this client');
}
- const client = await getClientById(input.id);
+ const client = await ctx.services.client.getClientById(input.id);
if (!client) {
throw new TRPCForbiddenError('Client not found');
}
- return updateClientForOrganization(input.id, client.organizationId, {
- name: input.name,
- });
+ return ctx.services.client.updateClientForOrganization(
+ input.id,
+ client.organizationId,
+ { name: input.name }
+ );
}),
create: procedure
@@ -82,11 +77,14 @@ export const clientRouter = createTRPCRouter({
message: 'Only organization admins can create API clients',
});
- const created = await createClientForOrganization(input.organizationId, {
- name: input.name,
- projectId: input.projectId,
- type: input.type,
- });
+ const created = await ctx.services.client.createClientForOrganization(
+ input.organizationId,
+ {
+ name: input.name,
+ projectId: input.projectId,
+ type: input.type,
+ }
+ );
if (!created) {
throw new TRPCForbiddenError(
@@ -101,7 +99,7 @@ export const clientRouter = createTRPCRouter({
.input(z.object({ id: z.string() }))
.mutation(async ({ input, ctx }) => {
const userId = requireLogin(ctx.session.userId);
- const client = await getClientById(input.id);
+ const client = await ctx.services.client.getClientById(input.id);
if (!client?.organizationId) {
throw new TRPCForbiddenError('You do not have access to this client');
@@ -114,7 +112,10 @@ export const clientRouter = createTRPCRouter({
message: 'Only organization admins can delete API clients',
});
- await deleteClientForOrganization(input.id, client.organizationId);
+ await ctx.services.client.deleteClientForOrganization(
+ input.id,
+ client.organizationId
+ );
return true;
}),
});
diff --git a/packages/core/src/modules/client/client.service.test.ts b/packages/core/src/modules/client/client.service.test.ts
index a7f6a1a10..0fac4e62a 100644
--- a/packages/core/src/modules/client/client.service.test.ts
+++ b/packages/core/src/modules/client/client.service.test.ts
@@ -1,8 +1,10 @@
-// client.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-004), so
+// Postgres needs no module mock at all — `deps.db` IS the fake below, same
+// idiom as reference.service.test.ts. `@openpanel/redis` is still stubbed:
+// `getClientByIdCached` calls `cacheable(...)` inside `createClientService`
+// itself now (not at this module's import time), but the binding is
+// resolved at `client.service.ts`'s own import time, so the mock must still
+// land before that import — hence the `await import` in `beforeAll`.
import { beforeAll, beforeEach, expect, mock, test } from 'bun:test';
@@ -135,15 +137,12 @@ mock.module('@openpanel/redis', () => ({
}),
}));
-const actualPrismaClient = await import('@openpanel/db/src/prisma-client');
-mock.module('@openpanel/db/src/prisma-client', () => ({
- ...actualPrismaClient,
- db: { project, client },
-}));
-
-let subject: typeof import('./client.service');
+let subject: import('./client.service').ClientService;
beforeAll(async () => {
- subject = await import('./client.service');
+ const { createClientService } = await import('./client.service');
+ subject = createClientService({
+ db: { project, client },
+ } as unknown as import('../../services').ServiceDeps);
});
beforeEach(() => {
diff --git a/packages/core/src/modules/client/client.service.ts b/packages/core/src/modules/client/client.service.ts
index d5b36d174..4b7a751cb 100644
--- a/packages/core/src/modules/client/client.service.ts
+++ b/packages/core/src/modules/client/client.service.ts
@@ -10,15 +10,26 @@
// too, so V1's controller and core's own client.routes.ts share one
// implementation (DELEGATE PATTERN).
//
-// db access is LAZY (`loadDb` below), not a static top-level import — see
-// project.service.ts's header for the full reasoning. No dependency on
+// M10-004: every function takes `ServiceDeps` and reaches Postgres as
+// `deps.db`; the `loadDb()` lazy loader is gone. No dependency on
// project.service.ts here (the reverse direction exists, for cache
// invalidation) — project-ownership checks below query `db.project`
// directly, matching V1's manage.controller.ts exactly.
+//
+// `getClientByIdCached` lives INSIDE `createClientService(deps)` rather than
+// at module scope: its `cacheable(...)` L1 LRU must survive across calls to
+// stay useful, which only holds if the closure it is built in is a
+// singleton. `ctx.services.client` is one Ctx per request, so this cache is
+// only actually a cross-call singleton through the v1-compat seam
+// (`registered`, built exactly once at boot) — see v1-compat.ts's header —
+// which is what `ingest/src/client-auth.ts`, `http/client-auth.ts` and
+// `mcp/src/auth.ts` read through, on the ingest hot path, with no `Ctx` of
+// their own to carry `ServiceDeps`.
import crypto from 'node:crypto';
import type { Client, Prisma } from '@openpanel/db/src/prisma-client';
import { cacheable } from '@openpanel/redis';
+import type { ServiceDeps } from '../../services';
import { hashPassword } from '../auth/auth.service';
export type IServiceClient = Client;
@@ -28,13 +39,13 @@ export type IServiceClientWithProject = Prisma.ClientGetPayload<{
};
}>;
-function loadDb() {
- return import('@openpanel/db/src/prisma-client').then((m) => m.db);
-}
+const FIVE_MINUTES_IN_SECONDS = 60 * 5;
-export async function getClientsByOrganizationId(organizationId: string) {
- const db = await loadDb();
- return db.client.findMany({
+export async function getClientsByOrganizationId(
+ deps: ServiceDeps,
+ organizationId: string
+) {
+ return deps.db.client.findMany({
where: {
organizationId,
},
@@ -48,9 +59,11 @@ export async function getClientsByOrganizationId(organizationId: string) {
}
/** trpc client.list — no access check of its own, ported verbatim. */
-export async function getClientsByProjectId(projectId: string) {
- const db = await loadDb();
- return db.client.findMany({
+export async function getClientsByProjectId(
+ deps: ServiceDeps,
+ projectId: string
+) {
+ return deps.db.client.findMany({
where: {
projectId,
},
@@ -58,10 +71,10 @@ export async function getClientsByProjectId(projectId: string) {
}
export async function getClientById(
+ deps: ServiceDeps,
id: string
): Promise<IServiceClientWithProject | null> {
- const db = await loadDb();
- return db.client.findUnique({
+ return deps.db.client.findUnique({
where: { id },
include: {
project: true,
@@ -69,22 +82,15 @@ export async function getClientById(
});
}
-const FIVE_MINUTES_IN_SECONDS = 60 * 5;
-export const getClientByIdCached = cacheable(
- getClientById,
- FIVE_MINUTES_IN_SECONDS
-);
-
// --- /manage REST CRUD (apps/api/src/controllers/manage.controller.ts) ---
export async function listClientsForOrganization(
+ deps: ServiceDeps,
organizationId: string,
projectId?: string
) {
- const db = await loadDb();
-
if (projectId) {
- const project = await db.project.findFirst({
+ const project = await deps.db.project.findFirst({
where: { id: projectId, organizationId },
});
if (!project) {
@@ -92,7 +98,7 @@ export async function listClientsForOrganization(
}
}
- return db.client.findMany({
+ return deps.db.client.findMany({
where: {
organizationId,
...(projectId ? { projectId } : {}),
@@ -104,11 +110,11 @@ export async function listClientsForOrganization(
}
export async function getClientForOrganization(
+ deps: ServiceDeps,
id: string,
organizationId: string
) {
- const db = await loadDb();
- return db.client.findFirst({
+ return deps.db.client.findFirst({
where: {
id,
organizationId,
@@ -121,87 +127,147 @@ export interface CreatedClient {
secret: string;
}
-export async function createClientForOrganization(
- organizationId: string,
- input: {
- name: string;
- projectId?: string | null;
- type?: 'read' | 'write' | 'root';
- }
-): Promise<CreatedClient | null> {
- const db = await loadDb();
+export interface ClientService {
+ getClientsByOrganizationId(
+ organizationId: string
+ ): ReturnType<typeof getClientsByOrganizationId>;
+ getClientsByProjectId(
+ projectId: string
+ ): ReturnType<typeof getClientsByProjectId>;
+ getClientById(id: string): ReturnType<typeof getClientById>;
+ getClientByIdCached(id: string): Promise<IServiceClientWithProject | null>;
+ /** Invalidates a single id in `getClientByIdCached`'s L1 LRU + Redis. Its
+ * own create/update/delete already call this; `project.service.ts`
+ * reaches it too, through the v1-compat singleton, to invalidate a
+ * project's clients on a project mutation — see that file's header. */
+ clearClientByIdCache(id: string): Promise<number>;
+ listClientsForOrganization(
+ organizationId: string,
+ projectId?: string
+ ): ReturnType<typeof listClientsForOrganization>;
+ getClientForOrganization(
+ id: string,
+ organizationId: string
+ ): ReturnType<typeof getClientForOrganization>;
+ createClientForOrganization(
+ organizationId: string,
+ input: {
+ name: string;
+ projectId?: string | null;
+ type?: 'read' | 'write' | 'root';
+ }
+ ): Promise<CreatedClient | null>;
+ updateClientForOrganization(
+ id: string,
+ organizationId: string,
+ input: { name?: string }
+ ): Promise<IServiceClient | null>;
+ deleteClientForOrganization(
+ id: string,
+ organizationId: string
+ ): Promise<boolean>;
+}
- if (input.projectId) {
- const project = await db.project.findFirst({
- where: { id: input.projectId, organizationId },
- });
- if (!project) {
- return null;
+export function createClientService(deps: ServiceDeps): ClientService {
+ /** L1 LRU (60s) + L2 Redis. clear() invalidates Redis + local LRU; other nodes may serve stale from LRU for up to 60s. */
+ const getClientByIdCached = cacheable(
+ (id: string) => getClientById(deps, id),
+ FIVE_MINUTES_IN_SECONDS
+ );
+
+ async function createClientForOrganization(
+ organizationId: string,
+ input: {
+ name: string;
+ projectId?: string | null;
+ type?: 'read' | 'write' | 'root';
+ }
+ ): Promise<CreatedClient | null> {
+ if (input.projectId) {
+ const project = await deps.db.project.findFirst({
+ where: { id: input.projectId, organizationId },
+ });
+ if (!project) {
+ return null;
+ }
}
- }
- const secret = `sec_${crypto.randomBytes(10).toString('hex')}`;
- const client = await db.client.create({
- data: {
- organizationId,
- projectId: input.projectId || null,
- name: input.name,
- type: input.type || 'write',
- secret: await hashPassword(secret),
- },
- });
+ const secret = `sec_${crypto.randomBytes(10).toString('hex')}`;
+ const client = await deps.db.client.create({
+ data: {
+ organizationId,
+ projectId: input.projectId || null,
+ name: input.name,
+ type: input.type || 'write',
+ secret: await hashPassword(secret),
+ },
+ });
- await getClientByIdCached.clear(client.id);
+ await getClientByIdCached.clear(client.id);
- return { client, secret };
-}
+ return { client, secret };
+ }
-export async function updateClientForOrganization(
- id: string,
- organizationId: string,
- input: { name?: string }
-): Promise<IServiceClient | null> {
- const db = await loadDb();
+ async function updateClientForOrganization(
+ id: string,
+ organizationId: string,
+ input: { name?: string }
+ ): Promise<IServiceClient | null> {
+ const existing = await deps.db.client.findFirst({
+ where: { id, organizationId },
+ });
- const existing = await db.client.findFirst({
- where: { id, organizationId },
- });
+ if (!existing) {
+ return null;
+ }
- if (!existing) {
- return null;
- }
+ const updateData: Prisma.ClientUpdateInput = {};
+ if (input.name !== undefined) {
+ updateData.name = input.name;
+ }
- const updateData: Prisma.ClientUpdateInput = {};
- if (input.name !== undefined) {
- updateData.name = input.name;
- }
+ const client = await deps.db.client.update({
+ where: { id },
+ data: updateData,
+ });
- const client = await db.client.update({
- where: { id },
- data: updateData,
- });
+ await getClientByIdCached.clear(client.id);
- await getClientByIdCached.clear(client.id);
+ return client;
+ }
- return client;
-}
+ async function deleteClientForOrganization(
+ id: string,
+ organizationId: string
+ ): Promise<boolean> {
+ const client = await deps.db.client.findFirst({
+ where: { id, organizationId },
+ });
-export async function deleteClientForOrganization(
- id: string,
- organizationId: string
-): Promise<boolean> {
- const db = await loadDb();
+ if (!client) {
+ return false;
+ }
- const client = await db.client.findFirst({
- where: { id, organizationId },
- });
+ await deps.db.client.delete({ where: { id } });
+ await getClientByIdCached.clear(id);
- if (!client) {
- return false;
+ return true;
}
- await db.client.delete({ where: { id } });
- await getClientByIdCached.clear(id);
-
- return true;
+ return {
+ getClientsByOrganizationId: (organizationId) =>
+ getClientsByOrganizationId(deps, organizationId),
+ getClientsByProjectId: (projectId) =>
+ getClientsByProjectId(deps, projectId),
+ getClientById: (id) => getClientById(deps, id),
+ getClientByIdCached: (id) => getClientByIdCached(id),
+ clearClientByIdCache: (id) => getClientByIdCached.clear(id),
+ listClientsForOrganization: (organizationId, projectId) =>
+ listClientsForOrganization(deps, organizationId, projectId),
+ getClientForOrganization: (id, organizationId) =>
+ getClientForOrganization(deps, id, organizationId),
+ createClientForOrganization,
+ updateClientForOrganization,
+ deleteClientForOrganization,
+ };
}
diff --git a/packages/core/src/modules/cohort/cohort.jobs.test.ts b/packages/core/src/modules/cohort/cohort.jobs.test.ts
index bb4ac2bc0..4357360a5 100644
--- a/packages/core/src/modules/cohort/cohort.jobs.test.ts
+++ b/packages/core/src/modules/cohort/cohort.jobs.test.ts
@@ -50,6 +50,14 @@ function stubJobCtx(cohort: Partial<CohortService>, jobName = 'test'): JobCtx {
export: {} as Services['export'],
share: {} as Services['share'],
reference: {} as Services['reference'],
+ client: {} as Services['client'],
+ project: {} as Services['project'],
+ user: {} as Services['user'],
+ subscription: {} as Services['subscription'],
+ salt: {} as Services['salt'],
+ conversation: {} as Services['conversation'],
+ assistant: {} as Services['assistant'],
+ mcp: {} as Services['mcp'],
};
return {
db: {} as AppDeps['db'],
diff --git a/packages/core/src/modules/conversation/conversation.rpc.ts b/packages/core/src/modules/conversation/conversation.rpc.ts
index fa3ebf40e..71ee750b1 100644
--- a/packages/core/src/modules/conversation/conversation.rpc.ts
+++ b/packages/core/src/modules/conversation/conversation.rpc.ts
@@ -7,8 +7,8 @@
// 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 conversation functions
-// (DELEGATE PATTERN) — this module has no queue/ClickHouse compute of its
-// own, so there is no `ctx.services.conversation`, same as `assistant`.
+// (DELEGATE PATTERN). `ctx.services.conversation` carries this module's
+// factory the same as every other module now (M10-004).
//
// The per-project access ladder itself IS shared: `./src/access.ts` binds
// core's shared/access.ts ladder to @openpanel/db's real lookups, the same
@@ -17,12 +17,7 @@
import { z } from 'zod';
import { createTRPCRouter, procedure } from '../../rpc/base';
import { TRPCAccessError, TRPCNotFoundError } from '../../rpc/errors';
-import {
- deleteConversation,
- getConversationById,
- listConversations,
- upsertConversationTitle,
-} from './conversation.service';
+import { getOrganizationByProjectIdCached } from '../organization/organization.service';
const LIST_LIMIT_MIN = 1;
const LIST_LIMIT_MAX = 200;
@@ -30,10 +25,6 @@ const LIST_LIMIT_DEFAULT = 50;
const TITLE_MIN_LENGTH = 1;
const TITLE_MAX_LENGTH = 80;
-function loadOrganizationService() {
- return import('@openpanel/core');
-}
-
function requireLogin(userId: string | null | undefined): string {
if (!userId) {
throw new TRPCAccessError('Not authenticated');
@@ -69,7 +60,7 @@ export const conversationRouter = createTRPCRouter({
level: 'read',
});
- return listConversations({
+ return ctx.services.conversation.listConversations({
projectId: input.projectId,
userId,
limit: input.limit,
@@ -80,7 +71,10 @@ export const conversationRouter = createTRPCRouter({
.input(z.object({ id: z.string() }))
.query(async ({ input, ctx }) => {
const userId = requireLogin(ctx.session.userId);
- const conv = await getConversationById(input.id, { withMessages: true });
+ const conv = await ctx.services.conversation.getConversationById(
+ input.id,
+ { withMessages: true }
+ );
if (!conv || conv.userId !== userId) {
throw new TRPCNotFoundError('Conversation not found');
}
@@ -111,7 +105,9 @@ export const conversationRouter = createTRPCRouter({
// If the conversation already exists, enforce ownership. If it
// doesn't, verify the caller has access to the project being
// created under before letting the upsert create a fresh row.
- const conv = await getConversationById(input.id);
+ const conv = await ctx.services.conversation.getConversationById(
+ input.id
+ );
if (conv) {
if (conv.userId !== userId) {
throw new TRPCNotFoundError('Conversation not found');
@@ -128,8 +124,6 @@ export const conversationRouter = createTRPCRouter({
// client-supplied value here, even if the caller has access to
// the project (they'd still be able to tag the conversation with
// an unrelated org id).
- const { getOrganizationByProjectIdCached } =
- await loadOrganizationService();
const organization = await getOrganizationByProjectIdCached(
input.projectId
);
@@ -137,7 +131,7 @@ export const conversationRouter = createTRPCRouter({
throw new TRPCNotFoundError('Project not found');
}
- return upsertConversationTitle({
+ return ctx.services.conversation.upsertConversationTitle({
id: input.id,
title: input.title,
projectId: input.projectId,
@@ -150,11 +144,13 @@ export const conversationRouter = createTRPCRouter({
.input(z.object({ id: z.string() }))
.mutation(async ({ input, ctx }) => {
const userId = requireLogin(ctx.session.userId);
- const conv = await getConversationById(input.id);
+ const conv = await ctx.services.conversation.getConversationById(
+ input.id
+ );
if (!conv || conv.userId !== userId) {
throw new TRPCNotFoundError('Conversation not found');
}
- await deleteConversation(input.id);
+ await ctx.services.conversation.deleteConversation(input.id);
return { success: true };
}),
});
diff --git a/packages/core/src/modules/conversation/conversation.service.test.ts b/packages/core/src/modules/conversation/conversation.service.test.ts
index 2d766ef0b..b16d0062e 100644
--- a/packages/core/src/modules/conversation/conversation.service.test.ts
+++ b/packages/core/src/modules/conversation/conversation.service.test.ts
@@ -1,10 +1,10 @@
-// conversation.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-004), so
+// Postgres needs no module mock at all — `deps.db` IS the fake below, same
+// idiom as reference.service.test.ts.
-import { beforeAll, beforeEach, expect, mock, test } from 'bun:test';
+import { beforeEach, expect, mock, test } from 'bun:test';
+import type { ServiceDeps } from '../../services';
+import { createConversationService } from './conversation.service';
interface FakeConversation {
id: string;
@@ -101,16 +101,9 @@ const conversation = {
}),
};
-const actualPrismaClient = await import('@openpanel/db/src/prisma-client');
-mock.module('@openpanel/db/src/prisma-client', () => ({
- ...actualPrismaClient,
+const subject = createConversationService({
db: { conversation },
-}));
-
-let subject: typeof import('./conversation.service');
-beforeAll(async () => {
- subject = await import('./conversation.service');
-});
+} as unknown as ServiceDeps);
beforeEach(() => {
conversationStore.clear();
diff --git a/packages/core/src/modules/conversation/conversation.service.ts b/packages/core/src/modules/conversation/conversation.service.ts
index e0c10d939..2d481e521 100644
--- a/packages/core/src/modules/conversation/conversation.service.ts
+++ b/packages/core/src/modules/conversation/conversation.service.ts
@@ -3,17 +3,15 @@
// apps/api's live chat route and this package's own assistant.routes.ts stub
// both still reach these through `@openpanel/db`'s barrel.
//
-// 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-004: every function takes `ServiceDeps` and reaches Postgres as
+// `deps.db`; the `loadDb()` lazy loader is gone.
import type {
ChatMessage,
Conversation,
Prisma,
} from '@openpanel/db/src/prisma-client';
+import type { ServiceDeps } from '../../services';
export type IServiceConversation = Conversation;
export type IServiceChatMessage = ChatMessage;
@@ -23,33 +21,31 @@ export type IServiceConversationWithMessages = Prisma.ConversationGetPayload<{
const DEFAULT_LIST_LIMIT = 50;
-function loadDb() {
- return import('@openpanel/db/src/prisma-client').then((m) => m.db);
-}
-
export async function getConversationById(
+ deps: ServiceDeps,
id: string,
options: { withMessages?: boolean } = {}
): Promise<IServiceConversation | IServiceConversationWithMessages | null> {
- const db = await loadDb();
if (options.withMessages) {
- return db.conversation.findUnique({
+ return deps.db.conversation.findUnique({
where: { id },
include: {
messages: { orderBy: { createdAt: 'asc' } },
},
});
}
- return db.conversation.findUnique({ where: { id } });
+ return deps.db.conversation.findUnique({ where: { id } });
}
-export async function listConversations(input: {
- projectId: string;
- userId: string;
- limit?: number;
-}): Promise<IServiceConversation[]> {
- const db = await loadDb();
- return db.conversation.findMany({
+export async function listConversations(
+ deps: ServiceDeps,
+ input: {
+ projectId: string;
+ userId: string;
+ limit?: number;
+ }
+): Promise<IServiceConversation[]> {
+ return deps.db.conversation.findMany({
where: {
projectId: input.projectId,
userId: input.userId,
@@ -67,15 +63,17 @@ export async function listConversations(input: {
* This upsert makes that race harmless — the row ends up with the
* right owner + title regardless of which side finishes first.
*/
-export async function upsertConversationTitle(input: {
- id: string;
- title: string;
- projectId: string;
- organizationId: string;
- userId: string;
-}): Promise<IServiceConversation> {
- const db = await loadDb();
- return db.conversation.upsert({
+export async function upsertConversationTitle(
+ deps: ServiceDeps,
+ input: {
+ id: string;
+ title: string;
+ projectId: string;
+ organizationId: string;
+ userId: string;
+ }
+): Promise<IServiceConversation> {
+ return deps.db.conversation.upsert({
where: { id: input.id },
create: {
id: input.id,
@@ -88,7 +86,35 @@ export async function upsertConversationTitle(input: {
});
}
-export async function deleteConversation(id: string): Promise<void> {
- const db = await loadDb();
- await db.conversation.delete({ where: { id } });
+export async function deleteConversation(
+ deps: ServiceDeps,
+ id: string
+): Promise<void> {
+ await deps.db.conversation.delete({ where: { id } });
+}
+
+export interface ConversationService {
+ getConversationById(
+ id: string,
+ options?: { withMessages?: boolean }
+ ): ReturnType<typeof getConversationById>;
+ listConversations(
+ input: Parameters<typeof listConversations>[1]
+ ): Promise<IServiceConversation[]>;
+ upsertConversationTitle(
+ input: Parameters<typeof upsertConversationTitle>[1]
+ ): Promise<IServiceConversation>;
+ deleteConversation(id: string): Promise<void>;
+}
+
+export function createConversationService(
+ deps: ServiceDeps
+): ConversationService {
+ return {
+ getConversationById: (id, options) =>
+ getConversationById(deps, id, options),
+ listConversations: (input) => listConversations(deps, input),
+ upsertConversationTitle: (input) => upsertConversationTitle(deps, input),
+ deleteConversation: (id) => deleteConversation(deps, id),
+ };
}
diff --git a/packages/core/src/modules/dashboard/dashboard.service.ts b/packages/core/src/modules/dashboard/dashboard.service.ts
index 1f7eee291..1a1692c03 100644
--- a/packages/core/src/modules/dashboard/dashboard.service.ts
+++ b/packages/core/src/modules/dashboard/dashboard.service.ts
@@ -95,7 +95,7 @@ export async function createDashboard(
projectId: string;
}
): Promise<Dashboard> {
- const project = await getProjectById(input.projectId);
+ const project = await getProjectById(deps, input.projectId);
if (!project) {
throw new TRPCNotFoundError('Project not found');
diff --git a/packages/core/src/modules/export/export.service.ts b/packages/core/src/modules/export/export.service.ts
index 66a2e3146..f6059494b 100644
--- a/packages/core/src/modules/export/export.service.ts
+++ b/packages/core/src/modules/export/export.service.ts
@@ -18,7 +18,16 @@ import type { AuthenticatedClient } from '../../http/client-auth';
import type { ServiceDeps } from '../../services';
import { getChartStartEndDate, resolveDateRange } from '../../shared/date';
import { getSettingsForProject } from '../organization/organization.service';
-import { resolveClientProjectId } from '../project/project.service';
+
+// project.service.ts's `resolveClientProjectId` takes `ServiceDeps` now
+// (M10-004); `resolveInsightsProjectId` below is called from ~35 route
+// handlers in export.routes.ts with no `deps` in their own signature, so it
+// reaches the bare, v1-compat-wrapped spelling instead of threading `deps`
+// through every one of them. GENUINE CYCLE, kept lazy: services.ts ->
+// export.service.ts (this file) -> v1-compat.ts -> services.ts.
+function loadProjectService() {
+ return import('../../v1-compat');
+}
export type ProjectIdResolution =
| { ok: true; projectId: string }
@@ -75,10 +84,11 @@ 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 function resolveInsightsProjectId(
+export async function resolveInsightsProjectId(
client: AuthenticatedClient,
params: { projectId?: string }
): Promise<string> {
+ const { resolveClientProjectId } = await loadProjectService();
return resolveClientProjectId({
clientType: client.type === 'root' ? 'root' : 'read',
clientProjectId: client.projectId,
diff --git a/packages/core/src/modules/gsc/gsc.jobs.test.ts b/packages/core/src/modules/gsc/gsc.jobs.test.ts
index f01757cba..81d9eed95 100644
--- a/packages/core/src/modules/gsc/gsc.jobs.test.ts
+++ b/packages/core/src/modules/gsc/gsc.jobs.test.ts
@@ -46,6 +46,14 @@ function stubJobCtx(gsc: Partial<GscService>, jobName = 'test'): JobCtx {
export: {} as Services['export'],
share: {} as Services['share'],
reference: {} as Services['reference'],
+ client: {} as Services['client'],
+ project: {} as Services['project'],
+ user: {} as Services['user'],
+ subscription: {} as Services['subscription'],
+ salt: {} as Services['salt'],
+ conversation: {} as Services['conversation'],
+ assistant: {} as Services['assistant'],
+ mcp: {} as Services['mcp'],
};
return {
db: {} as AppDeps['db'],
@@ -158,6 +166,14 @@ test('gscSync fans out one gscProjectSync enqueue per connected project', async
export: {} as Services['export'],
share: {} as Services['share'],
reference: {} as Services['reference'],
+ client: {} as Services['client'],
+ project: {} as Services['project'],
+ user: {} as Services['user'],
+ subscription: {} as Services['subscription'],
+ salt: {} as Services['salt'],
+ conversation: {} as Services['conversation'],
+ assistant: {} as Services['assistant'],
+ mcp: {} as Services['mcp'],
},
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.ts
index 201eb78b3..5c842a6dc 100644
--- a/packages/core/src/modules/import/import.jobs.test.ts
+++ b/packages/core/src/modules/import/import.jobs.test.ts
@@ -46,6 +46,14 @@ function stubJobCtx(importService: Partial<ImportService>): JobCtx {
export: {} as Services['export'],
share: {} as Services['share'],
reference: {} as Services['reference'],
+ client: {} as Services['client'],
+ project: {} as Services['project'],
+ user: {} as Services['user'],
+ subscription: {} as Services['subscription'],
+ salt: {} as Services['salt'],
+ conversation: {} as Services['conversation'],
+ assistant: {} as Services['assistant'],
+ mcp: {} as Services['mcp'],
};
return {
db: {} as AppDeps['db'],
diff --git a/packages/core/src/modules/ingest/ingest.service.test.ts b/packages/core/src/modules/ingest/ingest.service.test.ts
index 8cfc37971..57413ce2b 100644
--- a/packages/core/src/modules/ingest/ingest.service.test.ts
+++ b/packages/core/src/modules/ingest/ingest.service.test.ts
@@ -56,15 +56,17 @@ let getOverrideDeviceId: typeof import('./ingest.service').getOverrideDeviceId;
let handleReplay: typeof import('./ingest.service').handleReplay;
let ingestTrack: typeof import('./ingest.service').ingestTrack;
-// The profile and salt modules are spread and then overridden by name:
-// event.service imports more of profile.service than ingest.service does
-// (and salt.service exports fetchSalts/createInitialSalts/rotateSalt besides
-// getSalts), so a factory returning only the overrides makes the rest vanish
-// under `--isolate`. Overriding `identifyProfile` (not just `upsertProfile`)
-// is what keeps the identify path off Postgres and the profile buffer —
-// profile.service calls its own local `upsertProfile`, not the exported
-// binding.
-let realSaltService: typeof import('../salt/salt.service');
+// The profile module is spread and then overridden by name: event.service
+// imports more of profile.service than ingest.service does. Overriding
+// `identifyProfile` (not just `upsertProfile`) is what keeps the identify
+// path off Postgres and the profile buffer — profile.service calls its own
+// local `upsertProfile`, not the exported binding.
+//
+// M10-004: ingest.service.ts reaches `getSalts` through the v1-compat
+// singleton (salt.service.ts's own cache now lives inside
+// `createSaltService(deps)`, not at module scope — see both files' headers),
+// so that's the specifier mocked here, spread-actual like the rest.
+let realV1Compat: typeof import('../../v1-compat');
beforeAll(async () => {
const profile = await import('../profile/profile.service');
mock.module('../profile/profile.service', () => ({
@@ -73,21 +75,15 @@ beforeAll(async () => {
upsertProfile,
getProfileById,
}));
- realSaltService = { ...(await import('../salt/salt.service')) };
- mock.module('../salt/salt.service', () => ({ ...realSaltService, getSalts }));
+ realV1Compat = { ...(await import('../../v1-compat')) };
+ mock.module('../../v1-compat', () => ({ ...realV1Compat, getSalts }));
({ getOverrideDeviceId, handleReplay, ingestTrack } = await import(
'./ingest.service'
));
});
-// salt.service.ts's own rotateSalt calls the exported `getSalts` internally
-// (to invalidate its cache), so leaving this file's fake `getSalts` — which
-// has no `.clear()` — in the module registry after these tests finish breaks
-// salt.service.test.ts's own `rotateSalt` assertions under a bare (non
-// `--isolate`) `bun test` run, which shares one module registry across every
-// file in the run.
afterAll(() => {
- mock.module('../salt/salt.service', () => realSaltService);
+ mock.module('../../v1-compat', () => realV1Compat);
});
const track = (properties?: Record<string, unknown>): ITrackHandlerPayload =>
diff --git a/packages/core/src/modules/ingest/ingest.service.ts b/packages/core/src/modules/ingest/ingest.service.ts
index 91e8c60e5..b853566ce 100644
--- a/packages/core/src/modules/ingest/ingest.service.ts
+++ b/packages/core/src/modules/ingest/ingest.service.ts
@@ -36,7 +36,21 @@ import {
identifyProfile,
upsertProfile,
} from '../profile/profile.service';
-import { getSalts } from '../salt/salt.service';
+
+// M10-004: salt.service.ts's `getSalts` moved inside `createSaltService(deps)`
+// so its LRU survives across calls; this hot path has no `Ctx` to reach
+// `ctx.services.salt` from, so it reads the v1-compat singleton instead — see
+// v1-compat.ts's header and salt.service.ts's. GENUINE CYCLE, kept lazy:
+// services.ts -> ingest.service.ts (this file) -> v1-compat.ts -> services.ts;
+// the dynamic import is what keeps it a cycle ESM can evaluate, same as
+// auth.service.ts's `loadShare()`.
+function loadSalt() {
+ return import('../../v1-compat');
+}
+function getSalts() {
+ return loadSalt().then((m) => m.getSalts());
+}
+
import { convertClickhouseDateToJs } from '../session/src/dates';
import type {
DeprecatedPostEventPayload,
diff --git a/packages/core/src/modules/ingest/legacy-event.test.ts b/packages/core/src/modules/ingest/legacy-event.test.ts
index a031d5492..b0c95a46b 100644
--- a/packages/core/src/modules/ingest/legacy-event.test.ts
+++ b/packages/core/src/modules/ingest/legacy-event.test.ts
@@ -60,22 +60,20 @@ mock.module('../../clients/geo', () => ({ getGeoLocation, getAsnInfo }));
let ingestLegacyEvent: typeof import('./ingest.service').ingestLegacyEvent;
-// The salt module is spread and then overridden by name: it exports
-// fetchSalts/createInitialSalts/rotateSalt besides getSalts, so a factory
-// returning only the override makes the rest vanish.
-let realSaltService: typeof import('../salt/salt.service');
+// M10-004: ingest.service.ts reaches `getSalts` through the v1-compat
+// singleton now (salt.service.ts's own cache moved inside
+// `createSaltService(deps)` — see both files' headers), so that's the
+// specifier mocked here, spread-actual like everywhere else this seam is
+// overridden.
+let realV1Compat: typeof import('../../v1-compat');
beforeAll(async () => {
- realSaltService = { ...(await import('../salt/salt.service')) };
- mock.module('../salt/salt.service', () => ({ ...realSaltService, getSalts }));
+ realV1Compat = { ...(await import('../../v1-compat')) };
+ mock.module('../../v1-compat', () => ({ ...realV1Compat, getSalts }));
({ ingestLegacyEvent } = await import('./ingest.service'));
});
-// salt.service.ts's own rotateSalt calls the exported `getSalts` internally (to
-// invalidate its cache), so leaving this file's fake — which has no `.clear()`
-// — in the module registry breaks salt.service.test.ts under a bare (non
-// `--isolate`) `bun test`, which shares one registry across the whole run.
afterAll(() => {
- mock.module('../salt/salt.service', () => realSaltService);
+ mock.module('../../v1-compat', () => realV1Compat);
});
const produced: { payload: IncomingEventPayload; partitionKey: string }[] = [];
diff --git a/packages/core/src/modules/ingest/src/client-auth.test.ts b/packages/core/src/modules/ingest/src/client-auth.test.ts
index b8c7b4b65..a8a498018 100644
--- a/packages/core/src/modules/ingest/src/client-auth.test.ts
+++ b/packages/core/src/modules/ingest/src/client-auth.test.ts
@@ -8,7 +8,15 @@
* `request.clientSecretAuth` — the side channel the bot check reads.
*/
-import { beforeAll, beforeEach, describe, expect, it, mock } from 'bun:test';
+import {
+ afterAll,
+ beforeAll,
+ beforeEach,
+ describe,
+ expect,
+ it,
+ mock,
+} from 'bun:test';
const CLIENT_ID = '11111111-1111-4111-8111-111111111111';
const PROJECT_ID = 'legacy-event-project';
@@ -32,7 +40,20 @@ const client = {
const getClientByIdCached = mock(async (_id: string) => client);
-mock.module('../../client/client.service', () => ({ getClientByIdCached }));
+// M10-004: client-auth.ts reaches `getClientByIdCached` through the
+// v1-compat singleton now (its own header explains why) — mocked at that
+// specifier, spread-actual so the rest of the seam (`createServices` et al.,
+// which `services.ts`'s own import of `client.service.ts` still needs) stays
+// intact.
+const realV1Compat = { ...(await import('../../../v1-compat')) };
+mock.module('../../../v1-compat', () => ({
+ ...realV1Compat,
+ getClientByIdCached,
+}));
+
+afterAll(() => {
+ mock.module('../../../v1-compat', () => realV1Compat);
+});
let validateIngestRequest: typeof import('./client-auth').validateIngestRequest;
diff --git a/packages/core/src/modules/ingest/src/client-auth.ts b/packages/core/src/modules/ingest/src/client-auth.ts
index 089b43544..b2c133497 100644
--- a/packages/core/src/modules/ingest/src/client-auth.ts
+++ b/packages/core/src/modules/ingest/src/client-auth.ts
@@ -19,14 +19,20 @@ import type {
} from '@openpanel/validation';
import { path } from 'ramda';
import { verifyPassword } from '../../../shared/crypto';
+import type { IServiceClientWithProject } from '../../client/client.service';
import { headerValue, type IngestHeaders } from './headers';
export type { IngestHeaders } from './headers';
-import {
- getClientByIdCached,
- type IServiceClientWithProject,
-} from '../../client/client.service';
+// M10-004: `getClientByIdCached`'s L1 LRU now lives inside
+// `createClientService(deps)` (see that file's header), reached here through
+// the v1-compat singleton — this ingest hot path has no `Ctx` of its own.
+// GENUINE CYCLE, kept lazy: services.ts -> ingest.service.ts -> this file ->
+// v1-compat.ts -> services.ts; the dynamic import is what keeps it a cycle
+// ESM can evaluate.
+function loadClientService() {
+ return import('../../../v1-compat');
+}
const CLIENT_ID_UUID_REGEX =
/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
@@ -144,7 +150,9 @@ export async function validateIngestRequest({
return refuse('Ingestion: Client ID must be a valid UUIDv4');
}
- const client = await getClientByIdCached(clientId);
+ const client = await (await loadClientService()).getClientByIdCached(
+ clientId
+ );
if (!client) {
return refuse('Ingestion: Invalid client id');
diff --git a/packages/core/src/modules/ingest/src/incoming-event-handler.ts b/packages/core/src/modules/ingest/src/incoming-event-handler.ts
index c7165e444..87dc74c47 100644
--- a/packages/core/src/modules/ingest/src/incoming-event-handler.ts
+++ b/packages/core/src/modules/ingest/src/incoming-event-handler.ts
@@ -30,11 +30,20 @@ import {
type IServiceEvent,
} from '../../event/event.service';
import { matchEvent } from '../../notification/notification.service';
-// Static, not lazy: a dynamic edge into project.service becomes its own
-// rolldown chunk, which stops `hashPassword` (and with it the @node-rs/argon2
-// native addon, external in apps/worker's bundle) from being shaken out of
-// the worker build.
-import { getProjectByIdCached } from '../../project/project.service';
+
+// project.service.ts's `getProjectByIdCached` takes `ServiceDeps` now
+// (M10-004), and its `.clear()` LRU-invalidation must hit the SAME cache
+// instance ingest/http/mcp all read — see that file's header — so this
+// reaches the v1-compat singleton instead. Previously a STATIC import for a
+// rolldown-chunking reason tied to apps/worker's bundle: apps/worker is
+// gone (M9) and apps/api ships with no bundler at all (ADR-010), so that
+// constraint no longer applies — GENUINE CYCLE, kept lazy, same as every
+// other one in this wave: services.ts -> ingest.service.ts -> this file ->
+// v1-compat.ts -> services.ts.
+function loadProjectService() {
+ return import('../../../v1-compat');
+}
+
import type { IClickhouseSession } from '../../session/session.service';
import { sessionEndsEnqueued } from '../../session/src/session.metrics';
import type { EnqueueSessionEndInput } from '../../session/src/session-end';
@@ -110,11 +119,13 @@ export async function loadIncomingEventDeps(
enqueueSessionEnd: (input: EnqueueSessionEndInput) => Promise<unknown>,
overrides: Partial<IncomingEventDeps> = {}
): Promise<IncomingEventDeps> {
- const [{ sessionBuffer }, { db }, notifications] = await Promise.all([
- loadDbBuffers(),
- import('@openpanel/db/src/prisma-client'),
- import('@openpanel/queue/src/notification-dispatch'),
- ]);
+ const [{ sessionBuffer }, { db }, notifications, projectService] =
+ await Promise.all([
+ loadDbBuffers(),
+ import('@openpanel/db/src/prisma-client'),
+ import('@openpanel/queue/src/notification-dispatch'),
+ loadProjectService(),
+ ]);
return {
logger,
sessions: sessionBuffer,
@@ -122,13 +133,13 @@ export async function loadIncomingEventDeps(
checkNotificationRulesForEvent:
notifications.checkNotificationRulesForEvent,
projects: {
- getCached: getProjectByIdCached,
+ getCached: projectService.getProjectByIdCached,
markFirstEvent: async (projectId) => {
await db.project.updateMany({
where: { id: projectId, firstEventAt: null },
data: { firstEventAt: new Date() },
});
- await getProjectByIdCached.clear(projectId);
+ await projectService.clearProjectByIdCache(projectId);
},
},
enqueueSessionEnd,
diff --git a/packages/core/src/modules/insight/insight.jobs.test.ts b/packages/core/src/modules/insight/insight.jobs.test.ts
index 2c0f76b3c..4f87128ad 100644
--- a/packages/core/src/modules/insight/insight.jobs.test.ts
+++ b/packages/core/src/modules/insight/insight.jobs.test.ts
@@ -57,6 +57,14 @@ function stubJobCtx(
export: {} as Services['export'],
share: {} as Services['share'],
reference: {} as Services['reference'],
+ client: {} as Services['client'],
+ project: {} as Services['project'],
+ user: {} as Services['user'],
+ subscription: {} as Services['subscription'],
+ salt: {} as Services['salt'],
+ conversation: {} as Services['conversation'],
+ assistant: {} as Services['assistant'],
+ mcp: {} as Services['mcp'],
};
return {
db: {} as AppDeps['db'],
@@ -152,6 +160,14 @@ test('insightsDaily fans out one insightsProject enqueue per candidate, jobId de
export: {} as Services['export'],
share: {} as Services['share'],
reference: {} as Services['reference'],
+ client: {} as Services['client'],
+ project: {} as Services['project'],
+ user: {} as Services['user'],
+ subscription: {} as Services['subscription'],
+ salt: {} as Services['salt'],
+ conversation: {} as Services['conversation'],
+ assistant: {} as Services['assistant'],
+ mcp: {} as Services['mcp'],
},
requestId: 'req_1',
job: { id: 'job_1', attempt: 0, queue: 'cron', name: 'insightsDaily' },
diff --git a/packages/core/src/modules/mcp/mcp.routes.ts b/packages/core/src/modules/mcp/mcp.routes.ts
index 7b762e15d..333e92317 100644
--- a/packages/core/src/modules/mcp/mcp.routes.ts
+++ b/packages/core/src/modules/mcp/mcp.routes.ts
@@ -3,10 +3,10 @@
// not yet reachable — main.ts does not mount `dashboardRoutes` until a real
// `AppDeps` exists (P3/P4/P8).
//
-// `mcp.service` is loaded dynamically for the same reason assistant.routes.ts
-// gives for `assistant.service`: a static top-level import here reaches
-// `@openpanel/db`, which races `@openpanel/db`'s own circular
-// `buffers/base-buffer.ts` -> `@openpanel/core` import.
+// `ctx.services.mcp` carries this module's factory the same as every other
+// module now (M10-004) — `mcp.service.ts`'s own header explains why that
+// file is now safe to reach through `ctx.services` instead of this route's
+// former one-off `loadMcpService()`.
//
// Rate limiting (V1: 60/min via Fastify's activateRateLimiter) is not wired
// here yet — nothing reaches this route until dashboardRoutes mounts, so it
@@ -18,23 +18,15 @@
import { defineRoutes } from '../../http/define';
-function loadMcpService() {
- return import('./mcp.service');
-}
-
export const mcpRoutes = defineRoutes((app) =>
- app.post('/mcp', async ({ body, query, request, set }) => {
- const { extractToken, handleStatelessMcpRequest } = await loadMcpService();
-
- const token = extractToken(
+ app.post('/mcp', async ({ body, ctx, query, request, set }) => {
+ const token = ctx.services.mcp.extractToken(
query as Record<string, string>,
request.headers.get('authorization') ?? undefined
);
- const { status, body: responseBody } = await handleStatelessMcpRequest(
- token,
- body
- );
+ const { status, body: responseBody } =
+ await ctx.services.mcp.handleStatelessMcpRequest(token, body);
set.status = status;
return responseBody;
})
diff --git a/packages/core/src/modules/mcp/mcp.service.ts b/packages/core/src/modules/mcp/mcp.service.ts
index 51f074bc1..df87d8f67 100644
--- a/packages/core/src/modules/mcp/mcp.service.ts
+++ b/packages/core/src/modules/mcp/mcp.service.ts
@@ -9,20 +9,45 @@
//
// MCP is the one module the wave map allows to change its endpoint surface —
// every other module in this wave preserves its V1 contract byte-for-byte.
+//
+// M10-004: `createMcpService(deps)` lands here, which means THIS FILE is now
+// statically imported by services.ts. `./src/server`'s `registerAllTools`
+// pulls in ~20 tool files that reach this package's own barrel
+// (`@openpanel/core`) for cross-module functions, so it stays behind a lazy
+// loader — a static top-level import would make services.ts's own module
+// evaluation re-enter that barrel mid-evaluation, the exact TDZ hazard
+// index.ts's header used to document for this file before it was reached
+// only through a dynamic import. `./src/auth` stays a plain static import:
+// `extractToken` is synchronous today (`mcp.routes.ts` doesn't await it) and
+// auth.ts no longer reaches the barrel at its own top level (M10-004, see
+// that file's header) — nothing left to make lazy. `deps` is unused:
+// `handleStatelessMcpRequest`'s signature is a hard contract (its own tests
+// call it with none) and its tool tree already reaches Postgres/ClickHouse
+// through the v1-compat singleton, the same way every other bare, no-`Ctx`
+// caller in this wave does.
import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js';
import type { JSONRPCMessage } from '@modelcontextprotocol/sdk/types.js';
import { createLogger } from '../../clients/logger';
+import type { ServiceDeps } from '../../services';
import {
authenticateToken,
+ extractToken,
type McpAuthContext,
McpAuthError,
} from './src/auth';
-import { createMcpServer } from './src/server';
export type { McpAuthContext } from './src/auth';
export { extractToken, McpAuthError } from './src/auth';
+let _server: Promise<typeof import('./src/server')> | undefined;
+function loadServer() {
+ if (!_server) {
+ _server = import('./src/server');
+ }
+ return _server;
+}
+
const logger = createLogger({ name: 'mcp' });
const MCP_PROTOCOL_VERSION = '2024-11-05';
@@ -91,6 +116,7 @@ async function runOnEphemeralServer(
message: JSONRPCMessage,
isInitializeRequest: boolean
): Promise<JSONRPCMessage> {
+ const { createMcpServer } = await loadServer();
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
const server = createMcpServer(context);
@@ -169,3 +195,21 @@ function logToolResult(
'MCP tool result'
);
}
+
+export interface McpService {
+ extractToken(
+ query: Record<string, unknown>,
+ authHeader: string | undefined
+ ): ReturnType<typeof extractToken>;
+ handleStatelessMcpRequest(
+ token: string | undefined,
+ body: unknown
+ ): Promise<McpHttpResult>;
+}
+
+export function createMcpService(_deps: ServiceDeps): McpService {
+ return {
+ extractToken,
+ handleStatelessMcpRequest,
+ };
+}
diff --git a/packages/core/src/modules/mcp/src/auth.ts b/packages/core/src/modules/mcp/src/auth.ts
index b0c5f1835..52d4d0df1 100644
--- a/packages/core/src/modules/mcp/src/auth.ts
+++ b/packages/core/src/modules/mcp/src/auth.ts
@@ -1,12 +1,20 @@
import { createHash } from 'node:crypto';
-import { getClientByIdCached } from '@openpanel/core';
-import { ClientType } from '@openpanel/db';
import { getCache } from '@openpanel/redis';
import { createLogger } from '../../../clients/logger';
import { verifyPassword } from '../../../shared/crypto';
const logger = createLogger({ name: 'mcp:auth' });
+// GENUINE CYCLE, kept lazy: `mcp.service.ts` statically imports this file
+// (`extractToken` must stay synchronous — its own caller doesn't await it),
+// and this package's barrel (`@openpanel/core`) transitively reaches
+// services.ts, which registers `createMcpService`. services.ts -> mcp.service.ts
+// -> this file -> @openpanel/core (index.ts) -> v1-compat.ts -> services.ts;
+// the dynamic import is what keeps it a cycle ESM can evaluate.
+function loadClientService() {
+ return import('@openpanel/core');
+}
+
export interface McpAuthContext {
/**
* Fixed project ID for read clients.
@@ -80,6 +88,7 @@ export async function authenticateToken(
throw new McpAuthError('Client secret is required');
}
+ const { getClientByIdCached } = await loadClientService();
const client = await getClientByIdCached(clientId);
if (!client) {
logger.warn({ clientId }, 'MCP auth: client not found');
@@ -97,7 +106,7 @@ export async function authenticateToken(
);
}
- if (client.type === ClientType.write) {
+ if (client.type === 'write') {
logger.warn({ clientId }, 'MCP auth: write-only client rejected');
throw new McpAuthError(
'Write-only clients cannot use MCP — use a read or root client'
@@ -125,7 +134,7 @@ export async function authenticateToken(
throw new McpAuthError('Invalid credentials');
}
- const isRoot = client.type === ClientType.root;
+ const isRoot = client.type === 'root';
return {
projectId: isRoot ? null : (client.projectId ?? null),
diff --git a/packages/core/src/modules/mcp/src/tools/analytics/page-performance.test.ts b/packages/core/src/modules/mcp/src/tools/analytics/page-performance.test.ts
index 4b8a638dd..76ce524ef 100644
--- a/packages/core/src/modules/mcp/src/tools/analytics/page-performance.test.ts
+++ b/packages/core/src/modules/mcp/src/tools/analytics/page-performance.test.ts
@@ -1,4 +1,12 @@
-import { beforeAll, beforeEach, describe, expect, it, mock } from 'bun:test';
+import {
+ afterAll,
+ beforeAll,
+ beforeEach,
+ describe,
+ expect,
+ it,
+ mock,
+} from 'bun:test';
const mockGetTopPages = mock();
const mockGetSettingsForProject = mock(() =>
@@ -36,9 +44,26 @@ mock.module('@openpanel/db/src/clickhouse/client', () => ({
let registerPagePerformanceTools: typeof import('./page-performance').registerPagePerformanceTools;
beforeAll(async () => {
+ // `loadCompatCh` (../shared) reaches ClickHouse through v1-compat.ts's
+ // memoized fallback singleton — a process-lifetime cache once resolved,
+ // so an earlier test file's `bun test` (no `--isolate`) run can have
+ // already resolved it against a DIFFERENT `@openpanel/db/src/clickhouse/client`
+ // mock (or none at all). Reset it so this file's own mock above is what
+ // gets picked up.
+ const { resetV1CompatServicesForTests } = await import(
+ '../../../../../v1-compat'
+ );
+ resetV1CompatServicesForTests();
({ registerPagePerformanceTools } = await import('./page-performance'));
});
+afterAll(async () => {
+ const { resetV1CompatServicesForTests } = await import(
+ '../../../../../v1-compat'
+ );
+ resetV1CompatServicesForTests();
+});
+
function makeServer() {
let handler: ((input: unknown) => Promise<unknown>) | null = null;
return {
diff --git a/packages/core/src/modules/mcp/src/tools/analytics/page-performance.ts b/packages/core/src/modules/mcp/src/tools/analytics/page-performance.ts
index e82fc145b..340be9f9f 100644
--- a/packages/core/src/modules/mcp/src/tools/analytics/page-performance.ts
+++ b/packages/core/src/modules/mcp/src/tools/analytics/page-performance.ts
@@ -1,9 +1,9 @@
import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import { getSettingsForProject, PagesService } from '@openpanel/core';
-import { ch } from '@openpanel/db';
import { z } from 'zod';
import type { McpAuthContext } from '../../auth';
import {
+ loadCompatCh,
projectIdSchema,
resolveDateRange,
resolveProjectId,
@@ -73,6 +73,7 @@ export function registerPagePerformanceTools(
// shares one module registry without `--isolate` — see AGENTS.md),
// permanently defeating this file's own mocks whenever the
// integration suite imports it first.
+ const ch = await loadCompatCh();
const pagesService = new PagesService(ch);
const pages = await pagesService.getTopPages({
diff --git a/packages/core/src/modules/mcp/src/tools/analytics/property-values.ts b/packages/core/src/modules/mcp/src/tools/analytics/property-values.ts
index e798a128f..9bf90158d 100644
--- a/packages/core/src/modules/mcp/src/tools/analytics/property-values.ts
+++ b/packages/core/src/modules/mcp/src/tools/analytics/property-values.ts
@@ -1,9 +1,10 @@
import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import { EVENT_COLUMNS } from '@openpanel/core';
-import { ch, clix, TABLE_NAMES } from '@openpanel/db';
import { z } from 'zod';
import type { McpAuthContext } from '../../auth';
import {
+ loadCompatCh,
+ loadCompatChHelpers,
projectIdSchema,
resolveProjectId,
withErrorHandling,
@@ -75,6 +76,10 @@ export function registerPropertyValueTools(
async ({ projectId: inputProjectId, eventName, limit }) =>
withErrorHandling(async () => {
const projectId = await resolveProjectId(context, inputProjectId);
+ const [ch, { clix, TABLE_NAMES }] = await Promise.all([
+ loadCompatCh(),
+ loadCompatChHelpers(),
+ ]);
// GROUP BY rather than DISTINCT so the epv_keys projection can serve
// this (a multi-column DISTINCT cannot be matched against an
// aggregating projection); `name` tie-breaks the ORDER BY so the
@@ -124,6 +129,10 @@ export function registerPropertyValueTools(
async ({ projectId: inputProjectId, eventName, propertyKey, limit }) =>
withErrorHandling(async () => {
const projectId = await resolveProjectId(context, inputProjectId);
+ const [ch, { clix, TABLE_NAMES }] = await Promise.all([
+ loadCompatCh(),
+ loadCompatChHelpers(),
+ ]);
const take = limit ?? DEFAULT_VALUE_LIMIT;
// The MV holds one row per (property, value, day), so the same value
// recurs across the window — dedupe before counting against the limit,
diff --git a/packages/core/src/modules/mcp/src/tools/analytics/reports.ts b/packages/core/src/modules/mcp/src/tools/analytics/reports.ts
index efd83bfc0..291a4d21b 100644
--- a/packages/core/src/modules/mcp/src/tools/analytics/reports.ts
+++ b/packages/core/src/modules/mcp/src/tools/analytics/reports.ts
@@ -8,11 +8,11 @@ import {
getReportsByDashboardId,
getSettingsForProject,
} from '@openpanel/core';
-import { db } from '@openpanel/db';
import { z } from 'zod';
import type { McpAuthContext } from '../../auth';
import { dashboardBaseUrl } from '../dashboard-links';
import {
+ loadCompatDb,
projectIdSchema,
resolveProjectId,
table,
@@ -157,6 +157,7 @@ export function registerReportTools(
async ({ projectId: inputProjectId }) =>
withErrorHandling(async () => {
const projectId = await resolveProjectId(context, inputProjectId);
+ const db = await loadCompatDb();
const dashboards = await db.dashboard.findMany({
where: { projectId },
orderBy: { createdAt: 'desc' },
diff --git a/packages/core/src/modules/mcp/src/tools/dashboard-management.test.ts b/packages/core/src/modules/mcp/src/tools/dashboard-management.test.ts
index ee3f4cdb6..5995c4f76 100644
--- a/packages/core/src/modules/mcp/src/tools/dashboard-management.test.ts
+++ b/packages/core/src/modules/mcp/src/tools/dashboard-management.test.ts
@@ -1,4 +1,12 @@
-import { beforeAll, beforeEach, describe, expect, it, mock } from 'bun:test';
+import {
+ afterAll,
+ beforeAll,
+ beforeEach,
+ describe,
+ expect,
+ it,
+ mock,
+} from 'bun:test';
import { z } from 'zod';
const mockDb = {
@@ -62,11 +70,28 @@ mock.module('@openpanel/core', () => ({
let registerDashboardManagementTools: typeof import('./dashboard-management').registerDashboardManagementTools;
beforeAll(async () => {
+ // `loadCompatDb` (./shared) reaches Postgres through v1-compat.ts's
+ // memoized fallback singleton — a process-lifetime cache once resolved,
+ // so an earlier test file's `bun test` (no `--isolate`) run can have
+ // already resolved it against a DIFFERENT `@openpanel/db/src/prisma-client`
+ // mock (or none at all). Reset it so this file's own mock above is what
+ // gets picked up.
+ const { resetV1CompatServicesForTests } = await import(
+ '../../../../v1-compat'
+ );
+ resetV1CompatServicesForTests();
({ registerDashboardManagementTools } = await import(
'./dashboard-management'
));
});
+afterAll(async () => {
+ const { resetV1CompatServicesForTests } = await import(
+ '../../../../v1-compat'
+ );
+ resetV1CompatServicesForTests();
+});
+
import type { McpAuthContext } from '../auth';
type Handler = (input: any) => Promise<any>;
diff --git a/packages/core/src/modules/mcp/src/tools/dashboard-management.ts b/packages/core/src/modules/mcp/src/tools/dashboard-management.ts
index 140bd615e..25ee0e8f9 100644
--- a/packages/core/src/modules/mcp/src/tools/dashboard-management.ts
+++ b/packages/core/src/modules/mcp/src/tools/dashboard-management.ts
@@ -1,11 +1,16 @@
import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import { getDashboardById, getId, getProjectById } from '@openpanel/core';
-import { db, Prisma } from '@openpanel/db';
import { zReport } from '@openpanel/validation';
import { z } from 'zod';
import type { McpAuthContext } from '../auth';
import { dashboardBaseUrl } from './dashboard-links';
-import { projectIdSchema, resolveProjectId, withErrorHandling } from './shared';
+import {
+ loadCompatDb,
+ loadCompatPrisma,
+ projectIdSchema,
+ resolveProjectId,
+ withErrorHandling,
+} from './shared';
const reportSchema = zReport
.omit({ projectId: true, limit: true, offset: true })
@@ -134,7 +139,11 @@ function reportUrl(
return `${dashboardBaseUrl()}/${organizationId}/${projectId}/reports/${reportId}`;
}
-function reportData(report: z.infer<typeof reportSchema>) {
+// `dbNull` is `Prisma.DbNull` (an explicit SQL NULL on a nullable Json
+// column), threaded in as `unknown` rather than importing `@openpanel/db`
+// here — same shape notification.service.ts's `isValidPayload` uses for the
+// same sentinel. Callers resolve it via `loadCompatPrisma()` (./shared).
+function reportData(report: z.infer<typeof reportSchema>, dbNull: unknown) {
return {
name: report.name,
events: report.series,
@@ -148,7 +157,7 @@ function reportData(report: z.infer<typeof reportSchema>) {
previous: report.previous ?? false,
unit: report.unit ?? null,
metric: report.metric,
- options: report.options ?? Prisma.DbNull,
+ options: report.options ?? dbNull,
visibleSeries: report.visibleSeries ?? [],
startDate: report.range === 'custom' ? report.startDate : null,
endDate: report.range === 'custom' ? report.endDate : null,
@@ -163,7 +172,11 @@ async function requireDashboard(projectId: string, dashboardId: string) {
return dashboard;
}
-async function requireReport(projectId: string, reportId: string) {
+async function requireReport(
+ db: Awaited<ReturnType<typeof loadCompatDb>>,
+ projectId: string,
+ reportId: string
+) {
const report = await db.report.findFirst({
where: { id: reportId, projectId },
});
@@ -261,6 +274,7 @@ export function registerDashboardManagementTools(
},
async ({ projectId: inputProjectId, dashboardId }) =>
withErrorHandling(async () => {
+ const db = await loadCompatDb();
const projectId = await resolveProjectId(context, inputProjectId);
const dashboard = await requireDashboard(projectId, dashboardId);
const reports = await db.report.findMany({
@@ -305,6 +319,7 @@ export function registerDashboardManagementTools(
},
async ({ projectId: inputProjectId, name }) =>
withErrorHandling(async () => {
+ const db = await loadCompatDb();
const projectId = await resolveProjectId(context, inputProjectId);
const project = await getProjectById(projectId);
if (!project) {
@@ -342,6 +357,7 @@ export function registerDashboardManagementTools(
},
async ({ projectId: inputProjectId, dashboardId, name }) =>
withErrorHandling(async () => {
+ const db = await loadCompatDb();
const projectId = await resolveProjectId(context, inputProjectId);
await requireDashboard(projectId, dashboardId);
const dashboard = await db.dashboard.update({
@@ -372,6 +388,7 @@ export function registerDashboardManagementTools(
},
async ({ projectId: inputProjectId, dashboardId, forceDelete }) =>
withErrorHandling(async () => {
+ const db = await loadCompatDb();
const projectId = await resolveProjectId(context, inputProjectId);
const dashboard = await requireDashboard(projectId, dashboardId);
@@ -444,13 +461,15 @@ export function registerDashboardManagementTools(
},
async ({ projectId: inputProjectId, dashboardId, report }) =>
withErrorHandling(async () => {
+ const db = await loadCompatDb();
+ const { DbNull } = await loadCompatPrisma();
const projectId = await resolveProjectId(context, inputProjectId);
const dashboard = await requireDashboard(projectId, dashboardId);
const created = await db.report.create({
data: {
projectId: dashboard.projectId,
dashboardId,
- ...reportData(report),
+ ...reportData(report, DbNull),
},
});
@@ -470,11 +489,13 @@ export function registerDashboardManagementTools(
},
async ({ projectId: inputProjectId, reportId, report }) =>
withErrorHandling(async () => {
+ const db = await loadCompatDb();
+ const { DbNull } = await loadCompatPrisma();
const projectId = await resolveProjectId(context, inputProjectId);
- await requireReport(projectId, reportId);
+ await requireReport(db, projectId, reportId);
const updated = await db.report.update({
where: { id: reportId },
- data: reportData(report),
+ data: reportData(report, DbNull),
});
return {
@@ -492,8 +513,9 @@ export function registerDashboardManagementTools(
},
async ({ projectId: inputProjectId, reportId }) =>
withErrorHandling(async () => {
+ const db = await loadCompatDb();
const projectId = await resolveProjectId(context, inputProjectId);
- await requireReport(projectId, reportId);
+ await requireReport(db, projectId, reportId);
const deleted = await db.report.delete({ where: { id: reportId } });
return {
@@ -512,8 +534,10 @@ export function registerDashboardManagementTools(
},
async ({ projectId: inputProjectId, reportId }) =>
withErrorHandling(async () => {
+ const db = await loadCompatDb();
+ const { DbNull } = await loadCompatPrisma();
const projectId = await resolveProjectId(context, inputProjectId);
- const report = await requireReport(projectId, reportId);
+ const report = await requireReport(db, projectId, reportId);
const duplicate = await db.report.create({
data: {
projectId: report.projectId,
@@ -530,7 +554,7 @@ export function registerDashboardManagementTools(
previous: report.previous,
unit: report.unit,
metric: report.metric,
- options: report.options ?? Prisma.DbNull,
+ options: report.options ?? DbNull,
visibleSeries: report.visibleSeries,
startDate: report.startDate,
endDate: report.endDate,
@@ -556,8 +580,9 @@ export function registerDashboardManagementTools(
},
async ({ projectId: inputProjectId, reportId, layout }) =>
withErrorHandling(async () => {
+ const db = await loadCompatDb();
const projectId = await resolveProjectId(context, inputProjectId);
- await requireReport(projectId, reportId);
+ await requireReport(db, projectId, reportId);
return db.reportLayout.upsert({
where: { reportId },
create: { reportId, ...layout },
@@ -577,6 +602,7 @@ export function registerDashboardManagementTools(
},
async ({ projectId: inputProjectId, dashboardId }) =>
withErrorHandling(async () => {
+ const db = await loadCompatDb();
const projectId = await resolveProjectId(context, inputProjectId);
await requireDashboard(projectId, dashboardId);
const result = await db.reportLayout.deleteMany({
diff --git a/packages/core/src/modules/mcp/src/tools/projects.ts b/packages/core/src/modules/mcp/src/tools/projects.ts
index ce95a430d..f8f545fda 100644
--- a/packages/core/src/modules/mcp/src/tools/projects.ts
+++ b/packages/core/src/modules/mcp/src/tools/projects.ts
@@ -1,7 +1,6 @@
import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
-import { db } from '@openpanel/db';
import type { McpAuthContext } from '../auth';
-import { withErrorHandling } from './shared';
+import { loadCompatDb, withErrorHandling } from './shared';
export function registerProjectTools(
server: McpServer,
@@ -15,6 +14,8 @@ export function registerProjectTools(
{},
async () =>
withErrorHandling(async () => {
+ const db = await loadCompatDb();
+
if (context.clientType === 'root') {
const projects = await db.project.findMany({
where: { organizationId: context.organizationId },
diff --git a/packages/core/src/modules/mcp/src/tools/shared.ts b/packages/core/src/modules/mcp/src/tools/shared.ts
index a6283834a..ae7cc0ac6 100644
--- a/packages/core/src/modules/mcp/src/tools/shared.ts
+++ b/packages/core/src/modules/mcp/src/tools/shared.ts
@@ -5,6 +5,39 @@ import type { McpAuthContext } from '../auth';
const logger = createLogger({ name: 'mcp' });
+/**
+ * MCP's tool handlers have a fixed signature from `@modelcontextprotocol/sdk`
+ * — there is no `Ctx`/`ServiceDeps` parameter to thread through, so the few
+ * tools that still touch Postgres/ClickHouse directly (`projects.ts`,
+ * `dashboard-management.ts`, `analytics/property-values.ts`,
+ * `analytics/page-performance.ts`, `analytics/reports.ts`) reach them through
+ * the v1-compat singleton instead of `@openpanel/db` (M10-004, see
+ * v1-compat.ts's header) — the same pattern every other bare, no-`Ctx`
+ * caller in this wave uses.
+ */
+export async function loadCompatDb() {
+ return (await import('../../../../v1-compat')).compatDb();
+}
+
+export async function loadCompatCh() {
+ return (await import('../../../../v1-compat')).compatCh();
+}
+
+/** `dashboard-management.ts`'s only need from `@openpanel/db`: the
+ * `Prisma.DbNull` sentinel for an explicit SQL NULL on a nullable Json
+ * column, not a client — same seam as `loadCompatDb`/`loadCompatCh`. */
+export async function loadCompatPrisma() {
+ return (await import('../../../../v1-compat')).compatPrisma();
+}
+
+/** `analytics/property-values.ts` still builds its query with `clix`/
+ * `TABLE_NAMES` (ADR-013 converts the analytics read path one query per P7
+ * task) — the query-building helpers, not the client (`loadCompatCh`
+ * covers that), reached the same way. */
+export async function loadCompatChHelpers() {
+ return (await import('../../../../v1-compat')).compatChHelpers();
+}
+
/**
* Resolve the effective projectId from context + optional tool input.
* Thin adapter so tool files don't repeat the full argument object every call.
diff --git a/packages/core/src/modules/misc/src/data-health.ts b/packages/core/src/modules/misc/src/data-health.ts
index 3ddaddefc..359082437 100644
--- a/packages/core/src/modules/misc/src/data-health.ts
+++ b/packages/core/src/modules/misc/src/data-health.ts
@@ -62,10 +62,13 @@ export interface DataHealthDeps {
export async function loadDataHealthDeps(
logger: Logger
): Promise<DataHealthDeps> {
+ // project.service.ts's `getLastEventPerProject` takes `ServiceDeps` now
+ // (M10-004); this file has no `deps` of its own (just the bare `db` above),
+ // so it reaches the bare, v1-compat-wrapped, zero-arg spelling instead.
const [{ db }, { getLastEventPerProject }, { sendEmail }] = await Promise.all(
[
import('@openpanel/db/src/prisma-client'),
- import('../../project/project.service'),
+ import('../../../v1-compat'),
import('../../../clients/email'),
]
);
diff --git a/packages/core/src/modules/notification/notification.jobs.test.ts b/packages/core/src/modules/notification/notification.jobs.test.ts
index 1e503625c..6ddcd572e 100644
--- a/packages/core/src/modules/notification/notification.jobs.test.ts
+++ b/packages/core/src/modules/notification/notification.jobs.test.ts
@@ -46,6 +46,14 @@ function stubJobCtx(notification: Partial<NotificationService>): JobCtx {
export: {} as Services['export'],
share: {} as Services['share'],
reference: {} as Services['reference'],
+ client: {} as Services['client'],
+ project: {} as Services['project'],
+ user: {} as Services['user'],
+ subscription: {} as Services['subscription'],
+ salt: {} as Services['salt'],
+ conversation: {} as Services['conversation'],
+ assistant: {} as Services['assistant'],
+ mcp: {} as Services['mcp'],
};
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.ts
index f866a8632..d5b42a927 100644
--- a/packages/core/src/modules/onboarding/onboarding.jobs.test.ts
+++ b/packages/core/src/modules/onboarding/onboarding.jobs.test.ts
@@ -49,6 +49,14 @@ function stubJobCtx(
export: {} as Services['export'],
share: {} as Services['share'],
reference: {} as Services['reference'],
+ client: {} as Services['client'],
+ project: {} as Services['project'],
+ user: {} as Services['user'],
+ subscription: {} as Services['subscription'],
+ salt: {} as Services['salt'],
+ conversation: {} as Services['conversation'],
+ assistant: {} as Services['assistant'],
+ mcp: {} as Services['mcp'],
};
return {
db: {} as AppDeps['db'],
diff --git a/packages/core/src/modules/onboarding/onboarding.service.ts b/packages/core/src/modules/onboarding/onboarding.service.ts
index 1243d2c05..3659db332 100644
--- a/packages/core/src/modules/onboarding/onboarding.service.ts
+++ b/packages/core/src/modules/onboarding/onboarding.service.ts
@@ -26,9 +26,17 @@ import {
getOrganizationById,
getOrganizationEventsCount,
} from '../organization/organization.service';
-import { getUserById } from '../user/user.service';
import type { IOnboardingProject } from './onboarding.constants';
+// user.service.ts's `getUserById` now takes `ServiceDeps` (M10-004), which
+// this file's own still-lazy `loadDb()` functions don't carry — reached
+// through v1-compat.ts's bare re-export instead. GENUINE CYCLE, kept lazy:
+// services.ts -> onboarding.service.ts (this file) -> v1-compat.ts ->
+// services.ts; the dynamic import is what keeps it a cycle ESM can evaluate.
+function loadUserService() {
+ return import('../../v1-compat');
+}
+
const TRIAL_DURATION_IN_DAYS = 30;
// Generous trial allowance so trialing orgs never get flagged as
// "limit exceeded" (the limit defaults to 0, which trips on the first event).
@@ -97,7 +105,7 @@ async function createOrGetOnboardingOrganization(
}),
db.member.create({
data: {
- email: (await getUserById(userId)).email,
+ email: (await (await loadUserService()).getUserById(userId)).email,
organizationId,
role: 'org:admin',
userId,
diff --git a/packages/core/src/modules/organization/organization.jobs.test.ts b/packages/core/src/modules/organization/organization.jobs.test.ts
index 8a11e5b4d..aa65550ae 100644
--- a/packages/core/src/modules/organization/organization.jobs.test.ts
+++ b/packages/core/src/modules/organization/organization.jobs.test.ts
@@ -52,6 +52,14 @@ function stubJobCtx(
export: {} as Services['export'],
share: {} as Services['share'],
reference: {} as Services['reference'],
+ client: {} as Services['client'],
+ project: {} as Services['project'],
+ user: {} as Services['user'],
+ subscription: {} as Services['subscription'],
+ salt: {} as Services['salt'],
+ conversation: {} as Services['conversation'],
+ assistant: {} as Services['assistant'],
+ mcp: {} as Services['mcp'],
};
return {
db: {} as AppDeps['db'],
diff --git a/packages/core/src/modules/organization/src/wind-down.ts b/packages/core/src/modules/organization/src/wind-down.ts
index b788f9622..e6e5f59ae 100644
--- a/packages/core/src/modules/organization/src/wind-down.ts
+++ b/packages/core/src/modules/organization/src/wind-down.ts
@@ -130,7 +130,10 @@ export async function loadWindDownDeps(logger: Logger): Promise<WindDownDeps> {
] = await Promise.all([
import('@openpanel/db/src/prisma-client'),
import('../organization.service'),
- import('../../project/project.service'),
+ // project.service.ts's `getLastEventPerProject` takes `ServiceDeps` now
+ // (M10-004); this file has none, so it reaches the bare,
+ // v1-compat-wrapped, zero-arg spelling instead.
+ import('../../../v1-compat'),
import('../../../clients/email'),
import('./win-back-highlight'),
]);
diff --git a/packages/core/src/modules/project/project.routes.ts b/packages/core/src/modules/project/project.routes.ts
index fb0f32904..48e399b4c 100644
--- a/packages/core/src/modules/project/project.routes.ts
+++ b/packages/core/src/modules/project/project.routes.ts
@@ -15,13 +15,6 @@
import { z } from 'zod';
import { defineRoutes } from '../../http/define';
import { zCreateProject, zUpdateProject } from './project.constants';
-import {
- createProjectForOrganization,
- deleteProjectForOrganization,
- getProjectForOrganization,
- listProjectsForOrganization,
- updateProjectForOrganization,
-} from './project.service';
const idParams = z.object({ id: z.string() });
@@ -29,8 +22,10 @@ export const projectRoutes = defineRoutes((app) =>
app
.get(
'/manage/projects',
- async ({ client }) => ({
- data: await listProjectsForOrganization(client.organizationId),
+ async ({ client, ctx }) => ({
+ data: await ctx.services.project.listProjectsForOrganization(
+ client.organizationId
+ ),
}),
{
clientAuth: { allow: ['root'], label: 'Manage' },
@@ -39,8 +34,8 @@ export const projectRoutes = defineRoutes((app) =>
)
.get(
'/manage/projects/:id',
- async ({ client, params, status }) => {
- const project = await getProjectForOrganization(
+ async ({ client, ctx, params, status }) => {
+ const project = await ctx.services.project.getProjectForOrganization(
params.id,
client.organizationId
);
@@ -60,15 +55,18 @@ export const projectRoutes = defineRoutes((app) =>
)
.post(
'/manage/projects',
- async ({ body, client }) => {
+ async ({ body, client, ctx }) => {
const { project, client: firstClient } =
- await createProjectForOrganization(client.organizationId, {
- name: body.name,
- domain: body.domain,
- cors: body.cors,
- crossDomain: body.crossDomain,
- types: body.types,
- });
+ await ctx.services.project.createProjectForOrganization(
+ client.organizationId,
+ {
+ name: body.name,
+ domain: body.domain,
+ cors: body.cors,
+ crossDomain: body.crossDomain,
+ types: body.types,
+ }
+ );
return { data: { ...project, client: firstClient } };
},
{
@@ -79,8 +77,8 @@ export const projectRoutes = defineRoutes((app) =>
)
.patch(
'/manage/projects/:id',
- async ({ body, client, params, status }) => {
- const project = await updateProjectForOrganization(
+ async ({ body, client, ctx, params, status }) => {
+ const project = await ctx.services.project.updateProjectForOrganization(
params.id,
client.organizationId,
body
@@ -102,8 +100,8 @@ export const projectRoutes = defineRoutes((app) =>
)
.delete(
'/manage/projects/:id',
- async ({ client, params, status }) => {
- const deleted = await deleteProjectForOrganization(
+ async ({ client, ctx, params, status }) => {
+ const deleted = await ctx.services.project.deleteProjectForOrganization(
params.id,
client.organizationId
);
diff --git a/packages/core/src/modules/project/project.rpc.ts b/packages/core/src/modules/project/project.rpc.ts
index 38f6ded0f..3fba4f205 100644
--- a/packages/core/src/modules/project/project.rpc.ts
+++ b/packages/core/src/modules/project/project.rpc.ts
@@ -7,8 +7,8 @@
// 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 project functions (DELEGATE
-// PATTERN) — this module has no queue/cron of its own, so there is no
-// `ctx.services.project`, same as `user`/`conversation`.
+// PATTERN). `ctx.services.project` carries this module's factory the same
+// as every other module now (M10-004).
//
// The project-access ladder itself is bound once, in auth.service.ts
// (M10-002); every procedure here reaches it through `ctx.services.auth`.
@@ -17,16 +17,6 @@ import { zOnboardingProject, zProjectUpdate } from '@openpanel/validation';
import { z } from 'zod';
import { createTRPCRouter, procedure } from '../../rpc/base';
import { TRPCAccessError, TRPCForbiddenError } from '../../rpc/errors';
-import {
- cancelProjectDeletion,
- createProjectForOrganization,
- getProjectActivationStatus,
- getProjectById,
- getProjects,
- getProjectWithClients,
- scheduleProjectDeletion,
- updateProjectForOrganization,
-} from './project.service';
function requireLogin(userId: string | null | undefined): string {
if (!userId) {
@@ -47,7 +37,7 @@ export const projectRouter = createTRPCRouter({
if (!access) {
throw new TRPCForbiddenError('You do not have access to this project');
}
- return getProjectWithClients(projectId);
+ return ctx.services.project.getProjectWithClients(projectId);
}),
// Powers the activation checklist on the project overview: has the project
@@ -64,7 +54,7 @@ export const projectRouter = createTRPCRouter({
throw new TRPCForbiddenError('You do not have access to this project');
}
- return getProjectActivationStatus(projectId);
+ return ctx.services.project.getProjectActivationStatus(projectId);
}),
list: procedure
@@ -74,7 +64,7 @@ export const projectRouter = createTRPCRouter({
if (organizationId === null) {
return [];
}
- return getProjects({ organizationId, userId });
+ return ctx.services.project.getProjects({ organizationId, userId });
}),
update: procedure.input(zProjectUpdate).mutation(async ({ input, ctx }) => {
@@ -85,18 +75,22 @@ export const projectRouter = createTRPCRouter({
level: 'write',
});
- const project = await getProjectById(input.id);
+ const project = await ctx.services.project.getProjectById(input.id);
if (!project) {
throw new TRPCForbiddenError('Project not found');
}
- return updateProjectForOrganization(input.id, project.organizationId, {
- name: input.name,
- domain: input.domain,
- cors: input.cors,
- crossDomain: input.crossDomain,
- allowUnsafeRevenueTracking: input.allowUnsafeRevenueTracking,
- });
+ return ctx.services.project.updateProjectForOrganization(
+ input.id,
+ project.organizationId,
+ {
+ name: input.name,
+ domain: input.domain,
+ cors: input.cors,
+ crossDomain: input.crossDomain,
+ allowUnsafeRevenueTracking: input.allowUnsafeRevenueTracking,
+ }
+ );
}),
create: procedure
@@ -118,16 +112,17 @@ export const projectRouter = createTRPCRouter({
);
}
- const { project, client } = await createProjectForOrganization(
- input.organizationId,
- {
- name: input.project,
- domain: input.domain,
- cors: input.cors,
- crossDomain: false,
- types: [],
- }
- );
+ const { project, client } =
+ await ctx.services.project.createProjectForOrganization(
+ input.organizationId,
+ {
+ name: input.project,
+ domain: input.domain,
+ cors: input.cors,
+ crossDomain: false,
+ types: [],
+ }
+ );
return { ...project, client };
}),
@@ -143,7 +138,7 @@ export const projectRouter = createTRPCRouter({
message: 'Only organization admins can delete projects',
});
- await scheduleProjectDeletion(input.projectId);
+ await ctx.services.project.scheduleProjectDeletion(input.projectId);
return true;
}),
@@ -157,7 +152,7 @@ export const projectRouter = createTRPCRouter({
message: 'Only organization admins can cancel a project deletion',
});
- await cancelProjectDeletion(input.projectId);
+ await ctx.services.project.cancelProjectDeletion(input.projectId);
return true;
}),
});
diff --git a/packages/core/src/modules/project/project.service.test.ts b/packages/core/src/modules/project/project.service.test.ts
index 84af94852..cb7f37041 100644
--- a/packages/core/src/modules/project/project.service.test.ts
+++ b/packages/core/src/modules/project/project.service.test.ts
@@ -1,10 +1,14 @@
-// project.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. `getProjectEventsCount` / `getLastEventPerProject`
-// (ClickHouse) are a verbatim port with unchanged SQL — executed against
+// The subject is built by its factory over a fake `ServiceDeps` (M10-004), so
+// Postgres needs no module mock at all — `deps.db` IS the fake below, same
+// idiom as reference.service.test.ts. `getProjectEventsCount` /
+// `getLastEventPerProject` (ClickHouse) stay a verbatim, still-lazy-loaded
+// port with unchanged SQL (ADR-013 converts them in P7) — executed against
// local ClickHouse for this task's verification, not re-tested here.
+//
+// `../../v1-compat` is still mocked: `createProjectForOrganization`/
+// `updateProjectForOrganization` invalidate a project's clients through the
+// v1-compat singleton (see project.service.ts's header), which this test
+// has no real `AppDeps` to build.
import { beforeAll, beforeEach, expect, mock, test } from 'bun:test';
@@ -167,19 +171,19 @@ mock.module('@openpanel/redis', () => ({
}),
}));
-const actualPrismaClient = await import('@openpanel/db/src/prisma-client');
-mock.module('@openpanel/db/src/prisma-client', () => ({
- ...actualPrismaClient,
- db: { project, report, member },
-}));
-
-mock.module('@openpanel/core', () => ({
+mock.module('../../shared/slug-id', () => ({
getId: async (_table: string, name: string) => `${name}-slug`,
}));
-let subject: typeof import('./project.service');
+const clearClientByIdCache = mock(async () => 0);
+mock.module('../../v1-compat', () => ({ clearClientByIdCache }));
+
+let subject: import('./project.service').ProjectService;
beforeAll(async () => {
- subject = await import('./project.service');
+ const { createProjectService } = await import('./project.service');
+ subject = createProjectService({
+ db: { project, report, member },
+ } as unknown as import('../../services').ServiceDeps);
});
beforeEach(() => {
diff --git a/packages/core/src/modules/project/project.service.ts b/packages/core/src/modules/project/project.service.ts
index dbb62fa5c..97c57828d 100644
--- a/packages/core/src/modules/project/project.service.ts
+++ b/packages/core/src/modules/project/project.service.ts
@@ -4,28 +4,23 @@
// / `getProjectByIdCached` through the same relative path, and
// apps/api/src/utils/auth.ts reaches them through @openpanel/db's barrel;
// auth.service.ts's permission ladder (M10-002) reaches `getProjectById`
-// through a lazy dynamic import, same reasoning as this file's own `load*`
-// below — same shape as packages/db/src/services/organization.service.ts
-// since M6-001.
+// through `shared/access-lookups.ts`, which — with no `ServiceDeps` of its
+// own to carry — reaches it through the v1-compat singleton instead
+// (M10-004, see v1-compat.ts's header).
//
-// The /manage REST CRUD bodies (apps/api/src/controllers/manage.controller.ts's
-// listProjects/getProject/createProject/updateProject/deleteProject) move
-// here too, so V1's controller and core's own project.routes.ts share one
-// implementation (DELEGATE PATTERN).
+// M10-004: every function takes `ServiceDeps` and reaches Postgres as
+// `deps.db`; the `loadDb()` lazy loader is gone. `getProjectByIdCached` lives
+// INSIDE `createProjectService(deps)` for the same reason
+// `getClientByIdCached` does in client.service.ts — see that file's header.
//
-// db/ch access is LAZY (`load*` below), not a static top-level import — see
-// insight.service.ts's header for the full reasoning (jobs.registry.ts and
-// rpc.router.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).
-//
-// ClickHouse queries here still go through clix/sqlstring, not the `sql`
-// tag: ADR-013 converts the analytics read path one query per P7 task, and
-// this module's queries haven't been converted yet.
+// ClickHouse queries here still build with clix/sqlstring/chQuery, not raw
+// `sql` fragments: ADR-013 converts the analytics read path one query per P7
+// task, and this module's two queries (`getProjectEventsCount`/
+// `getLastEventPerProject`) haven't been converted yet — see `loadChHelpers`'s
+// own comment below. The CLIENT is `deps.ch` either way.
import crypto from 'node:crypto';
import { stripTrailingSlash } from '@openpanel/common';
-import { clix } from '@openpanel/db/src/clickhouse/query-builder';
import type {
Prisma,
Project,
@@ -34,8 +29,37 @@ import type {
import { cacheable } from '@openpanel/redis';
import sqlstring from 'sqlstring';
import { TRPCBadRequestError } from '../../rpc/errors';
+import type { ServiceDeps } from '../../services';
+import { getId } from '../../shared/slug-id';
import { hashPassword } from '../auth/auth.service';
-import { getClientByIdCached } from '../client/client.service';
+
+// `getProjectEventsCount` and `getLastEventPerProject` still build their
+// query with clix/sqlstring/`chQuery`, not raw `sql` fragments — converting
+// the query BODIES is ADR-013's P7 task (one query per task, with an
+// old-vs-new result-set diff), not this wave's; `chQuery` also does its own
+// retry/round-robin and Int-meta coercion (ClickHouse's JSON format returns
+// every Int*/UInt* column as a string) that would otherwise have to be
+// reimplemented by hand. The CLIENT is `deps.ch`, same as everywhere else in
+// this file; only the pure helper functions (`clix`, `TABLE_NAMES`,
+// `chQuery`, `convertClickhouseDateToJs`) come from `@openpanel/db`, and —
+// same as `loadClientService` below — that reach is through the v1-compat
+// singleton, not a direct import: services.ts -> project.service.ts (this
+// file) -> v1-compat.ts -> services.ts is a genuine cycle, kept lazy.
+function loadChHelpers() {
+ return import('../../v1-compat').then((m) => m.compatChHelpers());
+}
+
+// GENUINE CYCLE, kept lazy: `createClientForOrganization`/
+// `updateClientForOrganization` invalidate a project's clients' cache
+// entries, and that cache now lives inside `createClientService(deps)` (see
+// that file's header) — reached here through the v1-compat singleton so
+// every caller invalidates the SAME cache instance, the one `ingest`/`http`/
+// `mcp` actually read. services.ts -> project.service.ts (this file) ->
+// v1-compat.ts -> services.ts; the dynamic import is what keeps it a cycle
+// ESM can evaluate.
+function loadClientService() {
+ return import('../../v1-compat');
+}
export type IServiceProject = Project;
export type IServiceProjectWithClients = Prisma.ProjectGetPayload<{
@@ -44,21 +68,10 @@ export type IServiceProjectWithClients = Prisma.ProjectGetPayload<{
};
}>;
-function loadDb() {
- return import('@openpanel/db/src/prisma-client').then((m) => m.db);
-}
-
-function loadChClient() {
- return import('@openpanel/db/src/clickhouse/client');
-}
-
-function loadIdService() {
- return import('@openpanel/core').then((m) => m.getId);
-}
+const DAY_IN_SECONDS = 60 * 60 * 24;
-export async function getProjectById(id: string) {
- const db = await loadDb();
- const res = await db.project.findUnique({
+export async function getProjectById(deps: ServiceDeps, id: string) {
+ const res = await deps.db.project.findUnique({
where: {
id,
},
@@ -71,13 +84,8 @@ export async function getProjectById(id: string) {
return res;
}
-const DAY_IN_SECONDS = 60 * 60 * 24;
-/** L1 LRU (60s) + L2 Redis. clear() invalidates Redis + local LRU; other nodes may serve stale from LRU for up to 60s. */
-export const getProjectByIdCached = cacheable(getProjectById, DAY_IN_SECONDS);
-
-export async function getProjectWithClients(id: string) {
- const db = await loadDb();
- const res = await db.project.findUnique({
+export async function getProjectWithClients(deps: ServiceDeps, id: string) {
+ const res = await deps.db.project.findUnique({
where: {
id,
},
@@ -93,20 +101,22 @@ export async function getProjectWithClients(id: string) {
return res;
}
-export async function getProjects({
- organizationId,
- userId,
-}: {
- organizationId: string;
- userId: string | null;
-}) {
+export async function getProjects(
+ deps: ServiceDeps,
+ {
+ organizationId,
+ userId,
+ }: {
+ organizationId: string;
+ userId: string | null;
+ }
+) {
if (!userId) {
return [];
}
- const db = await loadDb();
const [projects, members, access] = await Promise.all([
- db.project.findMany({
+ deps.db.project.findMany({
where: {
organizationId,
},
@@ -114,13 +124,13 @@ export async function getProjects({
eventsCount: 'desc',
},
}),
- db.member.findMany({
+ deps.db.member.findMany({
where: {
userId,
organizationId,
},
}),
- db.projectAccess.findMany({
+ deps.db.projectAccess.findMany({
where: {
userId,
organizationId,
@@ -161,8 +171,11 @@ export async function getProjects({
* low on a 1.46B-event project) — acceptable for this display/onboarding
* counter.
*/
-export const getProjectEventsCount = async (projectId: string) => {
- const { chQuery, TABLE_NAMES } = await loadChClient();
+export const getProjectEventsCount = async (
+ _deps: ServiceDeps,
+ projectId: string
+) => {
+ const { chQuery, TABLE_NAMES } = await loadChHelpers();
const res = await chQuery<{ count: number }>(
`SELECT sum(event_count) as count FROM ${TABLE_NAMES.event_names_mv} WHERE project_id = ${sqlstring.escape(projectId)} AND name NOT IN ('session_start', 'session_end')`
);
@@ -176,9 +189,12 @@ export const getProjectEventsCount = async (projectId: string) => {
* rows instead of the raw events table. Projects with no events are absent
* from the map.
*/
-export const getLastEventPerProject = async (): Promise<Map<string, Date>> => {
- const { ch, TABLE_NAMES, convertClickhouseDateToJs } = await loadChClient();
- const res = await clix(ch)
+export const getLastEventPerProject = async (
+ deps: ServiceDeps
+): Promise<Map<string, Date>> => {
+ const { clix, TABLE_NAMES, convertClickhouseDateToJs } =
+ await loadChHelpers();
+ const res = await clix(deps.ch)
.select<{ project_id: string; last_event_at: string }>([
'project_id',
'max(created_at) AS last_event_at',
@@ -206,17 +222,20 @@ export const getLastEventPerProject = async (): Promise<Map<string, Date>> => {
* Throws if the project is not found or does not belong to the organization.
* Use this as the single source of truth for projectId resolution across the API and MCP.
*/
-export async function resolveClientProjectId({
- clientType,
- clientProjectId,
- organizationId,
- inputProjectId,
-}: {
- clientType: 'read' | 'root';
- clientProjectId: string | null;
- organizationId: string;
- inputProjectId: string | undefined;
-}): Promise<string> {
+export async function resolveClientProjectId(
+ deps: ServiceDeps,
+ {
+ clientType,
+ clientProjectId,
+ organizationId,
+ inputProjectId,
+ }: {
+ clientType: 'read' | 'root';
+ clientProjectId: string | null;
+ organizationId: string;
+ inputProjectId: string | undefined;
+ }
+): Promise<string> {
if (clientType !== 'root') {
if (!clientProjectId) {
throw new Error('Client is not associated with a project');
@@ -230,8 +249,7 @@ export async function resolveClientProjectId({
);
}
- const db = await loadDb();
- const project = await db.project.findFirst({
+ const project = await deps.db.project.findFirst({
where: { id: inputProjectId, organizationId },
select: { id: true },
});
@@ -255,10 +273,10 @@ export interface ProjectActivationStatus {
/** Powers the activation checklist on the project overview (trpc project.activationStatus). */
export async function getProjectActivationStatus(
+ deps: ServiceDeps,
projectId: string
): Promise<ProjectActivationStatus> {
- const db = await loadDb();
- const project = await db.project.findUniqueOrThrow({
+ const project = await deps.db.project.findUniqueOrThrow({
where: { id: projectId },
select: {
firstEventAt: true,
@@ -269,8 +287,8 @@ export async function getProjectActivationStatus(
});
const [reportCount, memberCount] = await Promise.all([
- db.report.count({ where: { projectId } }),
- db.member.count({ where: { organizationId: project.organizationId } }),
+ deps.db.report.count({ where: { projectId } }),
+ deps.db.member.count({ where: { organizationId: project.organizationId } }),
]);
return {
@@ -284,14 +302,16 @@ export async function getProjectActivationStatus(
};
}
-export async function listProjectsCore(input: {
- clientType: 'root' | 'read';
- organizationId: string;
- projectId: string | null;
-}) {
- const db = await loadDb();
+export async function listProjectsCore(
+ deps: ServiceDeps,
+ input: {
+ clientType: 'root' | 'read';
+ organizationId: string;
+ projectId: string | null;
+ }
+) {
if (input.clientType === 'root') {
- const projects = await db.project.findMany({
+ const projects = await deps.db.project.findMany({
where: { organizationId: input.organizationId },
orderBy: { eventsCount: 'desc' },
select: {
@@ -307,7 +327,7 @@ export async function listProjectsCore(input: {
}
const project = input.projectId
- ? await db.project.findUnique({
+ ? await deps.db.project.findUnique({
where: { id: input.projectId },
select: {
id: true,
@@ -333,9 +353,11 @@ export interface CreatedProjectClient {
secret: string;
}
-export async function listProjectsForOrganization(organizationId: string) {
- const db = await loadDb();
- return db.project.findMany({
+export async function listProjectsForOrganization(
+ deps: ServiceDeps,
+ organizationId: string
+) {
+ return deps.db.project.findMany({
where: {
organizationId,
deleteAt: null,
@@ -347,11 +369,11 @@ export async function listProjectsForOrganization(organizationId: string) {
}
export async function getProjectForOrganization(
+ deps: ServiceDeps,
id: string,
organizationId: string
) {
- const db = await loadDb();
- return db.project.findFirst({
+ return deps.db.project.findFirst({
where: {
id,
organizationId,
@@ -359,179 +381,272 @@ export async function getProjectForOrganization(
});
}
-export async function createProjectForOrganization(
- organizationId: string,
- input: {
- name: string;
- domain?: string | null;
- cors: string[];
- crossDomain: boolean;
- types: ProjectType[];
- }
-): Promise<{ project: IServiceProject; client: CreatedProjectClient | null }> {
- const db = await loadDb();
- const getId = await loadIdService();
-
- const secret = `sec_${crypto.randomBytes(10).toString('hex')}`;
- const project = await db.project.create({
- data: {
- id: await getId('project', input.name),
- organizationId,
- name: input.name,
- domain: input.domain ? stripTrailingSlash(input.domain) : null,
- cors: input.cors.map((c) => stripTrailingSlash(c)),
- crossDomain: input.crossDomain ?? false,
- allowUnsafeRevenueTracking: false,
- filters: [],
- types: input.types,
- clients: {
- create: {
- organizationId,
- name: 'First client',
- type: 'write',
- secret: await hashPassword(secret),
- },
- },
- },
- include: {
- clients: {
- select: {
- id: true,
- },
- },
- },
- });
-
- await Promise.all([
- getProjectByIdCached.clear(project.id),
- ...project.clients.map((client) => getClientByIdCached.clear(client.id)),
- ]);
+// Grace period between a scheduled deletion and the `delete` cron sweeping it
+// up — matches V1's `addHours(new Date(), 24)` (trpc) and the manage
+// controller's `Date.now() + 24 * 60 * 60 * 1000` (REST), same duration.
+const DELETE_GRACE_PERIOD_MS = 24 * 60 * 60 * 1000;
- return {
- project,
- client: project.clients[0] ? { id: project.clients[0].id, secret } : null,
- };
+export interface ProjectService {
+ getProjectById(id: string): ReturnType<typeof getProjectById>;
+ getProjectByIdCached(id: string): ReturnType<typeof getProjectById>;
+ /** Invalidates a single id in `getProjectByIdCached`'s L1 LRU + Redis —
+ * `ingest/src/incoming-event-handler.ts` reaches it, through the
+ * v1-compat singleton, right after marking a project's first event. */
+ clearProjectByIdCache(id: string): Promise<number>;
+ getProjectWithClients(id: string): ReturnType<typeof getProjectWithClients>;
+ getProjects(
+ input: Parameters<typeof getProjects>[1]
+ ): ReturnType<typeof getProjects>;
+ getProjectEventsCount(
+ projectId: string
+ ): ReturnType<typeof getProjectEventsCount>;
+ getLastEventPerProject(): ReturnType<typeof getLastEventPerProject>;
+ resolveClientProjectId(
+ input: Parameters<typeof resolveClientProjectId>[1]
+ ): ReturnType<typeof resolveClientProjectId>;
+ getProjectActivationStatus(
+ projectId: string
+ ): ReturnType<typeof getProjectActivationStatus>;
+ listProjectsCore(
+ input: Parameters<typeof listProjectsCore>[1]
+ ): ReturnType<typeof listProjectsCore>;
+ listProjectsForOrganization(
+ organizationId: string
+ ): ReturnType<typeof listProjectsForOrganization>;
+ getProjectForOrganization(
+ id: string,
+ organizationId: string
+ ): ReturnType<typeof getProjectForOrganization>;
+ createProjectForOrganization(
+ organizationId: string,
+ input: {
+ name: string;
+ domain?: string | null;
+ cors: string[];
+ crossDomain: boolean;
+ types: ProjectType[];
+ }
+ ): Promise<{ project: IServiceProject; client: CreatedProjectClient | null }>;
+ updateProjectForOrganization(
+ id: string,
+ organizationId: string,
+ input: {
+ name?: string;
+ domain?: string | null;
+ cors?: string[];
+ crossDomain?: boolean;
+ allowUnsafeRevenueTracking?: boolean;
+ }
+ ): Promise<IServiceProject | null>;
+ deleteProjectForOrganization(
+ id: string,
+ organizationId: string
+ ): Promise<boolean>;
+ scheduleProjectDeletion(id: string): Promise<void>;
+ cancelProjectDeletion(id: string): Promise<void>;
}
-export async function updateProjectForOrganization(
- id: string,
- organizationId: string,
- input: {
- name?: string;
- domain?: string | null;
- cors?: string[];
- crossDomain?: boolean;
- allowUnsafeRevenueTracking?: boolean;
- }
-): Promise<IServiceProject | null> {
- const db = await loadDb();
-
- const existing = await db.project.findFirst({
- where: { id, organizationId },
- include: { clients: { select: { id: true } } },
- });
+export function createProjectService(deps: ServiceDeps): ProjectService {
+ /** L1 LRU (60s) + L2 Redis. clear() invalidates Redis + local LRU; other nodes may serve stale from LRU for up to 60s. */
+ const getProjectByIdCached = cacheable(
+ (id: string) => getProjectById(deps, id),
+ DAY_IN_SECONDS
+ );
- if (!existing) {
- return null;
- }
+ async function createProjectForOrganization(
+ organizationId: string,
+ input: {
+ name: string;
+ domain?: string | null;
+ cors: string[];
+ crossDomain: boolean;
+ types: ProjectType[];
+ }
+ ): Promise<{
+ project: IServiceProject;
+ client: CreatedProjectClient | null;
+ }> {
+ const secret = `sec_${crypto.randomBytes(10).toString('hex')}`;
+ const project = await deps.db.project.create({
+ data: {
+ id: await getId('project', input.name),
+ organizationId,
+ name: input.name,
+ domain: input.domain ? stripTrailingSlash(input.domain) : null,
+ cors: input.cors.map((c) => stripTrailingSlash(c)),
+ crossDomain: input.crossDomain ?? false,
+ allowUnsafeRevenueTracking: false,
+ filters: [],
+ types: input.types,
+ clients: {
+ create: {
+ organizationId,
+ name: 'First client',
+ type: 'write',
+ secret: await hashPassword(secret),
+ },
+ },
+ },
+ include: {
+ clients: {
+ select: {
+ id: true,
+ },
+ },
+ },
+ });
- const updateData: Prisma.ProjectUpdateInput = {};
- if (input.name !== undefined) {
- updateData.name = input.name;
- }
- if (input.domain !== undefined) {
- updateData.domain = input.domain ? stripTrailingSlash(input.domain) : null;
- }
- if (input.cors !== undefined) {
- updateData.cors = input.cors.map((c) => stripTrailingSlash(c));
- }
- if (input.crossDomain !== undefined) {
- updateData.crossDomain = input.crossDomain;
+ const clientService = await loadClientService();
+ await Promise.all([
+ getProjectByIdCached.clear(project.id),
+ ...project.clients.map((client) =>
+ clientService.clearClientByIdCache(client.id)
+ ),
+ ]);
+
+ return {
+ project,
+ client: project.clients[0] ? { id: project.clients[0].id, secret } : null,
+ };
}
- if (input.allowUnsafeRevenueTracking !== undefined) {
- updateData.allowUnsafeRevenueTracking = input.allowUnsafeRevenueTracking;
- }
-
- const project = await db.project.update({
- where: { id },
- data: updateData,
- });
- await Promise.all([
- getProjectByIdCached.clear(project.id),
- ...existing.clients.map((client) => getClientByIdCached.clear(client.id)),
- ]);
+ async function updateProjectForOrganization(
+ id: string,
+ organizationId: string,
+ input: {
+ name?: string;
+ domain?: string | null;
+ cors?: string[];
+ crossDomain?: boolean;
+ allowUnsafeRevenueTracking?: boolean;
+ }
+ ): Promise<IServiceProject | null> {
+ const existing = await deps.db.project.findFirst({
+ where: { id, organizationId },
+ include: { clients: { select: { id: true } } },
+ });
- return project;
-}
+ if (!existing) {
+ return null;
+ }
-// Grace period between a scheduled deletion and the `delete` cron sweeping it
-// up — matches V1's `addHours(new Date(), 24)` (trpc) and the manage
-// controller's `Date.now() + 24 * 60 * 60 * 1000` (REST), same duration.
-const DELETE_GRACE_PERIOD_MS = 24 * 60 * 60 * 1000;
+ const updateData: Prisma.ProjectUpdateInput = {};
+ if (input.name !== undefined) {
+ updateData.name = input.name;
+ }
+ if (input.domain !== undefined) {
+ updateData.domain = input.domain
+ ? stripTrailingSlash(input.domain)
+ : null;
+ }
+ if (input.cors !== undefined) {
+ updateData.cors = input.cors.map((c) => stripTrailingSlash(c));
+ }
+ if (input.crossDomain !== undefined) {
+ updateData.crossDomain = input.crossDomain;
+ }
+ if (input.allowUnsafeRevenueTracking !== undefined) {
+ updateData.allowUnsafeRevenueTracking = input.allowUnsafeRevenueTracking;
+ }
-export async function deleteProjectForOrganization(
- id: string,
- organizationId: string
-): Promise<boolean> {
- const db = await loadDb();
+ const project = await deps.db.project.update({
+ where: { id },
+ data: updateData,
+ });
- const project = await db.project.findFirst({
- where: { id, organizationId },
- });
+ const clientService = await loadClientService();
+ await Promise.all([
+ getProjectByIdCached.clear(project.id),
+ ...existing.clients.map((client) =>
+ clientService.clearClientByIdCache(client.id)
+ ),
+ ]);
- if (!project) {
- return false;
+ return project;
}
- await db.project.update({
- where: { id },
- data: {
- deleteAt: new Date(Date.now() + DELETE_GRACE_PERIOD_MS),
- },
- });
+ async function deleteProjectForOrganization(
+ id: string,
+ organizationId: string
+ ): Promise<boolean> {
+ const project = await deps.db.project.findFirst({
+ where: { id, organizationId },
+ });
- await getProjectByIdCached.clear(id);
+ if (!project) {
+ return false;
+ }
- return true;
-}
+ await deps.db.project.update({
+ where: { id },
+ data: {
+ deleteAt: new Date(Date.now() + DELETE_GRACE_PERIOD_MS),
+ },
+ });
-// --- trpc project.delete / project.cancelDeletion ---
-// Caller has already been proven a project (or organization) admin by
-// requireProjectAdmin, so unlike the /manage functions above these take no
-// organizationId and do no ownership re-check.
+ await getProjectByIdCached.clear(id);
-export async function scheduleProjectDeletion(id: string): Promise<void> {
- const db = await loadDb();
- await db.project.update({
- where: { id },
- data: { deleteAt: new Date(Date.now() + DELETE_GRACE_PERIOD_MS) },
- });
-}
+ return true;
+ }
-export async function cancelProjectDeletion(id: string): Promise<void> {
- const db = await loadDb();
+ // --- trpc project.delete / project.cancelDeletion ---
+ // Caller has already been proven a project (or organization) admin by
+ // requireProjectAdmin, so unlike the /manage functions above these take no
+ // organizationId and do no ownership re-check.
- const project = await db.project.findUnique({
- where: { id },
- select: {
- organization: {
- select: { deleteAt: true },
+ async function scheduleProjectDeletion(id: string): Promise<void> {
+ await deps.db.project.update({
+ where: { id },
+ data: { deleteAt: new Date(Date.now() + DELETE_GRACE_PERIOD_MS) },
+ });
+ }
+
+ async function cancelProjectDeletion(id: string): Promise<void> {
+ const project = await deps.db.project.findUnique({
+ where: { id },
+ select: {
+ organization: {
+ select: { deleteAt: true },
+ },
},
- },
- });
+ });
- // If the whole organization is scheduled for deletion, this project's
- // deletion is part of it and can only be cancelled at the organization
- // level. Cancelling it here would leave the organization unable to delete.
- if (project?.organization?.deleteAt) {
- throw new TRPCBadRequestError(
- 'This organization is scheduled for deletion. Cancel the deletion from the organization settings.'
- );
+ // If the whole organization is scheduled for deletion, this project's
+ // deletion is part of it and can only be cancelled at the organization
+ // level. Cancelling it here would leave the organization unable to delete.
+ if (project?.organization?.deleteAt) {
+ throw new TRPCBadRequestError(
+ 'This organization is scheduled for deletion. Cancel the deletion from the organization settings.'
+ );
+ }
+
+ await deps.db.project.update({
+ where: { id },
+ data: { deleteAt: null },
+ });
}
- await db.project.update({
- where: { id },
- data: { deleteAt: null },
- });
+ return {
+ getProjectById: (id) => getProjectById(deps, id),
+ getProjectByIdCached: (id) => getProjectByIdCached(id),
+ clearProjectByIdCache: (id) => getProjectByIdCached.clear(id),
+ getProjectWithClients: (id) => getProjectWithClients(deps, id),
+ getProjects: (input) => getProjects(deps, input),
+ getProjectEventsCount: (projectId) =>
+ getProjectEventsCount(deps, projectId),
+ getLastEventPerProject: () => getLastEventPerProject(deps),
+ resolveClientProjectId: (input) => resolveClientProjectId(deps, input),
+ getProjectActivationStatus: (projectId) =>
+ getProjectActivationStatus(deps, projectId),
+ listProjectsCore: (input) => listProjectsCore(deps, input),
+ listProjectsForOrganization: (organizationId) =>
+ listProjectsForOrganization(deps, organizationId),
+ getProjectForOrganization: (id, organizationId) =>
+ getProjectForOrganization(deps, id, organizationId),
+ createProjectForOrganization,
+ updateProjectForOrganization,
+ deleteProjectForOrganization,
+ scheduleProjectDeletion,
+ cancelProjectDeletion,
+ };
}
diff --git a/packages/core/src/modules/salt/salt.jobs.ts b/packages/core/src/modules/salt/salt.jobs.ts
index 3bd52647e..2ba10c73e 100644
--- a/packages/core/src/modules/salt/salt.jobs.ts
+++ b/packages/core/src/modules/salt/salt.jobs.ts
@@ -9,14 +9,13 @@
import { z } from 'zod';
import { defineJob } from '../../jobs/define';
import type { SchedulerDefinition } from '../../jobs/schedulers';
-import { rotateSalt } from './salt.service';
/** This module's fragment of the `cron` queue's jobs. */
export const saltCronJobs = {
salt: defineJob({
payload: z.null(),
- handler: async () => {
- await rotateSalt();
+ handler: async ({ ctx }) => {
+ await ctx.services.salt.rotateSalt();
},
}),
};
diff --git a/packages/core/src/modules/salt/salt.service.test.ts b/packages/core/src/modules/salt/salt.service.test.ts
index a9b58838d..1873943d8 100644
--- a/packages/core/src/modules/salt/salt.service.test.ts
+++ b/packages/core/src/modules/salt/salt.service.test.ts
@@ -1,8 +1,16 @@
-// salt.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: the
-// mock is registered before the subject's first call, not before its
-// (side-effect-free) import.
+// The subject is built over a fake `ServiceDeps` (M10-004), so Postgres needs
+// no module mock at all — `deps.db` IS the fake below, same idiom as
+// reference.service.test.ts. `@openpanel/redis`'s `cacheable` is still
+// stubbed (module-level `getSalts` binds it at this file's first import), so
+// `rotateSalt`'s `getSalts.clear()` never reaches a real Redis connection —
+// same reasoning as before this wave, just without the `@openpanel/db` mock.
+//
+// `getSalts` itself stays untested here: it is bare (no `deps` argument)
+// because ingest.service.ts's hot path calls it with none — see the module
+// header — and its `cacheable(...)` wrapping binds at this module's
+// first-ever evaluation, which a bare (non `--isolate`) `bun test` run does
+// not let this file control. `fetchSalts` (the uncached read it wraps) is
+// exercised directly instead.
import { afterAll, beforeAll, beforeEach, expect, mock, test } from 'bun:test';
@@ -57,12 +65,6 @@ const $transaction = mock(
fn({ salt: saltDelegate })
);
-const actualPrismaClient = await import('@openpanel/db/src/prisma-client');
-mock.module('@openpanel/db/src/prisma-client', () => ({
- ...actualPrismaClient,
- db: { salt: saltDelegate, $transaction },
-}));
-
// Bypasses the Redis cache-aside entirely, same as organization.service.test.ts's
// `cacheableStub` — this module's own logic is exercised directly, caching is
// @openpanel/redis's concern. Only the `cacheable(name, fn, ttl)` overload
@@ -89,9 +91,15 @@ afterAll(() => {
mock.module('@openpanel/redis', () => realRedis);
});
-let subject: typeof import('./salt.service');
+let subject: import('./salt.service').SaltService;
+let fetchSalts: typeof import('./salt.service').fetchSalts;
beforeAll(async () => {
- subject = await import('./salt.service');
+ const mod = await import('./salt.service');
+ fetchSalts = mod.fetchSalts;
+ const deps = {
+ db: { salt: saltDelegate, $transaction },
+ } as unknown as import('../../services').ServiceDeps;
+ subject = mod.createSaltService(deps);
});
beforeEach(() => {
@@ -117,19 +125,17 @@ test('createInitialSalts is a no-op once a salt already exists', async () => {
expect(saltStore[0]?.salt).toBe('existing');
});
-// `fetchSalts` is the uncached read `getSalts` wraps — asserted directly
-// rather than through `getSalts` itself, because `getSalts`'s `cacheable(...)`
-// wrapping is bound at this module's first-ever evaluation, which a bare
-// (non `--isolate`) `bun test` run does not let this file control (see the
-// module header). `createInitialSalts`'s own tests above already exercise
-// the same "does a salt exist" branch through the production call path.
test('fetchSalts returns current + previous, newest first', async () => {
resetStore([
{ salt: 'older', createdAt: new Date('2024-01-01T00:00:00Z') },
{ salt: 'newer', createdAt: new Date('2024-01-02T00:00:00Z') },
]);
- await expect(subject.fetchSalts()).resolves.toEqual({
+ await expect(
+ fetchSalts({
+ db: { salt: saltDelegate },
+ } as unknown as import('../../services').ServiceDeps)
+ ).resolves.toEqual({
current: 'newer',
previous: 'older',
});
@@ -138,7 +144,11 @@ test('fetchSalts returns current + previous, newest first', async () => {
test('fetchSalts falls back previous to current when only one salt exists', async () => {
resetStore([{ salt: 'only-one', createdAt: new Date() }]);
- await expect(subject.fetchSalts()).resolves.toEqual({
+ await expect(
+ fetchSalts({
+ db: { salt: saltDelegate },
+ } as unknown as import('../../services').ServiceDeps)
+ ).resolves.toEqual({
current: 'only-one',
previous: 'only-one',
});
@@ -147,7 +157,11 @@ test('fetchSalts falls back previous to current when only one salt exists', asyn
test('fetchSalts throws when the table is empty', async () => {
resetStore([]);
- await expect(subject.fetchSalts()).rejects.toThrow('No salt found');
+ await expect(
+ fetchSalts({
+ db: { salt: saltDelegate },
+ } as unknown as import('../../services').ServiceDeps)
+ ).rejects.toThrow('No salt found');
});
test('rotateSalt adds a salt and prunes everything except it and the previous newest', async () => {
diff --git a/packages/core/src/modules/salt/salt.service.ts b/packages/core/src/modules/salt/salt.service.ts
index 475d02d75..3b55126a1 100644
--- a/packages/core/src/modules/salt/salt.service.ts
+++ b/packages/core/src/modules/salt/salt.service.ts
@@ -3,25 +3,22 @@
// and cron dispatch (rotateSalt, exported there as `salt`) stay the LIVE call
// sites (DELEGATE PATTERN); packages/db keeps a re-export shim.
//
-// db access is LAZY (`loadDb` below), narrowed to `@openpanel/db/src/prisma-client`
-// — this module is pulled into the eager barrel via ingest.service.ts, which
-// resolves salts on every /track call, and a static import of the full
-// @openpanel/db barrel here would spawn a pino-pretty transport worker per
-// `bun test --isolate` file (see organization.service.ts's header for the
-// fuller reasoning).
+// M10-004: reaches Postgres as `deps.db`, no `@openpanel/db` import left.
+// `main.ts` passes its own `deps` to `createInitialSalts` at boot;
+// `salt.jobs.ts`'s handler passes its `JobCtx` (a `ServiceDeps` by
+// construction) to `rotateSalt`.
//
-// `getSalts` wraps `fetchSalts` in `cacheable(...)` — called once, eagerly,
-// at this module's first evaluation. `createInitialSalts` deliberately calls
-// the raw `fetchSalts` rather than `getSalts`: under a bare (non `--isolate`)
-// `bun test` run this module's first evaluation can be forced by an unrelated
-// earlier test file (anything eagerly reaching ingest.service.ts or the
-// jobs registry), which permanently binds `getSalts`'s caching to whatever
-// `@openpanel/redis` was at that moment — the same reason
-// organization.service.test.ts never exercises its own `cacheable`-wrapped
-// exports. `fetchSalts` never touches `@openpanel/redis`, so it stays
-// deterministic regardless of evaluation order.
+// `getSalts` is built ONCE per `createSaltService(deps)` call — its
+// `cacheable(...)` L1 LRU must survive across calls to stay useful. That
+// holds for the two places that matter: `ctx.services.salt` (one Ctx per
+// request, but nothing hot-path reads it that way yet) and the v1-compat
+// singleton (`registered`, built exactly once at boot by
+// `setV1CompatServices`) that `ingest.service.ts`'s `/track` hot path reads
+// through — see v1-compat.ts's header. `generateNewSalt` clears the SAME
+// closure's cache, which is why it lives inside the factory too.
import { cacheable } from '@openpanel/redis';
+import type { ServiceDeps } from '../../services';
import { generateSalt } from '../../shared/crypto';
const SALT_CACHE_NAME = 'op:salt';
@@ -40,18 +37,18 @@ export interface Salts {
previous: string;
}
-function loadDb() {
- return import('@openpanel/db/src/prisma-client').then((m) => m.db);
-}
+/** Only Postgres — narrowed so `main.ts`'s `AppDeps` (which has no `queues`
+ * yet at the point it calls `createInitialSalts`) satisfies it with no
+ * cast. */
+type SaltDeps = Pick<ServiceDeps, 'db'>;
function sleep(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}
/** The uncached read `getSalts` wraps — also boot's own existence check. */
-export async function fetchSalts(): Promise<Salts> {
- const db = await loadDb();
- const [curr, prev] = await db.salt.findMany({
+export async function fetchSalts(deps: SaltDeps): Promise<Salts> {
+ const [curr, prev] = await deps.db.salt.findMany({
orderBy: { createdAt: 'desc' },
take: SALT_HISTORY_SIZE,
});
@@ -63,75 +60,90 @@ export async function fetchSalts(): Promise<Salts> {
return { current: curr.salt, previous: prev?.salt ?? curr.salt };
}
-export const getSalts = cacheable(
- SALT_CACHE_NAME,
- fetchSalts,
- SALT_CACHE_TTL_SECONDS
-);
-
/** Boot bootstrap: creates the first two salts the first time this ever runs. */
-export async function createInitialSalts(retryCount = 0): Promise<void> {
+export async function createInitialSalts(
+ deps: SaltDeps,
+ retryCount = 0
+): Promise<void> {
try {
// Uncached: boot has nothing worth reusing a stale answer for.
- await fetchSalts();
+ await fetchSalts(deps);
} catch (error) {
if (!(error instanceof Error && error.message === NO_SALT_FOUND_MESSAGE)) {
if (retryCount >= MAX_RETRIES) {
throw new Error(`Failed to create salts after ${MAX_RETRIES} attempts`);
}
await sleep(BASE_RETRY_DELAY_MS * 2 ** retryCount);
- await createInitialSalts(retryCount + 1);
+ await createInitialSalts(deps, retryCount + 1);
return;
}
- const db = await loadDb();
- await db.salt.create({
+ await deps.db.salt.create({
data: {
salt: generateSalt(),
createdAt: new Date(Date.now() - INITIAL_PREVIOUS_SALT_BACKDATE_MS),
},
});
- await db.salt.create({ data: { salt: generateSalt() } });
+ await deps.db.salt.create({ data: { salt: generateSalt() } });
}
}
-async function generateNewSalt() {
- const db = await loadDb();
- const created = await db.$transaction(async (tx) => {
- const existingSalts = await tx.salt.findMany({
- orderBy: { createdAt: 'desc' },
- take: SALT_HISTORY_SIZE,
- });
+export interface SaltService {
+ getSalts(): Promise<Salts>;
+ createInitialSalts(): Promise<void>;
+ rotateSalt(): Promise<{ salt: string; createdAt: Date }>;
+}
- const newSalt = await tx.salt.create({ data: { salt: generateSalt() } });
+export function createSaltService(deps: ServiceDeps): SaltService {
+ const getSalts = cacheable(
+ SALT_CACHE_NAME,
+ () => fetchSalts(deps),
+ SALT_CACHE_TTL_SECONDS
+ );
- // Keep the new salt + the previous newest (if any).
- const previousNewest = existingSalts[0];
- const saltsToKeep = previousNewest
- ? [newSalt.salt, previousNewest.salt]
- : [newSalt.salt];
+ async function generateNewSalt() {
+ const created = await deps.db.$transaction(async (tx) => {
+ const existingSalts = await tx.salt.findMany({
+ orderBy: { createdAt: 'desc' },
+ take: SALT_HISTORY_SIZE,
+ });
- await tx.salt.deleteMany({ where: { salt: { notIn: saltsToKeep } } });
+ const newSalt = await tx.salt.create({ data: { salt: generateSalt() } });
- return newSalt;
- });
+ // Keep the new salt + the previous newest (if any).
+ const previousNewest = existingSalts[0];
+ const saltsToKeep = previousNewest
+ ? [newSalt.salt, previousNewest.salt]
+ : [newSalt.salt];
- await getSalts.clear();
+ await tx.salt.deleteMany({ where: { salt: { notIn: saltsToKeep } } });
- return created;
-}
+ return newSalt;
+ });
-/** Daily rotation: the `salt` cron job's body. */
-export async function rotateSalt(
- retryCount = 0
-): ReturnType<typeof generateNewSalt> {
- try {
- return await generateNewSalt();
- } catch (error) {
- if (retryCount >= MAX_RETRIES) {
- throw error;
+ await getSalts.clear();
+
+ return created;
+ }
+
+ /** Daily rotation: the `salt` cron job's body. */
+ async function rotateSalt(
+ retryCount = 0
+ ): ReturnType<typeof generateNewSalt> {
+ try {
+ return await generateNewSalt();
+ } catch (error) {
+ if (retryCount >= MAX_RETRIES) {
+ throw error;
+ }
+ await sleep(BASE_RETRY_DELAY_MS * 2 ** retryCount);
+ return rotateSalt(retryCount + 1);
}
- await sleep(BASE_RETRY_DELAY_MS * 2 ** retryCount);
- return rotateSalt(retryCount + 1);
}
+
+ return {
+ getSalts: () => getSalts(),
+ createInitialSalts: () => createInitialSalts(deps),
+ rotateSalt: () => rotateSalt(),
+ };
}
diff --git a/packages/core/src/modules/session/src/usage.ts b/packages/core/src/modules/session/src/usage.ts
index 02869977f..7db74ee34 100644
--- a/packages/core/src/modules/session/src/usage.ts
+++ b/packages/core/src/modules/session/src/usage.ts
@@ -9,7 +9,15 @@ import { sendEmail } from '../../../clients/email';
import { createLogger, type ILogger } from '../../../clients/logger';
import type { Logger } from '../../../logger';
import { getOrganizationBillingEventsCount } from '../../organization/organization.service';
-import { getProjectEventsCount } from '../../project/project.service';
+
+// project.service.ts's `getProjectEventsCount` takes `ServiceDeps` now
+// (M10-004); this file has none (its own db access is the lazy `loadDb()`
+// below), so it reaches the bare, v1-compat-wrapped spelling instead.
+// GENUINE CYCLE, kept lazy: services.ts -> session.service.ts -> this file
+// -> v1-compat.ts -> services.ts.
+function loadProjectService() {
+ return import('../../../v1-compat');
+}
const INT4_MAX = 2_147_483_647;
const USAGE_WARNING_THRESHOLD = 0.8;
@@ -73,6 +81,7 @@ export const updateEventsCount = cacheable(async function updateEventsCount(
const organizationEventsCount =
await getOrganizationBillingEventsCount(organization);
+ const { getProjectEventsCount } = await loadProjectService();
const projectEventsCount = await getProjectEventsCount(projectId);
if (projectEventsCount) {
diff --git a/packages/core/src/modules/subscription/subscription.routes.ts b/packages/core/src/modules/subscription/subscription.routes.ts
index 5d8ed6792..57e421f93 100644
--- a/packages/core/src/modules/subscription/subscription.routes.ts
+++ b/packages/core/src/modules/subscription/subscription.routes.ts
@@ -17,7 +17,6 @@
// already used" (M9-004, which mounted this surface).
import { defineRoutes } from '../../http/define';
-import { handlePolarWebhookEvent } from './subscription.service';
export const subscriptionRoutes = defineRoutes((app) =>
app.post(
@@ -27,7 +26,11 @@ export const subscriptionRoutes = defineRoutes((app) =>
const headers = Object.fromEntries(request.headers);
try {
- await handlePolarWebhookEvent(rawBody, headers, ctx.logger);
+ await ctx.services.subscription.handlePolarWebhookEvent(
+ rawBody,
+ headers,
+ ctx.logger
+ );
} catch {
return status(500, 'Error');
}
diff --git a/packages/core/src/modules/subscription/subscription.rpc.ts b/packages/core/src/modules/subscription/subscription.rpc.ts
index c2a0509bc..731ec4558 100644
--- a/packages/core/src/modules/subscription/subscription.rpc.ts
+++ b/packages/core/src/modules/subscription/subscription.rpc.ts
@@ -10,7 +10,8 @@
// PATTERN), so nothing here is a live regression.
//
// `requireOrganizationAdmin` lives in subscription.service.ts, not here —
-// see that file's header.
+// see that file's header. `ctx.services.subscription` carries this module's
+// factory the same as every other module now (M10-004).
import { z } from 'zod';
import { createTRPCRouter, procedure } from '../../rpc/base';
@@ -20,17 +21,6 @@ import {
zCheckout,
zPauseSubscription,
} from './subscription.constants';
-import {
- applySaveDiscount,
- cancelSubscription,
- checkout,
- getCurrentSubscriptionProduct,
- getUsage,
- listProducts,
- pauseSubscription,
- portal,
- resumeSubscription,
-} from './subscription.service';
function requireLogin(userId: string | null | undefined): string {
if (!userId) {
@@ -42,49 +32,76 @@ function requireLogin(userId: string | null | undefined): string {
export const subscriptionRouter = createTRPCRouter({
getCurrent: procedure
.input(z.object({ organizationId: z.string() }))
- .query(({ input }) => getCurrentSubscriptionProduct(input.organizationId)),
+ .query(({ input, ctx }) =>
+ ctx.services.subscription.getCurrentSubscriptionProduct(
+ input.organizationId
+ )
+ ),
checkout: procedure
.input(zCheckout)
.mutation(({ input, ctx }) =>
- checkout(requireLogin(ctx.session.userId), input, ctx.remoteAddress)
+ ctx.services.subscription.checkout(
+ requireLogin(ctx.session.userId),
+ input,
+ ctx.remoteAddress
+ )
),
products: procedure
.input(z.object({ organizationId: z.string() }))
- .query(({ input }) => listProducts(input.organizationId)),
+ .query(({ input, ctx }) =>
+ ctx.services.subscription.listProducts(input.organizationId)
+ ),
usage: procedure
.input(z.object({ organizationId: z.string() }))
- .query(({ input }) => getUsage(input.organizationId)),
+ .query(({ input, ctx }) =>
+ ctx.services.subscription.getUsage(input.organizationId)
+ ),
cancelSubscription: procedure
.input(zCancelSubscription)
.mutation(({ input, ctx }) =>
- cancelSubscription(requireLogin(ctx.session.userId), input)
+ ctx.services.subscription.cancelSubscription(
+ requireLogin(ctx.session.userId),
+ input
+ )
),
pauseSubscription: procedure
.input(zPauseSubscription)
.mutation(({ input, ctx }) =>
- pauseSubscription(requireLogin(ctx.session.userId), input)
+ ctx.services.subscription.pauseSubscription(
+ requireLogin(ctx.session.userId),
+ input
+ )
),
resumeSubscription: procedure
.input(z.object({ organizationId: z.string() }))
.mutation(({ input, ctx }) =>
- resumeSubscription(requireLogin(ctx.session.userId), input.organizationId)
+ ctx.services.subscription.resumeSubscription(
+ requireLogin(ctx.session.userId),
+ input.organizationId
+ )
),
applySaveDiscount: procedure
.input(z.object({ organizationId: z.string() }))
.mutation(({ input, ctx }) =>
- applySaveDiscount(requireLogin(ctx.session.userId), input.organizationId)
+ ctx.services.subscription.applySaveDiscount(
+ requireLogin(ctx.session.userId),
+ input.organizationId
+ )
),
portal: procedure
.input(z.object({ organizationId: z.string() }))
.mutation(({ input, ctx }) =>
- portal(requireLogin(ctx.session.userId), input.organizationId)
+ ctx.services.subscription.portal(
+ requireLogin(ctx.session.userId),
+ input.organizationId
+ )
),
});
diff --git a/packages/core/src/modules/subscription/subscription.service.ts b/packages/core/src/modules/subscription/subscription.service.ts
index 2f5d7cdab..6089cb75c 100644
--- a/packages/core/src/modules/subscription/subscription.service.ts
+++ b/packages/core/src/modules/subscription/subscription.service.ts
@@ -8,23 +8,19 @@
// `requireOrganizationAdmin` travels with the business logic here rather than
// living in subscription.rpc.ts the way project.rpc.ts's simple ladder checks
// do: every mutating procedure in this module gates on it first, before
-// touching Polar. Every exported function here is still called directly by
-// `packages/trpc`'s LIVE V1 router with nothing but a `userId` (DELEGATE
-// PATTERN), so these can't take a `ctx`/`deps`; `requireOrganizationAdmin`
-// comes from auth.service.ts's single, lazily-memoized `getAccessChecks()`
-// (M10-002) instead.
+// touching Polar. `requireOrganizationAdmin` comes from auth.service.ts's
+// single, lazily-memoized `getAccessChecks()` (M10-002) — independent of
+// `ServiceDeps`, so it needs no change here.
//
-// db access and `getCache` are LAZY (`loadDb`/`loadCache` below), not a
-// static top-level import — see organization.service.ts's header for the db
-// half (constructing @openpanel/db's clients at import time would spawn a
-// pino-pretty transport worker thread per test file). `getCache` hit the same
-// barrel chain from the other direction: a static
-// `import { getCache } from '@openpanel/redis'` here broke every core test
-// that partially mocks `@openpanel/redis` (no `getCache` export) and reaches
-// this module through @openpanel/db's re-export shims (project.service.ts /
-// notification.service.ts -> @openpanel/core's barrel -> here), e.g.
-// organization.service.test.ts's `connectUserToOrganization` path via
-// access.service.ts.
+// M10-004: every function takes `ServiceDeps` and reaches Postgres as
+// `deps.db`; the `loadDb()`/`loadPrisma()` lazy loaders are gone.
+// `Prisma.DbNull` (the JSON-column null sentinel) has no home on `deps` — it
+// is a plain value on the namespace, not the client — so it is reached
+// through v1-compat.ts's `compatPrisma()` instead of importing
+// `@openpanel/db` here. `packages/trpc`'s still-live router calls every
+// function here bare (no `ServiceDeps`); those reach `createServices` through
+// the v1-compat singleton too — `subscription.routes.ts`'s own
+// `/webhook/polar` route already carries a `Ctx`.
import {
applySubscriptionDiscount,
@@ -40,10 +36,12 @@ import {
unpauseSubscription,
validatePolarEvent,
} from '@openpanel/payments';
+import { getCache, publishEvent } from '@openpanel/redis';
import { addMonths, subDays } from 'date-fns';
import { z } from 'zod';
import type { Logger } from '../../logger';
import { TRPCBadRequestError } from '../../rpc/errors';
+import type { ServiceDeps } from '../../services';
import { getAccessChecks } from '../auth/auth.service';
import {
getOrganizationBillingEventsCountSerieCached,
@@ -58,22 +56,18 @@ import {
zCancellationReason,
} from './subscription.constants';
+// GENUINE CYCLE, kept lazy: `services.ts` statically imports this file for
+// `createSubscriptionService`, and `v1-compat.ts` statically imports
+// `services.ts` for `createServices` — so `loadCompatPrisma` reaches
+// `v1-compat.ts` through a dynamic `import()`, not a static one.
+function loadCompatPrisma() {
+ return import('../../v1-compat').then((m) => m.compatPrisma());
+}
+
const POLAR_PRODUCTS_CACHE_KEY = 'polar:products';
const POLAR_PRODUCTS_CACHE_TTL_SECONDS = 60 * 60 * 24;
const DEFAULT_USAGE_WINDOW_DAYS = 30;
-function loadDb() {
- return import('@openpanel/db/src/prisma-client').then((m) => m.db);
-}
-
-function loadPrisma() {
- return import('@openpanel/db/src/prisma-client').then((m) => m.Prisma);
-}
-
-function loadCache() {
- return import('@openpanel/redis').then((m) => m.getCache);
-}
-
export async function getCurrentSubscriptionProduct(organizationId: string) {
const organization = await getOrganizationById(organizationId);
@@ -85,6 +79,7 @@ export async function getCurrentSubscriptionProduct(organizationId: string) {
}
export async function checkout(
+ deps: ServiceDeps,
userId: string,
input: ICheckout,
ipAddress: string | undefined
@@ -95,10 +90,11 @@ export async function checkout(
organizationId: input.organizationId,
});
- const db = await loadDb();
const [user, organization] = await Promise.all([
- db.user.findFirstOrThrow({ where: { id: userId } }),
- db.organization.findFirstOrThrow({ where: { id: input.organizationId } }),
+ deps.db.user.findFirstOrThrow({ where: { id: userId } }),
+ deps.db.organization.findFirstOrThrow({
+ where: { id: input.organizationId },
+ }),
]);
// A paused (or pause-scheduled) subscription still exists in Polar — a
@@ -147,15 +143,12 @@ export async function checkout(
return { url: checkoutSession.url };
}
-export async function listProducts(organizationId: string) {
- const db = await loadDb();
- const organization = await db.organization.findUniqueOrThrow({
+export async function listProducts(deps: ServiceDeps, organizationId: string) {
+ const organization = await deps.db.organization.findUniqueOrThrow({
where: { id: organizationId },
select: { subscriptionPeriodEventsCount: true },
});
- const getCache = await loadCache();
-
return (
await getCache(
POLAR_PRODUCTS_CACHE_KEY,
@@ -175,9 +168,8 @@ export async function listProducts(organizationId: string) {
});
}
-export async function getUsage(organizationId: string) {
- const db = await loadDb();
- const organization = await db.organization.findUniqueOrThrow({
+export async function getUsage(deps: ServiceDeps, organizationId: string) {
+ const organization = await deps.db.organization.findUniqueOrThrow({
where: { id: organizationId },
include: { projects: { select: { id: true } } },
});
@@ -200,6 +192,7 @@ export async function getUsage(organizationId: string) {
}
export async function cancelSubscription(
+ deps: ServiceDeps,
userId: string,
input: ICancelSubscription
) {
@@ -223,8 +216,7 @@ export async function cancelSubscription(
// delayed delivery can't lose the reason — or leave `canceledAt` unset,
// which would make the plan-change path skip reactivation and silently
// keep the cancellation scheduled.
- const db = await loadDb();
- await db.organization.update({
+ await deps.db.organization.update({
where: { id: input.organizationId },
data: {
subscriptionCancelReason: input.reason,
@@ -240,6 +232,7 @@ export async function cancelSubscription(
}
export async function pauseSubscription(
+ deps: ServiceDeps,
userId: string,
input: IPauseSubscription
) {
@@ -269,8 +262,7 @@ export async function pauseSubscription(
await pausePolarSubscription(organization.subscriptionId, resumesAt);
// Optimistic mirror — the subscription.updated webhook confirms it.
- const db = await loadDb();
- await db.organization.update({
+ await deps.db.organization.update({
where: { id: input.organizationId },
data: {
subscriptionPauseAtPeriodEnd: true,
@@ -282,6 +274,7 @@ export async function pauseSubscription(
}
export async function resumeSubscription(
+ deps: ServiceDeps,
userId: string,
organizationId: string
) {
@@ -303,8 +296,7 @@ export async function resumeSubscription(
throw new TRPCBadRequestError('Subscription is not paused');
}
- const db = await loadDb();
- await db.organization.update({
+ await deps.db.organization.update({
where: { id: organizationId },
data: {
subscriptionPauseAtPeriodEnd: false,
@@ -316,6 +308,7 @@ export async function resumeSubscription(
}
export async function applySaveDiscount(
+ deps: ServiceDeps,
userId: string,
organizationId: string
) {
@@ -336,8 +329,7 @@ export async function applySaveDiscount(
// conditional update lets exactly one concurrent request through. Roll
// the claim back if Polar rejects, so a transient failure doesn't burn
// the offer.
- const db = await loadDb();
- const claimed = await db.organization.updateMany({
+ const claimed = await deps.db.organization.updateMany({
where: { id: organizationId, subscriptionSaveDiscountAppliedAt: null },
data: { subscriptionSaveDiscountAppliedAt: new Date() },
});
@@ -348,7 +340,7 @@ export async function applySaveDiscount(
try {
await applySubscriptionDiscount(organization.subscriptionId, discountId);
} catch (error) {
- await db.organization.updateMany({
+ await deps.db.organization.updateMany({
where: { id: organizationId },
data: { subscriptionSaveDiscountAppliedAt: null },
});
@@ -474,9 +466,13 @@ function diffOrganizationFields(
return changes;
}
-async function clearOrganizationCache(organizationId: string) {
- const db = await loadDb();
- const projects = await db.project.findMany({ where: { organizationId } });
+async function clearOrganizationCache(
+ deps: ServiceDeps,
+ organizationId: string
+) {
+ const projects = await deps.db.project.findMany({
+ where: { organizationId },
+ });
for (const project of projects) {
await getOrganizationByProjectIdCached.clear(project.id);
}
@@ -490,6 +486,7 @@ async function clearOrganizationCache(organizationId: string) {
* reactivations, plan changes and payment-state changes in one place.
*/
async function syncSubscriptionToOrg(
+ deps: ServiceDeps,
data: PolarSubscriptionData,
eventType: string,
logger: Logger
@@ -497,8 +494,7 @@ async function syncSubscriptionToOrg(
const metadata = subscriptionMetadataSchema.parse(data.metadata);
const isCanceled = data.status === 'canceled';
- const db = await loadDb();
- const organization = await db.organization.findUniqueOrThrow({
+ const organization = await deps.db.organization.findUniqueOrThrow({
where: { id: metadata.organizationId },
});
@@ -563,7 +559,7 @@ async function syncSubscriptionToOrg(
);
}
- const Prisma = await loadPrisma();
+ const { DbNull } = await loadCompatPrisma();
const updateData = {
subscriptionId: data.id,
@@ -588,8 +584,7 @@ async function syncSubscriptionToOrg(
subscriptionCancelComment: data.customerCancellationComment ?? null,
subscriptionPauseAtPeriodEnd: data.pauseAtPeriodEnd,
subscriptionResumesAt: data.resumesAt,
- subscriptionDiscount:
- toSubscriptionDiscount(data.discount) ?? Prisma.DbNull,
+ subscriptionDiscount: toSubscriptionDiscount(data.discount) ?? DbNull,
// Stable tenure anchor: keep the stored value while the subscription id is
// unchanged; a new subscription (re-subscribe) restarts tenure.
subscriptionFirstStartedAt:
@@ -627,14 +622,13 @@ async function syncSubscriptionToOrg(
TRACKED_SUBSCRIPTION_FIELDS
);
- await db.organization.update({
+ await deps.db.organization.update({
where: { id: metadata.organizationId },
data: updateData,
});
- await clearOrganizationCache(metadata.organizationId);
+ await clearOrganizationCache(deps, metadata.organizationId);
- const { publishEvent } = await import('@openpanel/redis');
await publishEvent('organization', 'subscription_updated', {
organizationId: metadata.organizationId,
});
@@ -662,6 +656,7 @@ async function syncSubscriptionToOrg(
* this module's own Elysia route (via `request.text()`) both preserve this.
*/
export async function handlePolarWebhookEvent(
+ deps: ServiceDeps,
rawBody: string | Buffer,
headers: Record<string, string>,
logger: Logger
@@ -712,7 +707,7 @@ export async function handlePolarWebhookEvent(
}
try {
- await dispatchPolarWebhookEvent(event, eventCtx, logger);
+ await dispatchPolarWebhookEvent(deps, event, eventCtx, logger);
} catch (err) {
logger.error(
{ err, ...eventCtx },
@@ -723,6 +718,7 @@ export async function handlePolarWebhookEvent(
}
async function dispatchPolarWebhookEvent(
+ deps: ServiceDeps,
event: PolarEvent,
eventCtx: {
eventType: string;
@@ -753,13 +749,12 @@ async function dispatchPolarWebhookEvent(
.object({ organizationId: z.string() })
.parse(event.data.metadata);
- const db = await loadDb();
- const previous = await db.organization.findUnique({
+ const previous = await deps.db.organization.findUnique({
where: { id: metadata.organizationId },
select: { subscriptionPeriodEventsCount: true },
});
- await db.organization.update({
+ await deps.db.organization.update({
where: { id: metadata.organizationId },
data: {
subscriptionPeriodEventsCount: 0,
@@ -770,7 +765,7 @@ async function dispatchPolarWebhookEvent(
},
});
- await clearOrganizationCache(metadata.organizationId);
+ await clearOrganizationCache(deps, metadata.organizationId);
logger.info(
{
@@ -794,7 +789,7 @@ async function dispatchPolarWebhookEvent(
case 'subscription.canceled':
case 'subscription.revoked':
case 'subscription.past_due': {
- await syncSubscriptionToOrg(event.data, event.type, logger);
+ await syncSubscriptionToOrg(deps, event.data, event.type, logger);
return;
}
default: {
@@ -802,3 +797,61 @@ async function dispatchPolarWebhookEvent(
}
}
}
+
+export interface SubscriptionService {
+ getCurrentSubscriptionProduct(
+ organizationId: string
+ ): ReturnType<typeof getCurrentSubscriptionProduct>;
+ checkout(
+ userId: string,
+ input: ICheckout,
+ ipAddress: string | undefined
+ ): ReturnType<typeof checkout>;
+ listProducts(organizationId: string): ReturnType<typeof listProducts>;
+ getUsage(organizationId: string): ReturnType<typeof getUsage>;
+ cancelSubscription(
+ userId: string,
+ input: ICancelSubscription
+ ): ReturnType<typeof cancelSubscription>;
+ pauseSubscription(
+ userId: string,
+ input: IPauseSubscription
+ ): ReturnType<typeof pauseSubscription>;
+ resumeSubscription(
+ userId: string,
+ organizationId: string
+ ): ReturnType<typeof resumeSubscription>;
+ applySaveDiscount(
+ userId: string,
+ organizationId: string
+ ): ReturnType<typeof applySaveDiscount>;
+ portal(userId: string, organizationId: string): ReturnType<typeof portal>;
+ handlePolarWebhookEvent(
+ rawBody: string | Buffer,
+ headers: Record<string, string>,
+ logger: Logger
+ ): Promise<void>;
+}
+
+export function createSubscriptionService(
+ deps: ServiceDeps
+): SubscriptionService {
+ return {
+ getCurrentSubscriptionProduct,
+ checkout: (userId, input, ipAddress) =>
+ checkout(deps, userId, input, ipAddress),
+ listProducts: (organizationId) => listProducts(deps, organizationId),
+ getUsage: (organizationId) => getUsage(deps, organizationId),
+ cancelSubscription: (userId, input) =>
+ cancelSubscription(deps, userId, input),
+ pauseSubscription: (userId, input) =>
+ pauseSubscription(deps, userId, input),
+ resumeSubscription: (userId, organizationId) =>
+ resumeSubscription(deps, userId, organizationId),
+ applySaveDiscount: (userId, organizationId) =>
+ applySaveDiscount(deps, userId, organizationId),
+ portal,
+ handlePolarWebhookEvent: (rawBody, headers, logger) =>
+ handlePolarWebhookEvent(deps, rawBody, headers, logger),
+ };
+}
diff --git a/packages/core/src/modules/user/user.rpc.ts b/packages/core/src/modules/user/user.rpc.ts
index 6f111b447..acd14970e 100644
--- a/packages/core/src/modules/user/user.rpc.ts
+++ b/packages/core/src/modules/user/user.rpc.ts
@@ -7,18 +7,14 @@
// 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 user functions (DELEGATE PATTERN) —
-// this module has no queue/cron of its own, so there is no
-// `ctx.services.user`, same as `conversation`.
+// `ctx.services.user` carries this module's factory the same as every other
+// module now (M10-004); it has no queue/cron of its own, same as
+// `conversation`.
import { z } from 'zod';
import { createTRPCRouter, procedure } from '../../rpc/base';
import { TRPCAccessError } from '../../rpc/errors';
import { deleteSessionTokenCookie } from '../auth/auth.service';
-import {
- deleteUserAccount,
- listUserDeletionBlockers,
- updateUserProfile,
-} from './user.service';
function requireLogin(userId: string | null | undefined): string {
if (!userId) {
@@ -30,12 +26,12 @@ function requireLogin(userId: string | null | undefined): string {
export const userRouter = createTRPCRouter({
deletionBlockers: procedure.query(async ({ ctx }) => {
const userId = requireLogin(ctx.session.userId);
- return listUserDeletionBlockers(userId);
+ return ctx.services.user.listUserDeletionBlockers(userId);
}),
delete: procedure.mutation(async ({ ctx }) => {
const userId = requireLogin(ctx.session.userId);
- await deleteUserAccount(userId);
+ await ctx.services.user.deleteUserAccount(userId);
deleteSessionTokenCookie(ctx.setCookie);
return true;
}),
@@ -49,7 +45,7 @@ export const userRouter = createTRPCRouter({
)
.mutation(async ({ input, ctx }) => {
const userId = requireLogin(ctx.session.userId);
- return updateUserProfile({ userId, ...input });
+ return ctx.services.user.updateUserProfile({ userId, ...input });
}),
debugPostCookie: procedure
diff --git a/packages/core/src/modules/user/user.service.test.ts b/packages/core/src/modules/user/user.service.test.ts
index c268504b1..4404815b6 100644
--- a/packages/core/src/modules/user/user.service.test.ts
+++ b/packages/core/src/modules/user/user.service.test.ts
@@ -1,10 +1,10 @@
-// user.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-004), so
+// Postgres needs no module mock at all — `deps.db` IS the fake below, same
+// idiom as reference.service.test.ts.
-import { beforeAll, beforeEach, expect, mock, test } from 'bun:test';
+import { beforeEach, expect, mock, test } from 'bun:test';
+import type { ServiceDeps } from '../../services';
+import { createUserService } from './user.service';
interface FakeUser {
id: string;
@@ -90,16 +90,9 @@ const organization = {
),
};
-const actualPrismaClient = await import('@openpanel/db/src/prisma-client');
-mock.module('@openpanel/db/src/prisma-client', () => ({
- ...actualPrismaClient,
+const subject = createUserService({
db: { user, organization },
-}));
-
-let subject: typeof import('./user.service');
-beforeAll(async () => {
- subject = await import('./user.service');
-});
+} as unknown as ServiceDeps);
beforeEach(() => {
userStore.clear();
diff --git a/packages/core/src/modules/user/user.service.ts b/packages/core/src/modules/user/user.service.ts
index ad785da28..ef7867652 100644
--- a/packages/core/src/modules/user/user.service.ts
+++ b/packages/core/src/modules/user/user.service.ts
@@ -3,44 +3,45 @@
// ported) still reach `getUserById`/`getUserAccount`/`IServiceUser` through
// @openpanel/db's barrel, same shape as packages/db/src/gsc.ts since M5-002.
//
-// 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).
-//
-// No `UserService` / `createUserService` here: this module has no queue or
-// cron of its own (module map: user is R,S only), so there is nothing that
-// needs a Ctx-bound container — same shape as conversation.service.ts.
+// M10-004: every function takes `ServiceDeps` and reaches Postgres as
+// `deps.db`; the `loadDb()` lazy loader is gone. `onboarding.service.ts`'s
+// own `getUserById` call and `packages/trpc`'s bare calls have no `deps` to
+// hand it, so they reach these through v1-compat.ts's bare re-exports
+// instead (see v1-compat.ts's header) — `auth.service.ts` calls
+// `getUserAccount` directly since it already carries `deps` itself.
+import type { User } from '@openpanel/db/src/prisma-client';
import { TRPCBadRequestError } from '../../rpc/errors';
+import type { ServiceDeps } from '../../services';
export type IServiceUser = Awaited<ReturnType<typeof getUserById>>;
-function loadDb() {
- return import('@openpanel/db/src/prisma-client').then((m) => m.db);
-}
-
-export async function getUserById(id: string) {
- const db = await loadDb();
- return db.user.findUniqueOrThrow({
+// Explicit `Promise<User>` return type, not inferred: Prisma's
+// `findUniqueOrThrow` returns a chainable "fluent" client (PromiseLike, plus
+// relation-loading methods), which trips up `Services['user']['getUserById']`
+// in v1-compat.ts — a `.then(...)` wrapping a bare fluent type there can't
+// unify with the plain `Promise<User>` the interface declares.
+export function getUserById(deps: ServiceDeps, id: string): Promise<User> {
+ return deps.db.user.findUniqueOrThrow({
where: {
id,
},
});
}
-export async function getUserAccount({
- email,
- provider,
- providerId,
-}: {
- email: string;
- provider: string;
- providerId?: string;
-}) {
- const db = await loadDb();
- const res = await db.user.findFirst({
+export async function getUserAccount(
+ deps: ServiceDeps,
+ {
+ email,
+ provider,
+ providerId,
+ }: {
+ email: string;
+ provider: string;
+ providerId?: string;
+ }
+) {
+ const res = await deps.db.user.findFirst({
where: {
email: {
equals: email,
@@ -79,10 +80,10 @@ export interface UserDeletionBlocker {
* any of these exist.
*/
export async function listUserDeletionBlockers(
+ deps: ServiceDeps,
userId: string
): Promise<UserDeletionBlocker[]> {
- const db = await loadDb();
- const organizations = await db.organization.findMany({
+ const organizations = await deps.db.organization.findMany({
where: { createdByUserId: userId },
});
return organizations
@@ -103,8 +104,11 @@ export async function listUserDeletionBlockers(
* set to null (SetNull); any org left without an org:admin member is then
* removed by the organization module's `delete` cron.
*/
-export async function deleteUserAccount(userId: string): Promise<void> {
- const blockers = await listUserDeletionBlockers(userId);
+export async function deleteUserAccount(
+ deps: ServiceDeps,
+ userId: string
+): Promise<void> {
+ const blockers = await listUserDeletionBlockers(deps, userId);
if (blockers.length > 0) {
throw new TRPCBadRequestError(
@@ -114,17 +118,18 @@ export async function deleteUserAccount(userId: string): Promise<void> {
);
}
- const db = await loadDb();
- await db.user.delete({ where: { id: userId } });
+ await deps.db.user.delete({ where: { id: userId } });
}
-export async function updateUserProfile(input: {
- userId: string;
- firstName: string;
- lastName: string;
-}) {
- const db = await loadDb();
- return db.user.update({
+export async function updateUserProfile(
+ deps: ServiceDeps,
+ input: {
+ userId: string;
+ firstName: string;
+ lastName: string;
+ }
+) {
+ return deps.db.user.update({
where: {
id: input.userId,
},
@@ -134,3 +139,26 @@ export async function updateUserProfile(input: {
},
});
}
+
+export interface UserService {
+ getUserById(id: string): ReturnType<typeof getUserById>;
+ getUserAccount(
+ args: Parameters<typeof getUserAccount>[1]
+ ): ReturnType<typeof getUserAccount>;
+ listUserDeletionBlockers(userId: string): Promise<UserDeletionBlocker[]>;
+ deleteUserAccount(userId: string): Promise<void>;
+ updateUserProfile(
+ input: Parameters<typeof updateUserProfile>[1]
+ ): ReturnType<typeof updateUserProfile>;
+}
+
+export function createUserService(deps: ServiceDeps): UserService {
+ return {
+ getUserById: (id) => getUserById(deps, id),
+ getUserAccount: (args) => getUserAccount(deps, args),
+ listUserDeletionBlockers: (userId) =>
+ listUserDeletionBlockers(deps, userId),
+ deleteUserAccount: (userId) => deleteUserAccount(deps, userId),
+ updateUserProfile: (input) => updateUserProfile(deps, input),
+ };
+}
diff --git a/packages/core/src/services.ts b/packages/core/src/services.ts
index 3aeabe04f..5123bacf0 100644
--- a/packages/core/src/services.ts
+++ b/packages/core/src/services.ts
@@ -3,6 +3,10 @@
// before it with an empty interface.
import type { Ctx } from './context';
+import {
+ type AssistantService,
+ createAssistantService,
+} from './modules/assistant/assistant.service';
import {
type AuthService,
createAuthService,
@@ -11,10 +15,18 @@ import {
type ChartService,
createChartService,
} from './modules/chart/chart.service';
+import {
+ type ClientService,
+ createClientService,
+} from './modules/client/client.service';
import {
type CohortService,
createCohortService,
} from './modules/cohort/cohort.service';
+import {
+ type ConversationService,
+ createConversationService,
+} from './modules/conversation/conversation.service';
import {
createDashboardService,
type DashboardService,
@@ -44,6 +56,7 @@ import {
createInsightService,
type InsightService,
} from './modules/insight/insight.service';
+import { createMcpService, type McpService } from './modules/mcp/mcp.service';
import {
createMiscService,
type MiscService,
@@ -64,6 +77,10 @@ import {
createProfileService,
type ProfileService,
} from './modules/profile/profile.service';
+import {
+ createProjectService,
+ type ProjectService,
+} from './modules/project/project.service';
import {
createReferenceService,
type ReferenceService,
@@ -72,6 +89,10 @@ import {
createReportService,
type ReportService,
} from './modules/report/report.service';
+import {
+ createSaltService,
+ type SaltService,
+} from './modules/salt/salt.service';
import {
createSessionService,
type SessionService,
@@ -80,6 +101,14 @@ import {
createShareService,
type ShareService,
} from './modules/share/share.service';
+import {
+ createSubscriptionService,
+ type SubscriptionService,
+} from './modules/subscription/subscription.service';
+import {
+ createUserService,
+ type UserService,
+} from './modules/user/user.service';
/** What every service factory receives — derived from Ctx, so it cannot drift. */
export type ServiceDeps = Pick<
@@ -117,6 +146,14 @@ export interface Services {
export: ExportService;
share: ShareService;
reference: ReferenceService;
+ client: ClientService;
+ project: ProjectService;
+ user: UserService;
+ subscription: SubscriptionService;
+ salt: SaltService;
+ conversation: ConversationService;
+ assistant: AssistantService;
+ mcp: McpService;
}
export function createServices(deps: ServiceDeps): Services {
@@ -144,5 +181,13 @@ export function createServices(deps: ServiceDeps): Services {
export: createExportService(deps),
share: createShareService(deps),
reference: createReferenceService(deps),
+ client: createClientService(deps),
+ project: createProjectService(deps),
+ user: createUserService(deps),
+ subscription: createSubscriptionService(deps),
+ salt: createSaltService(deps),
+ conversation: createConversationService(deps),
+ assistant: createAssistantService(deps),
+ mcp: createMcpService(deps),
};
}
diff --git a/packages/core/src/shared/access-lookups.ts b/packages/core/src/shared/access-lookups.ts
index 76db4f186..40e5bda2f 100644
--- a/packages/core/src/shared/access-lookups.ts
+++ b/packages/core/src/shared/access-lookups.ts
@@ -10,15 +10,27 @@
// 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-004: `project.service.ts`'s `getProjectById` now takes `ServiceDeps`,
+// which this file has none of — reached through the v1-compat singleton
+// instead (see v1-compat.ts's header). GENUINE CYCLE, kept lazy: auth.service.ts
+// -> this file (via `access-lookups`) is already lazy on the OTHER side;
+// v1-compat.ts -> services.ts -> project.service.ts has no edge back to this
+// file, but `getAccessChecks()` in auth.service.ts reaches both this file and
+// project.service.ts, so a static import here risks the same evaluation-order
+// hazard `getAccessChecks()`'s own header warns about.
import type { AccessLevel } from '@openpanel/db/src/prisma-client';
import { cacheable } from '@openpanel/redis';
-import { getProjectById } from '../modules/project/project.service';
function loadDb() {
return import('@openpanel/db/src/prisma-client').then((m) => m.db);
}
+function loadProjectService() {
+ return import('../v1-compat');
+}
+
export interface IProjectAccess {
level: AccessLevel;
}
@@ -57,7 +69,9 @@ export const getProjectAccess = cacheable(
}): Promise<IProjectAccess | null> => {
try {
// Check if user has access to the project
- const project = await getProjectById(projectId);
+ const project = await (await loadProjectService()).getProjectById(
+ projectId
+ );
if (!project?.organizationId) {
return null;
}
diff --git a/packages/core/src/v1-compat.ts b/packages/core/src/v1-compat.ts
index 824fe1572..3317ed6e9 100644
--- a/packages/core/src/v1-compat.ts
+++ b/packages/core/src/v1-compat.ts
@@ -27,12 +27,34 @@
// what keeps `bun test` runnable offline.
import {
+ disableTotp as authDisableTotp,
+ enableTotp as authEnableTotp,
+ extendSessionCookie as authExtendSessionCookie,
+ getTotpStatus as authGetTotpStatus,
+ regenerateTotpRecoveryCodes as authRegenerateTotpRecoveryCodes,
+ requestPasswordReset as authRequestPasswordReset,
+ resetPasswordWithToken as authResetPasswordWithToken,
+ setupTotp as authSetupTotp,
+ signInWithEmail as authSignInWithEmail,
+ signInWithTotp as authSignInWithTotp,
+ signOutUser as authSignOutUser,
+ signUpWithEmail as authSignUpWithEmail,
type SignInShareInput,
signInToShare as signInToShareWithDeps,
} from './modules/auth/auth.service';
import { createServices, type ServiceDeps, type Services } from './services';
import type { ISetCookie } from './shared/cookie';
+/** Drops a function type's first (`deps`) parameter — every bare V1-compat
+ * wrapper below has the same shape: the underlying function's parameters
+ * minus `deps`, since this seam supplies that one itself. */
+type Tail<T extends readonly unknown[]> = T extends readonly [
+ unknown,
+ ...infer Rest,
+]
+ ? Rest
+ : never;
+
let registered: Services | undefined;
let registeredDeps: ServiceDeps | undefined;
@@ -104,6 +126,64 @@ function services(): Promise<Services> {
: fallbackServiceDeps().then(createServices);
}
+/**
+ * The hot-path escape hatches (M10-004): a handful of callers — the ingest
+ * pipeline's client auth, MCP's stateless tool handlers, the chat agent's
+ * Prisma persistence — have a fixed, third-party-owned function signature
+ * with no `Ctx`/`ServiceDeps` slot to add one to. They reach
+ * Postgres/ClickHouse through these instead of `@openpanel/db` directly, so
+ * a requestId minted at `/track` at least reaches AS FAR as this seam
+ * reaches (no further — see this file's header on why that's still "no
+ * worse" than before this wave).
+ */
+export async function compatDb(): Promise<ServiceDeps['db']> {
+ return (await compatServiceDeps()).db;
+}
+export async function compatCh(): Promise<ServiceDeps['ch']> {
+ return (await compatServiceDeps()).ch;
+}
+/**
+ * `subscription.service.ts` (has `deps`, but `deps.db`'s type is the client
+ * instance, not the namespace) and `mcp`'s `dashboard-management.ts` (no
+ * `deps` at all) both need `Prisma.DbNull` — a plain sentinel value, not a
+ * client — to write an explicit SQL NULL onto a nullable Json column. The
+ * namespace lives in the same module as the constructed `db` singleton, so
+ * this seam is the only way to reach it without either module importing
+ * `@openpanel/db` itself.
+ */
+export async function compatPrisma(): Promise<
+ typeof import('@openpanel/db/src/prisma-client').Prisma
+> {
+ return (await import('@openpanel/db/src/prisma-client')).Prisma;
+}
+
+/**
+ * ADR-013 keeps `clix`/`chQuery`/`TABLE_NAMES` alive until the analytics read
+ * path's P7 conversion (one query per task, old-vs-new result sets diffed) —
+ * `project.service.ts`'s two still-unconverted functions and mcp's
+ * `analytics/property-values.ts` reach the query-building helpers here
+ * instead of importing `@openpanel/db` themselves. The CLIENT itself is
+ * still `deps.ch` / `compatCh()`; this is only the pure helpers that live
+ * beside it.
+ */
+export async function compatChHelpers(): Promise<{
+ TABLE_NAMES: typeof import('@openpanel/db/src/clickhouse/client').TABLE_NAMES;
+ chQuery: typeof import('@openpanel/db/src/clickhouse/client').chQuery;
+ convertClickhouseDateToJs: typeof import('@openpanel/db/src/clickhouse/client').convertClickhouseDateToJs;
+ clix: typeof import('@openpanel/db/src/clickhouse/query-builder').clix;
+}> {
+ const [client, queryBuilder] = await Promise.all([
+ import('@openpanel/db/src/clickhouse/client'),
+ import('@openpanel/db/src/clickhouse/query-builder'),
+ ]);
+ return {
+ TABLE_NAMES: client.TABLE_NAMES,
+ chQuery: client.chQuery,
+ convertClickhouseDateToJs: client.convertClickhouseDateToJs,
+ clix: queryBuilder.clix,
+ };
+}
+
// --- chart -----------------------------------------------------------------
export const getProjectCard: Services['chart']['getProjectCard'] = (...args) =>
@@ -411,3 +491,284 @@ export function signInToShare(
signInToShareWithDeps(deps, input, setCookie)
);
}
+
+// M10-004: every other bare auth function gained `ServiceDeps` too — same
+// reasoning as `signInToShare` above, each reached through this seam.
+export const signOutUser: (
+ ...args: Tail<Parameters<typeof authSignOutUser>>
+) => ReturnType<typeof authSignOutUser> = (...args) =>
+ compatServiceDeps().then((deps) => authSignOutUser(deps, ...args));
+
+export const signUpWithEmail: (
+ ...args: Tail<Parameters<typeof authSignUpWithEmail>>
+) => ReturnType<typeof authSignUpWithEmail> = (...args) =>
+ compatServiceDeps().then((deps) => authSignUpWithEmail(deps, ...args));
+
+export const signInWithEmail: (
+ ...args: Tail<Parameters<typeof authSignInWithEmail>>
+) => ReturnType<typeof authSignInWithEmail> = (...args) =>
+ compatServiceDeps().then((deps) => authSignInWithEmail(deps, ...args));
+
+export const signInWithTotp: (
+ ...args: Tail<Parameters<typeof authSignInWithTotp>>
+) => ReturnType<typeof authSignInWithTotp> = (...args) =>
+ compatServiceDeps().then((deps) => authSignInWithTotp(deps, ...args));
+
+export const getTotpStatus: (
+ ...args: Tail<Parameters<typeof authGetTotpStatus>>
+) => ReturnType<typeof authGetTotpStatus> = (...args) =>
+ compatServiceDeps().then((deps) => authGetTotpStatus(deps, ...args));
+
+export const setupTotp: (
+ ...args: Tail<Parameters<typeof authSetupTotp>>
+) => ReturnType<typeof authSetupTotp> = (...args) =>
+ compatServiceDeps().then((deps) => authSetupTotp(deps, ...args));
+
+export const enableTotp: (
+ ...args: Tail<Parameters<typeof authEnableTotp>>
+) => ReturnType<typeof authEnableTotp> = (...args) =>
+ compatServiceDeps().then((deps) => authEnableTotp(deps, ...args));
+
+export const disableTotp: (
+ ...args: Tail<Parameters<typeof authDisableTotp>>
+) => ReturnType<typeof authDisableTotp> = (...args) =>
+ compatServiceDeps().then((deps) => authDisableTotp(deps, ...args));
+
+export const regenerateTotpRecoveryCodes: (
+ ...args: Tail<Parameters<typeof authRegenerateTotpRecoveryCodes>>
+) => ReturnType<typeof authRegenerateTotpRecoveryCodes> = (...args) =>
+ compatServiceDeps().then((deps) =>
+ authRegenerateTotpRecoveryCodes(deps, ...args)
+ );
+
+export const resetPasswordWithToken: (
+ ...args: Tail<Parameters<typeof authResetPasswordWithToken>>
+) => ReturnType<typeof authResetPasswordWithToken> = (...args) =>
+ compatServiceDeps().then((deps) => authResetPasswordWithToken(deps, ...args));
+
+export const requestPasswordReset: (
+ ...args: Tail<Parameters<typeof authRequestPasswordReset>>
+) => ReturnType<typeof authRequestPasswordReset> = (...args) =>
+ compatServiceDeps().then((deps) => authRequestPasswordReset(deps, ...args));
+
+export const extendSessionCookie: (
+ ...args: Tail<Parameters<typeof authExtendSessionCookie>>
+) => ReturnType<typeof authExtendSessionCookie> = (...args) =>
+ compatServiceDeps().then((deps) => authExtendSessionCookie(deps, ...args));
+
+// --- client ------------------------------------------------------------
+
+export const getClientById: Services['client']['getClientById'] = (...args) =>
+ services().then((container) => container.client.getClientById(...args));
+export const getClientByIdCached: Services['client']['getClientByIdCached'] = (
+ ...args
+) =>
+ services().then((container) => container.client.getClientByIdCached(...args));
+export const clearClientByIdCache: Services['client']['clearClientByIdCache'] =
+ (...args) =>
+ services().then((container) =>
+ container.client.clearClientByIdCache(...args)
+ );
+export const getClientsByOrganizationId: Services['client']['getClientsByOrganizationId'] =
+ (...args) =>
+ services().then((container) =>
+ container.client.getClientsByOrganizationId(...args)
+ );
+export const getClientsByProjectId: Services['client']['getClientsByProjectId'] =
+ (...args) =>
+ services().then((container) =>
+ container.client.getClientsByProjectId(...args)
+ );
+export const listClientsForOrganization: Services['client']['listClientsForOrganization'] =
+ (...args) =>
+ services().then((container) =>
+ container.client.listClientsForOrganization(...args)
+ );
+export const getClientForOrganization: Services['client']['getClientForOrganization'] =
+ (...args) =>
+ services().then((container) =>
+ container.client.getClientForOrganization(...args)
+ );
+export const createClientForOrganization: Services['client']['createClientForOrganization'] =
+ (...args) =>
+ services().then((container) =>
+ container.client.createClientForOrganization(...args)
+ );
+export const updateClientForOrganization: Services['client']['updateClientForOrganization'] =
+ (...args) =>
+ services().then((container) =>
+ container.client.updateClientForOrganization(...args)
+ );
+export const deleteClientForOrganization: Services['client']['deleteClientForOrganization'] =
+ (...args) =>
+ services().then((container) =>
+ container.client.deleteClientForOrganization(...args)
+ );
+
+// --- project -------------------------------------------------------------
+
+export const getProjectById: Services['project']['getProjectById'] = (
+ ...args
+) => services().then((container) => container.project.getProjectById(...args));
+export const getProjectByIdCached: Services['project']['getProjectByIdCached'] =
+ (...args) =>
+ services().then((container) =>
+ container.project.getProjectByIdCached(...args)
+ );
+export const clearProjectByIdCache: Services['project']['clearProjectByIdCache'] =
+ (...args) =>
+ services().then((container) =>
+ container.project.clearProjectByIdCache(...args)
+ );
+export const getProjectWithClients: Services['project']['getProjectWithClients'] =
+ (...args) =>
+ services().then((container) =>
+ container.project.getProjectWithClients(...args)
+ );
+export const getProjects: Services['project']['getProjects'] = (...args) =>
+ services().then((container) => container.project.getProjects(...args));
+export const getProjectEventsCount: Services['project']['getProjectEventsCount'] =
+ (...args) =>
+ services().then((container) =>
+ container.project.getProjectEventsCount(...args)
+ );
+export const getLastEventPerProject: Services['project']['getLastEventPerProject'] =
+ (...args) =>
+ services().then((container) =>
+ container.project.getLastEventPerProject(...args)
+ );
+export const resolveClientProjectId: Services['project']['resolveClientProjectId'] =
+ (...args) =>
+ services().then((container) =>
+ container.project.resolveClientProjectId(...args)
+ );
+export const getProjectActivationStatus: Services['project']['getProjectActivationStatus'] =
+ (...args) =>
+ services().then((container) =>
+ container.project.getProjectActivationStatus(...args)
+ );
+export const listProjectsCore: Services['project']['listProjectsCore'] = (
+ ...args
+) =>
+ services().then((container) => container.project.listProjectsCore(...args));
+export const listProjectsForOrganization: Services['project']['listProjectsForOrganization'] =
+ (...args) =>
+ services().then((container) =>
+ container.project.listProjectsForOrganization(...args)
+ );
+export const getProjectForOrganization: Services['project']['getProjectForOrganization'] =
+ (...args) =>
+ services().then((container) =>
+ container.project.getProjectForOrganization(...args)
+ );
+export const createProjectForOrganization: Services['project']['createProjectForOrganization'] =
+ (...args) =>
+ services().then((container) =>
+ container.project.createProjectForOrganization(...args)
+ );
+export const updateProjectForOrganization: Services['project']['updateProjectForOrganization'] =
+ (...args) =>
+ services().then((container) =>
+ container.project.updateProjectForOrganization(...args)
+ );
+export const deleteProjectForOrganization: Services['project']['deleteProjectForOrganization'] =
+ (...args) =>
+ services().then((container) =>
+ container.project.deleteProjectForOrganization(...args)
+ );
+export const scheduleProjectDeletion: Services['project']['scheduleProjectDeletion'] =
+ (...args) =>
+ services().then((container) =>
+ container.project.scheduleProjectDeletion(...args)
+ );
+export const cancelProjectDeletion: Services['project']['cancelProjectDeletion'] =
+ (...args) =>
+ services().then((container) =>
+ container.project.cancelProjectDeletion(...args)
+ );
+
+// --- user ------------------------------------------------------------------
+
+export const getUserById: Services['user']['getUserById'] = (...args) =>
+ services().then((container) => container.user.getUserById(...args));
+export const getUserAccount: Services['user']['getUserAccount'] = (...args) =>
+ services().then((container) => container.user.getUserAccount(...args));
+export const listUserDeletionBlockers: Services['user']['listUserDeletionBlockers'] =
+ (...args) =>
+ services().then((container) =>
+ container.user.listUserDeletionBlockers(...args)
+ );
+export const deleteUserAccount: Services['user']['deleteUserAccount'] = (
+ ...args
+) => services().then((container) => container.user.deleteUserAccount(...args));
+export const updateUserProfile: Services['user']['updateUserProfile'] = (
+ ...args
+) => services().then((container) => container.user.updateUserProfile(...args));
+
+// --- subscription ------------------------------------------------------
+
+// `getCurrentSubscriptionProduct` never touched Postgres directly, so it
+// kept its bare signature straight through — no wrapper needed, exported
+// directly from subscription.service.ts on the barrel.
+export const checkout: Services['subscription']['checkout'] = (...args) =>
+ services().then((container) => container.subscription.checkout(...args));
+export const listProducts: Services['subscription']['listProducts'] = (
+ ...args
+) =>
+ services().then((container) => container.subscription.listProducts(...args));
+export const getUsage: Services['subscription']['getUsage'] = (...args) =>
+ services().then((container) => container.subscription.getUsage(...args));
+export const cancelSubscription: Services['subscription']['cancelSubscription'] =
+ (...args) =>
+ services().then((container) =>
+ container.subscription.cancelSubscription(...args)
+ );
+export const pauseSubscription: Services['subscription']['pauseSubscription'] =
+ (...args) =>
+ services().then((container) =>
+ container.subscription.pauseSubscription(...args)
+ );
+export const resumeSubscription: Services['subscription']['resumeSubscription'] =
+ (...args) =>
+ services().then((container) =>
+ container.subscription.resumeSubscription(...args)
+ );
+export const applySaveDiscount: Services['subscription']['applySaveDiscount'] =
+ (...args) =>
+ services().then((container) =>
+ container.subscription.applySaveDiscount(...args)
+ );
+export const portal: Services['subscription']['portal'] = (...args) =>
+ services().then((container) => container.subscription.portal(...args));
+
+// --- salt ------------------------------------------------------------------
+
+// `ingest.service.ts`'s `/track` hot path has no `Ctx` to reach
+// `ctx.services.salt` from — see salt.service.ts's header for why `getSalts`
+// stays bare here instead of gaining a `deps` parameter like every other
+// function in this file.
+export const getSalts: Services['salt']['getSalts'] = () =>
+ services().then((container) => container.salt.getSalts());
+
+// --- conversation ------------------------------------------------------
+
+export const getConversationById: Services['conversation']['getConversationById'] =
+ (...args) =>
+ services().then((container) =>
+ container.conversation.getConversationById(...args)
+ );
+export const listConversations: Services['conversation']['listConversations'] =
+ (...args) =>
+ services().then((container) =>
+ container.conversation.listConversations(...args)
+ );
+export const upsertConversationTitle: Services['conversation']['upsertConversationTitle'] =
+ (...args) =>
+ services().then((container) =>
+ container.conversation.upsertConversationTitle(...args)
+ );
+export const deleteConversation: Services['conversation']['deleteConversation'] =
+ (...args) =>
+ services().then((container) =>
+ container.conversation.deleteConversation(...args)
+ );