|
| 1 | +# Backend Services Architecture |
| 2 | + |
| 3 | +## Module Boundaries |
| 4 | + |
| 5 | +``` |
| 6 | +backend/services/ |
| 7 | +├── container.ts # IoC Container — sole coupling point |
| 8 | +├── index.ts # Public API barrel |
| 9 | +├── shared/ # Cross-cutting infrastructure |
| 10 | +│ ├── errors.ts # DomainError base class |
| 11 | +│ ├── logging.ts # Structured logger |
| 12 | +│ ├── encryption.ts # PII encryption & blind indexes |
| 13 | +│ ├── apiResponse.ts # Standard API response envelope |
| 14 | +│ ├── apiClient.ts # HTTP client |
| 15 | +│ ├── auditService.ts # Audit trail |
| 16 | +│ ├── monitoring.ts # Health checks & metrics |
| 17 | +│ ├── rateLimitingService.ts # Rate limiting |
| 18 | +│ ├── gdpr.ts # Data subject requests |
| 19 | +│ ├── keyManager.ts # Key rotation |
| 20 | +│ └── piiAudit.ts # PII access audit |
| 21 | +├── subscription/ # Subscription domain |
| 22 | +│ ├── interfaces.ts # ISubscriptionEventStore, IElasticsearchService |
| 23 | +│ ├── errors.ts # SubscriptionError + SubscriptionErrorCode |
| 24 | +│ ├── subscriptionEventStore.ts |
| 25 | +│ ├── ElasticsearchService.ts |
| 26 | +│ └── __tests__/ |
| 27 | +├── billing/ # Billing domain |
| 28 | +│ ├── interfaces.ts # IMeteringService, IPricingService, ITaxService, etc. |
| 29 | +│ ├── errors.ts # BillingError + BillingErrorCode |
| 30 | +│ ├── meteringService.ts |
| 31 | +│ ├── pricingService.ts |
| 32 | +│ ├── taxService.ts |
| 33 | +│ ├── dunningService.ts |
| 34 | +│ ├── accountingExportService.ts |
| 35 | +│ └── __tests__/ |
| 36 | +├── notification/ # Notification domain |
| 37 | +│ ├── interfaces.ts # INotificationPreferenceService, IAlertingService, etc. |
| 38 | +│ ├── errors.ts # NotificationError + NotificationErrorCode |
| 39 | +│ ├── preferenceService.ts |
| 40 | +│ ├── alerting.ts |
| 41 | +│ ├── webhook.ts |
| 42 | +│ ├── websocket.ts |
| 43 | +│ └── __tests__/ |
| 44 | +└── analytics/ # Analytics domain |
| 45 | + ├── interfaces.ts # IPredictionService, IRecommendationService, etc. |
| 46 | + ├── errors.ts # AnalyticsError + AnalyticsErrorCode |
| 47 | + ├── campaignService.ts |
| 48 | + ├── complianceReport.ts |
| 49 | + ├── dataPipeline.ts |
| 50 | + ├── dataWarehouse.ts |
| 51 | + ├── predictionService.ts |
| 52 | + ├── recommendationService.ts |
| 53 | + ├── retentionService.ts |
| 54 | + ├── oracleMonitorService.ts |
| 55 | + └── __tests__/ |
| 56 | +``` |
| 57 | + |
| 58 | +## Domain Modules |
| 59 | + |
| 60 | +### subscription |
| 61 | +**Responsibility:** Subscription lifecycle, event sourcing, full-text search. |
| 62 | +**Interfaces:** `ISubscriptionEventStore`, `IElasticsearchService` |
| 63 | +**Depends on:** `shared` (errors, types, logging) |
| 64 | +**DOES NOT depend on:** `billing`, `notification`, `analytics` |
| 65 | + |
| 66 | +### billing |
| 67 | +**Responsibility:** Usage metering, pricing, tax calculation, dunning, accounting exports. |
| 68 | +**Interfaces:** `IMeteringService`, `IPricingService`, `ITaxService`, `IDunningService`, `IAccountingExportService` |
| 69 | +**Depends on:** `shared` (errors, types, logging) |
| 70 | +**DOES NOT depend on:** `subscription`, `notification`, `analytics` |
| 71 | + |
| 72 | +### notification |
| 73 | +**Responsibility:** Push notifications, webhooks, alerts, WebSocket real-time, user preferences. |
| 74 | +**Interfaces:** `INotificationPreferenceService`, `IAlertingService`, `IWebhookDeliveryService`, `IWebsocketService` |
| 75 | +**Depends on:** `shared` (errors, types, logging) |
| 76 | +**DOES NOT depend on:** `subscription`, `billing`, `analytics` |
| 77 | + |
| 78 | +### analytics |
| 79 | +**Responsibility:** Campaigns, churn prediction, recommendations, compliance reports, oracle data. |
| 80 | +**Interfaces:** `IPredictionService`, `IRecommendationService`, `IComplianceReportService`, `ICampaignService` |
| 81 | +**Depends on:** `shared` (errors, types, logging) |
| 82 | +**DOES NOT depend on:** `subscription`, `billing`, `notification` |
| 83 | + |
| 84 | +## Dependency Injection |
| 85 | + |
| 86 | +All cross-module communication flows through the `Container` in `container.ts`. Modules NEVER import concrete classes from sibling domains — they only depend on interfaces registered with I-prefix tokens. |
| 87 | + |
| 88 | +```typescript |
| 89 | +// ✅ CORRECT — resolve via container |
| 90 | +const billing = container.resolve<IBillingService>('IBillingService'); |
| 91 | + |
| 92 | +// ❌ WRONG — direct cross-module import |
| 93 | +import { SubscriptionEventStore } from '../subscription/subscriptionEventStore'; |
| 94 | +``` |
| 95 | + |
| 96 | +### Container API |
| 97 | + |
| 98 | +| Method | Description | |
| 99 | +|--------|-------------| |
| 100 | +| `register(token, instance)` | Register an eager singleton | |
| 101 | +| `bind(token, factory, lifetime?)` | Lazy binding (singleton by default) | |
| 102 | +| `bindTransient(token, factory)` | New instance on every resolve | |
| 103 | +| `resolve(token)` | Resolve a dependency (throws if missing) | |
| 104 | +| `tryResolve(token)` | Resolve or return null | |
| 105 | +| `has(token)` | Check if token is registered | |
| 106 | +| `registerModule(reg)` | Bulk-register module bindings | |
| 107 | +| `disposeAll()` | Call dispose() on all Disposable singletons | |
| 108 | +| `clear()` | Reset all bindings (test isolation) | |
| 109 | +| `listTokens()` | List all registered tokens | |
| 110 | + |
| 111 | +## Error Handling |
| 112 | + |
| 113 | +Each module has its own error class extending `DomainError` and a set of typed error codes: |
| 114 | + |
| 115 | +- `SubscriptionError` / `SubscriptionErrorCode` — `SUB_NOT_FOUND`, `SUB_EVENT_STORE_FULL`, etc. |
| 116 | +- `BillingError` / `BillingErrorCode` — `BILL_PAYMENT_FAILED`, `BILL_TAX_CALCULATION_FAILED`, etc. |
| 117 | +- `NotificationError` / `NotificationErrorCode` — `NOTIF_DELIVERY_FAILED`, `NOTIF_WEBHOOK_HEALTH_FAILED`, etc. |
| 118 | +- `AnalyticsError` / `AnalyticsErrorCode` — `ANALYTICS_PREDICTION_FAILED`, `ANALYTICS_INSUFFICIENT_DATA`, etc. |
| 119 | + |
| 120 | +Every error includes a factory method for common cases (e.g. `SubscriptionError.notFound(id)`). |
| 121 | + |
| 122 | +## Anti-Patterns (Avoid) |
| 123 | + |
| 124 | +1. **Cross-module imports of concrete classes** — Always use interfaces + container |
| 125 | +2. **Circular dependencies between modules** — Container detects and throws |
| 126 | +3. **Shared mutable state** — Each module owns its own state |
| 127 | +4. **Direct filesystem access between modules** — Use the shared infrastructure layer |
| 128 | +5. **Module A importing from module B's internal utils** — Abstract via shared/ or interfaces |
| 129 | + |
| 130 | +## Testing |
| 131 | + |
| 132 | +Each module has `__tests__/module.test.ts` validating: |
| 133 | +- Error codes are unique and correctly typed |
| 134 | +- DI container bindings resolve correctly |
| 135 | +- Container edge cases (circular deps, missing tokens, transient vs singleton) |
| 136 | + |
| 137 | +Run module-level tests: |
| 138 | +```bash |
| 139 | +npm test -- --testPathPattern="backend/services/.*/module.test.ts" |
| 140 | +``` |
0 commit comments