# @oshun/\* - Shared Infrastructure Libraries

This directory contains shared infrastructure libraries used across all Oshun
domains. These provide common functionality for logging, errors, caching,
database access, and more.

## Overview

All shared libraries use the `@oshun/*` namespace and are designed to be
domain-agnostic.

## What earns a home here (curation rule — deep-audit H-3)

A library belongs in `libs/shared/` only if it is **domain-agnostic
infrastructure** consumed (or designed to be consumed) by more than one domain.
Domain feature code goes in `libs/<domain>/` even when several apps consume it
(`tara-live-class-booking` was evicted to `libs/tara/live-class-booking` under
this rule, 2026-07-18). When a shared lib is superseded, record it in
`docs/DEPRECATIONS.md` — do not leave twins.

### Deliberate near-name pairs (adjudicated 2026-07-18, not duplicates)

| Pair                              | Split                                                                                                                                                                                                                                          |
| --------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `events` vs `event-bus`           | `events` = typed **in-process** emitter (single runtime, no transport); `event-bus` = **cross-domain distributed** pub/sub (transported). Importing the wrong one is a design smell, not a shim opportunity.                                   |
| `auth` vs `auth-primitives`       | `auth-primitives` = stateless building blocks (JWT sign/verify, session token shapes) with no storage or transport; `auth` = the full authn/z service composed on top. Services embed `auth`; edge code and tests reach for `auth-primitives`. |
| `logging` / `metrics` / `tracing` | Three observability planes kept separate on purpose — consumers routinely need exactly one (a worker with metrics but no tracing), and each has a different dependency weight.                                                                 |

## Libraries

```
libs/shared/
├── types/               # Base TypeScript types
├── errors/              # Error handling framework
├── config/              # Configuration management
├── logging/             # Structured logging (Pino)
├── metrics/             # Prometheus metrics
├── tracing/             # OpenTelemetry tracing
├── database/            # PostgreSQL/Prisma utilities
├── cache/               # Redis caching
├── storage/             # S3/MinIO abstraction
├── queue/               # BullMQ job queues
├── http-client/         # HTTP client with retries
├── websocket/           # WebSocket infrastructure
├── event-bus/           # Event pub/sub
├── service-discovery/   # Service registry
├── auth-primitives/     # JWT, session primitives
├── identity/            # User identity, RBAC
├── rate-limit/          # Rate limiting
├── ai/                  # LLM client abstraction
├── ai-advanced/         # Advanced AI features
├── health/              # Health checks
├── testing/             # Test utilities
├── migration/           # DB migration tools
├── proto/               # Protocol Buffers
└── gateway/             # API gateway primitives
```

## Quick Start

### Installation

All shared libraries are workspace packages:

```typescript
// Import from workspace packages
import { createLogger } from '@oshun/logging';
import { AppError, NotFoundError } from '@oshun/errors';
import { createPrismaClient } from '@oshun/database';
import { createRedisClient } from '@oshun/cache';
import { EventBus } from '@oshun/event-bus';
```

### Core Libraries

#### Logging

```typescript
import { createLogger } from '@oshun/logging';

const logger = createLogger('my-service');

logger.info('Starting service', { port: 4000 });
logger.error('Failed to connect', { error });
logger.debug('Processing request', { requestId });
```

#### Error Handling

```typescript
import { AppError, NotFoundError, ValidationError } from '@oshun/errors';

// Domain-specific error
throw new NotFoundError('User not found', { userId: '123' });

// Validation error
throw new ValidationError('Invalid email format', {
  field: 'email',
  value: input.email,
});

// Custom error
class MyDomainError extends AppError {
  constructor(message: string) {
    super(message, 'MY_DOMAIN_ERROR', 400);
  }
}
```

#### Database

```typescript
import { createPrismaClient } from '@oshun/database';

const prisma = createPrismaClient({
  schema: 'lilith',
  logging: process.env.NODE_ENV === 'development',
});

const users = await prisma.user.findMany();
```

#### Caching

```typescript
import { createRedisClient, createCache } from '@oshun/cache';

const redis = createRedisClient({ url: process.env.REDIS_URL });

const cache = createCache(redis, {
  prefix: 'myservice',
  ttl: 300, // 5 minutes
});

// Set/get
await cache.set('user:123', user);
const cached = await cache.get('user:123');

// With fetch fallback
const user = await cache.getOrFetch('user:123', () =>
  prisma.user.findUnique({ where: { id: '123' } })
);
```

#### Event Bus

```typescript
import { EventBus } from '@oshun/event-bus';

const eventBus = new EventBus({
  redis: { url: process.env.REDIS_URL },
  consumerGroup: 'my-service',
});

// Publish
await eventBus.publish('domain.entity.action', payload);

// Subscribe
eventBus.subscribe('domain.entity.*', async (event) => {
  console.log(event.type, event.payload);
});

await eventBus.start();
```

#### HTTP Client

```typescript
import { createHttpClient } from '@oshun/http-client';

const client = createHttpClient({
  baseUrl: 'https://api.example.com',
  timeout: 30000,
  retries: 3,
  headers: { 'X-API-Key': process.env.API_KEY },
});

const response = await client.get('/users/123');
const created = await client.post('/users', { name: 'John' });
```

#### Queue

```typescript
import { createQueue, createWorker } from '@oshun/queue';

const queue = createQueue('my-jobs', {
  redis: { url: process.env.REDIS_URL },
});

// Producer
await queue.add('process-data', { id: '123' }, { priority: 1 });

// Worker
const worker = createWorker('my-jobs', async (job) => {
  await processData(job.data);
  return { success: true };
});
```

#### Storage

```typescript
import { createStorageClient, StorageProvider } from '@oshun/storage';

const storage = createStorageClient({
  provider: StorageProvider.S3,
  bucket: process.env.ASSET_BUCKET,
  region: 'us-east-1',
});

// Upload
const result = await storage.upload({
  key: 'files/document.pdf',
  body: fileBuffer,
  contentType: 'application/pdf',
});

// Presigned URL
const uploadUrl = await storage.createPresignedUpload({
  key: 'files/new-document.pdf',
  expiresIn: 3600,
});
```

#### Auth Primitives

```typescript
import { verifyJWT, createSession } from '@oshun/auth-primitives';
import { hasPermission } from '@oshun/identity';

// Verify token
const payload = await verifyJWT(token, {
  issuer: 'oshun-auth',
  audience: ['lilith', 'yemaya'],
});

// Check permissions
if (!hasPermission(payload, 'write:projects')) {
  throw new ForbiddenError('Insufficient permissions');
}
```

### Observability

#### Metrics

```typescript
import { metrics, createHistogram, createCounter } from '@oshun/metrics';

const requestDuration = createHistogram({
  name: 'http_request_duration_seconds',
  help: 'HTTP request duration',
  labelNames: ['method', 'path', 'status'],
});

// Record
const end = requestDuration.startTimer();
// ... handle request
end({ method: 'GET', path: '/users', status: '200' });
```

#### Tracing

```typescript
import { withSpan, trace } from '@oshun/tracing';

// Wrap function with span
const result = await withSpan('process-user', async (span) => {
  span.setAttribute('user.id', userId);
  return await processUser(userId);
});

// Manual span
const span = trace.getTracer('my-service').startSpan('operation');
try {
  // ... operation
} finally {
  span.end();
}
```

## Configuration

All shared libraries read from environment variables:

```bash
# Core
NODE_ENV=production
LOG_LEVEL=info

# Database
DATABASE_URL=postgresql://...

# Redis
REDIS_URL=redis://localhost:6379

# Storage
S3_BUCKET=oshun-assets
S3_REGION=us-east-1

# Observability
OTEL_EXPORTER_OTLP_ENDPOINT=https://otel.oshun.io
SENTRY_DSN=https://...@sentry.io/...
```

## Testing

```typescript
import { describe, it, expect } from 'vitest';
import { createTestContext, TestEventBus } from '@oshun/testing';

describe('MyService', () => {
  const ctx = createTestContext();

  beforeEach(async () => {
    await ctx.reset();
  });

  it('should process events', async () => {
    const eventBus = new TestEventBus();

    // Test logic
    await myService.process();

    expect(eventBus.published).toContainEqual(
      expect.objectContaining({ type: 'my.event' })
    );
  });
});
```

## Building

```bash
# Build all shared libraries
nx run-many --target=build --projects=tag:scope:shared

# Build specific library
nx build @oshun/logging

# Run tests
nx test @oshun/errors
```

## Local Development

Start the full development environment:

```bash
# Start infrastructure (PostgreSQL, Redis, MinIO)
docker compose -f docker/docker-compose.dev.yml up -d

# Build all shared libraries
pnpm nx run-many --target=build --projects=tag:scope:shared

# Run tests
pnpm nx run-many --target=test --projects=tag:scope:shared
```

See [CLAUDE.md](/CLAUDE.md) for detailed local development setup.

## Related Documentation

- [Cross-Domain Integration](/docs/guides/cross-domain-integration.md)
- [Adding New Libraries](/docs/guides/adding-new-libraries.md)
- [Architecture](/ARCHITECTURE.md)
