chore: fold exchangeRateService into the nest budget domain

This commit is contained in:
jubnl
2026-07-27 22:58:09 +02:00
parent 132eb2035f
commit a3e6eb52a4
16 changed files with 340 additions and 103 deletions
+1 -1
View File
@@ -8,7 +8,7 @@ import {
toggleMemberPaid, getBudgetItem, freezeForeignRate,
calculateSettlement, listSettlements, createSettlement, updateSettlement, deleteSettlement,
} from '../../services/budgetService';
import { getRates } from '../../services/exchangeRateService';
import { getRates } from '../../nest/budget/exchange-rates.bridge';
import { getTripOwner, listMembers } from '../../services/tripService';
import {
safeBroadcast, TOOL_ANNOTATIONS_WRITE, TOOL_ANNOTATIONS_DELETE, TOOL_ANNOTATIONS_READONLY,
+11 -3
View File
@@ -184,10 +184,18 @@ require strings, scheduler, globalMiddleware, notifications) point at the
logger directly; 8 controllers + `PluginRuntimeService` inject `AuditService`,
and the domain e2e suites dropped the audit mock entirely — writeAudit runs
for real against an `audit_log` table in their temp DBs).
The exchangeRateService fold followed (the pure-infra FX helper — Frankfurter
fetch + module-scoped 6h cache, no SQL, no controller, no MCP registrar of its
own — folded into `nest/budget/` as a dep-free `ExchangeRatesService`, injected
by `BudgetService` and `PluginHostDepsFactory` (its 17th constructor dep), with
an `exchange-rates.bridge.ts` for the legacy `services/budgetService.ts` FX
seams and the `mcp/tools/budget.ts` registrar; the rate **cache stays
module-scoped** like the permissions cache, so the bridge instance and the
container singleton share one cached upstream feed).
Repeat these steps per
service (next up: the exchangeRateService fold → budgetService per the
dependency-honest order in `migration-graph.md`, now that the Wave-2
permissions + auditLog pair is folded). This is a
service (next up: **budgetService** — frontier-ready now that its
exchangeRateService dependency is folded, per the dependency-honest order in
`migration-graph.md`). This is a
**pure relocation** — byte-identical
SQL, statuses, bodies, and error strings. The plugin RPC host is **no longer a
bridge consumer**: since Option A of `src/nest/plugins/DI-MIGRATION.md` it
+3 -2
View File
@@ -1,14 +1,15 @@
import { Module } from '@nestjs/common';
import { BudgetController } from './budget.controller';
import { BudgetService } from './budget.service';
import { ExchangeRatesService } from './exchange-rates.service';
import { PermissionsModule } from '../permissions/permissions.module';
/** Budget domain (S4 — Phase 2 trip sub-domain). Registered in AppModule. */
@Module({
imports: [PermissionsModule],
controllers: [BudgetController],
providers: [BudgetService],
providers: [BudgetService, ExchangeRatesService],
// For in-container consumers (PluginHostDepsFactory).
exports: [BudgetService],
exports: [BudgetService, ExchangeRatesService],
})
export class BudgetModule {}
+3 -2
View File
@@ -4,7 +4,7 @@ import { broadcast } from '../../websocket';
import { PermissionsService } from '../permissions/permissions.service';
import type { User } from '../../types';
import * as svc from '../../services/budgetService';
import { getRates } from '../../services/exchangeRateService';
import { ExchangeRatesService } from './exchange-rates.service';
type Trip = NonNullable<ReturnType<typeof svc.verifyTripAccess>>;
@@ -18,6 +18,7 @@ export class BudgetService {
constructor(
private readonly dbs: DatabaseService,
private readonly permissions: PermissionsService,
private readonly exchangeRates: ExchangeRatesService,
) {}
private get db() {
@@ -46,7 +47,7 @@ export class BudgetService {
async settlement(tripId: string, base: string | undefined, tripCurrency: string) {
const effectiveBase = (base || tripCurrency || 'EUR').toUpperCase();
const rates = await getRates(effectiveBase);
const rates = await this.exchangeRates.getRates(effectiveBase);
return svc.calculateSettlement(tripId, { base: effectiveBase, rates, tripCurrency });
}
@@ -0,0 +1,32 @@
import { ExchangeRatesService } from './exchange-rates.service';
/**
* Non-Nest entry point for the exchange-rates fold — for code running OUTSIDE
* the Nest container (the legacy `services/budgetService.ts` FX-freeze/rebase
* seams and the legacy `get_settlement_summary` registrar in
* src/mcp/tools/budget.ts; the plugin RPC host injects ExchangeRatesService via
* PluginHostDepsFactory). Exports the legacy services/exchangeRateService names
* 1:1, so repointing a consumer is an import-path-only diff. Inside the
* container, inject ExchangeRatesService instead.
* Delete this file when the budgetService migration lands.
*
* Module-level construction is safe: the service has no dependencies and no
* side effects at construction; its rate cache is module-scoped in
* exchange-rates.service.ts, so this instance and the DI singleton share one
* cached upstream feed.
*/
const fx = new ExchangeRatesService();
export function getRates(base: string) {
return fx.getRates(base);
}
/** Unconsumed today (no call sites) — re-exported for 1:1 legacy surface parity. */
export function convertWithRates(
amount: number,
from: string | null | undefined,
base: string,
rates: Record<string, number> | null,
): number {
return fx.convertWithRates(amount, from, base, rates);
}
@@ -0,0 +1,87 @@
import { Injectable } from '@nestjs/common';
/**
* Live exchange rates for the Costs/Budget money conversion.
*
* Fetches from api.frankfurter.dev (no key, already CSP-allowlisted for the
* dashboard widget) and caches per base currency in-memory for a few hours so a
* settlement request never hammers the upstream. Rates are "units of X per 1
* base", so an amount in currency C converts to base as `amount / rates[C]`.
*
* Everything degrades gracefully: if the fetch fails (offline, upstream down),
* callers get `null`/identity conversion and amounts are treated as already in
* the base currency rather than throwing.
*
* Moved 1:1 from the legacy `services/exchangeRateService.ts` (the budget-domain
* fold): identical fetch, cache/coalescing behavior, `||` falsy-coercion
* defaults and null degradation. The cache and inflight maps are deliberately
* MODULE-scoped, not instance fields — the DI singleton and the
* exchange-rates.bridge instance wrap the same upstream feed, so they must
* share one cache (same reasoning as the permissions.service.ts cache).
*/
const TTL_MS = 6 * 60 * 60 * 1000; // 6h
const cache = new Map<string, { rates: Record<string, number>; ts: number }>();
const inflight = new Map<string, Promise<Record<string, number> | null>>();
async function fetchRates(base: string): Promise<Record<string, number> | null> {
try {
const res = await fetch(`https://api.frankfurter.dev/v2/rates?base=${encodeURIComponent(base)}`);
if (!res.ok) return null;
// Frankfurter returns an array of { date, base, quote, rate } and omits the
// base's own self-rate, so seed the map with `base = 1` then index by quote.
const data = (await res.json()) as Array<{ quote?: string; rate?: number }>;
if (!Array.isArray(data)) return null;
const rates: Record<string, number> = { [base.toUpperCase()]: 1 };
for (const r of data) {
if (r && typeof r.quote === 'string' && typeof r.rate === 'number') rates[r.quote] = r.rate;
}
return Object.keys(rates).length > 1 ? rates : null;
} catch {
return null;
}
}
@Injectable()
export class ExchangeRatesService {
/** Rates map for `base` (cached). Returns null if unavailable. */
async getRates(base: string): Promise<Record<string, number> | null> {
const key = (base || 'EUR').toUpperCase();
const hit = cache.get(key);
const now = Date.now();
if (hit && now - hit.ts < TTL_MS) return hit.rates;
// Coalesce concurrent fetches for the same base.
let p = inflight.get(key);
if (!p) {
p = fetchRates(key).then(rates => {
if (rates) cache.set(key, { rates, ts: Date.now() });
inflight.delete(key);
return rates;
});
inflight.set(key, p);
}
const rates = await p;
// On failure fall back to the last cached value if we have one.
if (!rates && hit) return hit.rates;
return rates;
}
/**
* Convert `amount` from `from` currency into `base` using a rates map obtained
* from getRates(base). Identity when same currency or the rate is missing.
*/
convertWithRates(
amount: number,
from: string | null | undefined,
base: string,
rates: Record<string, number> | null,
): number {
const fromCur = (from || base).toUpperCase();
const baseCur = base.toUpperCase();
if (fromCur === baseCur || !rates) return amount;
const r = rates[fromCur];
if (!r || r <= 0) return amount;
return amount / r;
}
}
+5 -3
View File
@@ -19,7 +19,7 @@ The plugin runtime has three layers. Only the third is "un-Nest".
|---|---|---|---|
| Sandbox / transport | `supervisor/plugin-supervisor.ts`, `runtime/plugin-host-entry.ts`, `protocol/envelope.ts` | Forked child per plugin, IPC envelopes, permission tables, actor resolution, rate limiting, RSS policing | Intentionally not — this is the security boundary |
| Enforcement | `host/rpc-host.ts` (~1330 lines) | `PluginRpcHost`: builds a per-plugin method map at spawn — a handler is registered **only if the plugin holds the unlocking permission** (registration = authorization). Depends only on the `HostDeps` interface | Neutral — decoupled by design |
| **Wiring** | `host/plugin-host-deps.factory.ts` (was `create-rpc-host.ts`) | Fills the ~130-member `HostDeps` object. Since Option A: an `@Injectable() PluginHostDepsFactory` with the DI-native domain services (`BudgetService`, `ReservationsService`, `TagsService`, `CategoriesService`, `TodoService`, `PluginOAuthService`) constructor-injected, fifteen domains as of 2026-07 (permissions joined with the Wave-2 pair); legacy `services/*` domains stay plain function imports until their own migration. Raw `db`/`broadcast` also stay until injectable equivalents exist | **Yes (Option A)** — drains further per §3 |
| **Wiring** | `host/plugin-host-deps.factory.ts` (was `create-rpc-host.ts`) | Fills the ~130-member `HostDeps` object. Since Option A: an `@Injectable() PluginHostDepsFactory` with the DI-native domain services (`BudgetService`, `ReservationsService`, `TagsService`, `CategoriesService`, `TodoService`, `PluginOAuthService`) constructor-injected, sixteen domains as of 2026-07 (exchange-rates joined with the budget-domain fold, after the Wave-2 permissions pair); legacy `services/*` domains stay plain function imports until their own migration. Raw `db`/`broadcast` also stay until injectable equivalents exist | **Yes (Option A)** — drains further per §3 |
| Host state | `host/plugin-host-state.ts` | Deliberately module-level (NOT a provider): the per-plugin data-DB map (`getPluginDataDb`/`closePluginDataDb`) and daily broker budgets (`budgetFor`/`pluginBudgetUsage`). Must be one shared instance across host recreations, and is read by `PluginsService`, which the factory imports from — folding it into the injectable would create a provider cycle | Intentionally not |
Key fact that made Option A cheap: the wiring is **called from inside a Nest
@@ -114,7 +114,9 @@ swapped in 2026-07 — its eleven imported symbols (the heaviest single import)
became the injected `DaysService`; permissions swapped in 2026-07 with the
Wave-2 pair — its `checkPermission` import became the injected
`PermissionsService` (the auditLog half never touched the factory: the plugin
host's audit trail is the separate `plugin-audit.ts`); the remaining factory
host's audit trail is the separate `plugin-audit.ts`); exchangeRateService
swapped in 2026-07 with the budget-domain fold — its `getRates` import became
the injected `ExchangeRatesService`; the remaining factory
imports are all Wave-4+ domains: trips, places, journeys, atlas, collections).
### Test impact (as landed)
@@ -123,7 +125,7 @@ imports are all Wave-4+ domains: trips, places, journeys, atlas, collections).
`PluginRpcHost` directly with hand-built `HostDeps`).
- `tests/unit/plugins/plugin-host-deps.factory.test.ts` (was
`create-rpc-host.test.ts`) — the six DI-domain path mocks became constructor
stubs (fifteen stubs as of the 2026-07 permissions migration); the ~22
stubs (sixteen stubs as of the 2026-07 exchange-rates fold); the ~22
legacy-service path mocks remain; a file-local shim keeps the
historical `createRealRpcHost(id, granted)` call sites and supplies a default
no-op router.
@@ -5,7 +5,6 @@ import { listBudgetItems } from '../../../services/budgetService';
import { isUpdateConflict } from '../../../services/conflictResult';
import { getWeather } from '../../../services/weatherService';
import { BLOCKED_EXTENSIONS, filesDir } from '../../files/files.constants';
import { getRates as getExchangeRates } from '../../../services/exchangeRateService';
import { joinTripAsMember } from '../../../services/tripMembership';
import { send as sendNotification } from '../../../services/notificationService';
import { createLlmClient } from '../../llm-parse/llm-client.factory';
@@ -24,6 +23,7 @@ import { listJourneys, listEntries as listJournalEntriesSvc, createEntry as crea
import { listVisitedCountries, listManuallyVisitedRegions, listBucketList, markCountryVisited, unmarkCountryVisited, markRegionVisited, unmarkRegionVisited, createBucketItem as createBucketItemSvc, deleteBucketItem as deleteBucketItemSvc } from '../../../services/atlasService';
import { listCollections, getCollection, createCollection, updateCollection, savePlace as saveCollectionPlaceSvc, copyToTrip as copyCollectionToTripSvc, deletePlace as deleteCollectionPlaceSvc } from '../../../services/collectionsService';
import { BudgetService } from '../../budget/budget.service';
import { ExchangeRatesService } from '../../budget/exchange-rates.service';
import { ReservationsService } from '../../reservations/reservations.service';
import { TagsService } from '../../tags/tags.service';
import { CategoriesService } from '../../categories/categories.service';
@@ -129,9 +129,9 @@ export interface PluginCallRouter {
* host (parent), never in the child. Broadcasts are force-namespaced to
* `plugin:{id}:{event}` so a plugin can't forge a core event.
*
* DI-native domain services (budget, reservations, tags, categories, todo,
* packing, day-notes, assignments, oauth, files, collab, vacay, the LLM
* config resolver) and
* DI-native domain services (budget, exchange-rates, reservations, tags,
* categories, todo, packing, day-notes, assignments, oauth, files, collab,
* vacay, the LLM config resolver) and
* the DatabaseService (all inline SQL + the trip-access helper) are
* constructor-injected; legacy `services/*` domains stay plain function
* imports until their own migration lands (DI-MIGRATION.md), at which point
@@ -156,6 +156,7 @@ export class PluginHostDepsFactory {
private readonly vacay: VacayService,
private readonly days: DaysService,
private readonly permissions: PermissionsService,
private readonly exchangeRates: ExchangeRatesService,
) {}
/**
@@ -534,7 +535,7 @@ export class PluginHostDepsFactory {
}
},
// --- Exchange rates: the same cached upstream feed the budget uses (tenant-free). ---
getRates: (base) => getExchangeRates(base),
getRates: (base) => this.exchangeRates.getRates(base),
// --- Trip (trip_edit). Only the schema-writable fields reach updateTrip; its
// NotFound/Validation errors are mapped to clean RPC codes. ---
canEditTrip: (tripId, userId) => this.canEditTripAs('trip_edit', tripId, userId),
+1 -1
View File
@@ -1,7 +1,7 @@
import { db } from '../db/database';
import { BudgetItem, BudgetItemMember, BudgetItemPayer } from '../types';
import { avatarUrl } from './avatarUrl';
import { getRates } from './exchangeRateService';
import { getRates } from '../nest/budget/exchange-rates.bridge';
// ---------------------------------------------------------------------------
// Helpers
@@ -1,75 +0,0 @@
/**
* Live exchange rates for the Costs/Budget money conversion.
*
* Fetches from api.frankfurter.dev (no key, already CSP-allowlisted for the
* dashboard widget) and caches per base currency in-memory for a few hours so a
* settlement request never hammers the upstream. Rates are "units of X per 1
* base", so an amount in currency C converts to base as `amount / rates[C]`.
*
* Everything degrades gracefully: if the fetch fails (offline, upstream down),
* callers get `null`/identity conversion and amounts are treated as already in
* the base currency rather than throwing.
*/
const TTL_MS = 6 * 60 * 60 * 1000; // 6h
const cache = new Map<string, { rates: Record<string, number>; ts: number }>();
const inflight = new Map<string, Promise<Record<string, number> | null>>();
async function fetchRates(base: string): Promise<Record<string, number> | null> {
try {
const res = await fetch(`https://api.frankfurter.dev/v2/rates?base=${encodeURIComponent(base)}`);
if (!res.ok) return null;
// Frankfurter returns an array of { date, base, quote, rate } and omits the
// base's own self-rate, so seed the map with `base = 1` then index by quote.
const data = (await res.json()) as Array<{ quote?: string; rate?: number }>;
if (!Array.isArray(data)) return null;
const rates: Record<string, number> = { [base.toUpperCase()]: 1 };
for (const r of data) {
if (r && typeof r.quote === 'string' && typeof r.rate === 'number') rates[r.quote] = r.rate;
}
return Object.keys(rates).length > 1 ? rates : null;
} catch {
return null;
}
}
/** Rates map for `base` (cached). Returns null if unavailable. */
export async function getRates(base: string): Promise<Record<string, number> | null> {
const key = (base || 'EUR').toUpperCase();
const hit = cache.get(key);
const now = Date.now();
if (hit && now - hit.ts < TTL_MS) return hit.rates;
// Coalesce concurrent fetches for the same base.
let p = inflight.get(key);
if (!p) {
p = fetchRates(key).then(rates => {
if (rates) cache.set(key, { rates, ts: Date.now() });
inflight.delete(key);
return rates;
});
inflight.set(key, p);
}
const rates = await p;
// On failure fall back to the last cached value if we have one.
if (!rates && hit) return hit.rates;
return rates;
}
/**
* Convert `amount` from `from` currency into `base` using a rates map obtained
* from getRates(base). Identity when same currency or the rate is missing.
*/
export function convertWithRates(
amount: number,
from: string | null | undefined,
base: string,
rates: Record<string, number> | null,
): number {
const fromCur = (from || base).toUpperCase();
const baseCur = base.toUpperCase();
if (fromCur === baseCur || !rates) return amount;
const r = rates[fromCur];
if (!r || r <= 0) return amount;
return amount / r;
}