@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,92 @@
|
|
|
1
|
+
import { type PolicyDecisionTag, ServiceCrossingPolicyTag } from '@entifix/authz';
|
|
2
|
+
import { IdempotencyStoreTag, type TokenServiceTag } from '@entifix/business';
|
|
3
|
+
import { type EndpointGuard, type EndpointGuardKind, type EndpointIdempotency } from '@entifix/core';
|
|
4
|
+
import { Context, Layer } from 'effect';
|
|
5
|
+
import { HttpApiMiddleware } from 'effect/http-api';
|
|
6
|
+
import { ServiceCrossingTokenTag } from '../auth/require-service-crossing.js';
|
|
7
|
+
import { type SharedToken } from '../auth/shared-token.js';
|
|
8
|
+
declare const EndpointGuardAnnotation_base: Context.ServiceClass<EndpointGuardAnnotation, "@entifix/service-shell/EndpointGuard", EndpointGuard>;
|
|
9
|
+
/**
|
|
10
|
+
* The guard an endpoint was declared with, as an endpoint annotation, so one
|
|
11
|
+
* middleware per kind reads the permission off the endpoint it guards.
|
|
12
|
+
*/
|
|
13
|
+
export declare class EndpointGuardAnnotation extends EndpointGuardAnnotation_base {
|
|
14
|
+
}
|
|
15
|
+
declare const EndpointIdempotencyAnnotation_base: Context.ServiceClass<EndpointIdempotencyAnnotation, "@entifix/service-shell/EndpointIdempotency", EndpointIdempotency>;
|
|
16
|
+
/** The endpoint's idempotency declaration, as an endpoint annotation. */
|
|
17
|
+
export declare class EndpointIdempotencyAnnotation extends EndpointIdempotencyAnnotation_base {
|
|
18
|
+
}
|
|
19
|
+
declare const FleetTokenTag_base: Context.ServiceClass<FleetTokenTag, "@entifix/service-shell/FleetToken", SharedToken>;
|
|
20
|
+
/**
|
|
21
|
+
* The shared token one service of the fleet presents to another, provided by
|
|
22
|
+
* the composition root for endpoints declared `fleet`.
|
|
23
|
+
*/
|
|
24
|
+
export declare class FleetTokenTag extends FleetTokenTag_base {
|
|
25
|
+
}
|
|
26
|
+
declare const SessionGuard_base: HttpApiMiddleware.ServiceClass<SessionGuard, "@entifix/service-shell/SessionGuard", {
|
|
27
|
+
requires: never;
|
|
28
|
+
provides: never;
|
|
29
|
+
error: never;
|
|
30
|
+
clientError: never;
|
|
31
|
+
requiredForClient: false;
|
|
32
|
+
security: never;
|
|
33
|
+
}, HttpApiMiddleware.HttpApiMiddleware<never, never, never>>;
|
|
34
|
+
export declare class SessionGuard extends SessionGuard_base {
|
|
35
|
+
}
|
|
36
|
+
declare const OrganizationGuard_base: HttpApiMiddleware.ServiceClass<OrganizationGuard, "@entifix/service-shell/OrganizationGuard", {
|
|
37
|
+
requires: never;
|
|
38
|
+
provides: never;
|
|
39
|
+
error: never;
|
|
40
|
+
clientError: never;
|
|
41
|
+
requiredForClient: false;
|
|
42
|
+
security: never;
|
|
43
|
+
}, HttpApiMiddleware.HttpApiMiddleware<never, never, never>>;
|
|
44
|
+
export declare class OrganizationGuard extends OrganizationGuard_base {
|
|
45
|
+
}
|
|
46
|
+
declare const CrossingGuard_base: HttpApiMiddleware.ServiceClass<CrossingGuard, "@entifix/service-shell/CrossingGuard", {
|
|
47
|
+
requires: never;
|
|
48
|
+
provides: never;
|
|
49
|
+
error: never;
|
|
50
|
+
clientError: never;
|
|
51
|
+
requiredForClient: false;
|
|
52
|
+
security: never;
|
|
53
|
+
}, HttpApiMiddleware.HttpApiMiddleware<never, never, never>>;
|
|
54
|
+
export declare class CrossingGuard extends CrossingGuard_base {
|
|
55
|
+
}
|
|
56
|
+
declare const FleetGuard_base: HttpApiMiddleware.ServiceClass<FleetGuard, "@entifix/service-shell/FleetGuard", {
|
|
57
|
+
requires: never;
|
|
58
|
+
provides: never;
|
|
59
|
+
error: never;
|
|
60
|
+
clientError: never;
|
|
61
|
+
requiredForClient: false;
|
|
62
|
+
security: never;
|
|
63
|
+
}, HttpApiMiddleware.HttpApiMiddleware<never, never, never>>;
|
|
64
|
+
export declare class FleetGuard extends FleetGuard_base {
|
|
65
|
+
}
|
|
66
|
+
declare const IdempotencyGuard_base: HttpApiMiddleware.ServiceClass<IdempotencyGuard, "@entifix/service-shell/IdempotencyGuard", {
|
|
67
|
+
requires: never;
|
|
68
|
+
provides: never;
|
|
69
|
+
error: never;
|
|
70
|
+
clientError: never;
|
|
71
|
+
requiredForClient: false;
|
|
72
|
+
security: never;
|
|
73
|
+
}, HttpApiMiddleware.HttpApiMiddleware<never, never, never>>;
|
|
74
|
+
export declare class IdempotencyGuard extends IdempotencyGuard_base {
|
|
75
|
+
}
|
|
76
|
+
/** The middleware each guard kind mounts; `public` mounts none. */
|
|
77
|
+
export declare const GUARD_MIDDLEWARE: {
|
|
78
|
+
readonly public: undefined;
|
|
79
|
+
readonly session: typeof SessionGuard;
|
|
80
|
+
readonly permission: typeof SessionGuard;
|
|
81
|
+
readonly organization: typeof OrganizationGuard;
|
|
82
|
+
readonly crossing: typeof CrossingGuard;
|
|
83
|
+
readonly fleet: typeof FleetGuard;
|
|
84
|
+
};
|
|
85
|
+
/** Every guard's implementation, provided to the API once. */
|
|
86
|
+
export declare const guardLayers: Layer.Layer<SessionGuard | OrganizationGuard | CrossingGuard | FleetGuard | IdempotencyGuard, never, never>;
|
|
87
|
+
/** The services a guard kind reads, so a host that omits one does not compile. */
|
|
88
|
+
export type GuardServices<Kind extends EndpointGuardKind> = Kind extends 'public' ? never : Kind extends 'session' | 'permission' | 'organization' ? TokenServiceTag | PolicyDecisionTag : Kind extends 'crossing' ? ServiceCrossingTokenTag | ServiceCrossingPolicyTag : Kind extends 'fleet' ? FleetTokenTag : never;
|
|
89
|
+
/** The services an idempotency declaration reads. */
|
|
90
|
+
export type IdempotencyServices<Mode> = Mode extends 'edge' ? IdempotencyStoreTag : never;
|
|
91
|
+
export {};
|
|
92
|
+
//# sourceMappingURL=guards.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"guards.d.ts","sourceRoot":"","sources":["../../src/http-api/guards.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,KAAK,iBAAiB,EACtB,wBAAwB,EACzB,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAEL,mBAAmB,EAInB,KAAK,eAAe,EACrB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAEL,KAAK,aAAa,EAClB,KAAK,iBAAiB,EACtB,KAAK,mBAAmB,EAOzB,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,OAAO,EAAU,KAAK,EAAU,MAAM,QAAQ,CAAC;AAExD,OAAO,EAAE,iBAAiB,EAAE,MAAM,iBAAiB,CAAC;AAIpD,OAAO,EAGL,uBAAuB,EACxB,MAAM,qCAAqC,CAAC;AAC7C,OAAO,EAAE,KAAK,WAAW,EAAgB,MAAM,yBAAyB,CAAC;;AAIzE;;;GAGG;AACH,qBAAa,uBAAwB,SAAQ,4BAGF;CAAG;;AAE9C,yEAAyE;AACzE,qBAAa,6BAA8B,SAAQ,kCAGF;CAAG;;AAEpD;;;GAGG;AACH,qBAAa,aAAc,SAAQ,kBAGK;CAAG;;;;;;;;;AAkK3C,qBAAa,YAAa,SAAQ,iBAEjC;CAAG;;;;;;;;;AACJ,qBAAa,iBAAkB,SAAQ,sBAEtC;CAAG;;;;;;;;;AACJ,qBAAa,aAAc,SAAQ,kBAElC;CAAG;;;;;;;;;AACJ,qBAAa,UAAW,SAAQ,eAE/B;CAAG;;;;;;;;;AACJ,qBAAa,gBAAiB,SAAQ,qBAErC;CAAG;AAEJ,mEAAmE;AACnE,eAAO,MAAM,gBAAgB;;;;;;;CAO0B,CAAC;AAExD,8DAA8D;AAC9D,eAAO,MAAM,WAAW,6GAMvB,CAAC;AAEF,kFAAkF;AAClF,MAAM,MAAM,aAAa,CAAC,IAAI,SAAS,iBAAiB,IACtD,IAAI,SAAS,QAAQ,GACjB,KAAK,GACL,IAAI,SAAS,SAAS,GAAG,YAAY,GAAG,cAAc,GACpD,eAAe,GAAG,iBAAiB,GACnC,IAAI,SAAS,UAAU,GACrB,uBAAuB,GAAG,wBAAwB,GAClD,IAAI,SAAS,OAAO,GAClB,aAAa,GACb,KAAK,CAAC;AAElB,qDAAqD;AACrD,MAAM,MAAM,mBAAmB,CAAC,IAAI,IAAI,IAAI,SAAS,MAAM,GACvD,mBAAmB,GACnB,KAAK,CAAC"}
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
import { ServiceCrossingPolicyTag } from '@entifix/authz';
|
|
2
|
+
import { IdempotencyKeyTag, OrganizationIdTag, RequestPrincipalTag } from '@entifix/business';
|
|
3
|
+
import { ACCESS_COOKIE, Forbidden, IDEMPOTENCY_KEY_HEADER, IdempotencyKeyMissing, Invalid, parseIdempotencyKey, Unauthenticated } from '@entifix/core';
|
|
4
|
+
import { Context, Effect, Layer, Option } from 'effect';
|
|
5
|
+
import { HttpServerRequest } from 'effect/http';
|
|
6
|
+
import { HttpApiMiddleware } from 'effect/http-api';
|
|
7
|
+
import { NoActiveOrganization } from '../auth/failures.js';
|
|
8
|
+
import { permits, resolveRequestPrincipal } from '../auth/require-principal.js';
|
|
9
|
+
import { CROSSING_TOKEN_HEADER, ORGANIZATION_HEADER, ServiceCrossingTokenTag } from '../auth/require-service-crossing.js';
|
|
10
|
+
import { tokenMatches } from '../auth/shared-token.js';
|
|
11
|
+
import { withVerifiedContext } from '../auth/verified-context.js';
|
|
12
|
+
import { requireIdempotencyKey } from '../idempotency.js';
|
|
13
|
+
/**
|
|
14
|
+
* The guard an endpoint was declared with, as an endpoint annotation, so one
|
|
15
|
+
* middleware per kind reads the permission off the endpoint it guards.
|
|
16
|
+
*/ export class EndpointGuardAnnotation extends Context.Service()('@entifix/service-shell/EndpointGuard') {
|
|
17
|
+
}
|
|
18
|
+
/** The endpoint's idempotency declaration, as an endpoint annotation. */ export class EndpointIdempotencyAnnotation extends Context.Service()('@entifix/service-shell/EndpointIdempotency') {
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* The shared token one service of the fleet presents to another, provided by
|
|
22
|
+
* the composition root for endpoints declared `fleet`.
|
|
23
|
+
*/ export class FleetTokenTag extends Context.Service()('@entifix/service-shell/FleetToken') {
|
|
24
|
+
}
|
|
25
|
+
/* eslint-enable @typescript-eslint/no-explicit-any */ const guardOf = (options)=>Context.getUnsafe(options.endpoint.annotations, EndpointGuardAnnotation);
|
|
26
|
+
const unauthenticated = Effect.fail(new Unauthenticated());
|
|
27
|
+
/**
|
|
28
|
+
* The session's principal, or `unauthenticated`. An empty cookie and an empty
|
|
29
|
+
* bearer are both no credential: `resolveRequestPrincipal` reads `''` as
|
|
30
|
+
* absent before anything is verified.
|
|
31
|
+
*/ const principal = Effect.flatMap(resolveRequestPrincipal, (found)=>Option.isSome(found) ? Effect.succeed(found.value) : unauthenticated);
|
|
32
|
+
const permitted = (who, guard)=>'permission' in guard ? Effect.flatMap(permits(who, guard.permission), (allowed)=>allowed ? Effect.void : Effect.fail(new Forbidden({
|
|
33
|
+
permission: guard.permission
|
|
34
|
+
}))) : Effect.void;
|
|
35
|
+
const asCaller = (who, httpEffect)=>withVerifiedContext(who, ()=>Effect.provideService(httpEffect, RequestPrincipalTag, who));
|
|
36
|
+
const sessionGuard = (httpEffect, options)=>Effect.gen(function*() {
|
|
37
|
+
const who = yield* principal;
|
|
38
|
+
yield* permitted(who, guardOf(options));
|
|
39
|
+
return yield* asCaller(who, httpEffect);
|
|
40
|
+
});
|
|
41
|
+
const organizationGuard = (httpEffect, options)=>Effect.gen(function*() {
|
|
42
|
+
const who = yield* principal;
|
|
43
|
+
yield* permitted(who, guardOf(options));
|
|
44
|
+
// The organization comes from the verified token and nowhere else.
|
|
45
|
+
if (who.organizationId === undefined) return yield* Effect.fail(new NoActiveOrganization());
|
|
46
|
+
return yield* asCaller(who, Effect.provideService(httpEffect, OrganizationIdTag, who.organizationId));
|
|
47
|
+
});
|
|
48
|
+
const organizationRequired = new Invalid({
|
|
49
|
+
errors: [
|
|
50
|
+
{
|
|
51
|
+
pointer: `/headers/${ORGANIZATION_HEADER}`,
|
|
52
|
+
detail: `${ORGANIZATION_HEADER} is required`,
|
|
53
|
+
code: 'organizationRequired'
|
|
54
|
+
}
|
|
55
|
+
]
|
|
56
|
+
});
|
|
57
|
+
const crossingGuard = (httpEffect, options)=>Effect.gen(function*() {
|
|
58
|
+
var _request_headers_ORGANIZATION_HEADER;
|
|
59
|
+
// The builder mounts this middleware for a crossing guard only.
|
|
60
|
+
const guard = guardOf(options);
|
|
61
|
+
const request = yield* HttpServerRequest.HttpServerRequest;
|
|
62
|
+
// Two accepted credentials make the weaker one the security level, so a
|
|
63
|
+
// crossing endpoint refuses a request that also carries a session — any
|
|
64
|
+
// session credential at all, verified or not.
|
|
65
|
+
if (carriesSession(request)) return yield* unauthenticated;
|
|
66
|
+
const expected = yield* ServiceCrossingTokenTag;
|
|
67
|
+
if (!tokenMatches(request.headers[CROSSING_TOKEN_HEADER], expected)) return yield* unauthenticated;
|
|
68
|
+
const policy = yield* ServiceCrossingPolicyTag;
|
|
69
|
+
if (!policy.allows(guard.permission)) return yield* Effect.fail(new Forbidden({
|
|
70
|
+
permission: guard.permission
|
|
71
|
+
}));
|
|
72
|
+
if (!guard.organization) return yield* httpEffect;
|
|
73
|
+
const organizationId = (_request_headers_ORGANIZATION_HEADER = request.headers[ORGANIZATION_HEADER]) == null ? void 0 : _request_headers_ORGANIZATION_HEADER.trim();
|
|
74
|
+
if (organizationId === undefined || organizationId === '') return yield* Effect.fail(organizationRequired);
|
|
75
|
+
return yield* Effect.provideService(httpEffect, OrganizationIdTag, organizationId);
|
|
76
|
+
});
|
|
77
|
+
const carriesSession = (request)=>{
|
|
78
|
+
var _request_cookies_ACCESS_COOKIE, _request_headers_authorization;
|
|
79
|
+
return ((_request_cookies_ACCESS_COOKIE = request.cookies[ACCESS_COOKIE]) != null ? _request_cookies_ACCESS_COOKIE : '') !== '' || ((_request_headers_authorization = request.headers['authorization']) != null ? _request_headers_authorization : '') !== '';
|
|
80
|
+
};
|
|
81
|
+
const fleetGuard = (httpEffect)=>Effect.gen(function*() {
|
|
82
|
+
const request = yield* HttpServerRequest.HttpServerRequest;
|
|
83
|
+
const fleet = yield* FleetTokenTag;
|
|
84
|
+
if (!tokenMatches(request.headers[fleet.header], fleet.token())) return yield* unauthenticated;
|
|
85
|
+
return yield* httpEffect;
|
|
86
|
+
});
|
|
87
|
+
/**
|
|
88
|
+
* The `Idempotency-Key` handling an endpoint declared. `unit` decodes the key
|
|
89
|
+
* for the handler's unit of work and records nothing; `edge` remembers the
|
|
90
|
+
* answer in the idempotency store. One write is recorded by one layer.
|
|
91
|
+
*/ const idempotencyGuard = (httpEffect, options)=>Effect.gen(function*() {
|
|
92
|
+
const mode = Context.getUnsafe(options.endpoint.annotations, EndpointIdempotencyAnnotation);
|
|
93
|
+
const request = yield* HttpServerRequest.HttpServerRequest;
|
|
94
|
+
const key = parseIdempotencyKey(request.headers[IDEMPOTENCY_KEY_HEADER]);
|
|
95
|
+
if (key === undefined) return yield* Effect.fail(new IdempotencyKeyMissing());
|
|
96
|
+
const keyed = Effect.provideService(httpEffect, IdempotencyKeyTag, key);
|
|
97
|
+
if (mode === 'unit') return yield* keyed;
|
|
98
|
+
// The guard ran first and provided the principal on a session endpoint;
|
|
99
|
+
// two callers choosing one key never collide.
|
|
100
|
+
const caller = Option.match((yield* Effect.serviceOption(RequestPrincipalTag)), {
|
|
101
|
+
onNone: ()=>'service',
|
|
102
|
+
onSome: (who)=>String(who.userId)
|
|
103
|
+
});
|
|
104
|
+
// The route's template, not the concrete path: the dedup key is per
|
|
105
|
+
// route, and the fingerprint is what tells two records on it apart.
|
|
106
|
+
return yield* requireIdempotencyKey({
|
|
107
|
+
route: `${options.endpoint.method} ${options.endpoint.path}`,
|
|
108
|
+
caller
|
|
109
|
+
})(keyed);
|
|
110
|
+
});
|
|
111
|
+
export class SessionGuard extends HttpApiMiddleware.Service()('@entifix/service-shell/SessionGuard') {
|
|
112
|
+
}
|
|
113
|
+
export class OrganizationGuard extends HttpApiMiddleware.Service()('@entifix/service-shell/OrganizationGuard') {
|
|
114
|
+
}
|
|
115
|
+
export class CrossingGuard extends HttpApiMiddleware.Service()('@entifix/service-shell/CrossingGuard') {
|
|
116
|
+
}
|
|
117
|
+
export class FleetGuard extends HttpApiMiddleware.Service()('@entifix/service-shell/FleetGuard') {
|
|
118
|
+
}
|
|
119
|
+
export class IdempotencyGuard extends HttpApiMiddleware.Service()('@entifix/service-shell/IdempotencyGuard') {
|
|
120
|
+
}
|
|
121
|
+
/** The middleware each guard kind mounts; `public` mounts none. */ export const GUARD_MIDDLEWARE = {
|
|
122
|
+
public: undefined,
|
|
123
|
+
session: SessionGuard,
|
|
124
|
+
permission: SessionGuard,
|
|
125
|
+
organization: OrganizationGuard,
|
|
126
|
+
crossing: CrossingGuard,
|
|
127
|
+
fleet: FleetGuard
|
|
128
|
+
};
|
|
129
|
+
/** Every guard's implementation, provided to the API once. */ export const guardLayers = Layer.mergeAll(Layer.succeed(SessionGuard)(sessionGuard), Layer.succeed(OrganizationGuard)(organizationGuard), Layer.succeed(CrossingGuard)(crossingGuard), Layer.succeed(FleetGuard)(fleetGuard), Layer.succeed(IdempotencyGuard)(idempotencyGuard));
|
|
130
|
+
|
|
131
|
+
//# sourceMappingURL=guards.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/http-api/guards.ts"],"sourcesContent":["import {\n type PolicyDecisionTag,\n ServiceCrossingPolicyTag,\n} from '@entifix/authz';\nimport {\n IdempotencyKeyTag,\n IdempotencyStoreTag,\n OrganizationIdTag,\n type RequestPrincipal,\n RequestPrincipalTag,\n type TokenServiceTag,\n} from '@entifix/business';\nimport {\n ACCESS_COOKIE,\n type EndpointGuard,\n type EndpointGuardKind,\n type EndpointIdempotency,\n Forbidden,\n IDEMPOTENCY_KEY_HEADER,\n IdempotencyKeyMissing,\n Invalid,\n parseIdempotencyKey,\n Unauthenticated,\n} from '@entifix/core';\nimport { Context, Effect, Layer, Option } from 'effect';\nimport { HttpServerRequest } from 'effect/http';\nimport { HttpApiMiddleware } from 'effect/http-api';\n\nimport { NoActiveOrganization } from '../auth/failures.js';\nimport { permits, resolveRequestPrincipal } from '../auth/require-principal.js';\nimport {\n CROSSING_TOKEN_HEADER,\n ORGANIZATION_HEADER,\n ServiceCrossingTokenTag,\n} from '../auth/require-service-crossing.js';\nimport { type SharedToken, tokenMatches } from '../auth/shared-token.js';\nimport { withVerifiedContext } from '../auth/verified-context.js';\nimport { requireIdempotencyKey } from '../idempotency.js';\n\n/**\n * The guard an endpoint was declared with, as an endpoint annotation, so one\n * middleware per kind reads the permission off the endpoint it guards.\n */\nexport class EndpointGuardAnnotation extends Context.Service<\n EndpointGuardAnnotation,\n EndpointGuard\n>()('@entifix/service-shell/EndpointGuard') {}\n\n/** The endpoint's idempotency declaration, as an endpoint annotation. */\nexport class EndpointIdempotencyAnnotation extends Context.Service<\n EndpointIdempotencyAnnotation,\n EndpointIdempotency\n>()('@entifix/service-shell/EndpointIdempotency') {}\n\n/**\n * The shared token one service of the fleet presents to another, provided by\n * the composition root for endpoints declared `fleet`.\n */\nexport class FleetTokenTag extends Context.Service<\n FleetTokenTag,\n SharedToken\n>()('@entifix/service-shell/FleetToken') {}\n\n/* eslint-disable @typescript-eslint/no-explicit-any -- the API is assembled\n from descriptors at runtime; the descriptors carry the types. */\ntype AnyEffect = Effect.Effect<any, any, any>;\ntype Middleware = (\n httpEffect: AnyEffect,\n options: {\n readonly endpoint: {\n readonly annotations: Context.Context<never>;\n readonly method: string;\n readonly path: string;\n };\n },\n) => AnyEffect;\n/* eslint-enable @typescript-eslint/no-explicit-any */\n\nconst guardOf = (options: Parameters<Middleware>[1]): EndpointGuard =>\n Context.getUnsafe(\n options.endpoint.annotations as Context.Context<EndpointGuardAnnotation>,\n EndpointGuardAnnotation,\n );\n\nconst unauthenticated = Effect.fail(new Unauthenticated());\n\n/**\n * The session's principal, or `unauthenticated`. An empty cookie and an empty\n * bearer are both no credential: `resolveRequestPrincipal` reads `''` as\n * absent before anything is verified.\n */\nconst principal = Effect.flatMap(resolveRequestPrincipal, found =>\n Option.isSome(found) ? Effect.succeed(found.value) : unauthenticated,\n);\n\nconst permitted = (who: RequestPrincipal, guard: EndpointGuard) =>\n 'permission' in guard\n ? Effect.flatMap(permits(who, guard.permission), allowed =>\n allowed\n ? Effect.void\n : Effect.fail(new Forbidden({ permission: guard.permission })),\n )\n : Effect.void;\n\nconst asCaller = (who: RequestPrincipal, httpEffect: AnyEffect) =>\n withVerifiedContext(who, () =>\n Effect.provideService(httpEffect, RequestPrincipalTag, who),\n );\n\nconst sessionGuard: Middleware = (httpEffect, options) =>\n Effect.gen(function* () {\n const who = yield* principal;\n yield* permitted(who, guardOf(options));\n return yield* asCaller(who, httpEffect);\n });\n\nconst organizationGuard: Middleware = (httpEffect, options) =>\n Effect.gen(function* () {\n const who = yield* principal;\n yield* permitted(who, guardOf(options));\n // The organization comes from the verified token and nowhere else.\n if (who.organizationId === undefined)\n return yield* Effect.fail(new NoActiveOrganization());\n return yield* asCaller(\n who,\n Effect.provideService(httpEffect, OrganizationIdTag, who.organizationId),\n );\n });\n\nconst organizationRequired = new Invalid({\n errors: [\n {\n pointer: `/headers/${ORGANIZATION_HEADER}`,\n detail: `${ORGANIZATION_HEADER} is required`,\n code: 'organizationRequired',\n },\n ],\n});\n\nconst crossingGuard: Middleware = (httpEffect, options) =>\n Effect.gen(function* () {\n // The builder mounts this middleware for a crossing guard only.\n const guard = guardOf(options) as Extract<\n EndpointGuard,\n { kind: 'crossing' }\n >;\n const request = yield* HttpServerRequest.HttpServerRequest;\n // Two accepted credentials make the weaker one the security level, so a\n // crossing endpoint refuses a request that also carries a session — any\n // session credential at all, verified or not.\n if (carriesSession(request)) return yield* unauthenticated;\n\n const expected = yield* ServiceCrossingTokenTag;\n if (!tokenMatches(request.headers[CROSSING_TOKEN_HEADER], expected))\n return yield* unauthenticated;\n\n const policy = yield* ServiceCrossingPolicyTag;\n if (!policy.allows(guard.permission))\n return yield* Effect.fail(\n new Forbidden({ permission: guard.permission }),\n );\n\n if (!guard.organization) return yield* httpEffect;\n const organizationId = request.headers[ORGANIZATION_HEADER]?.trim();\n if (organizationId === undefined || organizationId === '')\n return yield* Effect.fail(organizationRequired);\n return yield* Effect.provideService(\n httpEffect,\n OrganizationIdTag,\n organizationId,\n );\n });\n\nconst carriesSession = (\n request: HttpServerRequest.HttpServerRequest,\n): boolean =>\n (request.cookies[ACCESS_COOKIE] ?? '') !== '' ||\n (request.headers['authorization'] ?? '') !== '';\n\nconst fleetGuard: Middleware = httpEffect =>\n Effect.gen(function* () {\n const request = yield* HttpServerRequest.HttpServerRequest;\n const fleet = yield* FleetTokenTag;\n if (!tokenMatches(request.headers[fleet.header], fleet.token()))\n return yield* unauthenticated;\n return yield* httpEffect;\n });\n\n/**\n * The `Idempotency-Key` handling an endpoint declared. `unit` decodes the key\n * for the handler's unit of work and records nothing; `edge` remembers the\n * answer in the idempotency store. One write is recorded by one layer.\n */\nconst idempotencyGuard: Middleware = (httpEffect, options) =>\n Effect.gen(function* () {\n const mode = Context.getUnsafe(\n options.endpoint\n .annotations as Context.Context<EndpointIdempotencyAnnotation>,\n EndpointIdempotencyAnnotation,\n );\n const request = yield* HttpServerRequest.HttpServerRequest;\n const key = parseIdempotencyKey(request.headers[IDEMPOTENCY_KEY_HEADER]);\n if (key === undefined)\n return yield* Effect.fail(new IdempotencyKeyMissing());\n const keyed = Effect.provideService(httpEffect, IdempotencyKeyTag, key);\n if (mode === 'unit') return yield* keyed;\n // The guard ran first and provided the principal on a session endpoint;\n // two callers choosing one key never collide.\n const caller = Option.match(\n yield* Effect.serviceOption(RequestPrincipalTag),\n {\n onNone: () => 'service',\n onSome: who => String(who.userId),\n },\n );\n // The route's template, not the concrete path: the dedup key is per\n // route, and the fingerprint is what tells two records on it apart.\n return yield* requireIdempotencyKey({\n route: `${options.endpoint.method} ${options.endpoint.path}`,\n caller,\n })(keyed);\n });\n\nexport class SessionGuard extends HttpApiMiddleware.Service<SessionGuard>()(\n '@entifix/service-shell/SessionGuard',\n) {}\nexport class OrganizationGuard extends HttpApiMiddleware.Service<OrganizationGuard>()(\n '@entifix/service-shell/OrganizationGuard',\n) {}\nexport class CrossingGuard extends HttpApiMiddleware.Service<CrossingGuard>()(\n '@entifix/service-shell/CrossingGuard',\n) {}\nexport class FleetGuard extends HttpApiMiddleware.Service<FleetGuard>()(\n '@entifix/service-shell/FleetGuard',\n) {}\nexport class IdempotencyGuard extends HttpApiMiddleware.Service<IdempotencyGuard>()(\n '@entifix/service-shell/IdempotencyGuard',\n) {}\n\n/** The middleware each guard kind mounts; `public` mounts none. */\nexport const GUARD_MIDDLEWARE = {\n public: undefined,\n session: SessionGuard,\n permission: SessionGuard,\n organization: OrganizationGuard,\n crossing: CrossingGuard,\n fleet: FleetGuard,\n} as const satisfies Record<EndpointGuardKind, unknown>;\n\n/** Every guard's implementation, provided to the API once. */\nexport const guardLayers = Layer.mergeAll(\n Layer.succeed(SessionGuard)(sessionGuard as never),\n Layer.succeed(OrganizationGuard)(organizationGuard as never),\n Layer.succeed(CrossingGuard)(crossingGuard as never),\n Layer.succeed(FleetGuard)(fleetGuard as never),\n Layer.succeed(IdempotencyGuard)(idempotencyGuard as never),\n);\n\n/** The services a guard kind reads, so a host that omits one does not compile. */\nexport type GuardServices<Kind extends EndpointGuardKind> =\n Kind extends 'public'\n ? never\n : Kind extends 'session' | 'permission' | 'organization'\n ? TokenServiceTag | PolicyDecisionTag\n : Kind extends 'crossing'\n ? ServiceCrossingTokenTag | ServiceCrossingPolicyTag\n : Kind extends 'fleet'\n ? FleetTokenTag\n : never;\n\n/** The services an idempotency declaration reads. */\nexport type IdempotencyServices<Mode> = Mode extends 'edge'\n ? IdempotencyStoreTag\n : never;\n"],"names":["ServiceCrossingPolicyTag","IdempotencyKeyTag","OrganizationIdTag","RequestPrincipalTag","ACCESS_COOKIE","Forbidden","IDEMPOTENCY_KEY_HEADER","IdempotencyKeyMissing","Invalid","parseIdempotencyKey","Unauthenticated","Context","Effect","Layer","Option","HttpServerRequest","HttpApiMiddleware","NoActiveOrganization","permits","resolveRequestPrincipal","CROSSING_TOKEN_HEADER","ORGANIZATION_HEADER","ServiceCrossingTokenTag","tokenMatches","withVerifiedContext","requireIdempotencyKey","EndpointGuardAnnotation","Service","EndpointIdempotencyAnnotation","FleetTokenTag","guardOf","options","getUnsafe","endpoint","annotations","unauthenticated","fail","principal","flatMap","found","isSome","succeed","value","permitted","who","guard","permission","allowed","void","asCaller","httpEffect","provideService","sessionGuard","gen","organizationGuard","organizationId","undefined","organizationRequired","errors","pointer","detail","code","crossingGuard","request","carriesSession","expected","headers","policy","allows","organization","trim","cookies","fleetGuard","fleet","header","token","idempotencyGuard","mode","key","keyed","caller","match","serviceOption","onNone","onSome","String","userId","route","method","path","SessionGuard","OrganizationGuard","CrossingGuard","FleetGuard","IdempotencyGuard","GUARD_MIDDLEWARE","public","session","crossing","guardLayers","mergeAll"],"mappings":"AAAA,SAEEA,wBAAwB,QACnB,iBAAiB;AACxB,SACEC,iBAAiB,EAEjBC,iBAAiB,EAEjBC,mBAAmB,QAEd,oBAAoB;AAC3B,SACEC,aAAa,EAIbC,SAAS,EACTC,sBAAsB,EACtBC,qBAAqB,EACrBC,OAAO,EACPC,mBAAmB,EACnBC,eAAe,QACV,gBAAgB;AACvB,SAASC,OAAO,EAAEC,MAAM,EAAEC,KAAK,EAAEC,MAAM,QAAQ,SAAS;AACxD,SAASC,iBAAiB,QAAQ,cAAc;AAChD,SAASC,iBAAiB,QAAQ,kBAAkB;AAEpD,SAASC,oBAAoB,QAAQ,sBAAsB;AAC3D,SAASC,OAAO,EA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AEF,oEAAoE;QACpE,oEAAoE;QACpE,OAAO,OAAO7D,sBAAsB;YAClC8D,OAAO,GAAGxD,QAAQE,QAAQ,CAACuD,MAAM,CAAC,CAAC,EAAEzD,QAAQE,QAAQ,CAACwD,IAAI,EAAE;YAC5DT;QACF,GAAGD;IACL;AAEF,OAAO,MAAMW,qBAAqB1E,kBAAkBW,OAAO,GACzD;AACC;AACH,OAAO,MAAMgE,0BAA0B3E,kBAAkBW,OAAO,GAC9D;AACC;AACH,OAAO,MAAMiE,sBAAsB5E,kBAAkBW,OAAO,GAC1D;AACC;AACH,OAAO,MAAMkE,mBAAmB7E,kBAAkBW,OAAO,GACvD;AACC;AACH,OAAO,MAAMmE,yBAAyB9E,kBAAkBW,OAAO,GAC7D;AACC;AAEH,iEAAiE,GACjE,OAAO,MAAMoE,mBAAmB;IAC9BC,QAAQxC;IACRyC,SAASP;IACT5C,YAAY4C;IACZrB,cAAcsB;IACdO,UAAUN;IACVnB,OAAOoB;AACT,EAAwD;AAExD,4DAA4D,GAC5D,OAAO,MAAMM,cAActF,MAAMuF,QAAQ,CACvCvF,MAAM4B,OAAO,CAACiD,cAActC,eAC5BvC,MAAM4B,OAAO,CAACkD,mBAAmBrC,oBACjCzC,MAAM4B,OAAO,CAACmD,eAAe9B,gBAC7BjD,MAAM4B,OAAO,CAACoD,YAAYrB,aAC1B3D,MAAM4B,OAAO,CAACqD,kBAAkBlB,mBAChC"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/http-api/index.ts"],"names":[],"mappings":"AAAA,cAAc,gBAAgB,CAAC;AAC/B,cAAc,iBAAiB,CAAC;AAChC,cAAc,aAAa,CAAC;AAC5B,cAAc,oBAAoB,CAAC;AACnC,cAAc,oBAAoB,CAAC"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/http-api/index.ts"],"sourcesContent":["export * from './build-api.js';\nexport * from './entity-api.js';\nexport * from './guards.js';\nexport * from './problem-codec.js';\nexport * from './service-group.js';\n"],"names":[],"mappings":"AAAA,cAAc,iBAAiB;AAC/B,cAAc,kBAAkB;AAChC,cAAc,cAAc;AAC5B,cAAc,qBAAqB;AACnC,cAAc,qBAAqB"}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { type FailureClass } from '@entifix/core';
|
|
2
|
+
import { Schema } from 'effect';
|
|
3
|
+
/**
|
|
4
|
+
* A failure class as an endpoint's error schema: the problem body on the wire,
|
|
5
|
+
* the failure as its type, the policy's status and the problem content type
|
|
6
|
+
* ([ADR 0020](../../../../../docs/adr/0020-endpoints-are-descriptors-and-the-shell-builds-an-httpapi.md)).
|
|
7
|
+
*
|
|
8
|
+
* The wire side is the problem envelope plus the class's own fields, so the
|
|
9
|
+
* OpenAPI document shows what a client receives. Decoding goes through the
|
|
10
|
+
* registry, by `code`, so a body that names another code decodes to the
|
|
11
|
+
* failure it names rather than to this class.
|
|
12
|
+
*/
|
|
13
|
+
export declare const problemCodec: (failureClass: FailureClass, status: number) => Schema.Top;
|
|
14
|
+
//# sourceMappingURL=problem-codec.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"problem-codec.d.ts","sourceRoot":"","sources":["../../src/http-api/problem-codec.ts"],"names":[],"mappings":"AAAA,OAAO,EAGL,KAAK,YAAY,EAKlB,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,MAAM,EAAwB,MAAM,QAAQ,CAAC;AAStD;;;;;;;;;GASG;AACH,eAAO,MAAM,YAAY,GACvB,cAAc,YAAY,EAC1B,QAAQ,MAAM,KACb,MAAM,CAAC,GAcP,CAAC"}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
2
|
+
import { decodeProblem, isFailure, Problem, PROBLEM_CONTENT_TYPE, problemOf } from '@entifix/core';
|
|
3
|
+
import { Schema, SchemaTransformation } from 'effect';
|
|
4
|
+
import { HttpApiSchema } from 'effect/http-api';
|
|
5
|
+
/** The class's own fields; the tag is the problem's `title`, not a member. */ const ownFields = (failureClass)=>Object.fromEntries(Object.entries(failureClass.fields).filter(([key])=>key !== '_tag'));
|
|
6
|
+
/**
|
|
7
|
+
* A failure class as an endpoint's error schema: the problem body on the wire,
|
|
8
|
+
* the failure as its type, the policy's status and the problem content type
|
|
9
|
+
* ([ADR 0020](../../../../../docs/adr/0020-endpoints-are-descriptors-and-the-shell-builds-an-httpapi.md)).
|
|
10
|
+
*
|
|
11
|
+
* The wire side is the problem envelope plus the class's own fields, so the
|
|
12
|
+
* OpenAPI document shows what a client receives. Decoding goes through the
|
|
13
|
+
* registry, by `code`, so a body that names another code decodes to the
|
|
14
|
+
* failure it names rather than to this class.
|
|
15
|
+
*/ export const problemCodec = (failureClass, status)=>Schema.Struct(_extends({}, Problem.fields, ownFields(failureClass))).pipe(// The type side is any failure, not only this class: a body may name
|
|
16
|
+
// another code, and decoding it yields what it names.
|
|
17
|
+
Schema.decodeTo(Schema.declare((value)=>isFailure(value)), SchemaTransformation.transform({
|
|
18
|
+
decode: (body)=>decodeProblem(body, status),
|
|
19
|
+
encode: (failure)=>problemOf(failure, {
|
|
20
|
+
status
|
|
21
|
+
})
|
|
22
|
+
})), HttpApiSchema.status(status), HttpApiSchema.asJson({
|
|
23
|
+
contentType: PROBLEM_CONTENT_TYPE
|
|
24
|
+
}));
|
|
25
|
+
|
|
26
|
+
//# sourceMappingURL=problem-codec.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/http-api/problem-codec.ts"],"sourcesContent":["import {\n decodeProblem,\n type EntifixFailure,\n type FailureClass,\n isFailure,\n Problem,\n PROBLEM_CONTENT_TYPE,\n problemOf,\n} from '@entifix/core';\nimport { Schema, SchemaTransformation } from 'effect';\nimport { HttpApiSchema } from 'effect/http-api';\n\n/** The class's own fields; the tag is the problem's `title`, not a member. */\nconst ownFields = (failureClass: FailureClass): Schema.Struct.Fields =>\n Object.fromEntries(\n Object.entries(failureClass.fields).filter(([key]) => key !== '_tag'),\n );\n\n/**\n * A failure class as an endpoint's error schema: the problem body on the wire,\n * the failure as its type, the policy's status and the problem content type\n * ([ADR 0020](../../../../../docs/adr/0020-endpoints-are-descriptors-and-the-shell-builds-an-httpapi.md)).\n *\n * The wire side is the problem envelope plus the class's own fields, so the\n * OpenAPI document shows what a client receives. Decoding goes through the\n * registry, by `code`, so a body that names another code decodes to the\n * failure it names rather than to this class.\n */\nexport const problemCodec = (\n failureClass: FailureClass,\n status: number,\n): Schema.Top =>\n Schema.Struct({ ...Problem.fields, ...ownFields(failureClass) }).pipe(\n // The type side is any failure, not only this class: a body may name\n // another code, and decoding it yields what it names.\n Schema.decodeTo(\n Schema.declare((value): value is EntifixFailure => isFailure(value)),\n SchemaTransformation.transform({\n decode: body => decodeProblem(body, status),\n encode: failure =>\n problemOf(failure, { status }) as typeof Problem.Type,\n }),\n ),\n HttpApiSchema.status(status),\n HttpApiSchema.asJson({ contentType: PROBLEM_CONTENT_TYPE }),\n );\n"],"names":["decodeProblem","isFailure","Problem","PROBLEM_CONTENT_TYPE","problemOf","Schema","SchemaTransformation","HttpApiSchema","ownFields","failureClass","Object","fromEntries","entries","fields","filter","key","problemCodec","status","Struct","pipe","decodeTo","declare","value","transform","decode","body","encode","failure","asJson","contentType"],"mappings":";AAAA,SACEA,aAAa,EAGbC,SAAS,EACTC,OAAO,EACPC,oBAAoB,EACpBC,SAAS,QACJ,gBAAgB;AACvB,SAASC,MAAM,EAAEC,oBAAoB,QAAQ,SAAS;AACtD,SAASC,aAAa,QAAQ,kBAAkB;AAEhD,4EAA4E,GAC5E,MAAMC,YAAY,CAACC,eACjBC,OAAOC,WAAW,CAChBD,OAAOE,OAAO,CAACH,aAAaI,MAAM,EAAEC,MAAM,CAAC,CAAC,CAACC,IAAI,GAAKA,QAAQ;AAGlE;;;;;;;;;CASC,GACD,OAAO,MAAMC,eAAe,CAC1BP,cACAQ,SAEAZ,OAAOa,MAAM,CAAC,aAAKhB,QAAQW,MAAM,EAAKL,UAAUC,gBAAiBU,IAAI,CACnE,qEAAqE;IACrE,sDAAsD;IACtDd,OAAOe,QAAQ,CACbf,OAAOgB,OAAO,CAAC,CAACC,QAAmCrB,UAAUqB,SAC7DhB,qBAAqBiB,SAAS,CAAC;QAC7BC,QAAQC,CAAAA,OAAQzB,cAAcyB,MAAMR;QACpCS,QAAQC,CAAAA,UACNvB,UAAUuB,SAAS;gBAAEV;YAAO;IAChC,KAEFV,cAAcU,MAAM,CAACA,SACrBV,cAAcqB,MAAM,CAAC;QAAEC,aAAa1B;IAAqB,IACzD"}
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import { type BoundSubscription, HealthRegistryTag, ShutdownRegistryTag, WiringRegistryTag } from '@entifix/business';
|
|
2
|
+
import { type AnyEndpoint } from '@entifix/core';
|
|
3
|
+
import { Schema } from 'effect';
|
|
4
|
+
import type { HttpApi } from 'effect/http-api';
|
|
5
|
+
import { type EndpointGroup } from './build-api.js';
|
|
6
|
+
export declare const SERVICE_DESCRIPTION_PATH = "/api/$service";
|
|
7
|
+
export declare const OPENAPI_PATH = "/api/$openapi";
|
|
8
|
+
declare const NotReady_base: Schema.Class<NotReady, Schema.TaggedStruct<"NotReady", {
|
|
9
|
+
readonly service: Schema.String;
|
|
10
|
+
readonly terminating: Schema.Boolean;
|
|
11
|
+
readonly failing: Schema.$Array<Schema.String>;
|
|
12
|
+
}>, import("effect/Cause").YieldableError & import("@entifix/core").FailureFacts<"notReady", "unavailable">>;
|
|
13
|
+
/**
|
|
14
|
+
* A service that is up but cannot serve yet — a probe failing, or the process
|
|
15
|
+
* draining. `503`, so an orchestrator stops routing to it; the failing probe
|
|
16
|
+
* names ride on the problem.
|
|
17
|
+
*/
|
|
18
|
+
export declare class NotReady extends NotReady_base {
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* What a service says it does — the document a register diffs the service
|
|
22
|
+
* against. `endpoints` is every `METHOD /path` the built API serves.
|
|
23
|
+
*/
|
|
24
|
+
export declare const ServiceDescription: Schema.Struct<{
|
|
25
|
+
readonly service: Schema.String;
|
|
26
|
+
/** The slices this process hosts; more than one means co-deployment. */
|
|
27
|
+
readonly slices: Schema.$Array<Schema.String>;
|
|
28
|
+
readonly stores: Schema.$Array<Schema.Struct<{
|
|
29
|
+
/** The Store's register name, an exchange, or a service. Never a URI. */
|
|
30
|
+
readonly name: Schema.String;
|
|
31
|
+
/** The readiness probe that covers it, so the two documents line up. */
|
|
32
|
+
readonly probe: Schema.String;
|
|
33
|
+
}>>;
|
|
34
|
+
readonly brokers: Schema.$Array<Schema.Struct<{
|
|
35
|
+
/** The Store's register name, an exchange, or a service. Never a URI. */
|
|
36
|
+
readonly name: Schema.String;
|
|
37
|
+
/** The readiness probe that covers it, so the two documents line up. */
|
|
38
|
+
readonly probe: Schema.String;
|
|
39
|
+
}>>;
|
|
40
|
+
readonly upstreams: Schema.$Array<Schema.Struct<{
|
|
41
|
+
/** The Store's register name, an exchange, or a service. Never a URI. */
|
|
42
|
+
readonly name: Schema.String;
|
|
43
|
+
/** The readiness probe that covers it, so the two documents line up. */
|
|
44
|
+
readonly probe: Schema.String;
|
|
45
|
+
}>>;
|
|
46
|
+
/** Distinct event names this process has emitted since boot. */
|
|
47
|
+
readonly published: Schema.$Array<Schema.String>;
|
|
48
|
+
/** The bus bindings this process actually made. */
|
|
49
|
+
readonly subscriptions: Schema.$Array<Schema.Unknown>;
|
|
50
|
+
readonly endpoints: Schema.$Array<Schema.String>;
|
|
51
|
+
}>;
|
|
52
|
+
export type ServiceDescription = Omit<typeof ServiceDescription.Type, 'subscriptions'> & {
|
|
53
|
+
readonly subscriptions: readonly BoundSubscription[];
|
|
54
|
+
};
|
|
55
|
+
export interface ServiceGroupOptions {
|
|
56
|
+
readonly service: string;
|
|
57
|
+
readonly slices: readonly string[];
|
|
58
|
+
/** Mount `$service` and `$openapi`; absent means neither is served. */
|
|
59
|
+
readonly described: boolean;
|
|
60
|
+
/** Every `METHOD /path` the service serves, for `$service`. */
|
|
61
|
+
readonly endpoints: () => readonly string[];
|
|
62
|
+
/** The built API, for `$openapi`; read after it is built. */
|
|
63
|
+
readonly api: () => HttpApi.Top;
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* The endpoints every service serves: liveness, readiness, and — behind the
|
|
67
|
+
* fleet token — its wiring document and its OpenAPI document. The wiring
|
|
68
|
+
* document names every store, exchange and upstream, and an unguarded
|
|
69
|
+
* reconnaissance map is worse than none, so a service with no token serves
|
|
70
|
+
* neither.
|
|
71
|
+
*/
|
|
72
|
+
export declare const serviceGroup: (options: ServiceGroupOptions) => EndpointGroup<AnyEndpoint, HealthRegistryTag | ShutdownRegistryTag | WiringRegistryTag>;
|
|
73
|
+
export {};
|
|
74
|
+
//# sourceMappingURL=service-group.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"service-group.d.ts","sourceRoot":"","sources":["../../src/http-api/service-group.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,KAAK,iBAAiB,EACtB,iBAAiB,EAGjB,mBAAmB,EACnB,iBAAiB,EAClB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EACL,KAAK,WAAW,EAKjB,MAAM,eAAe,CAAC;AACvB,OAAO,EAAe,MAAM,EAAE,MAAM,QAAQ,CAAC;AAC7C,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,iBAAiB,CAAC;AAG/C,OAAO,EAAE,KAAK,aAAa,EAAiB,MAAM,gBAAgB,CAAC;AAEnE,eAAO,MAAM,wBAAwB,kBAAkB,CAAC;AACxD,eAAO,MAAM,YAAY,kBAAkB,CAAC;;;;;;AAE5C;;;;GAIG;AACH,qBAAa,QAAS,SAAQ,aAQ7B;CAAG;AAcJ;;;GAGG;AACH,eAAO,MAAM,kBAAkB;;IAE7B,wEAAwE;;;QAZxE,yEAAyE;;QAEzE,wEAAwE;;;;QAFxE,yEAAyE;;QAEzE,wEAAwE;;;;QAFxE,yEAAyE;;QAEzE,wEAAwE;;;IAexE,gEAAgE;;IAEhE,mDAAmD;;;EAGnD,CAAC;AACH,MAAM,MAAM,kBAAkB,GAAG,IAAI,CACnC,OAAO,kBAAkB,CAAC,IAAI,EAC9B,eAAe,CAChB,GAAG;IAAE,QAAQ,CAAC,aAAa,EAAE,SAAS,iBAAiB,EAAE,CAAA;CAAE,CAAC;AAsD7D,MAAM,WAAW,mBAAmB;IAClC,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,QAAQ,CAAC,MAAM,EAAE,SAAS,MAAM,EAAE,CAAC;IACnC,uEAAuE;IACvE,QAAQ,CAAC,SAAS,EAAE,OAAO,CAAC;IAC5B,+DAA+D;IAC/D,QAAQ,CAAC,SAAS,EAAE,MAAM,SAAS,MAAM,EAAE,CAAC;IAC5C,6DAA6D;IAC7D,QAAQ,CAAC,GAAG,EAAE,MAAM,OAAO,CAAC,GAAG,CAAC;CACjC;AAED;;;;;;GAMG;AACH,eAAO,MAAM,YAAY,GACvB,SAAS,mBAAmB,KAC3B,aAAa,CACd,WAAW,EACX,iBAAiB,GAAG,mBAAmB,GAAG,iBAAiB,CAuF5D,CAAC"}
|
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
import { HealthRegistryTag, ShutdownRegistryTag, WiringRegistryTag } from '@entifix/business';
|
|
2
|
+
import { defineEndpoint, Failure, implement, JsonBody } from '@entifix/core';
|
|
3
|
+
import { Effect, Ref, Schema } from 'effect';
|
|
4
|
+
import { OpenApi } from 'effect/http-api';
|
|
5
|
+
import { endpointGroup } from './build-api.js';
|
|
6
|
+
export const SERVICE_DESCRIPTION_PATH = '/api/$service';
|
|
7
|
+
export const OPENAPI_PATH = '/api/$openapi';
|
|
8
|
+
/**
|
|
9
|
+
* A service that is up but cannot serve yet — a probe failing, or the process
|
|
10
|
+
* draining. `503`, so an orchestrator stops routing to it; the failing probe
|
|
11
|
+
* names ride on the problem.
|
|
12
|
+
*/ export class NotReady extends Failure.unavailable()('NotReady', 'notReady', {
|
|
13
|
+
service: Schema.String,
|
|
14
|
+
terminating: Schema.Boolean,
|
|
15
|
+
failing: Schema.Array(Schema.String)
|
|
16
|
+
}) {
|
|
17
|
+
}
|
|
18
|
+
const HealthStatus = Schema.Struct({
|
|
19
|
+
status: Schema.String,
|
|
20
|
+
service: Schema.String
|
|
21
|
+
});
|
|
22
|
+
const DescribedTarget = Schema.Struct({
|
|
23
|
+
/** The Store's register name, an exchange, or a service. Never a URI. */ name: Schema.String,
|
|
24
|
+
/** The readiness probe that covers it, so the two documents line up. */ probe: Schema.String
|
|
25
|
+
});
|
|
26
|
+
/**
|
|
27
|
+
* What a service says it does — the document a register diffs the service
|
|
28
|
+
* against. `endpoints` is every `METHOD /path` the built API serves.
|
|
29
|
+
*/ export const ServiceDescription = Schema.Struct({
|
|
30
|
+
service: Schema.String,
|
|
31
|
+
/** The slices this process hosts; more than one means co-deployment. */ slices: Schema.Array(Schema.String),
|
|
32
|
+
stores: Schema.Array(DescribedTarget),
|
|
33
|
+
brokers: Schema.Array(DescribedTarget),
|
|
34
|
+
upstreams: Schema.Array(DescribedTarget),
|
|
35
|
+
/** Distinct event names this process has emitted since boot. */ published: Schema.Array(Schema.String),
|
|
36
|
+
/** The bus bindings this process actually made. */ subscriptions: Schema.Array(Schema.Unknown),
|
|
37
|
+
endpoints: Schema.Array(Schema.String)
|
|
38
|
+
});
|
|
39
|
+
const health = defineEndpoint({
|
|
40
|
+
name: 'health',
|
|
41
|
+
method: 'GET',
|
|
42
|
+
path: '/api/health',
|
|
43
|
+
success: HealthStatus,
|
|
44
|
+
errors: [],
|
|
45
|
+
guard: {
|
|
46
|
+
kind: 'public'
|
|
47
|
+
}
|
|
48
|
+
});
|
|
49
|
+
const live = defineEndpoint({
|
|
50
|
+
name: 'live',
|
|
51
|
+
method: 'GET',
|
|
52
|
+
path: '/api/health/live',
|
|
53
|
+
success: HealthStatus,
|
|
54
|
+
errors: [],
|
|
55
|
+
guard: {
|
|
56
|
+
kind: 'public'
|
|
57
|
+
}
|
|
58
|
+
});
|
|
59
|
+
const ready = defineEndpoint({
|
|
60
|
+
name: 'ready',
|
|
61
|
+
method: 'GET',
|
|
62
|
+
path: '/api/health/ready',
|
|
63
|
+
success: HealthStatus,
|
|
64
|
+
errors: [
|
|
65
|
+
NotReady
|
|
66
|
+
],
|
|
67
|
+
guard: {
|
|
68
|
+
kind: 'public'
|
|
69
|
+
}
|
|
70
|
+
});
|
|
71
|
+
const description = defineEndpoint({
|
|
72
|
+
name: 'description',
|
|
73
|
+
method: 'GET',
|
|
74
|
+
path: SERVICE_DESCRIPTION_PATH,
|
|
75
|
+
success: ServiceDescription,
|
|
76
|
+
errors: [],
|
|
77
|
+
guard: {
|
|
78
|
+
kind: 'fleet'
|
|
79
|
+
}
|
|
80
|
+
});
|
|
81
|
+
const openapi = defineEndpoint({
|
|
82
|
+
name: 'openapi',
|
|
83
|
+
method: 'GET',
|
|
84
|
+
path: OPENAPI_PATH,
|
|
85
|
+
success: JsonBody,
|
|
86
|
+
errors: [],
|
|
87
|
+
guard: {
|
|
88
|
+
kind: 'fleet'
|
|
89
|
+
}
|
|
90
|
+
});
|
|
91
|
+
const READY_CACHE_MS = 1000;
|
|
92
|
+
/**
|
|
93
|
+
* The endpoints every service serves: liveness, readiness, and — behind the
|
|
94
|
+
* fleet token — its wiring document and its OpenAPI document. The wiring
|
|
95
|
+
* document names every store, exchange and upstream, and an unguarded
|
|
96
|
+
* reconnaissance map is worse than none, so a service with no token serves
|
|
97
|
+
* neither.
|
|
98
|
+
*/ export const serviceGroup = (options)=>{
|
|
99
|
+
// One cache per server instance (the e2e mock profile boots services
|
|
100
|
+
// in-process, so a module-level cache would leak across them).
|
|
101
|
+
const cache = Ref.makeUnsafe(null);
|
|
102
|
+
const cachedReport = Effect.gen(function*() {
|
|
103
|
+
const now = Date.now();
|
|
104
|
+
const entry = yield* Ref.get(cache);
|
|
105
|
+
if (entry !== null && now - entry.at < READY_CACHE_MS) return entry.report;
|
|
106
|
+
const registry = yield* HealthRegistryTag;
|
|
107
|
+
const report = yield* registry.report;
|
|
108
|
+
yield* Ref.set(cache, {
|
|
109
|
+
at: now,
|
|
110
|
+
report
|
|
111
|
+
});
|
|
112
|
+
return report;
|
|
113
|
+
});
|
|
114
|
+
const always = [
|
|
115
|
+
implement(health, ()=>Effect.succeed({
|
|
116
|
+
status: 'ok',
|
|
117
|
+
service: options.service
|
|
118
|
+
})),
|
|
119
|
+
implement(live, ()=>Effect.succeed({
|
|
120
|
+
status: 'live',
|
|
121
|
+
service: options.service
|
|
122
|
+
})),
|
|
123
|
+
implement(ready, ()=>Effect.gen(function*() {
|
|
124
|
+
const shutdown = yield* ShutdownRegistryTag;
|
|
125
|
+
// Ahead of the cache, deliberately: a report cached a moment before
|
|
126
|
+
// the signal landed would go on answering `200` for up to
|
|
127
|
+
// READY_CACHE_MS, which is precisely the window a rolling restart
|
|
128
|
+
// lives in.
|
|
129
|
+
if (yield* shutdown.terminating) return yield* Effect.fail(new NotReady({
|
|
130
|
+
service: options.service,
|
|
131
|
+
terminating: true,
|
|
132
|
+
failing: []
|
|
133
|
+
}));
|
|
134
|
+
const report = yield* cachedReport;
|
|
135
|
+
if (!report.ready) return yield* Effect.fail(new NotReady({
|
|
136
|
+
service: options.service,
|
|
137
|
+
terminating: false,
|
|
138
|
+
failing: report.failing
|
|
139
|
+
}));
|
|
140
|
+
return {
|
|
141
|
+
status: 'ready',
|
|
142
|
+
service: options.service
|
|
143
|
+
};
|
|
144
|
+
}))
|
|
145
|
+
];
|
|
146
|
+
if (!options.described) return endpointGroup('service', ...always);
|
|
147
|
+
return endpointGroup('service', ...always, implement(description, ()=>Effect.gen(function*() {
|
|
148
|
+
const registry = yield* HealthRegistryTag;
|
|
149
|
+
const wiring = yield* WiringRegistryTag;
|
|
150
|
+
const probes = yield* registry.probes;
|
|
151
|
+
const ofKind = (kind)=>probes.filter((probe)=>probe.kind === kind).flatMap((probe)=>probe.targets.map((name)=>({
|
|
152
|
+
name,
|
|
153
|
+
probe: probe.name
|
|
154
|
+
})));
|
|
155
|
+
return {
|
|
156
|
+
service: options.service,
|
|
157
|
+
slices: options.slices,
|
|
158
|
+
stores: ofKind('datastore'),
|
|
159
|
+
brokers: ofKind('broker'),
|
|
160
|
+
upstreams: ofKind('upstream'),
|
|
161
|
+
published: yield* wiring.published,
|
|
162
|
+
subscriptions: yield* wiring.subscriptions,
|
|
163
|
+
endpoints: options.endpoints()
|
|
164
|
+
};
|
|
165
|
+
})), implement(openapi, ()=>Effect.sync(()=>OpenApi.fromApi(options.api()))));
|
|
166
|
+
};
|
|
167
|
+
|
|
168
|
+
//# sourceMappingURL=service-group.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/http-api/service-group.ts"],"sourcesContent":["import {\n type BoundSubscription,\n HealthRegistryTag,\n type HealthReport,\n type ProbeKind,\n ShutdownRegistryTag,\n WiringRegistryTag,\n} from '@entifix/business';\nimport {\n type AnyEndpoint,\n defineEndpoint,\n Failure,\n implement,\n JsonBody,\n} from '@entifix/core';\nimport { Effect, Ref, Schema } from 'effect';\nimport type { HttpApi } from 'effect/http-api';\nimport { OpenApi } from 'effect/http-api';\n\nimport { type EndpointGroup, endpointGroup } from './build-api.js';\n\nexport const SERVICE_DESCRIPTION_PATH = '/api/$service';\nexport const OPENAPI_PATH = '/api/$openapi';\n\n/**\n * A service that is up but cannot serve yet — a probe failing, or the process\n * draining. `503`, so an orchestrator stops routing to it; the failing probe\n * names ride on the problem.\n */\nexport class NotReady extends Failure.unavailable<NotReady>()(\n 'NotReady',\n 'notReady',\n {\n service: Schema.String,\n terminating: Schema.Boolean,\n failing: Schema.Array(Schema.String),\n },\n) {}\n\nconst HealthStatus = Schema.Struct({\n status: Schema.String,\n service: Schema.String,\n});\n\nconst DescribedTarget = Schema.Struct({\n /** The Store's register name, an exchange, or a service. Never a URI. */\n name: Schema.String,\n /** The readiness probe that covers it, so the two documents line up. */\n probe: Schema.String,\n});\n\n/**\n * What a service says it does — the document a register diffs the service\n * against. `endpoints` is every `METHOD /path` the built API serves.\n */\nexport const ServiceDescription = Schema.Struct({\n service: Schema.String,\n /** The slices this process hosts; more than one means co-deployment. */\n slices: Schema.Array(Schema.String),\n stores: Schema.Array(DescribedTarget),\n brokers: Schema.Array(DescribedTarget),\n upstreams: Schema.Array(DescribedTarget),\n /** Distinct event names this process has emitted since boot. */\n published: Schema.Array(Schema.String),\n /** The bus bindings this process actually made. */\n subscriptions: Schema.Array(Schema.Unknown),\n endpoints: Schema.Array(Schema.String),\n});\nexport type ServiceDescription = Omit<\n typeof ServiceDescription.Type,\n 'subscriptions'\n> & { readonly subscriptions: readonly BoundSubscription[] };\n\nconst health = defineEndpoint({\n name: 'health',\n method: 'GET',\n path: '/api/health',\n success: HealthStatus,\n errors: [],\n guard: { kind: 'public' },\n});\n\nconst live = defineEndpoint({\n name: 'live',\n method: 'GET',\n path: '/api/health/live',\n success: HealthStatus,\n errors: [],\n guard: { kind: 'public' },\n});\n\nconst ready = defineEndpoint({\n name: 'ready',\n method: 'GET',\n path: '/api/health/ready',\n success: HealthStatus,\n errors: [NotReady],\n guard: { kind: 'public' },\n});\n\nconst description = defineEndpoint({\n name: 'description',\n method: 'GET',\n path: SERVICE_DESCRIPTION_PATH,\n success: ServiceDescription,\n errors: [],\n guard: { kind: 'fleet' },\n});\n\nconst openapi = defineEndpoint({\n name: 'openapi',\n method: 'GET',\n path: OPENAPI_PATH,\n success: JsonBody,\n errors: [],\n guard: { kind: 'fleet' },\n});\n\nconst READY_CACHE_MS = 1_000;\n\ninterface CacheEntry {\n readonly at: number;\n readonly report: HealthReport;\n}\n\nexport interface ServiceGroupOptions {\n readonly service: string;\n readonly slices: readonly string[];\n /** Mount `$service` and `$openapi`; absent means neither is served. */\n readonly described: boolean;\n /** Every `METHOD /path` the service serves, for `$service`. */\n readonly endpoints: () => readonly string[];\n /** The built API, for `$openapi`; read after it is built. */\n readonly api: () => HttpApi.Top;\n}\n\n/**\n * The endpoints every service serves: liveness, readiness, and — behind the\n * fleet token — its wiring document and its OpenAPI document. The wiring\n * document names every store, exchange and upstream, and an unguarded\n * reconnaissance map is worse than none, so a service with no token serves\n * neither.\n */\nexport const serviceGroup = (\n options: ServiceGroupOptions,\n): EndpointGroup<\n AnyEndpoint,\n HealthRegistryTag | ShutdownRegistryTag | WiringRegistryTag\n> => {\n // One cache per server instance (the e2e mock profile boots services\n // in-process, so a module-level cache would leak across them).\n const cache = Ref.makeUnsafe<CacheEntry | null>(null);\n\n const cachedReport = Effect.gen(function* () {\n const now = Date.now();\n const entry = yield* Ref.get(cache);\n if (entry !== null && now - entry.at < READY_CACHE_MS) return entry.report;\n\n const registry = yield* HealthRegistryTag;\n const report = yield* registry.report;\n yield* Ref.set(cache, { at: now, report });\n return report;\n });\n\n const always = [\n implement(health, () =>\n Effect.succeed({ status: 'ok', service: options.service }),\n ),\n implement(live, () =>\n Effect.succeed({ status: 'live', service: options.service }),\n ),\n implement(ready, () =>\n Effect.gen(function* () {\n const shutdown = yield* ShutdownRegistryTag;\n // Ahead of the cache, deliberately: a report cached a moment before\n // the signal landed would go on answering `200` for up to\n // READY_CACHE_MS, which is precisely the window a rolling restart\n // lives in.\n if (yield* shutdown.terminating)\n return yield* Effect.fail(\n new NotReady({\n service: options.service,\n terminating: true,\n failing: [],\n }),\n );\n const report = yield* cachedReport;\n if (!report.ready)\n return yield* Effect.fail(\n new NotReady({\n service: options.service,\n terminating: false,\n failing: report.failing,\n }),\n );\n return { status: 'ready', service: options.service };\n }),\n ),\n ];\n\n if (!options.described) return endpointGroup('service', ...always);\n\n return endpointGroup(\n 'service',\n ...always,\n implement(description, () =>\n Effect.gen(function* () {\n const registry = yield* HealthRegistryTag;\n const wiring = yield* WiringRegistryTag;\n const probes = yield* registry.probes;\n\n const ofKind = (kind: ProbeKind) =>\n probes\n .filter(probe => probe.kind === kind)\n .flatMap(probe =>\n probe.targets.map(name => ({ name, probe: probe.name })),\n );\n\n return {\n service: options.service,\n slices: options.slices,\n stores: ofKind('datastore'),\n brokers: ofKind('broker'),\n upstreams: ofKind('upstream'),\n published: yield* wiring.published,\n subscriptions: yield* wiring.subscriptions,\n endpoints: options.endpoints(),\n };\n }),\n ),\n implement(openapi, () =>\n Effect.sync(() => OpenApi.fromApi(options.api() as never)),\n ),\n );\n};\n"],"names":["HealthRegistryTag","ShutdownRegistryTag","WiringRegistryTag","defineEndpoint","Failure","implement","JsonBody","Effect","Ref","Schema","OpenApi","endpointGroup","SERVICE_DESCRIPTION_PATH","OPENAPI_PATH","NotReady","unavailable","service","String","terminating","Boolean","failing","Array","HealthStatus","Struct","status","DescribedTarget","name","probe","ServiceDescription","slices","stores","brokers","upstreams","published","subscriptions","Unknown","endpoints","health","method","path","success","errors","guard","kind","live","ready","description","openapi","READY_CACHE_MS","serviceGroup","options","cache","makeUnsafe","cachedReport","gen","now","Date","entry","get","at","report","registry","set","always","succeed","shutdown","fail","described","wiring","probes","ofKind","filter","flatMap","targets","map","sync","fromApi","api"],"mappings":"AAAA,SAEEA,iBAAiB,EAGjBC,mBAAmB,EACnBC,iBAAiB,QACZ,oBAAoB;AAC3B,SAEEC,cAAc,EACdC,OAAO,EACPC,SAAS,EACTC,QAAQ,QACH,gBAAgB;AACvB,SAASC,MAAM,EAAEC,GAAG,EAAEC,MAAM,QAAQ,SAAS;AAE7C,SAASC,OAAO,QAAQ,kBAAkB;AAE1C,SAA6BC,aAAa,QAAQ,iBAAiB;AAEnE,OAAO,MAAMC,2BAA2B,gBAAgB;AACxD,OAAO,MAAMC,eAAe,gBAAgB;AAE5C;;;;CAIC,GACD,OAAO,MAAMC,iBAAiBV,QAAQW,WAAW,GAC/C,YACA,YACA;IACEC,SAASP,OAAOQ,MAAM;IACtBC,aAAaT,OAAOU,OAAO;IAC3BC,SAASX,OAAOY,KAAK,CAACZ,OAAOQ,MAAM;AACrC;AACC;AAEH,MAAMK,eAAeb,OAAOc,MAAM,CAAC;IACjCC,QAA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