Skip to content

πŸͺ’ Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

chore: improve claude code and review md (#10145)

Max Deichmannd2720b8c9071
diff --git a/.claude/skills/backend-dev-guidelines/SKILL.md b/.claude/skills/backend-dev-guidelines/SKILL.md
index 0d8037fb68..2df427998c 100644
--- a/.claude/skills/backend-dev-guidelines/SKILL.md
+++ b/.claude/skills/backend-dev-guidelines/SKILL.md
@@ -1,6 +1,6 @@
---
name: backend-dev-guidelines
-description: Comprehensive backend development guide for Langfuse's Next.js 14/tRPC/Express/TypeScript monorepo. Use when creating tRPC routers, public API endpoints, BullMQ queue processors, services, or working with tRPC procedures, Next.js API routes, Prisma database access, ClickHouse analytics queries, Redis queues, OpenTelemetry instrumentation, Zod v4 validation, env.mjs configuration, or async patterns. Covers layered architecture (tRPC procedures β†’ services, queue processors β†’ services), traceException error handling, observability patterns, and testing strategies.
+description: Comprehensive backend development guide for Langfuse's Next.js 14/tRPC/Express/TypeScript monorepo. Use when creating tRPC routers, public API endpoints, BullMQ queue processors, services, or working with tRPC procedures, Next.js API routes, Prisma database access, ClickHouse analytics queries, Redis queues, OpenTelemetry instrumentation, Zod v4 validation, env.mjs configuration, tenant isolation patterns, or async patterns. Covers layered architecture (tRPC procedures β†’ services, queue processors β†’ services), dual database system (PostgreSQL + ClickHouse), projectId filtering for multi-tenant isolation, traceException error handling, observability patterns, and testing strategies (Jest for web, vitest for worker).
---
# Backend Development Guidelines
@@ -21,7 +21,7 @@ Automatically activates when working on:
- Accessing resources based on entitlements
- Implementing middleware (tRPC, NextAuth, public API)
- Database operations with Prisma (PostgreSQL) or ClickHouse
-- Error tracking with traceException and OpenTelemetry instrumentation
+- Observability with OpenTelemetry, DataDog, logger, and traceException
- Input validation with Zod v4
- Environment configuration from env variables
- Backend testing and refactoring
@@ -299,31 +299,63 @@ const schema = z.object({
const validated = schema.parse(input);
```
-### 4. Direct Prisma Usage from @langfuse/shared from within services
+### 4. Services Use Prisma Directly for Simple CRUD or Repositories for Complex Queries
```typescript
-// Services use Prisma directly
+// Services use Prisma directly for simple CRUD
import { prisma } from "@langfuse/shared/src/db";
const dataset = await prisma.dataset.findUnique({
- where: { id: datasetId },
+ where: { id: datasetId, projectId }, // Always filter by projectId for tenant isolation
+});
+
+// Or use repositories for complex queries (traces, observations, scores)
+import { getTracesTable } from "@langfuse/shared/src/server";
+
+const traces = await getTracesTable({
+ projectId,
+ filter: [...],
+ limit: 1000,
});
```
-### 6. Instrument Critical Operations (all API routes are auto-instrumented by a wrapper span)
+### 6. Observability: OpenTelemetry + DataDog (Not Sentry for Backend)
+
+**Langfuse uses OpenTelemetry for backend observability, with traces and logs sent to DataDog.**
```typescript
-import { instrumentAsync } from "@langfuse/shared/src/server";
+// Import observability utilities
+import {
+ logger, // Winston logger with OpenTelemetry/DataDog context
+ traceException, // Record exceptions to OpenTelemetry spans
+ instrumentAsync, // Create instrumented spans
+} from "@langfuse/shared/src/server";
+
+// Structured logging (includes trace_id, span_id, dd.trace_id)
+logger.info("Processing dataset", { datasetId, projectId });
+logger.error("Failed to create dataset", { error: err.message });
+
+// Record exceptions to OpenTelemetry (sent to DataDog)
+try {
+ await operation();
+} catch (error) {
+ traceException(error); // Records to current span
+ throw error;
+}
+// Instrument critical operations (all API routes auto-instrumented)
const result = await instrumentAsync(
{ name: "dataset.create" },
async (span) => {
+ span.setAttributes({ datasetId, projectId });
// Operation here
return dataset;
},
);
```
+**Note**: Frontend uses Sentry, but backend (tRPC, API routes, services, worker) uses OpenTelemetry + DataDog.
+
### 7. Comprehensive Testing Required
Write tests for all new features and bug fixes. See [testing-guide.md](resources/testing-guide.md) for detailed examples.
@@ -372,6 +404,25 @@ expect(rows).toHaveLength(2);
- Tests must be independent and runnable in any order
- Never use `pruneDatabase` in tests
+### 8. Always Filter by projectId for Tenant Isolation
+
+```typescript
+// βœ… CORRECT: Filter by projectId for tenant isolation
+const trace = await prisma.trace.findUnique({
+ where: { id: traceId, projectId }, // Required for multi-tenant data isolation
+});
+
+// βœ… CORRECT: ClickHouse queries also require projectId
+const traces = await queryClickhouse({
+ query: `
+ SELECT * FROM traces
+ WHERE project_id = {projectId: String}
+ AND timestamp >= {startTime: DateTime64(3)}
+ `,
+ params: { projectId, startTime },
+});
+```
+
---
## Common Imports
@@ -390,13 +441,17 @@ import { prisma } from "@langfuse/shared/src/db";
import type { Prisma } from "@prisma/client";
// ClickHouse
-import { getTracesTable } from "@langfuse/shared/src/server";
+import {
+ queryClickhouse,
+ queryClickhouseStream,
+ upsertClickhouse,
+} from "@langfuse/shared/src/server";
-// Error tracking & instrumentation
+// Observability - OpenTelemetry + DataDog (NOT Sentry for backend)
import {
- traceException,
- instrumentAsync,
- logger,
+ logger, // Winston logger with OTEL/DataDog trace context
+ traceException, // Record exceptions to OpenTelemetry spans
+ instrumentAsync, // Create instrumented spans for operations
} from "@langfuse/shared/src/server";
// Config
@@ -429,21 +484,24 @@ import { QueueName, TQueueJobTypes } from "@langfuse/shared/src/server";
| 404 | Not Found |
| 500 | Server Error |
-### Service Templates
+### Example Features to Reference
-**Blog API** (βœ… Mature) - Use as template for REST APIs
-**Auth Service** (βœ… Mature) - Use as template for authentication patterns
+Reference existing Langfuse features for implementation patterns:
+- **Datasets** (`web/src/features/datasets/`) - Complete feature with tRPC router, public API, and service
+- **Prompts** (`web/src/features/prompts/`) - Feature with versioning and templates
+- **Evaluations** (`web/src/features/evals/`) - Complex feature with worker integration
+- **Public API** (`web/src/features/public-api/`) - Middleware and route patterns
---
## Anti-Patterns to Avoid
-❌ Business logic in routes
-❌ Direct process.env usage
+❌ Business logic in routes/procedures
+❌ Direct process.env usage (always use env.mjs/env.ts)
❌ Missing error handling
-❌ No input validation
-❌ Direct Prisma everywhere
-❌ console.log instead of Sentry
+❌ No input validation (always use Zod v4)
+❌ Missing projectId filter on tenant-scoped queries
+❌ console.log instead of logger/traceException (OpenTelemetry)
---
@@ -451,57 +509,55 @@ import { QueueName, TQueueJobTypes } from "@langfuse/shared/src/server";
| Need to... | Read this |
| ------------------------- | ------------------------------------------------------------ |
-| Understand architecture | [architecture-overview.md](architecture-overview.md) |
-| Create routes/controllers | [routing-and-controllers.md](routing-and-controllers.md) |
-| Organize business logic | [services-and-repositories.md](services-and-repositories.md) |
-| Create middleware | [middleware-guide.md](middleware-guide.md) |
-| Database access | [database-patterns.md](database-patterns.md) |
-| Manage config | [configuration.md](configuration.md) |
-| Write tests | [testing-guide.md](testing-guide.md) |
-| See examples | [complete-examples.md](complete-examples.md) |
+| Understand architecture | [architecture-overview.md](resources/architecture-overview.md) |
+| Create routes/controllers | [routing-and-controllers.md](resources/routing-and-controllers.md) |
+| Organize business logic | [services-and-repositories.md](resources/services-and-repositories.md) |
+| Create middleware | [middleware-guide.md](resources/middleware-guide.md) |
+| Database access | [database-patterns.md](resources/database-patterns.md) |
+| Manage config | [configuration.md](resources/configuration.md) |
+| Write tests | [testing-guide.md](resources/testing-guide.md) |
---
## Resource Files
-### [architecture-overview.md](architecture-overview.md)
+### [architecture-overview.md](resources/architecture-overview.md)
-Layered architecture, request lifecycle, separation of concerns
+Three-layer architecture (tRPC/Public API β†’ Services β†’ Data Access), request lifecycle for tRPC/Public API/Worker, Next.js 14 directory structure, dual database system (PostgreSQL + ClickHouse), separation of concerns, repository pattern for complex queries
-### [routing-and-controllers.md](routing-and-controllers.md)
+### [routing-and-controllers.md](resources/routing-and-controllers.md)
-Route definitions, BaseController, error handling, examples
+Next.js file-based routing, tRPC router patterns, Public REST API routes, layered architecture (Entry Points β†’ Services β†’ Repositories β†’ Database), service layer organization, anti-patterns to avoid
-### [services-and-repositories.md](services-and-repositories.md)
+### [services-and-repositories.md](resources/services-and-repositories.md)
-Service patterns, DI, repository pattern, caching
+Service layer overview, dependency injection patterns, singleton patterns, repository pattern for data access, service design principles, caching strategies, testing services
-### [middleware-guide.md](middleware-guide.md)
+### [middleware-guide.md](resources/middleware-guide.md)
-Auth, audit, error boundaries, AsyncLocalStorage
+tRPC middleware (withErrorHandling, withOtelInstrumentation, enforceUserIsAuthed), seven tRPC procedure types (publicProcedure, authenticatedProcedure, protectedProjectProcedure, etc.), Public API middleware (withMiddlewares, createAuthedProjectAPIRoute), authentication patterns (NextAuth for tRPC, Basic Auth for Public API)
-### [database-patterns.md](database-patterns.md)
+### [database-patterns.md](resources/database-patterns.md)
-PrismaService, repositories, transactions, optimization
+Dual database architecture (PostgreSQL via Prisma + ClickHouse via direct client), PostgreSQL CRUD operations, ClickHouse query patterns (queryClickhouse, queryClickhouseStream, upsertClickhouse), repository pattern for complex queries, tenant isolation with projectId filtering, when to use which database
-### [configuration.md](configuration.md)
+### [configuration.md](resources/configuration.md)
-UnifiedConfig, environment configs, secrets
+Environment variable validation with Zod, package-specific configs (web/env.mjs with t3-oss/env-nextjs, worker/env.ts, shared/env.ts), NEXT_PUBLIC_LANGFUSE_CLOUD_REGION usage, LANGFUSE_EE_LICENSE_KEY for enterprise features, best practices for env management
-### [testing-guide.md](testing-guide.md)
+### [testing-guide.md](resources/testing-guide.md)
-Unit/integration tests, mocking, coverage
+Integration tests (Public API with makeZodVerifiedAPICall), tRPC tests (createInnerTRPCContext, appRouter.createCaller), service-level tests (repository/service functions), worker tests (vitest with streams), test isolation principles, running tests (Jest for web, vitest for worker)
---
## Related Skills
- **database-verification** - Verify column names and schema consistency
-- **error-tracking** - Sentry integration patterns
- **skill-developer** - Meta-skill for creating and managing skills
---
**Skill Status**: COMPLETE βœ…
-**Line Count**: < 500 βœ…
-**Progressive Disclosure**: 11 resource files βœ…
+**Line Count**: ~540 lines
+**Progressive Disclosure**: 7 resource files βœ…
diff --git a/.claude/skills/backend-dev-guidelines/resources/architecture-overview.md b/.claude/skills/backend-dev-guidelines/resources/architecture-overview.md
index 7c78db5d6b..f3323df7b1 100644
--- a/.claude/skills/backend-dev-guidelines/resources/architecture-overview.md
+++ b/.claude/skills/backend-dev-guidelines/resources/architecture-overview.md
@@ -711,6 +711,7 @@ await redis.set(`cache:${key}`, value, "EX", 3600);
**Repository Pattern:**
Langfuse uses repositories in `packages/shared/src/server/repositories/` for complex data access patterns. Repositories provide:
+
- Abstraction over complex queries (traces, observations, scores, events)
- Data converters for transforming database models to application models
- ClickHouse query builders and stream processing
@@ -768,25 +769,49 @@ export async function createDataset(ctx: TRPCContext) {
}
```
-### 3. Instrument Critical Operations
+### 3. Observability with OpenTelemetry + DataDog
+
+**Langfuse uses OpenTelemetry for backend observability, with traces and logs sent to DataDog.**
-Use OpenTelemetry for observability:
+Use structured logging and instrumentation:
```typescript
-import { instrumentAsync } from "@langfuse/shared/src/server";
+import {
+ logger,
+ traceException,
+ instrumentAsync,
+} from "@langfuse/shared/src/server";
export async function processEvaluation(evalId: string) {
return await instrumentAsync(
{ name: "evaluation.process", attributes: { evalId } },
async (span) => {
- // Operation here
- span.setAttributes({ score: result.score });
- return result;
+ // Structured logging (includes trace_id, span_id, dd.trace_id)
+ logger.info("Starting evaluation", { evalId });
+
+ try {
+ // Operation here
+ const result = await runEvaluation(evalId);
+
+ span.setAttributes({
+ score: result.score,
+ status: "success",
+ });
+
+ return result;
+ } catch (error) {
+ // Record exception to OpenTelemetry span (sent to DataDog)
+ traceException(error, span);
+ logger.error("Evaluation failed", { evalId, error: error.message });
+ throw error;
+ }
},
);
}
```
+**Note**: Frontend uses Sentry for error tracking, but backend (tRPC, API routes, services, worker) uses OpenTelemetry + DataDog.
+
### 4. Use Proper Error Handling
Transform errors at entry points:
@@ -796,7 +821,7 @@ Transform errors at entry points:
try {
return await service();
} catch (error) {
- traceException(error); // Log to Sentry
+ traceException(error); // Record to OpenTelemetry span (sent to DataDog)
throw new TRPCError({
code: "INTERNAL_SERVER_ERROR",
message: "User-friendly message",
@@ -808,7 +833,7 @@ try {
try {
return await service();
} catch (error) {
- traceException(error);
+ traceException(error); // Record to OpenTelemetry span (sent to DataDog)
return res.status(500).json({
error: "User-friendly message",
});
diff --git a/.claude/skills/backend-dev-guidelines/resources/database-patterns.md b/.claude/skills/backend-dev-guidelines/resources/database-patterns.md
index b2500012a7..df4196dba3 100644
--- a/.claude/skills/backend-dev-guidelines/resources/database-patterns.md
+++ b/.claude/skills/backend-dev-guidelines/resources/database-patterns.md
@@ -25,6 +25,8 @@ Langfuse uses a **dual database architecture**:
**Key Principle**: Use PostgreSQL for transactional data and relationships. Use ClickHouse for high-volume analytics and time-series data.
+**⚠️ Important**: All queries must filter by `project_id` (or `projectId`) to ensure proper data isolation between tenants. This is essential for the multi-tenant architecture.
+
---
## PostgreSQL with Prisma
@@ -42,6 +44,8 @@ const user = await prisma.user.findUnique({ where: { id } });
### Common CRUD Operations
+**⚠️ ALWAYS include `projectId` in WHERE clauses** for project-scoped data:
+
```typescript
// Create
const project = await prisma.project.create({
@@ -51,29 +55,34 @@ const project = await prisma.project.create({
},
});
-// Read with relations
+// βœ… GOOD: Read with projectId filter
const trace = await prisma.trace.findUnique({
- where: { id: traceId, projectId },
+ where: { id: traceId, projectId }, // ← Always include projectId for tenant isolation
include: {
scores: true,
project: { select: { id: true, name: true } },
},
});
+// ❌ BAD: Missing projectId filter
+// const trace = await prisma.trace.findUnique({
+// where: { id: traceId }, // ← Missing projectId!
+// });
+
// Update
await prisma.user.update({
where: { id: userId },
data: { lastLogin: new Date() },
});
-// Delete
+// βœ… GOOD: Delete with projectId
await prisma.apiKey.delete({
- where: { id: apiKeyId, projectId },
+ where: { id: apiKeyId, projectId }, // ← Always include projectId
});
-// Count
+// βœ… GOOD: Count with projectId
const traceCount = await prisma.trace.count({
- where: { projectId, userId },
+ where: { projectId, userId }, // ← Always include projectId
});
```
@@ -198,27 +207,36 @@ const client = clickhouseClient(undefined, "ReadOnly");
ClickHouse queries use **raw SQL** with parameterized queries. Parameters use `{paramName: Type}` syntax:
+**⚠️ Important**: All ClickHouse queries must include `project_id` filter to ensure proper tenant isolation.
+
**Simple query:**
```typescript
import { queryClickhouse } from "@langfuse/shared/src/server/repositories/clickhouse";
+// βœ… GOOD: Always filter by project_id
const rows = await queryClickhouse<{ id: string; name: string }>({
query: `
SELECT id, name, timestamp
FROM traces
- WHERE project_id = {projectId: String}
+ WHERE project_id = {projectId: String} -- ← REQUIRED: Always filter by project_id
AND timestamp >= {startTime: DateTime64(3)}
ORDER BY timestamp DESC
LIMIT {limit: UInt32}
`,
params: {
- projectId,
+ projectId, // ← Required for tenant isolation
startTime: convertDateToClickhouseDateTime(startDate),
limit: 100,
},
tags: { feature: "tracing", type: "trace" },
});
+
+// ❌ BAD: Missing project_id filter
+// const rows = await queryClickhouse({
+// query: `SELECT * FROM traces WHERE timestamp >= {startTime: DateTime64(3)}`,
+// params: { startTime },
+// });
```
**Streaming query (for large result sets):**
@@ -305,33 +323,55 @@ const params = {
### ClickHouse Query Best Practices
-**Use LIMIT BY for deduplication:**
+**1. Always filter by `project_id` for tenant isolation:**
+
+```typescript
+// βœ… CORRECT: project_id filter is required
+const query = `
+ SELECT *
+ FROM traces
+ WHERE project_id = {projectId: String} -- ← Required for tenant isolation
+ AND timestamp >= {startTime: DateTime64(3)}
+`;
+
+// ❌ WRONG: Missing project_id filter
+// const query = `
+// SELECT * FROM traces WHERE timestamp >= {startTime: DateTime64(3)}
+// `;
+```
+
+**Why this is important:**
+- Langfuse is multi-tenant - each project's data must be isolated
+- The `project_id` filter ensures queries only access data from the intended tenant
+- All queries on project-scoped tables (traces, observations, scores, sessions, etc.) must filter by `project_id`
+
+**2. Use LIMIT BY for deduplication:**
```typescript
// Get latest version of each trace
const query = `
SELECT *
FROM traces
- WHERE project_id = {projectId: String}
+ WHERE project_id = {projectId: String} -- ← Always include project_id
ORDER BY event_ts DESC
LIMIT 1 BY id, project_id
`;
```
-**Use time-based filtering:**
+**3. Use time-based filtering for performance:**
```typescript
-// Always filter by timestamp for performance
+// Combine project_id filter with timestamp for optimal performance
const query = `
SELECT *
FROM observations
- WHERE project_id = {projectId: String}
- AND start_time >= {startTime: DateTime64(3)}
+ WHERE project_id = {projectId: String} -- ← Required for tenant isolation
+ AND start_time >= {startTime: DateTime64(3)} -- ← Improves performance
AND start_time < {endTime: DateTime64(3)}
`;
```
-**Use CTEs for complex queries:**
+**4. Use CTEs for complex queries (still require `project_id`):**
```typescript
const query = `
@@ -341,7 +381,7 @@ const query = `
count() as observation_count,
sum(total_cost) as total_cost
FROM observations
- WHERE project_id = {projectId: String}
+ WHERE project_id = {projectId: String} -- ← Filter in CTE
GROUP BY trace_id
)
SELECT
@@ -351,10 +391,12 @@ const query = `
o.total_cost
FROM traces t
LEFT JOIN observations_agg o ON t.id = o.trace_id
- WHERE t.project_id = {projectId: String}
+ WHERE t.project_id = {projectId: String} -- ← Filter in main query
`;
```
+**Note**: When using CTEs or subqueries, ensure `project_id` filter is applied at each level.
+
**Error handling with retries:**
ClickHouse queries automatically retry on network errors (socket hang up). Custom error handling for resource limits:
@@ -475,6 +517,44 @@ export const getScoresByTraceId = async (
5. Is it frequently updated? β†’ **PostgreSQL**
6. Is it append-only analytics data? β†’ **ClickHouse**
+### Project-Scoped vs Global Tables
+
+**Project-scoped tables (MUST filter by `project_id`):**
+- `traces` - All trace queries require `project_id`
+- `observations` - All observation queries require `project_id`
+- `scores` - All score queries require `project_id`
+- `events` - All event queries require `project_id`
+- `dataset_run_items_rmt` - All dataset run queries require `project_id`
+
+**Global tables (no `project_id` filter needed):**
+- `users` - User management (use `id` for filtering)
+- `organizations` - Organization data (use `id` for filtering)
+- System configuration tables
+
+**Example of correct filtering:**
+
+```typescript
+// βœ… CORRECT: Project-scoped query
+const traces = await queryClickhouse({
+ query: `
+ SELECT * FROM traces
+ WHERE project_id = {projectId: String}
+ AND timestamp >= {startTime: DateTime64(3)}
+ `,
+ params: { projectId, startTime },
+});
+
+// βœ… CORRECT: Global table query (no project_id needed)
+const user = await prisma.user.findUnique({
+ where: { id: userId },
+});
+
+// ❌ WRONG: Project-scoped query without project_id filter
+// const traces = await queryClickhouse({
+// query: `SELECT * FROM traces WHERE timestamp >= {startTime: DateTime64(3)}`,
+// });
+```
+
---
## Error Handling
diff --git a/.claude/skills/backend-dev-guidelines/resources/services-and-repositories.md b/.claude/skills/backend-dev-guidelines/resources/services-and-repositories.md
index 749b26b6d6..5a50e4a4c7 100644
--- a/.claude/skills/backend-dev-guidelines/resources/services-and-repositories.md
+++ b/.claude/skills/backend-dev-guidelines/resources/services-and-repositories.md
@@ -27,6 +27,7 @@ Repository executes: "Here's the data you requested"
```
**Services are responsible for:**
+
- βœ… Business rules enforcement
- βœ… Orchestrating multiple repositories
- βœ… Transaction management
@@ -35,6 +36,7 @@ Repository executes: "Here's the data you requested"
- βœ… Business validations
**Services should NOT:**
+
- ❌ Know about HTTP (Request/Response)
- ❌ Direct Prisma access (use repositories)
- ❌ Handle route-specific logic
@@ -47,6 +49,7 @@ Repository executes: "Here's the data you requested"
### Why Dependency Injection?
**Benefits:**
+
- Easy to test (inject mocks)
- Clear dependencies
- Flexible configuration
@@ -59,143 +62,169 @@ Repository executes: "Here's the data you requested"
```typescript
// Define dependencies interface for clarity
export interface NotificationServiceDependencies {
- prisma: PrismaClient;
- batchingService: BatchingService;
- emailComposer: EmailComposer;
+ prisma: PrismaClient;
+ batchingService: BatchingService;
+ emailComposer: EmailComposer;
}
// Service with dependency injection
export class NotificationService {
- private prisma: PrismaClient;
- private batchingService: BatchingService;
- private emailComposer: EmailComposer;
- private preferencesCache: Map<string, { preferences: UserPreference; timestamp: number }> = new Map();
- private CACHE_TTL = (notificationConfig.preferenceCacheTTLMinutes || 5) * 60 * 1000;
-
- // Dependencies injected via constructor
- constructor(dependencies: NotificationServiceDependencies) {
- this.prisma = dependencies.prisma;
- this.batchingService = dependencies.batchingService;
- this.emailComposer = dependencies.emailComposer;
+ private prisma: PrismaClient;
+ private batchingService: BatchingService;
+ private emailComposer: EmailComposer;
+ private preferencesCache: Map<
+ string,
+ { preferences: UserPreference; timestamp: number }
+ > = new Map();
+ private CACHE_TTL =
+ (notificationConfig.preferenceCacheTTLMinutes || 5) * 60 * 1000;
+
+ // Dependencies injected via constructor
+ constructor(dependencies: NotificationServiceDependencies) {
+ this.prisma = dependencies.prisma;
+ this.batchingService = dependencies.batchingService;
+ this.emailComposer = dependencies.emailComposer;
+ }
+
+ /**
+ * Create a notification and route it appropriately
+ */
+ async createNotification(params: CreateNotificationParams) {
+ const {
+ recipientID,
+ type,
+ title,
+ message,
+ link,
+ context = {},
+ channel = "both",
+ priority = NotificationPriority.NORMAL,
+ } = params;
+
+ try {
+ // Get template and render content
+ const template = getNotificationTemplate(type);
+ const rendered = renderNotificationContent(template, context);
+
+ // Create in-app notification record
+ const notificationId = await createNotificationRecord({
+ instanceId: parseInt(context.instanceId || "0", 10),
+ template: type,
+ recipientUserId: recipientID,
+ channel: channel === "email" ? "email" : "inApp",
+ contextData: context,
+ title: finalTitle,
+ message: finalMessage,
+ link: finalLink,
+ });
+
+ // Route notification based on channel
+ if (channel === "email" || channel === "both") {
+ await this.routeNotification({
+ notificationId,
+ userId: recipientID,
+ type,
+ priority,
+ title: finalTitle,
+ message: finalMessage,
+ link: finalLink,
+ context,
+ });
+ }
+
+ return notification;
+ } catch (error) {
+ ErrorLogger.log(error, {
+ context: {
+ "[NotificationService] createNotification": {
+ type: params.type,
+ recipientID: params.recipientID,
+ },
+ },
+ });
+ throw error;
}
-
- /**
- * Create a notification and route it appropriately
- */
- async createNotification(params: CreateNotificationParams) {
- const { recipientID, type, title, message, link, context = {}, channel = 'both', priority = NotificationPriority.NORMAL } = params;
-
- try {
- // Get template and render content
- const template = getNotificationTemplate(type);
- const rendered = renderNotificationContent(template, context);
-
- // Create in-app notification record
- const notificationId = await createNotificationRecord({
- instanceId: parseInt(context.instanceId || '0', 10),
- template: type,
- recipientUserId: recipientID,
- channel: channel === 'email' ? 'email' : 'inApp',
- contextData: context,
- title: finalTitle,
- message: finalMessage,
- link: finalLink,
- });
-
- // Route notification based on channel
- if (channel === 'email' || channel === 'both') {
- await this.routeNotification({
- notificationId,
- userId: recipientID,
- type,
- priority,
- title: finalTitle,
- message: finalMessage,
- link: finalLink,
- context,
- });
- }
-
- return notification;
- } catch (error) {
- ErrorLogger.log(error, {
- context: {
- '[NotificationService] createNotification': {
- type: params.type,
- recipientID: params.recipientID,
- },
- },
- });
- throw error;
- }
+ }
+
+ /**
+ * Route notification based on user preferences
+ */
+ private async routeNotification(params: {
+ notificationId: number;
+ userId: string;
+ type: string;
+ priority: NotificationPriority;
+ title: string;
+ message: string;
+ link?: string;
+ context?: Record<string, any>;
+ }) {
+ // Get user preferences with caching
+ const preferences = await this.getUserPreferences(params.userId);
+
+ // Check if we should batch or send immediately
+ if (this.shouldBatchEmail(preferences, params.type, params.priority)) {
+ await this.batchingService.queueNotificationForBatch({
+ notificationId: params.notificationId,
+ userId: params.userId,
+ userPreference: preferences,
+ priority: params.priority,
+ });
+ } else {
+ // Send immediately via EmailComposer
+ await this.sendImmediateEmail({
+ userId: params.userId,
+ title: params.title,
+ message: params.message,
+ link: params.link,
+ context: params.context,
+ type: params.type,
+ });
}
-
- /**
- * Route notification based on user preferences
- */
- private async routeNotification(params: { notificationId: number; userId: string; type: string; priority: NotificationPriority; title: string; message: string; link?: string; context?: Record<string, any> }) {
- // Get user preferences with caching
- const preferences = await this.getUserPreferences(params.userId);
-
- // Check if we should batch or send immediately
- if (this.shouldBatchEmail(preferences, params.type, params.priority)) {
- await this.batchingService.queueNotificationForBatch({
- notificationId: params.notificationId,
- userId: params.userId,
- userPreference: preferences,
- priority: params.priority,
- });
- } else {
- // Send immediately via EmailComposer
- await this.sendImmediateEmail({
- userId: params.userId,
- title: params.title,
- message: params.message,
- link: params.link,
- context: params.context,
- type: params.type,
- });
- }
+ }
+
+ /**
+ * Determine if email should be batched
+ */
+ shouldBatchEmail(
+ preferences: UserPreference,
+ notificationType: string,
+ priority: NotificationPriority,
+ ): boolean {
+ // HIGH priority always immediate
+ if (priority === NotificationPriority.HIGH) {
+ return false;
}
- /**
- * Determine if email should be batched
- */
- shouldBatchEmail(preferences: UserPreference, notificationType: string, priority: NotificationPriority): boolean {
- // HIGH priority always immediate
- if (priority === NotificationPriority.HIGH) {
- return false;
- }
-
- // Check batch mode
- const batchMode = preferences.emailBatchMode || BatchMode.IMMEDIATE;
- return batchMode !== BatchMode.IMMEDIATE;
+ // Check batch mode
+ const batchMode = preferences.emailBatchMode || BatchMode.IMMEDIATE;
+ return batchMode !== BatchMode.IMMEDIATE;
+ }
+
+ /**
+ * Get user preferences with caching
+ */
+ async getUserPreferences(userId: string): Promise<UserPreference> {
+ // Check cache first
+ const cached = this.preferencesCache.get(userId);
+ if (cached && Date.now() - cached.timestamp < this.CACHE_TTL) {
+ return cached.preferences;
}
- /**
- * Get user preferences with caching
- */
- async getUserPreferences(userId: string): Promise<UserPreference> {
- // Check cache first
- const cached = this.preferencesCache.get(userId);
- if (cached && Date.now() - cached.timestamp < this.CACHE_TTL) {
- return cached.preferences;
- }
-
- const preference = await this.prisma.userPreference.findUnique({
- where: { userID: userId },
- });
+ const preference = await this.prisma.userPreference.findUnique({
+ where: { userID: userId },
+ });
- const finalPreferences = preference || DEFAULT_PREFERENCES;
+ const finalPreferences = preference || DEFAULT_PREFERENCES;
- // Update cache
- this.preferencesCache.set(userId, {
- preferences: finalPreferences,
- timestamp: Date.now(),
- });
+ // Update cache
+ this.preferencesCache.set(userId, {
+ preferences: finalPreferences,
+ timestamp: Date.now(),
+ });
- return finalPreferences;
- }
+ return finalPreferences;
+ }
}
```
@@ -204,20 +233,21 @@ export class NotificationService {
```typescript
// Instantiate with dependencies
const notificationService = new NotificationService({
- prisma: PrismaService.main,
- batchingService: new BatchingService(PrismaService.main),
- emailComposer: new EmailComposer(),
+ prisma: PrismaService.main,
+ batchingService: new BatchingService(PrismaService.main),
+ emailComposer: new EmailComposer(),
});
// Use in controller
const notification = await notificationService.createNotification({
- recipientID: 'user-123',
- type: 'AFRLWorkflowNotification',
- context: { workflowName: 'AFRL Monthly Report' },
+ recipientID: "user-123",
+ type: "AFRLWorkflowNotification",
+ context: { workflowName: "AFRL Monthly Report" },
});
```
**Key Takeaways:**
+
- Dependencies passed via constructor
- Clear interface defines required dependencies
- Easy to test (inject mocks)
@@ -231,6 +261,7 @@ const notification = await notificationService.createNotification({
### When to Use Singletons
**Use for:**
+
- Services with expensive initialization
- Services with shared state (caching)
- Services accessed from many places
@@ -242,90 +273,99 @@ const notification = await notificationService.createNotification({
**File:** `/blog-api/src/services/permissionService.ts`
```typescript
-import { PrismaClient } from '@prisma/client';
+import { PrismaClient } from "@prisma/client";
class PermissionService {
- private static instance: PermissionService;
- private prisma: PrismaClient;
- private permissionCache: Map<string, { canAccess: boolean; timestamp: number }> = new Map();
- private CACHE_TTL = 5 * 60 * 1000; // 5 minutes
-
- // Private constructor prevents direct instantiation
- private constructor() {
- this.prisma = PrismaService.main;
- }
-
- // Get singleton instance
- public static getInstance(): PermissionService {
- if (!PermissionService.instance) {
- PermissionService.instance = new PermissionService();
- }
- return PermissionService.instance;
+ private static instance: PermissionService;
+ private prisma: PrismaClient;
+ private permissionCache: Map<
+ string,
+ { canAccess: boolean; timestamp: number }
+ > = new Map();
+ private CACHE_TTL = 5 * 60 * 1000; // 5 minutes
+
+ // Private constructor prevents direct instantiation
+ private constructor() {
+ this.prisma = PrismaService.main;
+ }
+
+ // Get singleton instance
+ public static getInstance(): PermissionService {
+ if (!PermissionService.instance) {
+ PermissionService.instance = new PermissionService();
}
-
- /**
- * Check if user can complete a workflow step
- */
- async canCompleteStep(userId: string, stepInstanceId: number): Promise<boolean> {
- const cacheKey = `${userId}:${stepInstanceId}`;
-
- // Check cache
- const cached = this.permissionCache.get(cacheKey);
- if (cached && Date.now() - cached.timestamp < this.CACHE_TTL) {
- return cached.canAccess;
- }
-
- try {
- const post = await this.prisma.post.findUnique({
- where: { id: postId },
- include: {
- author: true,
- comments: {
- include: {
- user: true,
- },
- },
- },
- });
-
- if (!post) {
- return false;
- }
-
- // Check if user has permission
- const canEdit = post.authorId === userId ||
- await this.isUserAdmin(userId);
-
- // Cache result
- this.permissionCache.set(cacheKey, {
- canAccess: isAssigned,
- timestamp: Date.now(),
- });
-
- return isAssigned;
- } catch (error) {
- console.error('[PermissionService] Error checking step permission:', error);
- return false;
- }
+ return PermissionService.instance;
+ }
+
+ /**
+ * Check if user can complete a workflow step
+ */
+ async canCompleteStep(
+ userId: string,
+ stepInstanceId: number,
+ ): Promise<boolean> {
+ const cacheKey = `${userId}:${stepInstanceId}`;
+
+ // Check cache
+ const cached = this.permissionCache.get(cacheKey);
+ if (cached && Date.now() - cached.timestamp < this.CACHE_TTL) {
+ return cached.canAccess;
}
- /**
- * Clear cache for user
- */
- clearUserCache(userId: string): void {
- for (const [key] of this.permissionCache) {
- if (key.startsWith(`${userId}:`)) {
- this.permissionCache.delete(key);
- }
- }
+ try {
+ const post = await this.prisma.post.findUnique({
+ where: { id: postId },
+ include: {
+ author: true,
+ comments: {
+ include: {
+ user: true,
+ },
+ },
+ },
+ });
+
+ if (!post) {
+ return false;
+ }
+
+ // Check if user has permission
+ const canEdit =
+ post.authorId === userId || (await this.isUserAdmin(userId));
+
+ // Cache result
+ this.permissionCache.set(cacheKey, {
+ canAccess: isAssigned,
+ timestamp: Date.now(),
+ });
+
+ return isAssigned;
+ } catch (error) {
+ console.error(
+ "[PermissionService] Error checking step permission:",
+ error,
+ );
+ return false;
}
-
- /**
- * Clear all cache
- */
- clearCache(): void {
- this.permissionCache.clear();
+ }
+
+ /**
+ * Clear cache for user
+ */
+ clearUserCache(userId: string): void {
+ for (const [key] of this.permissionCache) {
+ if (key.startsWith(`${userId}:`)) {
+ this.permissionCache.delete(key);
+ }
}
+ }
+
+ /**
+ * Clear all cache
+ */
+ clearCache(): void {
+ this.permissionCache.clear();
+ }
}
// Export singleton instance
@@ -335,13 +375,13 @@ export const permissionService = PermissionService.getInstance();
**Usage:**
```typescript
-import { permissionService } from '../services/permissionService';
+import { permissionService } from "../services/permissionService";
// Use anywhere in the codebase
const canComplete = await permissionService.canCompleteStep(userId, stepId);
if (!canComplete) {
- throw new ForbiddenError('You do not have permission to complete this step');
+ throw new ForbiddenError("You do not have permission to complete this step");
}
```
@@ -359,6 +399,7 @@ Repository: "Here's the Prisma query that does that"
```
**Repositories are responsible for:**
+
- βœ… All Prisma operations
- βœ… Query construction
- βœ… Query optimization (select, include)
@@ -366,6 +407,7 @@ Repository: "Here's the Prisma query that does that"
- βœ… Caching database results
**Repositories should NOT:**
+
- ❌ Contain business logic
- ❌ Know about HTTP
- ❌ Make decisions (that's service layer)
@@ -374,124 +416,126 @@ Repository: "Here's the Prisma query that does that"
```typescript
// repositories/UserRepository.ts
-import { PrismaService } from '@project-lifecycle-portal/database';
-import type { User, Prisma } from '@project-lifecycle-portal/database';
+import { PrismaService } from "@project-lifecycle-portal/database";
+import type { User, Prisma } from "@project-lifecycle-portal/database";
export class UserRepository {
- /**
- * Find user by ID with optimized query
- */
- async findById(userId: string): Promise<User | null> {
- try {
- return await PrismaService.main.user.findUnique({
- where: { userID: userId },
- select: {
- userID: true,
- email: true,
- name: true,
- isActive: true,
- roles: true,
- createdAt: true,
- updatedAt: true,
- },
- });
- } catch (error) {
- console.error('[UserRepository] Error finding user by ID:', error);
- throw new Error(`Failed to find user: ${userId}`);
- }
+ /**
+ * Find user by ID with optimized query
+ */
+ async findById(userId: string): Promise<User | null> {
+ try {
+ return await PrismaService.main.user.findUnique({
+ where: { userID: userId },
+ select: {
+ userID: true,
+ email: true,
+ name: true,
+ isActive: true,
+ roles: true,
+ createdAt: true,
+ updatedAt: true,
+ },
+ });
+ } catch (error) {
+ console.error("[UserRepository] Error finding user by ID:", error);
+ throw new Error(`Failed to find user: ${userId}`);
}
-
- /**
- * Find all active users
- */
- async findActive(options?: { orderBy?: Prisma.UserOrderByWithRelationInput }): Promise<User[]> {
- try {
- return await PrismaService.main.user.findMany({
- where: { isActive: true },
- orderBy: options?.orderBy || { name: 'asc' },
- select: {
- userID: true,
- email: true,
- name: true,
- roles: true,
- },
- });
- } catch (error) {
- console.error('[UserRepository] Error finding active users:', error);
- throw new Error('Failed to find active users');
- }
+ }
+
+ /**
+ * Find all active users
+ */
+ async findActive(options?: {
+ orderBy?: Prisma.UserOrderByWithRelationInput;
+ }): Promise<User[]> {
+ try {
+ return await PrismaService.main.user.findMany({
+ where: { isActive: true },
+ orderBy: options?.orderBy || { name: "asc" },
+ select: {
+ userID: true,
+ email: true,
+ name: true,
+ roles: true,
+ },
+ });
+ } catch (error) {
+ console.error("[UserRepository] Error finding active users:", error);
+ throw new Error("Failed to find active users");
}
-
- /**
- * Find user by email
- */
- async findByEmail(email: string): Promise<User | null> {
- try {
- return await PrismaService.main.user.findUnique({
- where: { email },
- });
- } catch (error) {
- console.error('[UserRepository] Error finding user by email:', error);
- throw new Error(`Failed to find user with email: ${email}`);
- }
+ }
+
+ /**
+ * Find user by email
+ */
+ async findByEmail(email: string): Promise<User | null> {
+ try {
+ return await PrismaService.main.user.findUnique({
+ where: { email },
+ });
+ } catch (error) {
+ console.error("[UserRepository] Error finding user by email:", error);
+ throw new Error(`Failed to find user with email: ${email}`);
}
-
- /**
- * Create new user
- */
- async create(data: Prisma.UserCreateInput): Promise<User> {
- try {
- return await PrismaService.main.user.create({ data });
- } catch (error) {
- console.error('[UserRepository] Error creating user:', error);
- throw new Error('Failed to create user');
- }
+ }
+
+ /**
+ * Create new user
+ */
+ async create(data: Prisma.UserCreateInput): Promise<User> {
+ try {
+ return await PrismaService.main.user.create({ data });
+ } catch (error) {
+ console.error("[UserRepository] Error creating user:", error);
+ throw new Error("Failed to create user");
}
-
- /**
- * Update user
- */
- async update(userId: string, data: Prisma.UserUpdateInput): Promise<User> {
- try {
- return await PrismaService.main.user.update({
- where: { userID: userId },
- data,
- });
- } catch (error) {
- console.error('[UserRepository] Error updating user:', error);
- throw new Error(`Failed to update user: ${userId}`);
- }
+ }
+
+ /**
+ * Update user
+ */
+ async update(userId: string, data: Prisma.UserUpdateInput): Promise<User> {
+ try {
+ return await PrismaService.main.user.update({
+ where: { userID: userId },
+ data,
+ });
+ } catch (error) {
+ console.error("[UserRepository] Error updating user:", error);
+ throw new Error(`Failed to update user: ${userId}`);
}
-
- /**
- * Delete user (soft delete by setting isActive = false)
- */
- async delete(userId: string): Promise<User> {
- try {
- return await PrismaService.main.user.update({
- where: { userID: userId },
- data: { isActive: false },
- });
- } catch (error) {
- console.error('[UserRepository] Error deleting user:', error);
- throw new Error(`Failed to delete user: ${userId}`);
- }
+ }
+
+ /**
+ * Delete user (soft delete by setting isActive = false)
+ */
+ async delete(userId: string): Promise<User> {
+ try {
+ return await PrismaService.main.user.update({
+ where: { userID: userId },
+ data: { isActive: false },
+ });
+ } catch (error) {
+ console.error("[UserRepository] Error deleting user:", error);
+ throw new Error(`Failed to delete user: ${userId}`);
}
-
- /**
- * Check if email exists
- */
- async emailExists(email: string): Promise<boolean> {
- try {
- const count = await PrismaService.main.user.count({
- where: { email },
- });
- return count > 0;
- } catch (error) {
- console.error('[UserRepository] Error checking email exists:', error);
- throw new Error('Failed to check if email exists');
- }
+ }
+
+ /**
+ * Check if email exists
+ */
+ async emailExists(email: string): Promise<boolean> {
+ try {
+ const count = await PrismaService.main.user.count({
+ where: { email },
+ });
+ return count > 0;
+ } catch (error) {
+ console.error("[UserRepository] Error checking email exists:", error);
+ throw new Error("Failed to check if email exists");
}
+ }
}
// Export singleton instance
@@ -502,48 +546,54 @@ export const userRepository = new UserRepository();
```typescript
// services/userService.ts
-import { userRepository } from '../repositories/UserRepository';
-import { ConflictError, NotFoundError } from '../utils/errors';
+import { userRepository } from "../repositories/UserRepository";
+import { ConflictError, NotFoundError } from "../utils/errors";
export class UserService {
- /**
- * Create new user with business rules
- */
- async createUser(data: { email: string; name: string; roles: string[] }): Promise<User> {
- // Business rule: Check if email already exists
- const emailExists = await userRepository.emailExists(data.email);
- if (emailExists) {
- throw new ConflictError('Email already exists');
- }
-
- // Business rule: Validate roles
- const validRoles = ['admin', 'operations', 'user'];
- const invalidRoles = data.roles.filter((role) => !validRoles.includes(role));
- if (invalidRoles.length > 0) {
- throw new ValidationError(`Invalid roles: ${invalidRoles.join(', ')}`);
- }
-
- // Create user via repository
- return await userRepository.create({
- email: data.email,
- name: data.name,
- roles: data.roles,
- isActive: true,
- });
+ /**
+ * Create new user with business rules
+ */
+ async createUser(data: {
+ email: string;
+ name: string;
+ roles: string[];
+ }): Promise<User> {
+ // Business rule: Check if email already exists
+ const emailExists = await userRepository.emailExists(data.email);
+ if (emailExists) {
+ throw new ConflictError("Email already exists");
}
- /**
- * Get user by ID
- */
- async getUser(userId: string): Promise<User> {
- const user = await userRepository.findById(userId);
+ // Business rule: Validate roles
+ const validRoles = ["admin", "operations", "user"];
+ const invalidRoles = data.roles.filter(
+ (role) => !validRoles.includes(role),
+ );
+ if (invalidRoles.length > 0) {
+ throw new ValidationError(`Invalid roles: ${invalidRoles.join(", ")}`);
+ }
+
+ // Create user via repository
+ return await userRepository.create({
+ email: data.email,
+ name: data.name,
+ roles: data.roles,
+ isActive: true,
+ });
+ }
- if (!user) {
- throw new NotFoundError(`User not found: ${userId}`);
- }
+ /**
+ * Get user by ID
+ */
+ async getUser(userId: string): Promise<User> {
+ const user = await userRepository.findById(userId);
- return user;
+ if (!user) {
+ throw new NotFoundError(`User not found: ${userId}`);
}
+
+ return user;
+ }
}
```
@@ -558,22 +608,22 @@ Each service should have ONE clear purpose:
```typescript
// βœ… GOOD - Single responsibility
class UserService {
- async createUser() {}
- async updateUser() {}
- async deleteUser() {}
+ async createUser() {}
+ async updateUser() {}
+ async deleteUser() {}
}
class EmailService {
- async sendEmail() {}
- async sendBulkEmails() {}
+ async sendEmail() {}
+ async sendBulkEmails() {}
}
// ❌ BAD - Too many responsibilities
class UserService {
- async createUser() {}
- async sendWelcomeEmail() {} // Should be EmailService
- async logUserActivity() {} // Should be AuditService
- async processPayment() {} // Should be PaymentService
+ async createUser() {}
+ async sendWelcomeEmail() {} // Should be EmailService
+ async logUserActivity() {} // Should be AuditService
+ async processPayment() {} // Should be PaymentService
}
```
@@ -616,16 +666,16 @@ Services should throw meaningful errors:
```typescript
// βœ… GOOD - Meaningful errors
if (!user) {
- throw new NotFoundError(`User not found: ${userId}`);
+ throw new NotFoundError(`User not found: ${userId}`);
}
if (emailExists) {
- throw new ConflictError('Email already exists');
+ throw new ConflictError("Email already exists");
}
// ❌ BAD - Generic errors
if (!user) {
- throw new Error('Error'); // What error?
+ throw new Error("Error"); // What error?
}
```
@@ -636,30 +686,30 @@ Don't create services that do everything:
```typescript
// ❌ BAD - God service
class WorkflowService {
- async startWorkflow() {}
- async completeStep() {}
- async assignRoles() {}
- async sendNotifications() {} // Should be NotificationService
- async validatePermissions() {} // Should be PermissionService
- async logAuditTrail() {} // Should be AuditService
- // ... 50 more methods
+ async startWorkflow() {}
+ async completeStep() {}
+ async assignRoles() {}
+ async sendNotifications() {} // Should be NotificationService
+ async validatePermissions() {} // Should be PermissionService
+ async logAuditTrail() {} // Should be AuditService
+ // ... 50 more methods
}
// βœ… GOOD - Focused services
class WorkflowService {
- constructor(
- private notificationService: NotificationService,
- private permissionService: PermissionService,
- private auditService: AuditService
- ) {}
-
- async startWorkflow() {
- // Orchestrate other services
- await this.permissionService.checkPermission();
- await this.workflowRepository.create();
- await this.notificationService.notify();
- await this.auditService.log();
- }
+ constructor(
+ private notificationService: NotificationService,
+ private permissionService: PermissionService,
+ private auditService: AuditService,
+ ) {}
+
+ async startWorkflow() {
+ // Orchestrate other services
+ await this.permissionService.checkPermission();
+ await this.workflowRepository.create();
+ await this.notificationService.notify();
+ await this.auditService.log();
+ }
}
```
@@ -671,30 +721,30 @@ class WorkflowService {
```typescript
class UserService {
- private cache: Map<string, { user: User; timestamp: number }> = new Map();
- private CACHE_TTL = 5 * 60 * 1000; // 5 minutes
-
- async getUser(userId: string): Promise<User> {
- // Check cache
- const cached = this.cache.get(userId);
- if (cached && Date.now() - cached.timestamp < this.CACHE_TTL) {
- return cached.user;
- }
-
- // Fetch from database
- const user = await userRepository.findById(userId);
+ private cache: Map<string, { user: User; timestamp: number }> = new Map();
+ private CACHE_TTL = 5 * 60 * 1000; // 5 minutes
+
+ async getUser(userId: string): Promise<User> {
+ // Check cache
+ const cached = this.cache.get(userId);
+ if (cached && Date.now() - cached.timestamp < this.CACHE_TTL) {
+ return cached.user;
+ }
- // Update cache
- if (user) {
- this.cache.set(userId, { user, timestamp: Date.now() });
- }
+ // Fetch from database
+ const user = await userRepository.findById(userId);
- return user;
+ // Update cache
+ if (user) {
+ this.cache.set(userId, { user, timestamp: Date.now() });
}
- clearUserCache(userId: string): void {
- this.cache.delete(userId);
- }
+ return user;
+ }
+
+ clearUserCache(userId: string): void {
+ this.cache.delete(userId);
+ }
}
```
@@ -702,15 +752,15 @@ class UserService {
```typescript
class UserService {
- async updateUser(userId: string, data: UpdateUserDTO): Promise<User> {
- // Update in database
- const user = await userRepository.update(userId, data);
+ async updateUser(userId: string, data: UpdateUserDTO): Promise<User> {
+ // Update in database
+ const user = await userRepository.update(userId, data);
- // Invalidate cache
- this.clearUserCache(userId);
+ // Invalidate cache
+ this.clearUserCache(userId);
- return user;
- }
+ return user;
+ }
}
```
@@ -722,67 +772,70 @@ class UserService {
```typescript
// tests/userService.test.ts
-import { UserService } from '../services/userService';
-import { userRepository } from '../repositories/UserRepository';
-import { ConflictError } from '../utils/errors';
+import { UserService } from "../services/userService";
+import { userRepository } from "../repositories/UserRepository";
+import { ConflictError } from "../utils/errors";
// Mock repository
-jest.mock('../repositories/UserRepository');
-
-describe('UserService', () => {
- let userService: UserService;
-
- beforeEach(() => {
- userService = new UserService();
- jest.clearAllMocks();
+jest.mock("../repositories/UserRepository");
+
+describe("UserService", () => {
+ let userService: UserService;
+
+ beforeEach(() => {
+ userService = new UserService();
+ jest.clearAllMocks();
+ });
+
+ describe("createUser", () => {
+ it("should create user when email does not exist", async () => {
+ // Arrange
+ const userData = {
+ email: "[email protected]",
+ name: "Test User",
+ roles: ["user"],
+ };
+
+ (userRepository.emailExists as jest.Mock).mockResolvedValue(false);
+ (userRepository.create as jest.Mock).mockResolvedValue({
+ userID: "123",
+ ...userData,
+ });
+
+ // Act
+ const user = await userService.createUser(userData);
+
+ // Assert
+ expect(user).toBeDefined();
+ expect(user.email).toBe(userData.email);
+ expect(userRepository.emailExists).toHaveBeenCalledWith(userData.email);
+ expect(userRepository.create).toHaveBeenCalled();
});
- describe('createUser', () => {
- it('should create user when email does not exist', async () => {
- // Arrange
- const userData = {
- email: '[email protected]',
- name: 'Test User',
- roles: ['user'],
- };
-
- (userRepository.emailExists as jest.Mock).mockResolvedValue(false);
- (userRepository.create as jest.Mock).mockResolvedValue({
- userID: '123',
- ...userData,
- });
-
- // Act
- const user = await userService.createUser(userData);
-
- // Assert
- expect(user).toBeDefined();
- expect(user.email).toBe(userData.email);
- expect(userRepository.emailExists).toHaveBeenCalledWith(userData.email);
- expect(userRepository.create).toHaveBeenCalled();
- });
-
- it('should throw ConflictError when email exists', async () => {
- // Arrange
- const userData = {
- email: '[email protected]',
- name: 'Test User',
- roles: ['user'],
- };
-
- (userRepository.emailExists as jest.Mock).mockResolvedValue(true);
-
- // Act & Assert
- await expect(userService.createUser(userData)).rejects.toThrow(ConflictError);
- expect(userRepository.create).not.toHaveBeenCalled();
- });
+ it("should throw ConflictError when email exists", async () => {
+ // Arrange
+ const userData = {
+ email: "[email protected]",
+ name: "Test User",
+ roles: ["user"],
+ };
+
+ (userRepository.emailExists as jest.Mock).mockResolvedValue(true);
+
+ // Act & Assert
+ await expect(userService.createUser(userData)).rejects.toThrow(
+ ConflictError,
+ );
+ expect(userRepository.create).not.toHaveBeenCalled();
});
+ });
});
```
---
**Related Files:**
+
- [SKILL.md](SKILL.md) - Main guide
- [routing-and-controllers.md](routing-and-controllers.md) - Controllers that use services
- [database-patterns.md](database-patterns.md) - Prisma and repository patterns
diff --git a/REVIEW.md b/REVIEW.md
index ee9dfac627..eac2868f9b 100644
--- a/REVIEW.md
+++ b/REVIEW.md
@@ -9,10 +9,12 @@
- ClickHouse migrations in the `packages/shared/clickhouse/migrations/unclustered` directory must not include `ON CLUSTER` statements and must not use `Replicated` merge tree table types.
- Migrations in `packages/shared/clickhouse/migrations/clustered` should match their counterparts in `packages/shared/clickhouse/migrations/unclustered` aside from the restrictions listed above.
- When adding new indexes on ClickHouse, ensure that there is a corresponding `MATERIALIZE INDEX` statement in the same migration. The materialization can use `SETTINGS mutations_sync = 2` if they operate on smaller tables, but may timeout otherwise.
+- All ClickHouse queries on project-scoped tables (traces, observations, scores, events, sessions, etc.) must include `WHERE project_id = {projectId: String}` filter to ensure proper tenant isolation and that queries only access data from the intended project.
### Postgres
- Most `schema.prisma` changes should produce a change in `packages/shared/prisma/migrations`.
+- All Prisma queries on project-scoped tables must include `projectId` in the WHERE clause (e.g., `where: { id: traceId, projectId }`) to ensure proper tenant isolation and that queries only access data from the intended project.
### Environment Variables