@classytic/supplier-performance 0.2.0 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,9 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.2.1
4
+
5
+ Patch — outbox support, §P8.1 session guard, awaited publish, tenant-isolation fix.
6
+
3
7
  ## 0.2.0
4
8
 
5
9
  Stack upgrade + tenant-isolation fix + PACKAGE_RULES compliance + real test
package/dist/index.d.ts CHANGED
@@ -3,6 +3,7 @@ import { PluginType, Repository, RepositoryContext } from "@classytic/mongokit";
3
3
  import { ResolvedTenantConfig, TenantConfig } from "@classytic/repo-core/tenant";
4
4
  import { ClientSession, Connection, Document, Model, Schema, Types } from "mongoose";
5
5
  import { EventTransport } from "@classytic/primitives/events";
6
+ import { OutboxStore } from "@classytic/primitives/outbox";
6
7
  import { HttpError } from "@classytic/repo-core/errors";
7
8
 
8
9
  //#region src/models/performance-event.model.d.ts
@@ -241,6 +242,11 @@ interface ScoreServiceConfig {
241
242
  events: PerformanceEventRepository;
242
243
  scores: SupplierScoreRepository;
243
244
  eventTransport?: EventTransport | undefined;
245
+ /**
246
+ * Optional durable outbox. Required for calling verbs under a
247
+ * host-owned ctx.session — see UnmanagedSessionError (§P8.1).
248
+ */
249
+ outbox?: OutboxStore | undefined;
244
250
  logger?: {
245
251
  error(message: string, ...args: unknown[]): void;
246
252
  } | undefined;
@@ -249,6 +255,7 @@ declare class ScoreService {
249
255
  private events;
250
256
  private scores;
251
257
  private eventTransport;
258
+ private outbox;
252
259
  private logger;
253
260
  constructor(config: ScoreServiceConfig);
254
261
  /**
@@ -273,11 +280,12 @@ declare class ScoreService {
273
280
  */
274
281
  getScorecard(supplierId: string, ctx: SupplierPerformanceContext, period?: ScorePeriod): Promise<SupplierScoreDocument | null>;
275
282
  /**
276
- * Publish a domain event via the injected transport (rule 14). There is
277
- * no outbox in this package (host-composed per §5.5 / §16), so a publish
278
- * failure is logged and swallowed — there is no durable row to roll back
279
- * and no transaction in flight. Hosts wanting at-least-once delivery wire
280
- * their own transport (Redis/Kafka) + relay.
283
+ * P8 dispatch. Outbox save (when wired) runs first, session-bound, and
284
+ * failures PROPAGATE; the transport publish is best-effort (swallowed)
285
+ * and skipped under a host session — the relay delivers the durable
286
+ * row post-commit (§P8.1). A host session with NO outbox throws
287
+ * `UnmanagedSessionError` before any side effect: the pre-guard
288
+ * fire-and-forget publish could leak ghost events on rollback.
281
289
  */
282
290
  private publish;
283
291
  }
@@ -308,6 +316,8 @@ interface SupplierPerformanceConfig {
308
316
  * the bundled `InProcessSupplierPerformanceBus`. Omit to skip event
309
317
  * emission entirely.
310
318
  */
319
+ /** Optional durable outbox — enables host-session (relay-only) mode. */
320
+ outbox?: OutboxStore | undefined;
311
321
  eventTransport?: EventTransport | undefined;
312
322
  /**
313
323
  * Tenant scoping config — `TenantConfig` from `@classytic/repo-core/tenant`
@@ -354,6 +364,11 @@ declare class SupplierPerformanceError extends Error implements HttpError {
354
364
  readonly status: number;
355
365
  constructor(message: string, code: string, status: number);
356
366
  }
367
+ /**
368
+ * Thrown when a host passes ctx.session but no OutboxStore is wired —
369
+ * publishing mid-transaction would leak ghost events on rollback (§P8.1).
370
+ */
371
+
357
372
  /** Invalid input to `recordEvent` / `computeScore` (missing supplierId, bad period). */
358
373
  declare class SupplierPerformanceValidationError extends SupplierPerformanceError {
359
374
  constructor(message: string);
package/dist/index.js CHANGED
@@ -360,6 +360,33 @@ var SupplierScoreRepository = class extends Repository {
360
360
  }
361
361
  };
362
362
  //#endregion
363
+ //#region src/domain/errors/supplier-performance.errors.ts
364
+ var SupplierPerformanceError = class extends Error {
365
+ code;
366
+ status;
367
+ constructor(message, code, status) {
368
+ super(message);
369
+ this.code = code;
370
+ this.status = status;
371
+ this.name = this.constructor.name;
372
+ }
373
+ };
374
+ /**
375
+ * Thrown when a host passes ctx.session but no OutboxStore is wired —
376
+ * publishing mid-transaction would leak ghost events on rollback (§P8.1).
377
+ */
378
+ var UnmanagedSessionError = class extends SupplierPerformanceError {
379
+ constructor() {
380
+ super("ctx.session provided but no OutboxStore is wired — events would leak or be lost. Wire an outbox or drop the session.", "supplier_performance.session.unmanaged", 409);
381
+ }
382
+ };
383
+ /** Invalid input to `recordEvent` / `computeScore` (missing supplierId, bad period). */
384
+ var SupplierPerformanceValidationError = class extends SupplierPerformanceError {
385
+ constructor(message) {
386
+ super(message, "supplier_performance.validation.invalid_input", 400);
387
+ }
388
+ };
389
+ //#endregion
363
390
  //#region src/calc/score-calculator.ts
364
391
  const COMPOSITE_WEIGHTS = {
365
392
  onTime: .5,
@@ -430,34 +457,30 @@ function round(value, digits) {
430
457
  return Math.round(value * factor) / factor;
431
458
  }
432
459
  //#endregion
433
- //#region src/domain/errors/supplier-performance.errors.ts
434
- var SupplierPerformanceError = class extends Error {
435
- code;
436
- status;
437
- constructor(message, code, status) {
438
- super(message);
439
- this.code = code;
440
- this.status = status;
441
- this.name = this.constructor.name;
442
- }
443
- };
444
- /** Invalid input to `recordEvent` / `computeScore` (missing supplierId, bad period). */
445
- var SupplierPerformanceValidationError = class extends SupplierPerformanceError {
446
- constructor(message) {
447
- super(message, "supplier_performance.validation.invalid_input", 400);
448
- }
449
- };
450
- //#endregion
451
460
  //#region src/services/score.service.ts
461
+ /**
462
+ * ScoreService — orchestration on top of the two repositories.
463
+ *
464
+ * Service-justified per PACKAGE_RULES §2 (multi-repo orchestration + event
465
+ * emission + pure aggregation algorithm). Pure scoring math lives in
466
+ * `calc/score-calculator.ts`; the service handles persistence + events.
467
+ *
468
+ * Verbs:
469
+ * recordEvent(input, ctx) — append to event log + emit `event.recorded`
470
+ * computeScore(input, ctx) — aggregate + upsert + emit `score.computed`
471
+ * getScorecard(supplierId, period?, ctx) — read-or-compute (lazy refresh)
472
+ */
452
473
  var ScoreService = class {
453
474
  events;
454
475
  scores;
455
476
  eventTransport;
477
+ outbox;
456
478
  logger;
457
479
  constructor(config) {
458
480
  this.events = config.events;
459
481
  this.scores = config.scores;
460
482
  this.eventTransport = config.eventTransport;
483
+ this.outbox = config.outbox;
461
484
  this.logger = config.logger ?? console;
462
485
  }
463
486
  /**
@@ -479,7 +502,7 @@ var ScoreService = class {
479
502
  ...input.sourceType !== void 0 ? { sourceType: input.sourceType } : {},
480
503
  ...input.metadata !== void 0 ? { metadata: input.metadata } : {}
481
504
  }, repoOptionsFromCtx(ctx));
482
- this.publish(SupplierPerformanceEvents.EVENT_RECORDED, ctx, {
505
+ await this.publish(SupplierPerformanceEvents.EVENT_RECORDED, ctx, {
483
506
  supplierId: input.supplierId,
484
507
  type: input.type,
485
508
  occurredAt: occurredAt.toISOString(),
@@ -503,7 +526,7 @@ var ScoreService = class {
503
526
  metrics,
504
527
  eventCount: eventsForCalc.length
505
528
  }, ctx);
506
- this.publish(SupplierPerformanceEvents.SCORE_COMPUTED, ctx, {
529
+ await this.publish(SupplierPerformanceEvents.SCORE_COMPUTED, ctx, {
507
530
  supplierId: input.supplierId,
508
531
  period: {
509
532
  start: period.start.toISOString(),
@@ -528,18 +551,28 @@ var ScoreService = class {
528
551
  return this.scores.findLatest(supplierId, ctx);
529
552
  }
530
553
  /**
531
- * Publish a domain event via the injected transport (rule 14). There is
532
- * no outbox in this package (host-composed per §5.5 / §16), so a publish
533
- * failure is logged and swallowed — there is no durable row to roll back
534
- * and no transaction in flight. Hosts wanting at-least-once delivery wire
535
- * their own transport (Redis/Kafka) + relay.
554
+ * P8 dispatch. Outbox save (when wired) runs first, session-bound, and
555
+ * failures PROPAGATE; the transport publish is best-effort (swallowed)
556
+ * and skipped under a host session — the relay delivers the durable
557
+ * row post-commit (§P8.1). A host session with NO outbox throws
558
+ * `UnmanagedSessionError` before any side effect: the pre-guard
559
+ * fire-and-forget publish could leak ghost events on rollback.
536
560
  */
537
- publish(type, ctx, data) {
538
- if (!this.eventTransport) return;
561
+ async publish(type, ctx, data) {
562
+ if (!this.eventTransport && !this.outbox) return;
563
+ if (ctx.session && !this.outbox) throw new UnmanagedSessionError();
539
564
  const event = createEvent(type, data, ctx);
540
- this.eventTransport.publish(event).catch((err) => {
565
+ if (this.outbox) try {
566
+ await this.outbox.save(event, { session: ctx.session });
567
+ } catch (err) {
568
+ this.logger.error(`[supplier-performance] outbox.save failed for ${type}:`, err);
569
+ throw err;
570
+ }
571
+ if (this.eventTransport && !ctx.session) try {
572
+ await this.eventTransport.publish(event);
573
+ } catch (err) {
541
574
  this.logger.error(`[supplier-performance] publish failed for ${type}:`, err);
542
- });
575
+ }
543
576
  }
544
577
  };
545
578
  function toCalcEvent(doc) {
@@ -601,6 +634,7 @@ async function createSupplierPerformance(config) {
601
634
  events: performanceEvent,
602
635
  scores: supplierScore,
603
636
  eventTransport: events,
637
+ ...config.outbox !== void 0 ? { outbox: config.outbox } : {},
604
638
  logger
605
639
  });
606
640
  return {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@classytic/supplier-performance",
3
- "version": "0.2.0",
3
+ "version": "0.2.1",
4
4
  "description": "Framework-agnostic supplier performance engine — on-time-delivery, defect, and price-variance tracking with append-only event log + cached scorecards. Powered by MongoDB via @classytic/mongokit. Zero framework deps — usable from Arc, Express, Nest, Next.js, or raw Node.",
5
5
  "author": "Classytic",
6
6
  "license": "MIT",