@entifix/service-shell 0.10.2 → 0.12.0
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/README.md +1 -4
- package/dist/auth/index.d.ts +1 -0
- package/dist/auth/index.d.ts.map +1 -1
- package/dist/auth/index.js +1 -0
- package/dist/auth/index.js.map +1 -1
- package/dist/auth/require-organization.d.ts +1 -1
- package/dist/auth/require-organization.d.ts.map +1 -1
- package/dist/auth/require-organization.js.map +1 -1
- package/dist/auth/require-principal.d.ts +9 -49
- package/dist/auth/require-principal.d.ts.map +1 -1
- package/dist/auth/require-principal.js +21 -15
- package/dist/auth/require-principal.js.map +1 -1
- package/dist/auth/require-service-crossing.d.ts.map +1 -1
- package/dist/auth/require-service-crossing.js +3 -13
- package/dist/auth/require-service-crossing.js.map +1 -1
- package/dist/auth/shared-token.d.ts +2 -0
- package/dist/auth/shared-token.d.ts.map +1 -1
- package/dist/auth/shared-token.js +2 -2
- package/dist/auth/shared-token.js.map +1 -1
- package/dist/auth/verified-context.d.ts +24 -0
- package/dist/auth/verified-context.d.ts.map +1 -0
- package/dist/auth/verified-context.js +40 -0
- package/dist/auth/verified-context.js.map +1 -0
- package/dist/entity-facet-routes.d.ts +7 -1
- package/dist/entity-facet-routes.d.ts.map +1 -1
- package/dist/entity-facet-routes.js +8 -5
- package/dist/entity-facet-routes.js.map +1 -1
- package/dist/entity-metadata-route.d.ts +2 -1
- package/dist/entity-metadata-route.d.ts.map +1 -1
- package/dist/entity-metadata-route.js +20 -3
- package/dist/entity-metadata-route.js.map +1 -1
- package/dist/entity-route-guard.d.ts +5 -3
- package/dist/entity-route-guard.d.ts.map +1 -1
- package/dist/entity-route-guard.js +12 -6
- package/dist/entity-route-guard.js.map +1 -1
- package/dist/entity-routes.d.ts +13 -1
- package/dist/entity-routes.d.ts.map +1 -1
- package/dist/entity-routes.js +20 -6
- package/dist/entity-routes.js.map +1 -1
- package/dist/http-api/build-api.d.ts +78 -0
- package/dist/http-api/build-api.d.ts.map +1 -0
- package/dist/http-api/build-api.js +189 -0
- package/dist/http-api/build-api.js.map +1 -0
- package/dist/http-api/entity-api.d.ts +69 -0
- package/dist/http-api/entity-api.d.ts.map +1 -0
- package/dist/http-api/entity-api.js +522 -0
- package/dist/http-api/entity-api.js.map +1 -0
- package/dist/http-api/guards.d.ts +92 -0
- package/dist/http-api/guards.d.ts.map +1 -0
- package/dist/http-api/guards.js +131 -0
- package/dist/http-api/guards.js.map +1 -0
- package/dist/http-api/index.d.ts +6 -0
- package/dist/http-api/index.d.ts.map +1 -0
- package/dist/http-api/index.js +7 -0
- package/dist/http-api/index.js.map +1 -0
- package/dist/http-api/problem-codec.d.ts +14 -0
- package/dist/http-api/problem-codec.d.ts.map +1 -0
- package/dist/http-api/problem-codec.js +26 -0
- package/dist/http-api/problem-codec.js.map +1 -0
- package/dist/http-api/service-group.d.ts +74 -0
- package/dist/http-api/service-group.d.ts.map +1 -0
- package/dist/http-api/service-group.js +168 -0
- package/dist/http-api/service-group.js.map +1 -0
- package/dist/idempotency.d.ts +64 -0
- package/dist/idempotency.d.ts.map +1 -0
- package/dist/idempotency.js +112 -0
- package/dist/idempotency.js.map +1 -0
- package/dist/index.d.ts +4 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +4 -2
- package/dist/index.js.map +1 -1
- package/dist/make-service.d.ts +39 -6
- package/dist/make-service.d.ts.map +1 -1
- package/dist/make-service.js +54 -16
- package/dist/make-service.js.map +1 -1
- package/dist/metadata-composition.d.ts +28 -0
- package/dist/metadata-composition.d.ts.map +1 -0
- package/dist/metadata-composition.js +68 -0
- package/dist/metadata-composition.js.map +1 -0
- package/dist/narrowing.d.ts +13 -0
- package/dist/narrowing.d.ts.map +1 -0
- package/dist/narrowing.js +34 -0
- package/dist/narrowing.js.map +1 -0
- package/dist/respond.d.ts +6 -4
- package/dist/respond.d.ts.map +1 -1
- package/dist/respond.js +11 -7
- package/dist/respond.js.map +1 -1
- package/dist/serve-test-service.d.ts +2 -1
- package/dist/serve-test-service.d.ts.map +1 -1
- package/dist/serve-test-service.js.map +1 -1
- package/dist/sse.d.ts +7 -4
- package/dist/sse.d.ts.map +1 -1
- package/dist/sse.js +21 -5
- package/dist/sse.js.map +1 -1
- package/package.json +7 -6
- package/dist/health-routes.d.ts +0 -24
- package/dist/health-routes.d.ts.map +0 -1
- package/dist/health-routes.js +0 -86
- package/dist/health-routes.js.map +0 -1
- package/dist/service-description-route.d.ts +0 -66
- package/dist/service-description-route.d.ts.map +0 -1
- package/dist/service-description-route.js +0 -60
- package/dist/service-description-route.js.map +0 -1
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import { dryRun } from '@entifix/business';
|
|
2
|
+
import { SLIP_VERSION, unmetRequirements } from '@entifix/business/flow';
|
|
3
|
+
/**
|
|
4
|
+
* Throws at mount when a descriptor names a variant set or a recipe the
|
|
5
|
+
* service was not given: a verb that cannot be resolved would otherwise be
|
|
6
|
+
* silently missing from every caller's document.
|
|
7
|
+
*/ export const assertCompositionsDeclared = (descriptors, compositions)=>{
|
|
8
|
+
const missing = descriptors.flatMap((descriptor)=>{
|
|
9
|
+
var _compositions_variants, _compositions_recipes;
|
|
10
|
+
return [
|
|
11
|
+
...descriptor.variants !== undefined && ((_compositions_variants = compositions.variants) == null ? void 0 : _compositions_variants[descriptor.variants]) === undefined ? [
|
|
12
|
+
`variants '${descriptor.variants}' (${descriptor.key})`
|
|
13
|
+
] : [],
|
|
14
|
+
...descriptor.recipe !== undefined && ((_compositions_recipes = compositions.recipes) == null ? void 0 : _compositions_recipes[descriptor.recipe]) === undefined ? [
|
|
15
|
+
`recipe '${descriptor.recipe}' (${descriptor.key})`
|
|
16
|
+
] : []
|
|
17
|
+
];
|
|
18
|
+
});
|
|
19
|
+
if (missing.length > 0) throw new Error(`$metadata cannot resolve ${missing.join(', ')}: provide them to the route`);
|
|
20
|
+
};
|
|
21
|
+
/**
|
|
22
|
+
* What a verb resolves to for one caller: its composition, `undefined` for a
|
|
23
|
+
* verb that resolves nothing (no variants, no recipe), or `'unreachable'` when
|
|
24
|
+
* the caller is offered no variant — or the recipe needs a fragment whose
|
|
25
|
+
* requirements the caller does not meet, in a stage no gate can skip. An
|
|
26
|
+
* unreachable verb is omitted from the document.
|
|
27
|
+
*/ export const compositionFor = (descriptor, context, compositions)=>{
|
|
28
|
+
var _ref, _ref1, _ref2;
|
|
29
|
+
var _compositions_recipes;
|
|
30
|
+
if (descriptor.variants === undefined && descriptor.recipe === undefined) return undefined;
|
|
31
|
+
let variant;
|
|
32
|
+
if (descriptor.variants !== undefined) {
|
|
33
|
+
var _ref3;
|
|
34
|
+
var _compositions_variants;
|
|
35
|
+
const chosen = dryRun((_ref3 = (_compositions_variants = compositions.variants) == null ? void 0 : _compositions_variants[descriptor.variants]) != null ? _ref3 : [], context);
|
|
36
|
+
if (chosen === undefined) return 'unreachable';
|
|
37
|
+
variant = chosen.variant;
|
|
38
|
+
}
|
|
39
|
+
// No recipe means the verb named variants, so one was chosen above.
|
|
40
|
+
if (descriptor.recipe === undefined) return {
|
|
41
|
+
useCase: descriptor.key,
|
|
42
|
+
variant: variant
|
|
43
|
+
};
|
|
44
|
+
const recipe = (_compositions_recipes = compositions.recipes) == null ? void 0 : _compositions_recipes[descriptor.recipe];
|
|
45
|
+
for (const resolution of (_ref = recipe == null ? void 0 : recipe.resolve) != null ? _ref : []){
|
|
46
|
+
const chosen = dryRun(resolution.rules, context);
|
|
47
|
+
if (chosen === undefined) return 'unreachable';
|
|
48
|
+
variant != null ? variant : variant = chosen.variant;
|
|
49
|
+
}
|
|
50
|
+
const always = ((_ref1 = recipe == null ? void 0 : recipe.stages) != null ? _ref1 : []).filter((stage)=>stage.when === undefined).flatMap((stage)=>stage.steps.filter((step)=>step.when === undefined));
|
|
51
|
+
const blocked = always.some((step)=>{
|
|
52
|
+
var _compositions_catalog_get, _compositions_catalog;
|
|
53
|
+
const requires = (_compositions_catalog = compositions.catalog) == null ? void 0 : (_compositions_catalog_get = _compositions_catalog.get(step.ref)) == null ? void 0 : _compositions_catalog_get.requires;
|
|
54
|
+
return requires !== undefined && unmetRequirements(requires, context).length > 0;
|
|
55
|
+
});
|
|
56
|
+
if (blocked) return 'unreachable';
|
|
57
|
+
return {
|
|
58
|
+
useCase: descriptor.key,
|
|
59
|
+
variant: variant != null ? variant : 'default',
|
|
60
|
+
recipe: descriptor.recipe,
|
|
61
|
+
slipVersion: SLIP_VERSION,
|
|
62
|
+
fragments: [
|
|
63
|
+
...new Set(((_ref2 = recipe == null ? void 0 : recipe.stages) != null ? _ref2 : []).flatMap((stage)=>stage.steps.map((step)=>step.ref)))
|
|
64
|
+
]
|
|
65
|
+
};
|
|
66
|
+
};
|
|
67
|
+
|
|
68
|
+
//# sourceMappingURL=metadata-composition.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/metadata-composition.ts"],"sourcesContent":["import {\n dryRun,\n type ResolutionRule,\n type VerifiedContext,\n} from '@entifix/business';\nimport type { Recipe } from '@entifix/business/compose';\nimport {\n type FragmentCatalog,\n SLIP_VERSION,\n unmetRequirements,\n} from '@entifix/business/flow';\nimport type { UseCaseComposition, UseCaseDescriptor } from '@entifix/core';\n\n/**\n * What a service can resolve its verbs against, by the names `@useCase()`\n * gives: variant rules, recipes, and the catalog their fragments come from.\n */\nexport interface MetadataCompositions {\n readonly variants?: Readonly<\n Record<string, readonly ResolutionRule<unknown>[]>\n >;\n // A recipe's start input differs per recipe; the document reads none of it.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n readonly recipes?: Readonly<Record<string, Recipe<any>>>;\n readonly catalog?: FragmentCatalog;\n}\n\n/**\n * Throws at mount when a descriptor names a variant set or a recipe the\n * service was not given: a verb that cannot be resolved would otherwise be\n * silently missing from every caller's document.\n */\nexport const assertCompositionsDeclared = (\n descriptors: readonly UseCaseDescriptor[],\n compositions: MetadataCompositions,\n): void => {\n const missing = descriptors.flatMap(descriptor => [\n ...(descriptor.variants !== undefined &&\n compositions.variants?.[descriptor.variants] === undefined\n ? [`variants '${descriptor.variants}' (${descriptor.key})`]\n : []),\n ...(descriptor.recipe !== undefined &&\n compositions.recipes?.[descriptor.recipe] === undefined\n ? [`recipe '${descriptor.recipe}' (${descriptor.key})`]\n : []),\n ]);\n if (missing.length > 0)\n throw new Error(\n `$metadata cannot resolve ${missing.join(', ')}: provide them to the route`,\n );\n};\n\n/**\n * What a verb resolves to for one caller: its composition, `undefined` for a\n * verb that resolves nothing (no variants, no recipe), or `'unreachable'` when\n * the caller is offered no variant — or the recipe needs a fragment whose\n * requirements the caller does not meet, in a stage no gate can skip. An\n * unreachable verb is omitted from the document.\n */\nexport const compositionFor = (\n descriptor: UseCaseDescriptor,\n context: VerifiedContext,\n compositions: MetadataCompositions,\n): UseCaseComposition | 'unreachable' | undefined => {\n if (descriptor.variants === undefined && descriptor.recipe === undefined)\n return undefined;\n\n let variant: string | undefined;\n if (descriptor.variants !== undefined) {\n const chosen = dryRun(\n compositions.variants?.[descriptor.variants] ?? [],\n context,\n );\n if (chosen === undefined) return 'unreachable';\n variant = chosen.variant;\n }\n // No recipe means the verb named variants, so one was chosen above.\n if (descriptor.recipe === undefined)\n return { useCase: descriptor.key, variant: variant as string };\n\n const recipe = compositions.recipes?.[descriptor.recipe];\n for (const resolution of recipe?.resolve ?? []) {\n const chosen = dryRun(resolution.rules, context);\n if (chosen === undefined) return 'unreachable';\n variant ??= chosen.variant;\n }\n const always = (recipe?.stages ?? [])\n .filter(stage => stage.when === undefined)\n .flatMap(stage => stage.steps.filter(step => step.when === undefined));\n const blocked = always.some(step => {\n const requires = compositions.catalog?.get(step.ref)?.requires;\n return (\n requires !== undefined && unmetRequirements(requires, context).length > 0\n );\n });\n if (blocked) return 'unreachable';\n\n return {\n useCase: descriptor.key,\n variant: variant ?? 'default',\n recipe: descriptor.recipe,\n slipVersion: SLIP_VERSION,\n fragments: [\n ...new Set(\n (recipe?.stages ?? []).flatMap(stage =>\n stage.steps.map(step => step.ref),\n ),\n ),\n ],\n };\n};\n"],"names":["dryRun","SLIP_VERSION","unmetRequirements","assertCompositionsDeclared","descriptors","compositions","missing","flatMap","descriptor","variants","undefined","key","recipe","recipes","length","Error","join","compositionFor","context","variant","chosen","useCase","resolution","resolve","rules","always","stages","filter","stage","when","steps","step","blocked","some","requires","catalog","get","ref","slipVersion","fragments","Set","map"],"mappings":"AAAA,SACEA,MAAM,QAGD,oBAAoB;AAE3B,SAEEC,YAAY,EACZC,iBAAiB,QACZ,yBAAyB;AAiBhC;;;;CAIC,GACD,OAAO,MAAMC,6BAA6B,CACxCC,aACAC;IAEA,MAAMC,UAAUF,YAAYG,OAAO,CAACC,CAAAA;YAElCH,wBAIAA;eANgD;eAC5CG,WAAWC,QAAQ,KAAKC,aAC5BL,EAAAA,yBAAAA,aAAaI,QAAQ,qBAArBJ,sBAAuB,CAACG,WAAWC,QAAQ,CAAC,MAAKC,YAC7C;gBAAC,CAAC,UAAU,EAAEF,WAAWC,QAAQ,CAAC,GAAG,EAAED,WAAWG,GAAG,CAAC,CAAC,CAAC;aAAC,GACzD,EAAE;eACFH,WAAWI,MAAM,KAAKF,aAC1BL,EAAAA,wBAAAA,aAAaQ,OAAO,qBAApBR,qBAAsB,CAACG,WAAWI,MAAM,CAAC,MAAKF,YAC1C;gBAAC,CAAC,QAAQ,EAAEF,WAAWI,MAAM,CAAC,GAAG,EAAEJ,WAAWG,GAAG,CAAC,CAAC,CAAC;aAAC,GACrD,EAAE;SACP;;IACD,IAAIL,QAAQQ,MAAM,GAAG,GACnB,MAAM,IAAIC,MACR,CAAC,yBAAyB,EAAET,QAAQU,IAAI,CAAC,MAAM,2BAA2B,CAAC;AAEjF,EAAE;AAEF;;;;;;CAMC,GACD,OAAO,MAAMC,iBAAiB,CAC5BT,YACAU,SACAb;;QAkBeA;IAhBf,IAAIG,WAAWC,QAAQ,KAAKC,aAAaF,WAAWI,MAAM,KAAKF,WAC7D,OAAOA;IAET,IAAIS;IACJ,IAAIX,WAAWC,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C;QACbsC,WAAW;eACN,IAAIC,IACL,UAAC5B,0BAAAA,OAAQc,MAAM,oBAAI,EAAE,EAAEnB,OAAO,CAACqB,CAAAA,QAC7BA,MAAME,KAAK,CAACW,GAAG,CAACV,CAAAA,OAAQA,KAAKM,GAAG;SAGrC;IACH;AACF,EAAE"}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { type Narrowing, type NarrowingRules, type VerifiedContext } from '@entifix/business';
|
|
2
|
+
import type { Entity, EntityId, EntityLoadRequest, FilterGroup } from '@entifix/core';
|
|
3
|
+
/** The narrowing `rules` choose for `context`. */
|
|
4
|
+
export declare const narrowingFor: <T extends Entity>(rules: NarrowingRules<T>, context: VerifiedContext) => Narrowing<T>;
|
|
5
|
+
/** Conjoins a filter narrowing onto a load request; `unscoped` leaves it as it is. */
|
|
6
|
+
export declare const narrowLoadRequest: <T extends Entity>(request: EntityLoadRequest<T>, narrowing: Exclude<Narrowing<T>, "nothing">) => EntityLoadRequest<T>;
|
|
7
|
+
/**
|
|
8
|
+
* The by-id read under a narrowing: a load of the narrowing plus id equality,
|
|
9
|
+
* so a record out of the caller's sight answers exactly as an absent one does,
|
|
10
|
+
* and the list and the read can never disagree about which records those are.
|
|
11
|
+
*/
|
|
12
|
+
export declare const narrowedByIdRequest: <T extends Entity>(narrowing: FilterGroup<T>, id: EntityId) => EntityLoadRequest<T>;
|
|
13
|
+
//# sourceMappingURL=narrowing.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"narrowing.d.ts","sourceRoot":"","sources":["../src/narrowing.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,KAAK,SAAS,EACd,KAAK,cAAc,EACnB,KAAK,eAAe,EACrB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,KAAK,EACV,MAAM,EACN,QAAQ,EACR,iBAAiB,EACjB,WAAW,EACZ,MAAM,eAAe,CAAC;AAEvB,kDAAkD;AAClD,eAAO,MAAM,YAAY,GAAI,CAAC,SAAS,MAAM,EAC3C,OAAO,cAAc,CAAC,CAAC,CAAC,EACxB,SAAS,eAAe,KACvB,SAAS,CAAC,CAAC,CAMb,CAAC;AAEF,sFAAsF;AACtF,eAAO,MAAM,iBAAiB,GAAI,CAAC,SAAS,MAAM,EAChD,SAAS,iBAAiB,CAAC,CAAC,CAAC,EAC7B,WAAW,OAAO,CAAC,SAAS,CAAC,CAAC,CAAC,EAAE,SAAS,CAAC,KAC1C,iBAAiB,CAAC,CAAC,CAGoD,CAAC;AAE3E;;;;GAIG;AACH,eAAO,MAAM,mBAAmB,GAAI,CAAC,SAAS,MAAM,EAClD,WAAW,WAAW,CAAC,CAAC,CAAC,EACzB,IAAI,QAAQ,KACX,iBAAiB,CAAC,CAAC,CAGiB,CAAC"}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
2
|
+
import { dryRun } from '@entifix/business';
|
|
3
|
+
/** The narrowing `rules` choose for `context`. */ export const narrowingFor = (rules, context)=>{
|
|
4
|
+
const chosen = dryRun(rules, context);
|
|
5
|
+
if (chosen === undefined) return 'nothing';
|
|
6
|
+
// `dryRun` answers the index of a rule it found, so the rule is there.
|
|
7
|
+
const rule = rules[chosen.rule];
|
|
8
|
+
return rule.variant.impl(context);
|
|
9
|
+
};
|
|
10
|
+
/** Conjoins a filter narrowing onto a load request; `unscoped` leaves it as it is. */ export const narrowLoadRequest = (request, narrowing)=>{
|
|
11
|
+
var _request_filtering;
|
|
12
|
+
return narrowing === 'unscoped' ? request : _extends({}, request, {
|
|
13
|
+
filtering: [
|
|
14
|
+
...(_request_filtering = request.filtering) != null ? _request_filtering : [],
|
|
15
|
+
narrowing
|
|
16
|
+
]
|
|
17
|
+
});
|
|
18
|
+
};
|
|
19
|
+
/**
|
|
20
|
+
* The by-id read under a narrowing: a load of the narrowing plus id equality,
|
|
21
|
+
* so a record out of the caller's sight answers exactly as an absent one does,
|
|
22
|
+
* and the list and the read can never disagree about which records those are.
|
|
23
|
+
*/ export const narrowedByIdRequest = (narrowing, id)=>({
|
|
24
|
+
filtering: [
|
|
25
|
+
narrowing,
|
|
26
|
+
{
|
|
27
|
+
property: 'id',
|
|
28
|
+
operator: 'eq',
|
|
29
|
+
value: id
|
|
30
|
+
}
|
|
31
|
+
]
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
//# sourceMappingURL=narrowing.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/narrowing.ts"],"sourcesContent":["import {\n dryRun,\n type Narrowing,\n type NarrowingRules,\n type VerifiedContext,\n} from '@entifix/business';\nimport type {\n Entity,\n EntityId,\n EntityLoadRequest,\n FilterGroup,\n} from '@entifix/core';\n\n/** The narrowing `rules` choose for `context`. */\nexport const narrowingFor = <T extends Entity>(\n rules: NarrowingRules<T>,\n context: VerifiedContext,\n): Narrowing<T> => {\n const chosen = dryRun(rules, context);\n if (chosen === undefined) return 'nothing';\n // `dryRun` answers the index of a rule it found, so the rule is there.\n const rule = rules[chosen.rule] as NarrowingRules<T>[number];\n return rule.variant.impl(context);\n};\n\n/** Conjoins a filter narrowing onto a load request; `unscoped` leaves it as it is. */\nexport const narrowLoadRequest = <T extends Entity>(\n request: EntityLoadRequest<T>,\n narrowing: Exclude<Narrowing<T>, 'nothing'>,\n): EntityLoadRequest<T> =>\n narrowing === 'unscoped'\n ? request\n : { ...request, filtering: [...(request.filtering ?? []), narrowing] };\n\n/**\n * The by-id read under a narrowing: a load of the narrowing plus id equality,\n * so a record out of the caller's sight answers exactly as an absent one does,\n * and the list and the read can never disagree about which records those are.\n */\nexport const narrowedByIdRequest = <T extends Entity>(\n narrowing: FilterGroup<T>,\n id: EntityId,\n): EntityLoadRequest<T> =>\n ({\n filtering: [narrowing, { property: 'id', operator: 'eq', value: id }],\n }) as unknown as EntityLoadRequest<T>;\n"],"names":["dryRun","narrowingFor","rules","context","chosen","undefined","rule","variant","impl","narrowLoadRequest","request","narrowing","filtering","narrowedByIdRequest","id","property","operator","value"],"mappings":";AAAA,SACEA,MAAM,QAID,oBAAoB;AAQ3B,gDAAgD,GAChD,OAAO,MAAMC,eAAe,CAC1BC,OACAC;IAEA,MAAMC,SAASJ,OAAOE,OAAOC;IAC7B,IAAIC,WAAWC,WAAW,OAAO;IACjC,uEAAuE;IACvE,MAAMC,OAAOJ,KAAK,CAACE,OAAOE,IAAI,CAAC;IAC/B,OAAOA,KAAKC,OAAO,CAACC,IAAI,CAACL;AAC3B,EAAE;AAEF,oFAAoF,GACpF,OAAO,MAAMM,oBAAoB,CAC/BC,SACAC;QAIkCD;WAFlCC,cAAc,aACVD,UACA,aAAKA;QAASE,WAAW;gBAAKF,qBAAAA,QAAQE,SAAS,YAAjBF,qBAAqB,EAAE;YAAGC;SAAU;;EAAG;AAE3E;;;;CAIC,GACD,OAAO,MAAME,sBAAsB,CACjCF,WACAG,KAEC,CAAA;QACCF,WAAW;YAACD;YAAW;gBAAEI,UAAU;gBAAMC,UAAU;gBAAMC,OAAOH;YAAG;SAAE;IACvE,CAAA,EAAsC"}
|
package/dist/respond.d.ts
CHANGED
|
@@ -64,10 +64,12 @@ export declare const respond: <E extends RouteFailure, R>(effect: Effect.Effect<
|
|
|
64
64
|
*/
|
|
65
65
|
export declare const mountRoutes: <const Routes extends ReadonlyArray<HttpRouter.Route<RouteFailure, any>>>(routes: Routes, policy?: FailurePolicy) => import("effect/Layer").Layer<never, never, HttpRouter.HttpRouter | HttpRouter.Request.From<"Requires", Exclude<HttpRouter.Route.Context<{ readonly [K in keyof Routes]: HttpRouter.Route<never, HttpRouter.Route.Context<Routes[K]>>; }[number]>, HttpRouter.Provided>> | HttpRouter.Request.From<"Error", HttpRouter.Route.Error<{ readonly [K in keyof Routes]: HttpRouter.Route<never, HttpRouter.Route.Context<Routes[K]>>; }[number]>>>;
|
|
66
66
|
/**
|
|
67
|
-
* The router's last net
|
|
68
|
-
*
|
|
69
|
-
*
|
|
70
|
-
*
|
|
67
|
+
* The router's last net. A path no route matches answers a `404` problem
|
|
68
|
+
* rather than an empty body, and a defect that escaped every route — one not
|
|
69
|
+
* mounted through {@link mountRoutes}, or one thrown while a response was
|
|
70
|
+
* being written — answers the same opaque `500` problem. It catches those two
|
|
71
|
+
* and nothing else, never the whole cause, so an interruption still
|
|
72
|
+
* interrupts.
|
|
71
73
|
*/
|
|
72
74
|
export declare const problemNet: import("effect/Layer").Layer<never, never, HttpRouter.HttpRouter>;
|
|
73
75
|
/**
|
package/dist/respond.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"respond.d.ts","sourceRoot":"","sources":["../src/respond.ts"],"names":[],"mappings":"AAAA,OAAO,EAIL,KAAK,cAAc,EACnB,KAAK,eAAe,
|
|
1
|
+
{"version":3,"file":"respond.d.ts","sourceRoot":"","sources":["../src/respond.ts"],"names":[],"mappings":"AAAA,OAAO,EAIL,KAAK,cAAc,EACnB,KAAK,eAAe,EAMrB,MAAM,eAAe,CAAC;AACvB,OAAO,EAAgB,MAAM,EAAU,MAAM,QAAQ,CAAC;AACtD,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAC5C,OAAO,EACL,UAAU,EAGV,kBAAkB,EACnB,MAAM,aAAa,CAAC;AACrB,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAEhD;;;;;;GAMG;AACH,MAAM,MAAM,YAAY,GAAG,cAAc,GAAG,QAAQ,CAAC,aAAa,CAAC;AAEnE;;;;;;GAMG;AACH,MAAM,WAAW,aAAa;IAC5B,QAAQ,CAAC,cAAc,EAAE,QAAQ,CAAC,MAAM,CAAC,eAAe,EAAE,MAAM,CAAC,CAAC,CAAC;IACnE,QAAQ,CAAC,SAAS,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAAC;IACrD,QAAQ,CAAC,gBAAgB,EAAE,QAAQ,CAAC,MAAM,CAAC,eAAe,EAAE,QAAQ,CA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AAC,EAC/C,QAAQ,MAAM,CAAC,MAAM,CAAC,kBAAkB,CAAC,kBAAkB,EAAE,CAAC,EAAE,CAAC,CAAC,EAClE,SAAQ,aAAoC,KAC3C,MAAM,CAAC,MAAM,CAAC,kBAAkB,CAAC,kBAAkB,EAAE,KAAK,EAAE,CAAC,CAQ7D,CAAC;AAEJ;;;;GAIG;AACH,eAAO,MAAM,WAAW,GAEtB,KAAK,CAAC,MAAM,SAAS,aAAa,CAAC,UAAU,CAAC,KAAK,CAAC,YAAY,EAAE,GAAG,CAAC,CAAC,EAEvE,QAAQ,MAAM,EACd,SAAQ,aAAoC,yJAa9B,CAAC,yLAAD,CAAC,6FAKd,CAAC;AAEJ;;;;;;;GAOG;AACH,eAAO,MAAM,UAAU,mEAiBtB,CAAC;AAEF;;;;;GAKG;AACH,MAAM,WAAW,gBAAgB;IAC/B,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,OAAO,CAAC,EAAE,OAAO,CAAC;IAC3B,QAAQ,EAAE,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC;CACnC;AAED,wEAAwE;AACxE,eAAO,MAAM,wBAAwB,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,QAAQ,CAAC,CAOvE,CAAC;AAEF;;;;GAIG;AACH,eAAO,MAAM,mBAAmB,GAC9B,SAAS,gBAAgB,KACxB,MAAM,CAAC,MAAM,CAAC,IAAI,CAUpB,CAAC"}
|
package/dist/respond.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
2
2
|
import { _ as _object_without_properties_loose } from "@swc/helpers/_/_object_without_properties_loose";
|
|
3
|
-
import { DEADLINE_HEADER, deadlineFromHeader, DeadlineTag, Internal, isFailure, PROBLEM_CONTENT_TYPE, problemOf } from '@entifix/core';
|
|
3
|
+
import { DEADLINE_HEADER, deadlineFromHeader, DeadlineTag, Internal, isFailure, NotFound, PROBLEM_CONTENT_TYPE, problemOf } from '@entifix/core';
|
|
4
4
|
import { Cause, Clock, Effect, Option } from 'effect';
|
|
5
|
-
import { HttpRouter, HttpServerRequest, HttpServerResponse } from 'effect/http';
|
|
5
|
+
import { HttpRouter, HttpServerError, HttpServerRequest, HttpServerResponse } from 'effect/http';
|
|
6
6
|
/**
|
|
7
7
|
* The defaults: the category table's statuses, business failures at `Debug`
|
|
8
8
|
* because an answer is not an incident, the transient technical categories at
|
|
@@ -139,11 +139,15 @@ const answerFailure = (failure, policy)=>Effect.gen(function*() {
|
|
|
139
139
|
uninterruptible: route.uninterruptible
|
|
140
140
|
})));
|
|
141
141
|
/**
|
|
142
|
-
* The router's last net
|
|
143
|
-
*
|
|
144
|
-
*
|
|
145
|
-
*
|
|
146
|
-
|
|
142
|
+
* The router's last net. A path no route matches answers a `404` problem
|
|
143
|
+
* rather than an empty body, and a defect that escaped every route — one not
|
|
144
|
+
* mounted through {@link mountRoutes}, or one thrown while a response was
|
|
145
|
+
* being written — answers the same opaque `500` problem. It catches those two
|
|
146
|
+
* and nothing else, never the whole cause, so an interruption still
|
|
147
|
+
* interrupts.
|
|
148
|
+
*/ export const problemNet = HttpRouter.middleware((effect)=>effect.pipe(Effect.catchIf((error)=>HttpServerError.isHttpServerError(error) && error.reason._tag === 'RouteNotFound', ()=>Effect.map(currentInstance, (instance)=>problemResponse(new NotFound({}), defaultFailurePolicy, {
|
|
149
|
+
instance
|
|
150
|
+
}))), Effect.catchDefect(answerDefect)), {
|
|
147
151
|
global: true
|
|
148
152
|
});
|
|
149
153
|
/** The level each outcome is logged at; anything unnamed is `Debug`. */ export const MECHANISM_OUTCOME_LEVELS = {
|
package/dist/respond.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/respond.ts"],"sourcesContent":["import {\n DEADLINE_HEADER,\n deadlineFromHeader,\n DeadlineTag,\n type EntifixFailure,\n type FailureCategory,\n Internal,\n isFailure,\n PROBLEM_CONTENT_TYPE,\n problemOf,\n} from '@entifix/core';\nimport { Cause, Clock, Effect, Option } from 'effect';\nimport type { HttpBody } from 'effect/http';\nimport { HttpRouter, HttpServerRequest, HttpServerResponse } from 'effect/http';\nimport type { Severity } from 'effect/LogLevel';\n\n/**\n * What a mounted handler may fail with: a categorised failure, or the\n * response body failing to encode. Anything else — a plain `Error`, a string —\n * does not compile at the mount, which is the point: a failure the shell cannot\n * categorise is one it cannot answer honestly\n * ([ADR 0013](../../../../docs/adr/0013-failures-are-typed-values-decided-at-the-shell.md)).\n */\nexport type RouteFailure = EntifixFailure | HttpBody.HttpBodyError;\n\n/**\n * How a host answers and logs its failures: the status a category answers with\n * and the level it is logged at, each overridable per tag.\n *\n * The composition root owns it. A cell never decides a status, a retry or a\n * log line; it fails, and the shell's policy says what that means.\n */\nexport interface FailurePolicy {\n readonly categoryStatus: Readonly<Record<FailureCategory, number>>;\n readonly tagStatus: Readonly<Record<string, number>>;\n readonly categoryLogLevel: Readonly<Record<FailureCategory, Severity>>;\n readonly tagLogLevel: Readonly<Record<string, Severity>>;\n}\n\n/**\n * The defaults: the category table's statuses, business failures at `Debug`\n * because an answer is not an incident, the transient technical categories at\n * `Warn`, and what is broken — a peer speaking nonsense, a bug — at `Error`.\n */\nexport const defaultFailurePolicy: FailurePolicy = {\n categoryStatus: {\n invalid: 400,\n unauthenticated: 401,\n forbidden: 403,\n notFound: 404,\n conflict: 409,\n declined: 422,\n contention: 409,\n exhausted: 429,\n unavailable: 503,\n timeout: 504,\n protocol: 502,\n internal: 500,\n },\n tagStatus: {},\n categoryLogLevel: {\n invalid: 'Debug',\n unauthenticated: 'Debug',\n forbidden: 'Debug',\n notFound: 'Debug',\n conflict: 'Debug',\n declined: 'Debug',\n contention: 'Warn',\n exhausted: 'Warn',\n unavailable: 'Warn',\n timeout: 'Warn',\n protocol: 'Error',\n internal: 'Error',\n },\n tagLogLevel: {},\n};\n\nexport interface FailurePolicyOverrides {\n readonly categoryStatus?: Partial<Record<FailureCategory, number>>;\n readonly tagStatus?: Readonly<Record<string, number>>;\n readonly categoryLogLevel?: Partial<Record<FailureCategory, Severity>>;\n readonly tagLogLevel?: Readonly<Record<string, Severity>>;\n}\n\n/** A policy with some of its entries replaced — how a slice extends the fleet's. */\nexport const extendFailurePolicy = (\n base: FailurePolicy,\n overrides: FailurePolicyOverrides,\n): FailurePolicy => ({\n categoryStatus: { ...base.categoryStatus, ...overrides.categoryStatus },\n tagStatus: { ...base.tagStatus, ...overrides.tagStatus },\n categoryLogLevel: {\n ...base.categoryLogLevel,\n ...overrides.categoryLogLevel,\n },\n tagLogLevel: { ...base.tagLogLevel, ...overrides.tagLogLevel },\n});\n\nexport const statusFor = (\n failure: EntifixFailure,\n policy: FailurePolicy,\n): number =>\n policy.tagStatus[failure._tag] ?? policy.categoryStatus[failure.category];\n\nexport const logLevelFor = (\n failure: EntifixFailure,\n policy: FailurePolicy,\n): Severity =>\n policy.tagLogLevel[failure._tag] ?? policy.categoryLogLevel[failure.category];\n\nexport interface ProblemResponseOptions {\n readonly traceId?: string | undefined;\n readonly instance?: string | undefined;\n}\n\nconst retryAfterOf = (failure: EntifixFailure): number | undefined => {\n const seconds = (failure as { readonly retryAfterSeconds?: unknown })\n .retryAfterSeconds;\n return typeof seconds === 'number' ? seconds : undefined;\n};\n\n/**\n * The `application/problem+json` answer to a failure, with the policy's\n * status. Built synchronously — the body is already plain data — so it cannot\n * itself fail to encode.\n */\nexport const problemResponse = (\n failure: EntifixFailure,\n policy: FailurePolicy = defaultFailurePolicy,\n options: ProblemResponseOptions = {},\n): HttpServerResponse.HttpServerResponse => {\n const status = statusFor(failure, policy);\n const retryAfter = retryAfterOf(failure);\n return HttpServerResponse.text(\n JSON.stringify(\n problemOf(failure, {\n status,\n ...(options.traceId === undefined ? {} : { traceId: options.traceId }),\n ...(options.instance === undefined\n ? {}\n : { instance: options.instance }),\n }),\n ),\n {\n status,\n contentType: PROBLEM_CONTENT_TYPE,\n ...(retryAfter === undefined\n ? {}\n : { headers: { 'retry-after': String(retryAfter) } }),\n },\n );\n};\n\n/** The current span's trace id, when a span is open. */\nconst currentTraceId: Effect.Effect<string | undefined> = Effect.option(\n Effect.currentSpan,\n).pipe(\n Effect.map(span => Option.getOrUndefined(Option.map(span, s => s.traceId))),\n);\n\n/** The path being answered, when a request is in scope. */\nconst currentInstance: Effect.Effect<string | undefined> = Effect.serviceOption(\n HttpServerRequest.HttpServerRequest,\n).pipe(\n Effect.map(request =>\n Option.getOrUndefined(Option.map(request, r => r.url.split('?')[0])),\n ),\n);\n\nconst answerFailure = (failure: EntifixFailure, policy: FailurePolicy) =>\n Effect.gen(function* () {\n const traceId = yield* currentTraceId;\n const instance = yield* currentInstance;\n yield* Effect.logWithLevel(logLevelFor(failure, policy))(\n 'request failed',\n ).pipe(\n Effect.annotateLogs({\n code: failure.code,\n category: failure.category,\n tag: failure._tag,\n ...(traceId === undefined ? {} : { traceId }),\n }),\n );\n return problemResponse(failure, policy, { traceId, instance });\n });\n\n/**\n * The opaque `500` for anything nobody categorised. The defect is logged in\n * full here, where it was caught; the body carries the trace id to find that\n * line by, and nothing of the defect itself.\n */\nconst answerDefect = (defect: unknown) =>\n Effect.gen(function* () {\n const traceId = yield* currentTraceId;\n const instance = yield* currentInstance;\n yield* Effect.logError('request defect').pipe(\n Effect.annotateLogs({\n code: 'internal',\n category: 'internal',\n cause: Cause.pretty(Cause.die(defect)),\n ...(traceId === undefined ? {} : { traceId }),\n }),\n );\n return problemResponse(new Internal(), defaultFailurePolicy, {\n traceId,\n instance,\n });\n });\n\n/**\n * The request's deadline, when its caller sent one, provided to the handler\n * so a retry below it never starts past it and an outbound call forwards what\n * is left ([ADR 0014](../../../../docs/adr/0014-retry-once-at-the-layer-above-under-a-budget.md)).\n */\nconst withRequestDeadline = <A, E, R>(effect: Effect.Effect<A, E, R>) =>\n Effect.gen(function* () {\n const request = yield* Effect.serviceOption(\n HttpServerRequest.HttpServerRequest,\n );\n const now = yield* Clock.currentTimeMillis;\n const deadline = Option.isSome(request)\n ? deadlineFromHeader(request.value.headers[DEADLINE_HEADER], now)\n : undefined;\n return yield* deadline === undefined\n ? effect\n : Effect.provideService(effect, DeadlineTag, deadline);\n });\n\n/**\n * The terminal reaction: every failure answered as a problem body with the\n * policy's status and logged at the policy's level, every defect answered as\n * an opaque `500`. Interruption is left alone — a request whose client went\n * away has nobody to answer.\n */\nexport const respond = <E extends RouteFailure, R>(\n effect: Effect.Effect<HttpServerResponse.HttpServerResponse, E, R>,\n policy: FailurePolicy = defaultFailurePolicy,\n): Effect.Effect<HttpServerResponse.HttpServerResponse, never, R> =>\n withRequestDeadline(effect).pipe(\n Effect.catch((failure: E) =>\n isFailure(failure)\n ? answerFailure(failure, policy)\n : answerDefect(failure),\n ),\n Effect.catchDefect(answerDefect),\n );\n\n/**\n * Mounts a set of routes with every handler wrapped in {@link respond}, once,\n * at the composition root. A route whose handler fails with anything but a\n * {@link RouteFailure} does not compile here.\n */\nexport const mountRoutes = <\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const Routes extends ReadonlyArray<HttpRouter.Route<RouteFailure, any>>,\n>(\n routes: Routes,\n policy: FailurePolicy = defaultFailurePolicy,\n) =>\n HttpRouter.addAll(\n routes.map(route =>\n HttpRouter.route(\n route.method,\n route.path,\n respond(route.handler, policy),\n {\n uninterruptible: route.uninterruptible,\n },\n ),\n ) as unknown as {\n readonly [K in keyof Routes]: HttpRouter.Route<\n never,\n HttpRouter.Route.Context<Routes[K]>\n >;\n },\n );\n\n/**\n * The router's last net: a defect that escaped every route — one not mounted\n * through {@link mountRoutes}, or one thrown while a response was being\n * written — answers the same opaque `500` problem. It catches defects only,\n * never the whole cause, so an interruption still interrupts.\n */\nexport const problemNet = HttpRouter.middleware(\n effect => effect.pipe(Effect.catchDefect(answerDefect)),\n { global: true },\n);\n\n/**\n * What a mechanism reports instead of logging — a relay pass, a shutdown drain\n * ([ADR 0013](../../../../docs/adr/0013-failures-are-typed-values-decided-at-the-shell.md)).\n * Structural, so the shell can log an outcome from a package it does not\n * depend on.\n */\nexport interface MechanismOutcome {\n readonly _tag: string;\n readonly failure?: unknown;\n readonly [field: string]: unknown;\n}\n\n/** The level each outcome is logged at; anything unnamed is `Debug`. */\nexport const MECHANISM_OUTCOME_LEVELS: Readonly<Record<string, Severity>> = {\n quarantined: 'Error',\n sweepFailed: 'Error',\n hookFailed: 'Error',\n drainFailed: 'Warn',\n draining: 'Info',\n drained: 'Debug',\n};\n\n/**\n * The fork site's logger for a mechanism's outcomes: the level from the\n * outcome's tag, the outcome's own fields as annotations, and a typed\n * failure's code and category beside them — never `String(error)`.\n */\nexport const logMechanismOutcome = (\n outcome: MechanismOutcome,\n): Effect.Effect<void> => {\n const { _tag, failure, ...fields } = outcome;\n const typed = isFailure(failure)\n ? { code: failure.code, category: failure.category, tag: failure._tag }\n : failure === undefined\n ? {}\n : { code: 'internal', category: 'internal' };\n return Effect.logWithLevel(MECHANISM_OUTCOME_LEVELS[_tag] ?? 'Debug')(\n _tag,\n ).pipe(Effect.annotateLogs({ ...fields, ...typed }));\n};\n"],"names":["DEADLINE_HEADER","deadlineFromHeader","DeadlineTag","Internal","isFailure","PROBLEM_CONTENT_TYPE","problemOf","Cause","Clock","Effect","Option","HttpRouter","HttpServerRequest","HttpServerResponse","defaultFailurePolicy","categoryStatus","invalid","unauthenticated","forbidden","notFound","conflict","declined","contention","exhausted","unavailable","timeout","protocol","internal","tagStatus","categoryLogLevel","tagLogLevel","extendFailurePolicy","base","overrides","statusFor","failure","policy","_tag","category","logLevelFor","retryAfterOf","seconds","retryAfterSeconds","undefined","problemResponse","options","status","retryAfter","text","JSON","stringify","traceId","instance","contentType","headers","String","currentTraceId","option","currentSpan","pipe","map","span","getOrUndefined","s","currentInstance","serviceOption","request","r","url","split","answerFailure","gen","logWithLevel","annotateLogs","code","tag","answerDefect","defect","logError","cause","pretty","die","withRequestDeadline","effect","now","currentTimeMillis","deadline","isSome","value","provideService","respond","catch","catchDefect","mountRoutes","routes","addAll","route","method","path","handler","uninterruptible","problemNet","middleware","global","MECHANISM_OUTCOME_LEVELS","quarantined","sweepFailed","hookFailed","drainFailed","draining","drained","logMechanismOutcome","outcome","fields","typed"],"mappings":";;AAAA,SACEA,eAAe,EACfC,kBAAkB,EAClBC,WAAW,EAGXC,QAAQ,EACRC,SAAS,EACTC,oBAAoB,EACpBC,SAAS,QACJ,gBAAgB;AACvB,SAASC,KAAK,EAAEC,KAAK,EAAEC,MAAM,EAAEC,MAAM,QAAQ,SAAS;AAEtD,SAASC,UAAU,EAAEC,iBAAiB,EAAEC,kBAAkB,QAAQ,cAAc;AA0BhF;;;;CAIC,GACD,OAAO,MAAMC,uBAAsC;IACjDC,gBAAgB;QACdC,SAAS;QACTC,iBAAiB;QACjBC,WAAW;QACXC,UAAU;QACVC,UAAU;QACVC,UAAU;QACVC,YAAY;QACZC,WAAW;QACXC,aAAa;QACbC,SAAS;QACTC,UAAU;QACVC,UAAU;IACZ;IACAC,WAAW,CAAC;IACZC,kBAAkB;QAChBb,SAAS;QACTC,iBAAiB;QACjBC,WAAW;QACXC,UAAU;QACVC,UAAU;QACVC,UAAU;QACVC,YAAY;QACZC,WAAW;QACXC,aAAa;QACbC,SAAS;QACTC,UAAU;QACVC,UAAU;IACZ;IACAG,aAAa,CAAC;AAChB,EAAE;AASF,kFAAkF,GAClF,OAAO,MAAMC,sBAAsB,CACjCC,MACAC,YACmB,CAAA;QACnBlB,gBAAgB,aAAKiB,KAAKjB,cAAc,EAAKkB,UAAUlB,cAAc;QACrEa,WAAW,aAAKI,KAAKJ,SAAS,EAAKK,UAAUL,SAAS;QACtDC,kBAAkB,aACbG,KAAKH,gBAAgB,EACrBI,UAAUJ,gBAAgB;QAE/BC,aAAa,aAAKE,KAAKF,WAAW,EAAKG,UAAUH,WAAW;IAC9D,CAAA,EAAG;AAEH,OAAO,MAAMI,YAAY,CACvBC,SACAC;QAEAA;YAAAA,iCAAAA,OAAOR,SAAS,CAACO,QAAQE,IAAI,CAAC,YAA9BD,iCA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AO7B,OAAO+D,YAAY,EAACgC,iCAAAA,wBAAwB,CAACnE,KAAK,YAA9BmE,iCAAkC,SAC3DnE,MACAsB,IAAI,CAAClD,OAAOgE,YAAY,CAAC,aAAKwC,QAAWC;AAC7C,EAAE"}
|
|
1
|
+
{"version":3,"sources":["../src/respond.ts"],"sourcesContent":["import {\n DEADLINE_HEADER,\n deadlineFromHeader,\n DeadlineTag,\n type EntifixFailure,\n type FailureCategory,\n Internal,\n isFailure,\n NotFound,\n PROBLEM_CONTENT_TYPE,\n problemOf,\n} from '@entifix/core';\nimport { Cause, Clock, Effect, Option } from 'effect';\nimport type { HttpBody } from 'effect/http';\nimport {\n HttpRouter,\n HttpServerError,\n HttpServerRequest,\n HttpServerResponse,\n} from 'effect/http';\nimport type { Severity } from 'effect/LogLevel';\n\n/**\n * What a mounted handler may fail with: a categorised failure, or the\n * response body failing to encode. Anything else — a plain `Error`, a string —\n * does not compile at the mount, which is the point: a failure the shell cannot\n * categorise is one it cannot answer honestly\n * ([ADR 0013](../../../../docs/adr/0013-failures-are-typed-values-decided-at-the-shell.md)).\n */\nexport type RouteFailure = EntifixFailure | HttpBody.HttpBodyError;\n\n/**\n * How a host answers and logs its failures: the status a category answers with\n * and the level it is logged at, each overridable per tag.\n *\n * The composition root owns it. A cell never decides a status, a retry or a\n * log line; it fails, and the shell's policy says what that means.\n */\nexport interface FailurePolicy {\n readonly categoryStatus: Readonly<Record<FailureCategory, number>>;\n readonly tagStatus: Readonly<Record<string, number>>;\n readonly categoryLogLevel: Readonly<Record<FailureCategory, Severity>>;\n readonly tagLogLevel: Readonly<Record<string, Severity>>;\n}\n\n/**\n * The defaults: the category table's statuses, business failures at `Debug`\n * because an answer is not an incident, the transient technical categories at\n * `Warn`, and what is broken — a peer speaking nonsense, a bug — at `Error`.\n */\nexport const defaultFailurePolicy: FailurePolicy = {\n categoryStatus: {\n invalid: 400,\n unauthenticated: 401,\n forbidden: 403,\n notFound: 404,\n conflict: 409,\n declined: 422,\n contention: 409,\n exhausted: 429,\n unavailable: 503,\n timeout: 504,\n protocol: 502,\n internal: 500,\n },\n tagStatus: {},\n categoryLogLevel: {\n invalid: 'Debug',\n unauthenticated: 'Debug',\n forbidden: 'Debug',\n notFound: 'Debug',\n conflict: 'Debug',\n declined: 'Debug',\n contention: 'Warn',\n exhausted: 'Warn',\n unavailable: 'Warn',\n timeout: 'Warn',\n protocol: 'Error',\n internal: 'Error',\n },\n tagLogLevel: {},\n};\n\nexport interface FailurePolicyOverrides {\n readonly categoryStatus?: Partial<Record<FailureCategory, number>>;\n readonly tagStatus?: Readonly<Record<string, number>>;\n readonly categoryLogLevel?: Partial<Record<FailureCategory, Severity>>;\n readonly tagLogLevel?: Readonly<Record<string, Severity>>;\n}\n\n/** A policy with some of its entries replaced — how a slice extends the fleet's. */\nexport const extendFailurePolicy = (\n base: FailurePolicy,\n overrides: FailurePolicyOverrides,\n): FailurePolicy => ({\n categoryStatus: { ...base.categoryStatus, ...overrides.categoryStatus },\n tagStatus: { ...base.tagStatus, ...overrides.tagStatus },\n categoryLogLevel: {\n ...base.categoryLogLevel,\n ...overrides.categoryLogLevel,\n },\n tagLogLevel: { ...base.tagLogLevel, ...overrides.tagLogLevel },\n});\n\nexport const statusFor = (\n failure: EntifixFailure,\n policy: FailurePolicy,\n): number =>\n policy.tagStatus[failure._tag] ?? policy.categoryStatus[failure.category];\n\nexport const logLevelFor = (\n failure: EntifixFailure,\n policy: FailurePolicy,\n): Severity =>\n policy.tagLogLevel[failure._tag] ?? policy.categoryLogLevel[failure.category];\n\nexport interface ProblemResponseOptions {\n readonly traceId?: string | undefined;\n readonly instance?: string | undefined;\n}\n\nconst retryAfterOf = (failure: EntifixFailure): number | undefined => {\n const seconds = (failure as { readonly retryAfterSeconds?: unknown })\n .retryAfterSeconds;\n return typeof seconds === 'number' ? seconds : undefined;\n};\n\n/**\n * The `application/problem+json` answer to a failure, with the policy's\n * status. Built synchronously — the body is already plain data — so it cannot\n * itself fail to encode.\n */\nexport const problemResponse = (\n failure: EntifixFailure,\n policy: FailurePolicy = defaultFailurePolicy,\n options: ProblemResponseOptions = {},\n): HttpServerResponse.HttpServerResponse => {\n const status = statusFor(failure, policy);\n const retryAfter = retryAfterOf(failure);\n return HttpServerResponse.text(\n JSON.stringify(\n problemOf(failure, {\n status,\n ...(options.traceId === undefined ? {} : { traceId: options.traceId }),\n ...(options.instance === undefined\n ? {}\n : { instance: options.instance }),\n }),\n ),\n {\n status,\n contentType: PROBLEM_CONTENT_TYPE,\n ...(retryAfter === undefined\n ? {}\n : { headers: { 'retry-after': String(retryAfter) } }),\n },\n );\n};\n\n/** The current span's trace id, when a span is open. */\nconst currentTraceId: Effect.Effect<string | undefined> = Effect.option(\n Effect.currentSpan,\n).pipe(\n Effect.map(span => Option.getOrUndefined(Option.map(span, s => s.traceId))),\n);\n\n/** The path being answered, when a request is in scope. */\nconst currentInstance: Effect.Effect<string | undefined> = Effect.serviceOption(\n HttpServerRequest.HttpServerRequest,\n).pipe(\n Effect.map(request =>\n Option.getOrUndefined(Option.map(request, r => r.url.split('?')[0])),\n ),\n);\n\nconst answerFailure = (failure: EntifixFailure, policy: FailurePolicy) =>\n Effect.gen(function* () {\n const traceId = yield* currentTraceId;\n const instance = yield* currentInstance;\n yield* Effect.logWithLevel(logLevelFor(failure, policy))(\n 'request failed',\n ).pipe(\n Effect.annotateLogs({\n code: failure.code,\n category: failure.category,\n tag: failure._tag,\n ...(traceId === undefined ? {} : { traceId }),\n }),\n );\n return problemResponse(failure, policy, { traceId, instance });\n });\n\n/**\n * The opaque `500` for anything nobody categorised. The defect is logged in\n * full here, where it was caught; the body carries the trace id to find that\n * line by, and nothing of the defect itself.\n */\nconst answerDefect = (defect: unknown) =>\n Effect.gen(function* () {\n const traceId = yield* currentTraceId;\n const instance = yield* currentInstance;\n yield* Effect.logError('request defect').pipe(\n Effect.annotateLogs({\n code: 'internal',\n category: 'internal',\n cause: Cause.pretty(Cause.die(defect)),\n ...(traceId === undefined ? {} : { traceId }),\n }),\n );\n return problemResponse(new Internal(), defaultFailurePolicy, {\n traceId,\n instance,\n });\n });\n\n/**\n * The request's deadline, when its caller sent one, provided to the handler\n * so a retry below it never starts past it and an outbound call forwards what\n * is left ([ADR 0014](../../../../docs/adr/0014-retry-once-at-the-layer-above-under-a-budget.md)).\n */\nconst withRequestDeadline = <A, E, R>(effect: Effect.Effect<A, E, R>) =>\n Effect.gen(function* () {\n const request = yield* Effect.serviceOption(\n HttpServerRequest.HttpServerRequest,\n );\n const now = yield* Clock.currentTimeMillis;\n const deadline = Option.isSome(request)\n ? deadlineFromHeader(request.value.headers[DEADLINE_HEADER], now)\n : undefined;\n return yield* deadline === undefined\n ? effect\n : Effect.provideService(effect, DeadlineTag, deadline);\n });\n\n/**\n * The terminal reaction: every failure answered as a problem body with the\n * policy's status and logged at the policy's level, every defect answered as\n * an opaque `500`. Interruption is left alone — a request whose client went\n * away has nobody to answer.\n */\nexport const respond = <E extends RouteFailure, R>(\n effect: Effect.Effect<HttpServerResponse.HttpServerResponse, E, R>,\n policy: FailurePolicy = defaultFailurePolicy,\n): Effect.Effect<HttpServerResponse.HttpServerResponse, never, R> =>\n withRequestDeadline(effect).pipe(\n Effect.catch((failure: E) =>\n isFailure(failure)\n ? answerFailure(failure, policy)\n : answerDefect(failure),\n ),\n Effect.catchDefect(answerDefect),\n );\n\n/**\n * Mounts a set of routes with every handler wrapped in {@link respond}, once,\n * at the composition root. A route whose handler fails with anything but a\n * {@link RouteFailure} does not compile here.\n */\nexport const mountRoutes = <\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const Routes extends ReadonlyArray<HttpRouter.Route<RouteFailure, any>>,\n>(\n routes: Routes,\n policy: FailurePolicy = defaultFailurePolicy,\n) =>\n HttpRouter.addAll(\n routes.map(route =>\n HttpRouter.route(\n route.method,\n route.path,\n respond(route.handler, policy),\n {\n uninterruptible: route.uninterruptible,\n },\n ),\n ) as unknown as {\n readonly [K in keyof Routes]: HttpRouter.Route<\n never,\n HttpRouter.Route.Context<Routes[K]>\n >;\n },\n );\n\n/**\n * The router's last net. A path no route matches answers a `404` problem\n * rather than an empty body, and a defect that escaped every route — one not\n * mounted through {@link mountRoutes}, or one thrown while a response was\n * being written — answers the same opaque `500` problem. It catches those two\n * and nothing else, never the whole cause, so an interruption still\n * interrupts.\n */\nexport const problemNet = HttpRouter.middleware(\n effect =>\n effect.pipe(\n Effect.catchIf(\n (error: unknown) =>\n HttpServerError.isHttpServerError(error) &&\n error.reason._tag === 'RouteNotFound',\n () =>\n Effect.map(currentInstance, instance =>\n problemResponse(new NotFound({}), defaultFailurePolicy, {\n instance,\n }),\n ),\n ),\n Effect.catchDefect(answerDefect),\n ),\n { global: true },\n);\n\n/**\n * What a mechanism reports instead of logging — a relay pass, a shutdown drain\n * ([ADR 0013](../../../../docs/adr/0013-failures-are-typed-values-decided-at-the-shell.md)).\n * Structural, so the shell can log an outcome from a package it does not\n * depend on.\n */\nexport interface MechanismOutcome {\n readonly _tag: string;\n readonly failure?: unknown;\n readonly [field: string]: unknown;\n}\n\n/** The level each outcome is logged at; anything unnamed is `Debug`. */\nexport const MECHANISM_OUTCOME_LEVELS: Readonly<Record<string, Severity>> = {\n quarantined: 'Error',\n sweepFailed: 'Error',\n hookFailed: 'Error',\n drainFailed: 'Warn',\n draining: 'Info',\n drained: 'Debug',\n};\n\n/**\n * The fork site's logger for a mechanism's outcomes: the level from the\n * outcome's tag, the outcome's own fields as annotations, and a typed\n * failure's code and category beside them — never `String(error)`.\n */\nexport const logMechanismOutcome = (\n outcome: MechanismOutcome,\n): Effect.Effect<void> => {\n const { _tag, failure, ...fields } = outcome;\n const typed = isFailure(failure)\n ? { code: failure.code, category: failure.category, tag: failure._tag }\n : failure === undefined\n ? {}\n : { code: 'internal', category: 'internal' };\n return Effect.logWithLevel(MECHANISM_OUTCOME_LEVELS[_tag] ?? 'Debug')(\n _tag,\n ).pipe(Effect.annotateLogs({ ...fields, ...typed }));\n};\n"],"names":["DEADLINE_HEADER","deadlineFromHeader","DeadlineTag","Internal","isFailure","NotFound","PROBLEM_CONTENT_TYPE","problemOf","Cause","Clock","Effect","Option","HttpRouter","HttpServerError","HttpServerRequest","HttpServerResponse","defaultFailurePolicy","categoryStatus","invalid","unauthenticated","forbidden","notFound","conflict","declined","contention","exhausted","unavailable","timeout","protocol","internal","tagStatus","categoryLogLevel","tagLogLevel","extendFailurePolicy","base","overrides","statusFor","failure","policy","_tag","category","logLevelFor","retryAfterOf","seconds","retryAfterSeconds","undefined","problemResponse","options","status","retryAfter","text","JSON","stringify","traceId","instance","contentType","headers","String","currentTraceId","option","currentSpan","pipe","map","span","getOrUndefined","s","currentInstance","serviceOption","request","r","url","split","answerFailure","gen","logWithLevel","annotateLogs","code","tag","answerDefect","defect","logError","cause","pretty","die","withRequestDeadline","effect","now","currentTimeMillis","deadline","isSome","value","provideService","respond","catch","catchDefect","mountRoutes","routes","addAll","route","method","path","handler","uninterruptible","problemNet","middleware","catchIf","error","isHttpServerError","reason","global","MECHANISM_OUTCOME_LEVELS","quarantined","sweepFailed","hookFailed","drainFailed","draining","drained","logMechanismOutcome","outcome","fields","typed"],"mappings":";;AAAA,SACEA,eAAe,EACfC,kBAAkB,EAClBC,WAAW,EAGXC,QAAQ,EACRC,SAAS,EACTC,QAAQ,EACRC,oBAAoB,EACpBC,SAAS,QACJ,gBAAgB;AACvB,SAASC,KAAK,EAAEC,KAAK,EAAEC,MAAM,EAAEC,MAAM,QAAQ,SAAS;AAEtD,SACEC,UAAU,EACVC,eAAe,EACfC,iBAAiB,EACjBC,kBAAkB,QACb,cAAc;AA0BrB;;;;CAIC,GACD,OAAO,MAAMC,uBAAsC;IACjDC,gBAAgB;QACdC,SAAS;QACTC,iBAAiB;QACjBC,WAAW;QACXC,UAAU;QACVC,UAAU;QACVC,UAAU;QACVC,YAAY;QACZC,WAAW;QACXC,aAAa;QACbC,SAAS;QACTC,UAAU;QACVC,UAAU;IACZ;IACAC,WAAW,CAAC;IACZC,kBAAkB;QAChBb,SA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D,OAAO,MAAMC,aAAa3F,WAAW4F,UAAU,CAC7CnB,CAAAA,SACEA,OAAOxB,IAAI,CACTnD,OAAO+F,OAAO,CACZ,CAACC,QACC7F,gBAAgB8F,iBAAiB,CAACD,UAClCA,MAAME,MAAM,CAACrE,IAAI,KAAK,iBACxB,IACE7B,OAAOoD,GAAG,CAACI,iBAAiBZ,CAAAA,WAC1BR,gBAAgB,IAAIzC,SAAS,CAAC,IAAIW,sBAAsB;gBACtDsC;YACF,MAGN5C,OAAOoF,WAAW,CAAChB,gBAEvB;IAAE+B,QAAQ;AAAK,GACf;AAcF,sEAAsE,GACtE,OAAO,MAAMC,2BAA+D;IAC1EC,aAAa;IACbC,aAAa;IACbC,YAAY;IACZC,aAAa;IACbC,UAAU;IACVC,SAAS;AACX,EAAE;AAEF;;;;CAIC,GACD,OAAO,MAAMC,sBAAsB,CACjCC;QAQ2BR;IAN3B,MAAM,EAAEvE,IAAI,EAAEF,OAAO,EAAa,GAAGiF,SAAXC,0CAAWD;;;;IACrC,MAAME,QAAQpH,UAAUiC,WACpB;QAAEuC,MAAMvC,QAAQuC,IAAI;QAAEpC,UAAUH,QAAQG,QAAQ;QAAEqC,KAAKxC,QAAQE,IAAI;IAAC,IACpEF,YAAYQ,YACV,CAAC,IACD;QAAE+B,MAAM;QAAYpC,UAAU;IAAW;IAC/C,OAAO9B,OAAOgE,YAAY,EAACoC,iCAAAA,wBAAwB,CAACvE,KAAK,YAA9BuE,iCAAkC,SAC3DvE,MACAsB,IAAI,CAACnD,OAAOiE,YAAY,CAAC,aAAK4C,QAAWC;AAC7C,EAAE"}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { AnyEndpointGroup } from './http-api/build-api.js';
|
|
1
2
|
import { type ServiceDefinition } from './make-service.js';
|
|
2
3
|
import { type WaitForHttpOptions } from './wait-for-http.js';
|
|
3
4
|
/** A service booted in-process, and the handle that shuts it down. */
|
|
@@ -33,5 +34,5 @@ export declare const freePort: () => Promise<number>;
|
|
|
33
34
|
* timeout: the launch fiber is raced against the health check, so a missing
|
|
34
35
|
* dependency reports its own cause.
|
|
35
36
|
*/
|
|
36
|
-
export declare const serveTestService: <RRoutes>(def: ServiceDefinition<RRoutes>, { port, ...waitOptions }?: ServeTestServiceOptions) => Promise<RunningTestService>;
|
|
37
|
+
export declare const serveTestService: <RRoutes, const Groups extends ReadonlyArray<AnyEndpointGroup> = readonly []>(def: ServiceDefinition<RRoutes, Groups>, { port, ...waitOptions }?: ServeTestServiceOptions) => Promise<RunningTestService>;
|
|
37
38
|
//# sourceMappingURL=serve-test-service.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"serve-test-service.d.ts","sourceRoot":"","sources":["../src/serve-test-service.ts"],"names":[],"mappings":"AAKA,OAAO,EAAmB,KAAK,iBAAiB,EAAE,MAAM,mBAAmB,CAAC;AAC5E,OAAO,EAAe,KAAK,kBAAkB,EAAE,MAAM,oBAAoB,CAAC;AAE1E,sEAAsE;AACtE,MAAM,WAAW,kBAAkB;IACjC,yEAAyE;IACzE,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,oEAAoE;IACpE,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;CACxB;AAED,MAAM,WAAW,uBAAwB,SAAQ,kBAAkB;IACjE,2EAA2E;IAC3E,IAAI,CAAC,EAAE,MAAM,CAAC;CACf;AAED;;;;;;GAMG;AACH,eAAO,MAAM,QAAQ,QAAO,OAAO,CAAC,MAAM,CAUtC,CAAC;AAEL;;;;;;;;;;;;;GAaG;AACH,eAAO,MAAM,gBAAgB,
|
|
1
|
+
{"version":3,"file":"serve-test-service.d.ts","sourceRoot":"","sources":["../src/serve-test-service.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,yBAAyB,CAAC;AAChE,OAAO,EAAmB,KAAK,iBAAiB,EAAE,MAAM,mBAAmB,CAAC;AAC5E,OAAO,EAAe,KAAK,kBAAkB,EAAE,MAAM,oBAAoB,CAAC;AAE1E,sEAAsE;AACtE,MAAM,WAAW,kBAAkB;IACjC,yEAAyE;IACzE,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,oEAAoE;IACpE,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;CACxB;AAED,MAAM,WAAW,uBAAwB,SAAQ,kBAAkB;IACjE,2EAA2E;IAC3E,IAAI,CAAC,EAAE,MAAM,CAAC;CACf;AAED;;;;;;GAMG;AACH,eAAO,MAAM,QAAQ,QAAO,OAAO,CAAC,MAAM,CAUtC,CAAC;AAEL;;;;;;;;;;;;;GAaG;AACH,eAAO,MAAM,gBAAgB,GAC3B,OAAO,EACP,KAAK,CAAC,MAAM,SAAS,aAAa,CAAC,gBAAgB,CAAC,GAAG,SAAS,EAAE,EAElE,KAAK,iBAAiB,CAAC,OAAO,EAAE,MAAM,CAAC,EACvC,2BAA0B,uBAA4B,KACrD,OAAO,CAAC,kBAAkB,CA6B5B,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/serve-test-service.ts"],"sourcesContent":["import { createServer } from 'node:http';\nimport type { AddressInfo } from 'node:net';\n\nimport { Effect, Fiber, Layer } from 'effect';\n\nimport { makeServerLayer, type ServiceDefinition } from './make-service.js';\nimport { waitForHttp, type WaitForHttpOptions } from './wait-for-http.js';\n\n/** A service booted in-process, and the handle that shuts it down. */\nexport interface RunningTestService {\n /** Origin the service is listening on, e.g. `http://127.0.0.1:53211`. */\n readonly baseUrl: string;\n /** Interrupts the launch fiber, releasing every Layer finalizer. */\n close(): Promise<void>;\n}\n\nexport interface ServeTestServiceOptions extends WaitForHttpOptions {\n /** Fixed port. Omit to bind an ephemeral one, which is what tests want. */\n port?: number;\n}\n\n/**\n * Asks the OS for a free port by binding one and letting it go again.\n *\n * Exported because an ephemeral port is useful to any in-process boot, and\n * because a helper with its own name is easier to reason about than an inline\n * promise inside the launch sequence.\n */\nexport const freePort = (): Promise<number> =>\n new Promise<number>((resolve, reject) => {\n const probe = createServer();\n probe.on('error', reject);\n probe.listen(0, '127.0.0.1', () => {\n const { port } = probe.address() as AddressInfo;\n probe.close(() => {\n resolve(port);\n });\n });\n });\n\n/**\n * Boots a service definition in-process on an ephemeral port and waits until it\n * answers `/api/health`.\n *\n * This is the seam the e2e `mock` profile runs on: the service's REAL `router`\n * and the REAL {@link makeServerLayer} wiring are used, with only the `appLayer`\n * swapped for one built from driver fakes. So the routes, the use-cases, the\n * repository adapter and the query translation all execute — what is absent is\n * the infrastructure, not the service.\n *\n * A boot failure (a Layer that dies) surfaces here rather than as a readiness\n * timeout: the launch fiber is raced against the health check, so a missing\n * dependency reports its own cause.\n */\nexport const serveTestService = async <
|
|
1
|
+
{"version":3,"sources":["../src/serve-test-service.ts"],"sourcesContent":["import { createServer } from 'node:http';\nimport type { AddressInfo } from 'node:net';\n\nimport { Effect, Fiber, Layer } from 'effect';\n\nimport type { AnyEndpointGroup } from './http-api/build-api.js';\nimport { makeServerLayer, type ServiceDefinition } from './make-service.js';\nimport { waitForHttp, type WaitForHttpOptions } from './wait-for-http.js';\n\n/** A service booted in-process, and the handle that shuts it down. */\nexport interface RunningTestService {\n /** Origin the service is listening on, e.g. `http://127.0.0.1:53211`. */\n readonly baseUrl: string;\n /** Interrupts the launch fiber, releasing every Layer finalizer. */\n close(): Promise<void>;\n}\n\nexport interface ServeTestServiceOptions extends WaitForHttpOptions {\n /** Fixed port. Omit to bind an ephemeral one, which is what tests want. */\n port?: number;\n}\n\n/**\n * Asks the OS for a free port by binding one and letting it go again.\n *\n * Exported because an ephemeral port is useful to any in-process boot, and\n * because a helper with its own name is easier to reason about than an inline\n * promise inside the launch sequence.\n */\nexport const freePort = (): Promise<number> =>\n new Promise<number>((resolve, reject) => {\n const probe = createServer();\n probe.on('error', reject);\n probe.listen(0, '127.0.0.1', () => {\n const { port } = probe.address() as AddressInfo;\n probe.close(() => {\n resolve(port);\n });\n });\n });\n\n/**\n * Boots a service definition in-process on an ephemeral port and waits until it\n * answers `/api/health`.\n *\n * This is the seam the e2e `mock` profile runs on: the service's REAL `router`\n * and the REAL {@link makeServerLayer} wiring are used, with only the `appLayer`\n * swapped for one built from driver fakes. So the routes, the use-cases, the\n * repository adapter and the query translation all execute — what is absent is\n * the infrastructure, not the service.\n *\n * A boot failure (a Layer that dies) surfaces here rather than as a readiness\n * timeout: the launch fiber is raced against the health check, so a missing\n * dependency reports its own cause.\n */\nexport const serveTestService = async <\n RRoutes,\n const Groups extends ReadonlyArray<AnyEndpointGroup> = readonly [],\n>(\n def: ServiceDefinition<RRoutes, Groups>,\n { port, ...waitOptions }: ServeTestServiceOptions = {},\n): Promise<RunningTestService> => {\n const boundPort = port ?? (await freePort());\n const baseUrl = `http://127.0.0.1:${boundPort}`;\n\n const fiber = Effect.runFork(Layer.launch(makeServerLayer(def, boundPort)));\n\n // `Layer.launch` only ends when the service stops, so any failure of the\n // launch fiber during startup is the real reason the health check would\n // otherwise have timed out. `Fiber.join` re-raises the cause, so the defect\n // that killed the Layer — not a generic timeout — is what gets reported.\n const launchFailure = Effect.runPromise(Fiber.join(fiber)).catch(\n (error: unknown) => {\n throw new Error(`The service exited during startup: ${String(error)}`);\n },\n );\n // The same rejection fires again on a clean shutdown, when nobody is racing\n // it any more. Observed here so it is never an unhandled rejection.\n launchFailure.catch(() => undefined);\n\n await Promise.race([\n waitForHttp(`${baseUrl}/api/health`, waitOptions),\n launchFailure,\n ]);\n\n return {\n baseUrl,\n close: () =>\n Effect.runPromise(Fiber.interrupt(fiber)).then(() => undefined),\n };\n};\n"],"names":["createServer","Effect","Fiber","Layer","makeServerLayer","waitForHttp","freePort","Promise","resolve","reject","probe","on","listen","port","address","close","serveTestService","def","waitOptions","boundPort","baseUrl","fiber","runFork","launch","launchFailure","runPromise","join","catch","error","Error","String","undefined","race","interrupt","then"],"mappings":";AAAA,SAASA,YAAY,QAAQ,YAAY;AAGzC,SAASC,MAAM,EAAEC,KAAK,EAAEC,KA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from '@entifix/core';
|
|
1
|
+
import { type DomainEvent, type EntityChangeEvent } from '@entifix/core';
|
|
2
2
|
import { Stream } from 'effect';
|
|
3
3
|
import { HttpServerResponse } from 'effect/http';
|
|
4
4
|
/**
|
|
@@ -11,9 +11,12 @@ import { HttpServerResponse } from 'effect/http';
|
|
|
11
11
|
* re-reading the record.
|
|
12
12
|
*
|
|
13
13
|
* `data:` is a full `event` envelope, which is what keeps the stream from
|
|
14
|
-
* becoming a fourth framing: the same bytes a bus consumer would read.
|
|
14
|
+
* becoming a fourth framing: the same bytes a bus consumer would read. It is
|
|
15
|
+
* encoded through the entity-change schema, the one shape this stream carries;
|
|
16
|
+
* an event that does not encode is no frame at all (`undefined`), because a
|
|
17
|
+
* browser would drop it on decode anyway.
|
|
15
18
|
*/
|
|
16
|
-
export declare const sseFrame: (event: DomainEvent) => string;
|
|
19
|
+
export declare const sseFrame: (event: DomainEvent<EntityChangeEvent>) => string | undefined;
|
|
17
20
|
export interface SseResponseOptions {
|
|
18
21
|
/**
|
|
19
22
|
* Unix seconds at which to close the connection — the verified token's `exp`.
|
|
@@ -36,5 +39,5 @@ export interface SseResponseOptions {
|
|
|
36
39
|
* a pass-through arm for exactly this content type, because reading the body to
|
|
37
40
|
* completion first holds the request open forever and delivers nothing.
|
|
38
41
|
*/
|
|
39
|
-
export declare const sseResponse: (events: Stream.Stream<DomainEvent
|
|
42
|
+
export declare const sseResponse: (events: Stream.Stream<DomainEvent<EntityChangeEvent>>, { expiresAt, now }?: SseResponseOptions) => HttpServerResponse.HttpServerResponse;
|
|
40
43
|
//# sourceMappingURL=sse.d.ts.map
|
package/dist/sse.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sse.d.ts","sourceRoot":"","sources":["../src/sse.ts"],"names":[],"mappings":"AAAA,OAAO,
|
|
1
|
+
{"version":3,"file":"sse.d.ts","sourceRoot":"","sources":["../src/sse.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,KAAK,WAAW,EAEhB,KAAK,iBAAiB,EACvB,MAAM,eAAe,CAAC;AACvB,OAAO,EAAkC,MAAM,EAAE,MAAM,QAAQ,CAAC;AAChE,OAAO,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AAcjD;;;;;;;;;;;;;;GAcG;AACH,eAAO,MAAM,QAAQ,GACnB,OAAO,WAAW,CAAC,iBAAiB,CAAC,KACpC,MAAM,GAAG,SASX,CAAC;AAEF,MAAM,WAAW,kBAAkB;IACjC;;;;;;;OAOG;IACH,QAAQ,CAAC,SAAS,CAAC,EAAE,MAAM,CAAC;IAC5B,wDAAwD;IACxD,QAAQ,CAAC,GAAG,CAAC,EAAE,MAAM,MAAM,CAAC;CAC7B;AAED;;;;;;;;GAQG;AACH,eAAO,MAAM,WAAW,GACtB,QAAQ,MAAM,CAAC,MAAM,CAAC,WAAW,CAAC,iBAAiB,CAAC,CAAC,EACrD,qBAA+B,kBAAuB,KACrD,kBAAkB,CAAC,kBA+CrB,CAAC"}
|
package/dist/sse.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
1
|
+
import { _ as _object_without_properties_loose } from "@swc/helpers/_/_object_without_properties_loose";
|
|
2
|
+
import { EntityChangeEnvelope } from '@entifix/core';
|
|
3
|
+
import { Duration, Effect, Exit, Schema, Stream } from 'effect';
|
|
3
4
|
import { HttpServerResponse } from 'effect/http';
|
|
4
5
|
/**
|
|
5
6
|
* How often an idle connection emits a comment frame.
|
|
@@ -20,8 +21,23 @@ const encoder = new TextEncoder();
|
|
|
20
21
|
* re-reading the record.
|
|
21
22
|
*
|
|
22
23
|
* `data:` is a full `event` envelope, which is what keeps the stream from
|
|
23
|
-
* becoming a fourth framing: the same bytes a bus consumer would read.
|
|
24
|
-
|
|
24
|
+
* becoming a fourth framing: the same bytes a bus consumer would read. It is
|
|
25
|
+
* encoded through the entity-change schema, the one shape this stream carries;
|
|
26
|
+
* an event that does not encode is no frame at all (`undefined`), because a
|
|
27
|
+
* browser would drop it on decode anyway.
|
|
28
|
+
*/ export const sseFrame = (event)=>{
|
|
29
|
+
const { data } = event, meta = _object_without_properties_loose(event, [
|
|
30
|
+
"data"
|
|
31
|
+
]);
|
|
32
|
+
const encoded = Schema.encodeUnknownExit(EntityChangeEnvelope)({
|
|
33
|
+
meta: {
|
|
34
|
+
type: 'event',
|
|
35
|
+
event: meta
|
|
36
|
+
},
|
|
37
|
+
data
|
|
38
|
+
});
|
|
39
|
+
return Exit.isSuccess(encoded) ? `id: ${event.id}\ndata: ${JSON.stringify(encoded.value)}\n\n` : undefined;
|
|
40
|
+
};
|
|
25
41
|
/**
|
|
26
42
|
* Serves a stream of domain events as `text/event-stream`.
|
|
27
43
|
*
|
|
@@ -32,7 +48,7 @@ const encoder = new TextEncoder();
|
|
|
32
48
|
* completion first holds the request open forever and delivers nothing.
|
|
33
49
|
*/ export const sseResponse = (events, { expiresAt, now = Date.now } = {})=>{
|
|
34
50
|
const keepalive = Stream.fromEffectRepeat(Effect.as(Effect.sleep(KEEPALIVE), ': keepalive\n\n'));
|
|
35
|
-
const frames = Stream.merge(Stream.map(events, sseFrame), keepalive, {
|
|
51
|
+
const frames = Stream.merge(Stream.filter(Stream.map(events, sseFrame), (frame)=>frame !== undefined), keepalive, {
|
|
36
52
|
haltStrategy: 'left'
|
|
37
53
|
});
|
|
38
54
|
// An opening comment, emitted before anything has happened.
|
package/dist/sse.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/sse.ts"],"sourcesContent":["import {
|
|
1
|
+
{"version":3,"sources":["../src/sse.ts"],"sourcesContent":["import {\n type DomainEvent,\n EntityChangeEnvelope,\n type EntityChangeEvent,\n} from '@entifix/core';\nimport { Duration, Effect, Exit, Schema, Stream } from 'effect';\nimport { HttpServerResponse } from 'effect/http';\n\n/**\n * How often an idle connection emits a comment frame.\n *\n * An SSE connection that sends nothing for minutes is indistinguishable from a\n * dead one to anything between the browser and the service, and a proxy that\n * decides it is dead closes it with no error either side can report. A comment\n * (`:` and nothing else) is ignored by `EventSource` and costs three bytes.\n */\nconst KEEPALIVE = Duration.seconds(20);\n\nconst encoder = new TextEncoder();\n\n/**\n * One `EventSource` frame.\n *\n * `id:` carries the message's own id — `<transactionId>:<step>` for a\n * transaction event — so the `Last-Event-ID` a browser re-sends on reconnect\n * names a message that actually exists, rather than a counter invented for the\n * wire. The server does not replay it; the client reconciles by\n * re-reading the record.\n *\n * `data:` is a full `event` envelope, which is what keeps the stream from\n * becoming a fourth framing: the same bytes a bus consumer would read. It is\n * encoded through the entity-change schema, the one shape this stream carries;\n * an event that does not encode is no frame at all (`undefined`), because a\n * browser would drop it on decode anyway.\n */\nexport const sseFrame = (\n event: DomainEvent<EntityChangeEvent>,\n): string | undefined => {\n const { data, ...meta } = event;\n const encoded = Schema.encodeUnknownExit(EntityChangeEnvelope)({\n meta: { type: 'event', event: meta },\n data,\n });\n return Exit.isSuccess(encoded)\n ? `id: ${event.id}\\ndata: ${JSON.stringify(encoded.value)}\\n\\n`\n : undefined;\n};\n\nexport interface SseResponseOptions {\n /**\n * Unix seconds at which to close the connection — the verified token's `exp`.\n *\n * A held-open response has no next request to fail verification, so the bound\n * every REST route gets implicitly has to be applied explicitly here. The\n * browser reconnects with the cookie the app refreshed in the meantime\n *. Omitted, the stream runs until the client goes away.\n */\n readonly expiresAt?: number;\n /** Injectable for tests; defaults to the wall clock. */\n readonly now?: () => number;\n}\n\n/**\n * Serves a stream of domain events as `text/event-stream`.\n *\n * `cache-control: no-store` is not politeness — a cached event stream is served\n * to whoever asks next, and this one is scoped to a single principal. The\n * response is deliberately *not* rebuilt anywhere downstream: the Next proxy has\n * a pass-through arm for exactly this content type, because reading the body to\n * completion first holds the request open forever and delivers nothing.\n */\nexport const sseResponse = (\n events: Stream.Stream<DomainEvent<EntityChangeEvent>>,\n { expiresAt, now = Date.now }: SseResponseOptions = {},\n): HttpServerResponse.HttpServerResponse => {\n const keepalive = Stream.fromEffectRepeat(\n Effect.as(Effect.sleep(KEEPALIVE), ': keepalive\\n\\n'),\n );\n\n const frames = Stream.merge(\n Stream.filter(\n Stream.map(events, sseFrame),\n (frame): frame is string => frame !== undefined,\n ),\n keepalive,\n { haltStrategy: 'left' },\n );\n\n // An opening comment, emitted before anything has happened.\n //\n // Not cosmetic: a chunked response writes its headers with its first chunk,\n // so a stream that stays silent until something occurs leaves the client in\n // `CONNECTING` — indefinitely, since a stream whose whole purpose is to be\n // idle most of the time may have nothing to say for hours. Measured: without\n // it, `fetch` against this route does not resolve at all.\n const opened = Stream.concat(Stream.make(': open\\n\\n'), frames);\n\n const bounded =\n expiresAt === undefined\n ? opened\n : Stream.interruptWhen(\n opened,\n // Never negative: an already-expired token closes at once rather than\n // scheduling a sleep into the past, which `Effect.sleep` treats as\n // zero anyway but reads as an oversight.\n Effect.sleep(Duration.millis(Math.max(0, expiresAt * 1000 - now()))),\n );\n\n return HttpServerResponse.stream(\n Stream.map(bounded, frame => encoder.encode(frame)),\n {\n contentType: 'text/event-stream',\n headers: {\n 'cache-control': 'no-store',\n connection: 'keep-alive',\n // nginx buffers a proxied response by default, which would hold every\n // frame until the stream ends — that is, forever.\n 'x-accel-buffering': 'no',\n },\n },\n );\n};\n"],"names":["EntityChangeEnvelope","Duration","Effect","Exit","Schema","Stream","HttpServerResponse","KEEPALIVE","seconds","encoder","TextEncoder","sseFrame","event","data","meta","encoded","encodeUnknownExit","type","isSuccess","id","JSON","stringify","value","undefined","sseResponse","events","expiresAt","now","Date","keepalive","fromEffectRepeat","as","sleep","frames","merge","filter","map","frame","haltStrategy","opened","concat","make","bounded","interruptWhen","millis","Math","max","stream","encode","contentType","headers","connection"],"mappings":";AAAA,SAEEA,oBAAoB,QAEf,gBAAgB;AACvB,SAASC,QAAQ,EAAEC,MAAM,EAAEC,IAAI,EAAEC,MAAM,EAAEC,MAAM,QAAQ,SAAS;AAChE,SAASC,kBAAkB,QAAQ,cAAc;AAEjD;;;;;;;CAOC,GACD,MA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C9B1C,OAAO+B,GAAG,CAACM,SAASL,CAAAA,QAAS5B,QAAQuC,MAAM,CAACX,SAC5C;QACEY,aAAa;QACbC,SAAS;YACP,iBAAiB;YACjBC,YAAY;YACZ,sEAAsE;YACtE,kDAAkD;YAClD,qBAAqB;QACvB;IACF;AAEJ,EAAE"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@entifix/service-shell",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.12.0",
|
|
4
4
|
"description": "Effect HTTP service skeleton: server layer, health and metadata routes, permission guards, remote configuration and OpenTelemetry.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"repository": {
|
|
@@ -66,10 +66,10 @@
|
|
|
66
66
|
},
|
|
67
67
|
"dependencies": {
|
|
68
68
|
"@swc/helpers": "0.5.23",
|
|
69
|
-
"@entifix/authz": "0.
|
|
70
|
-
"@entifix/
|
|
71
|
-
"@entifix/
|
|
72
|
-
"@entifix/
|
|
69
|
+
"@entifix/authz": "0.12.0",
|
|
70
|
+
"@entifix/business": "0.12.0",
|
|
71
|
+
"@entifix/core": "0.12.0",
|
|
72
|
+
"@entifix/tooling": "0.12.0"
|
|
73
73
|
},
|
|
74
74
|
"devDependencies": {
|
|
75
75
|
"@effect/opentelemetry": "4.0.6",
|
|
@@ -81,7 +81,8 @@
|
|
|
81
81
|
"@opentelemetry/sdk-metrics": "2.12.0",
|
|
82
82
|
"@opentelemetry/sdk-trace-base": "2.12.0",
|
|
83
83
|
"effect": "4.0.6",
|
|
84
|
-
"@entifix/
|
|
84
|
+
"@entifix/rest": "0.12.0",
|
|
85
|
+
"@entifix/testing-unit": "0.12.0"
|
|
85
86
|
},
|
|
86
87
|
"peerDependencies": {
|
|
87
88
|
"@effect/opentelemetry": "^4.0.6",
|
package/dist/health-routes.d.ts
DELETED
|
@@ -1,24 +0,0 @@
|
|
|
1
|
-
import { HealthRegistryTag, ShutdownRegistryTag } from '@entifix/business';
|
|
2
|
-
import { HttpRouter } from 'effect/http';
|
|
3
|
-
/**
|
|
4
|
-
* The probe endpoints, as a route layer to merge beside a service's own.
|
|
5
|
-
*
|
|
6
|
-
* - `GET /api/health` — the original endpoint, unchanged. Kept because
|
|
7
|
-
* Playwright's `readyPath` and existing tooling point at it.
|
|
8
|
-
* - `GET /api/health/live` — **liveness**. Answers from the process alone: no
|
|
9
|
-
* datastore, no config-service, no session. This is deliberate and load
|
|
10
|
-
* bearing. A liveness probe that checks dependencies turns a Mongo blip into
|
|
11
|
-
* "Kubernetes restarts every replica", which is an outage the probe caused.
|
|
12
|
-
* - `GET /api/health/ready` — **readiness**: `200` when every registered probe
|
|
13
|
-
* passes, `503 {status:'degraded', failing:[…]}` otherwise. Kubernetes pulls
|
|
14
|
-
* a not-ready pod out of the load balancer without killing it, which is what
|
|
15
|
-
* a reconnecting client wants. A process that has begun terminating answers
|
|
16
|
-
* `503 {status:'terminating'}` instead, **before** any probe runs: nothing is
|
|
17
|
-
* failing, and running the probes would ask a closing pool a question whose
|
|
18
|
-
* answer changes nothing.
|
|
19
|
-
*
|
|
20
|
-
* The failing list carries probe **names** only — never a URI, host, or driver
|
|
21
|
-
* message. This endpoint answers anyone who can reach the port.
|
|
22
|
-
*/
|
|
23
|
-
export declare const healthRoutes: (serviceName: string) => import("effect/Layer").Layer<never, never, HttpRouter.HttpRouter | HttpRouter.Request<"Requires", HealthRegistryTag> | HttpRouter.Request<"Requires", ShutdownRegistryTag> | HttpRouter.Request<"Error", import("effect/http/HttpBody").HttpBodyError>>;
|
|
24
|
-
//# sourceMappingURL=health-routes.d.ts.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"health-routes.d.ts","sourceRoot":"","sources":["../src/health-routes.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,iBAAiB,EAAE,mBAAmB,EAAE,MAAM,mBAAmB,CAAC;AAE3E,OAAO,EAAE,UAAU,EAAsB,MAAM,aAAa,CAAC;AAiB7D;;;;;;;;;;;;;;;;;;;GAmBG;AAIH,eAAO,MAAM,YAAY,GAAI,aAAa,MAAM,4PA0D/C,CAAC"}
|