@decohere/core 0.0.1-dev.20261106.217 → 0.0.1-dev.20261106.228
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/es6/src/composition/index.js +33 -1
- package/es6/src/hosting/app.js +147 -0
- package/es6/src/hosting/builder.js +91 -0
- package/es6/src/hosting/const.js +3 -0
- package/es6/src/hosting/hosted-service-host.js +81 -0
- package/es6/src/hosting/hosted-service.js +8 -0
- package/es6/src/hosting/index.js +6 -0
- package/es6/src/hosting/readiness.types.js +4 -0
- package/package.json +6 -2
- package/types/src/composition/index.d.ts +31 -1
- package/types/src/hosting/app.d.ts +52 -0
- package/types/src/hosting/builder.d.ts +45 -0
- package/types/src/hosting/const.d.ts +4 -0
- package/types/src/hosting/hosted-service-host.d.ts +37 -0
- package/types/src/hosting/hosted-service.d.ts +31 -0
- package/types/src/hosting/index.d.ts +6 -0
- package/types/src/hosting/readiness.types.d.ts +14 -0
|
@@ -1 +1,33 @@
|
|
|
1
|
-
|
|
1
|
+
import { defineMeta, getMeta } from "../reflection/index.js";
|
|
2
|
+
/** Resolves to the scope that is resolving: inject it to resolve services later. */ export const LifetimeScopeToken = Symbol("LifetimeScope");
|
|
3
|
+
export const ContainerMeta = {
|
|
4
|
+
injecttoken: "Container:injecttoken"
|
|
5
|
+
};
|
|
6
|
+
/**
|
|
7
|
+
* Bind a constructor parameter to a registration key. Keys match by identity: a class matches only
|
|
8
|
+
* itself (not a string of its name), and a symbol only itself. Prefer the class; use a symbol for an
|
|
9
|
+
* interface or several implementations. `@inject(SomeClass)` also keeps SomeClass's import, which
|
|
10
|
+
* a parameter used only as a type can lose (its run-time type then collapses to `Object`).
|
|
11
|
+
*/ export function inject(key) {
|
|
12
|
+
return updateToken((token)=>({
|
|
13
|
+
...token,
|
|
14
|
+
key
|
|
15
|
+
}));
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* Mark a constructor parameter as optional: when nothing is registered for it, the container
|
|
19
|
+
* passes `undefined` (so a default value applies) instead of throwing.
|
|
20
|
+
*/ export function optional() {
|
|
21
|
+
return updateToken((token)=>({
|
|
22
|
+
...token,
|
|
23
|
+
optional: true
|
|
24
|
+
}));
|
|
25
|
+
}
|
|
26
|
+
function updateToken(update) {
|
|
27
|
+
return (target, _propertyKey, idx)=>{
|
|
28
|
+
// Copy: the metadata can be inherited from a base class, which must not change.
|
|
29
|
+
const metadata = new Map(getMeta(ContainerMeta.injecttoken, target));
|
|
30
|
+
metadata.set(idx, update(metadata.get(idx)));
|
|
31
|
+
defineMeta(ContainerMeta.injecttoken, metadata, target);
|
|
32
|
+
};
|
|
33
|
+
}
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
function _ts_decorate(decorators, target, key, desc) {
|
|
2
|
+
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
3
|
+
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
4
|
+
else for(var i = decorators.length - 1; i >= 0; i--)if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
|
5
|
+
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
6
|
+
}
|
|
7
|
+
function _ts_metadata(k, v) {
|
|
8
|
+
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
|
|
9
|
+
}
|
|
10
|
+
function _ts_param(paramIndex, decorator) {
|
|
11
|
+
return function(target, key) {
|
|
12
|
+
decorator(target, key, paramIndex);
|
|
13
|
+
};
|
|
14
|
+
}
|
|
15
|
+
import { scribe } from "@decohere/scribe";
|
|
16
|
+
import { inject, LifetimeScopeToken, optional } from "../composition/index.js";
|
|
17
|
+
import { ConfigurationServiceToken } from "../configuration/index.js";
|
|
18
|
+
import { AppServerToken, HostedServiceHostToken } from "./const.js";
|
|
19
|
+
const DEFAULT_PORT = 3000;
|
|
20
|
+
const DEFAULT_SHUTDOWN_SIGNALS = [
|
|
21
|
+
"SIGTERM",
|
|
22
|
+
"SIGINT"
|
|
23
|
+
];
|
|
24
|
+
const DEFAULT_SHUTDOWN_TIMEOUT_MS = 10_000;
|
|
25
|
+
export class ApiConfiguration {
|
|
26
|
+
port;
|
|
27
|
+
}
|
|
28
|
+
export class App {
|
|
29
|
+
container;
|
|
30
|
+
configurationService;
|
|
31
|
+
server;
|
|
32
|
+
hostedServices;
|
|
33
|
+
_addresses = Array.of();
|
|
34
|
+
logger = scribe.logger(App.name);
|
|
35
|
+
disposing;
|
|
36
|
+
disposingContainer = false;
|
|
37
|
+
signalHandler;
|
|
38
|
+
shutdownSignals = [];
|
|
39
|
+
constructor(container, configurationService, server, hostedServices){
|
|
40
|
+
this.container = container;
|
|
41
|
+
this.configurationService = configurationService;
|
|
42
|
+
this.server = server;
|
|
43
|
+
this.hostedServices = hostedServices;
|
|
44
|
+
}
|
|
45
|
+
get addresses() {
|
|
46
|
+
return this._addresses;
|
|
47
|
+
}
|
|
48
|
+
async start(options) {
|
|
49
|
+
this.logger.info("Starting app");
|
|
50
|
+
// Before the server, so a request never reaches a service that has not started.
|
|
51
|
+
await this.hostedServices?.start(this.container);
|
|
52
|
+
// The app was stopped while a hosted service was still starting.
|
|
53
|
+
if (this.disposing != null) return undefined;
|
|
54
|
+
const hasHostedServices = this.hostedServices != null && !this.hostedServices.isEmpty;
|
|
55
|
+
if (!this.server) {
|
|
56
|
+
if (hasHostedServices) this.stopOnSignals(options);
|
|
57
|
+
return undefined;
|
|
58
|
+
}
|
|
59
|
+
const port = await this.getPort(options);
|
|
60
|
+
this.logger.info(`Starting server on port ${port}`);
|
|
61
|
+
const startResponse = await this.server.start({
|
|
62
|
+
port,
|
|
63
|
+
...options?.host != null ? {
|
|
64
|
+
host: options.host
|
|
65
|
+
} : {}
|
|
66
|
+
});
|
|
67
|
+
this._addresses = [
|
|
68
|
+
...startResponse.addresses
|
|
69
|
+
];
|
|
70
|
+
this.logger.info("Listening on:", this._addresses);
|
|
71
|
+
this.stopOnSignals(options);
|
|
72
|
+
return startResponse;
|
|
73
|
+
}
|
|
74
|
+
[Symbol.asyncDispose]() {
|
|
75
|
+
// The container holds this App too; when stop() disposes the container it lands
|
|
76
|
+
// here, and awaiting our own shutdown would deadlock.
|
|
77
|
+
if (this.disposingContainer) return Promise.resolve();
|
|
78
|
+
return this.dispose();
|
|
79
|
+
}
|
|
80
|
+
/** Stop the app. Calling it again (or from a signal) returns the same shutdown. */ dispose() {
|
|
81
|
+
this.disposing ??= this.stop();
|
|
82
|
+
return this.disposing;
|
|
83
|
+
}
|
|
84
|
+
async stop() {
|
|
85
|
+
// Removed first, so a second Ctrl+C / SIGTERM gets Node's default: exit now.
|
|
86
|
+
this.removeSignalHandlers();
|
|
87
|
+
this.logger.info("Stopping");
|
|
88
|
+
// Hosted services hear the signal at once, so background work winds down while the server drains.
|
|
89
|
+
this.hostedServices?.abort();
|
|
90
|
+
try {
|
|
91
|
+
// The server first: in-flight requests still need the services (DB pools etc.) that
|
|
92
|
+
// disposing the container would close.
|
|
93
|
+
await this.server?.stop();
|
|
94
|
+
// Hosted services next, while what they use is still open.
|
|
95
|
+
await this.hostedServices?.stop();
|
|
96
|
+
} finally{
|
|
97
|
+
this.disposingContainer = true;
|
|
98
|
+
await this.container[Symbol.asyncDispose]();
|
|
99
|
+
await scribe.stop();
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
stopOnSignals(options) {
|
|
103
|
+
const signals = options?.shutdownSignals ?? DEFAULT_SHUTDOWN_SIGNALS;
|
|
104
|
+
const timeoutMs = options?.shutdownTimeoutMs ?? DEFAULT_SHUTDOWN_TIMEOUT_MS;
|
|
105
|
+
if (signals === false || signals.length === 0) return;
|
|
106
|
+
this.signalHandler = (signal)=>{
|
|
107
|
+
this.logger.info(`Received ${signal}; finishing in-flight requests`);
|
|
108
|
+
// console.error, not the logger: scribe may be the thing that's stuck.
|
|
109
|
+
const timer = setTimeout(()=>{
|
|
110
|
+
console.error(`Shutdown did not finish within ${timeoutMs}ms; exiting.`);
|
|
111
|
+
process.exit(1);
|
|
112
|
+
}, timeoutMs);
|
|
113
|
+
timer.unref();
|
|
114
|
+
this.dispose().then(()=>clearTimeout(timer), (error)=>{
|
|
115
|
+
clearTimeout(timer);
|
|
116
|
+
console.error("Shutdown failed:", error);
|
|
117
|
+
process.exit(1);
|
|
118
|
+
});
|
|
119
|
+
};
|
|
120
|
+
this.shutdownSignals = signals;
|
|
121
|
+
for (const signal of signals)process.on(signal, this.signalHandler);
|
|
122
|
+
}
|
|
123
|
+
removeSignalHandlers() {
|
|
124
|
+
if (!this.signalHandler) return;
|
|
125
|
+
for (const signal of this.shutdownSignals)process.off(signal, this.signalHandler);
|
|
126
|
+
}
|
|
127
|
+
async getPort(options) {
|
|
128
|
+
const port = options?.port ?? (await this.configurationService?.get(ApiConfiguration))?.port ?? DEFAULT_PORT;
|
|
129
|
+
return port;
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
App = _ts_decorate([
|
|
133
|
+
_ts_param(0, inject(LifetimeScopeToken)),
|
|
134
|
+
_ts_param(1, inject(ConfigurationServiceToken)),
|
|
135
|
+
_ts_param(1, optional()),
|
|
136
|
+
_ts_param(2, inject(AppServerToken)),
|
|
137
|
+
_ts_param(2, optional()),
|
|
138
|
+
_ts_param(3, inject(HostedServiceHostToken)),
|
|
139
|
+
_ts_param(3, optional()),
|
|
140
|
+
_ts_metadata("design:type", Function),
|
|
141
|
+
_ts_metadata("design:paramtypes", [
|
|
142
|
+
typeof LifetimeScope === "undefined" ? Object : LifetimeScope,
|
|
143
|
+
typeof IConfigurationService === "undefined" ? Object : IConfigurationService,
|
|
144
|
+
typeof AppServer === "undefined" ? Object : AppServer,
|
|
145
|
+
typeof HostedServiceHost === "undefined" ? Object : HostedServiceHost
|
|
146
|
+
])
|
|
147
|
+
], App);
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
import { scribe } from "@decohere/scribe";
|
|
2
|
+
import { ConfigurationServiceToken } from "../configuration/index.js";
|
|
3
|
+
import { App } from "./app.js";
|
|
4
|
+
import { HostedServiceHostToken } from "./const.js";
|
|
5
|
+
import { HostedServiceHost } from "./hosted-service-host.js";
|
|
6
|
+
export class Builder {
|
|
7
|
+
/**
|
|
8
|
+
* @param containerBuilder The container the app runs on: `new ServiceContainerBuilder()` from
|
|
9
|
+
* `@decohere/crucible`. It is an argument because `core` sits below the container that implements it.
|
|
10
|
+
*/ static create(containerBuilder, options) {
|
|
11
|
+
return new Builder(containerBuilder, options);
|
|
12
|
+
}
|
|
13
|
+
containerBuilder;
|
|
14
|
+
applicationName;
|
|
15
|
+
logger = scribe.logger(Builder.name);
|
|
16
|
+
userServices = [];
|
|
17
|
+
preBuildSteps = [];
|
|
18
|
+
postBuildSteps = [];
|
|
19
|
+
hostedServices = new HostedServiceHost();
|
|
20
|
+
constructor(containerBuilder, options){
|
|
21
|
+
this.containerBuilder = containerBuilder;
|
|
22
|
+
this.applicationName = options?.applicationName;
|
|
23
|
+
}
|
|
24
|
+
use(plugin) {
|
|
25
|
+
plugin(this);
|
|
26
|
+
return this;
|
|
27
|
+
}
|
|
28
|
+
withServices(userServices) {
|
|
29
|
+
this.userServices.push(userServices);
|
|
30
|
+
return this;
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Run {@link HostedService}s for the life of the app: started in this order before the
|
|
34
|
+
* server listens, stopped in reverse when the app stops (including SIGTERM and Flux reboots).
|
|
35
|
+
* Each is registered as a singleton, so other services can inject it by its class.
|
|
36
|
+
*/ withHostedService(...types) {
|
|
37
|
+
for (const type of types)this.containerBuilder.registerSingleton(type);
|
|
38
|
+
this.hostedServices.add(...types);
|
|
39
|
+
return this;
|
|
40
|
+
}
|
|
41
|
+
registerPreBuildStep(step) {
|
|
42
|
+
this.preBuildSteps.push(step);
|
|
43
|
+
}
|
|
44
|
+
registerPostBuildStep(step) {
|
|
45
|
+
this.postBuildSteps.push(step);
|
|
46
|
+
}
|
|
47
|
+
async buildAndStart(type) {
|
|
48
|
+
const app = await this.build(type);
|
|
49
|
+
await app.start();
|
|
50
|
+
this.logger.info("App started...");
|
|
51
|
+
return app;
|
|
52
|
+
}
|
|
53
|
+
async build(type) {
|
|
54
|
+
this.logger.info("Building App...");
|
|
55
|
+
this.configureUserServices();
|
|
56
|
+
this.configureApp(type);
|
|
57
|
+
await this.runPreBuildSteps(this.containerBuilder);
|
|
58
|
+
const container = this.containerBuilder.build();
|
|
59
|
+
await this.runPostBuildSteps(container);
|
|
60
|
+
const app = this.resolveApp(container, type);
|
|
61
|
+
return app;
|
|
62
|
+
}
|
|
63
|
+
configureUserServices() {
|
|
64
|
+
for (const userService of this.userServices){
|
|
65
|
+
userService(this.containerBuilder);
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
async runPreBuildSteps(containerBuilder) {
|
|
69
|
+
if (this.preBuildSteps.length === 0) {
|
|
70
|
+
return;
|
|
71
|
+
}
|
|
72
|
+
const container = containerBuilder.build();
|
|
73
|
+
const config = container.resolve(ConfigurationServiceToken);
|
|
74
|
+
for (const step of this.preBuildSteps){
|
|
75
|
+
await step(config, containerBuilder);
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
async runPostBuildSteps(container) {
|
|
79
|
+
for (const step of this.postBuildSteps){
|
|
80
|
+
await step(container);
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
configureApp(type) {
|
|
84
|
+
this.containerBuilder.registerSingleton(HostedServiceHostToken, this.hostedServices);
|
|
85
|
+
this.containerBuilder.registerSingleton(type ?? App);
|
|
86
|
+
}
|
|
87
|
+
resolveApp(container, type) {
|
|
88
|
+
const app = type ? container.resolve(type) : container.resolve(App);
|
|
89
|
+
return app;
|
|
90
|
+
}
|
|
91
|
+
}
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
/** The {@link AppServer} the app starts last and stops first. Registered by a plugin such as `http`. */ export const AppServerToken = Symbol("AppServer");
|
|
2
|
+
export const HostedServiceHostToken = Symbol("HostedServiceHost");
|
|
3
|
+
export const ReadinessCheckToken = Symbol("ReadinessCheck");
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import { scribe } from "@decohere/scribe";
|
|
2
|
+
/**
|
|
3
|
+
* Starts and stops the app's {@link HostedService}s. One per app; `Builder.withHostedService`
|
|
4
|
+
* adds the types and `App` drives it.
|
|
5
|
+
*/ export class HostedServiceHost {
|
|
6
|
+
logger = scribe.logger(HostedServiceHost.name);
|
|
7
|
+
types = [];
|
|
8
|
+
controller = new AbortController();
|
|
9
|
+
/** In start order; stopped in reverse. */ started = [];
|
|
10
|
+
starting;
|
|
11
|
+
stopping;
|
|
12
|
+
add(...types) {
|
|
13
|
+
this.types.push(...types);
|
|
14
|
+
}
|
|
15
|
+
get isEmpty() {
|
|
16
|
+
return this.types.length === 0;
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* Start every service in registration order. If one throws, the ones already started are
|
|
20
|
+
* stopped and the error is rethrown. Stops launching more once {@link stop} has begun.
|
|
21
|
+
*/ start(container) {
|
|
22
|
+
this.starting ??= this.startAll(container);
|
|
23
|
+
return this.starting;
|
|
24
|
+
}
|
|
25
|
+
/** Abort the services' signal: background work should wind down. {@link stop} does this too. */ abort() {
|
|
26
|
+
this.controller.abort();
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* Abort the signal, wait for a start still in progress, then stop the started services in
|
|
30
|
+
* reverse order. Every `stop()` runs even if one throws; the failures are rethrown after.
|
|
31
|
+
*/ stop() {
|
|
32
|
+
this.stopping ??= this.stopAll();
|
|
33
|
+
return this.stopping;
|
|
34
|
+
}
|
|
35
|
+
/** The started services that report readiness, for `GET /ready`. */ readinessChecks() {
|
|
36
|
+
return this.started.filter((service)=>typeof service.check === "function").map((service)=>({
|
|
37
|
+
name: service.constructor.name,
|
|
38
|
+
check: ()=>service.check?.() ?? Promise.resolve()
|
|
39
|
+
}));
|
|
40
|
+
}
|
|
41
|
+
async startAll(container) {
|
|
42
|
+
const { signal } = this.controller;
|
|
43
|
+
for (const type of this.types){
|
|
44
|
+
if (signal.aborted) return;
|
|
45
|
+
const service = container.resolve(type);
|
|
46
|
+
try {
|
|
47
|
+
await service.start(signal);
|
|
48
|
+
} catch (error) {
|
|
49
|
+
this.logger.error(`Hosted service ${type.name} failed to start`, error);
|
|
50
|
+
// Not stop(): it waits for this start to settle.
|
|
51
|
+
this.controller.abort();
|
|
52
|
+
await this.stopStarted().catch(()=>{});
|
|
53
|
+
throw error;
|
|
54
|
+
}
|
|
55
|
+
this.started.push(service);
|
|
56
|
+
this.logger.debug(`Hosted service ${type.name} started`);
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
async stopAll() {
|
|
60
|
+
this.controller.abort();
|
|
61
|
+
await Promise.allSettled([
|
|
62
|
+
this.starting
|
|
63
|
+
]);
|
|
64
|
+
await this.stopStarted();
|
|
65
|
+
}
|
|
66
|
+
/** Stop what is started, newest first. Takes each service off the list, so it runs once. */ async stopStarted() {
|
|
67
|
+
const failures = [];
|
|
68
|
+
for(let service = this.started.pop(); service != null; service = this.started.pop()){
|
|
69
|
+
try {
|
|
70
|
+
await service.stop?.();
|
|
71
|
+
} catch (error) {
|
|
72
|
+
this.logger.error(`Hosted service ${service.constructor.name} failed to stop`, error);
|
|
73
|
+
failures.push(error);
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
if (failures.length === 1) throw failures[0];
|
|
77
|
+
if (failures.length > 1) {
|
|
78
|
+
throw new AggregateError(failures, `${failures.length} hosted services failed to stop`);
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Work that runs for the life of the app outside a request: a feed, a poller, a queue consumer.
|
|
3
|
+
* Register it with `builder.withHostedService(Type)`; it is a singleton, so other services can
|
|
4
|
+
* inject it by its class.
|
|
5
|
+
*
|
|
6
|
+
* The app starts hosted services in registration order before the HTTP server listens, and stops
|
|
7
|
+
* them in reverse order when it stops (`app.dispose()`, SIGTERM or SIGINT, a Flux reboot).
|
|
8
|
+
*/ export { };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@decohere/core",
|
|
3
|
-
"version": "0.0.1-dev.20261106.
|
|
3
|
+
"version": "0.0.1-dev.20261106.228",
|
|
4
4
|
"description": "The runtime base every Decohere package builds on: reflection, composition, configuration types, extensibility, collections, objects, caching on a Map, and basic file IO. No side effects on import.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"typescript",
|
|
@@ -39,6 +39,10 @@
|
|
|
39
39
|
"types": "./types/src/extensibility/index.d.ts",
|
|
40
40
|
"import": "./es6/src/extensibility/index.js"
|
|
41
41
|
},
|
|
42
|
+
"./hosting": {
|
|
43
|
+
"types": "./types/src/hosting/index.d.ts",
|
|
44
|
+
"import": "./es6/src/hosting/index.js"
|
|
45
|
+
},
|
|
42
46
|
"./io": {
|
|
43
47
|
"types": "./types/src/io/index.d.ts",
|
|
44
48
|
"import": "./es6/src/io/index.js"
|
|
@@ -64,7 +68,7 @@
|
|
|
64
68
|
"test": "echo \"Error: no test specified\" && exit 1"
|
|
65
69
|
},
|
|
66
70
|
"dependencies": {
|
|
67
|
-
"@decohere/scribe": "0.0.1-dev.20261106.
|
|
71
|
+
"@decohere/scribe": "0.0.1-dev.20261106.228",
|
|
68
72
|
"reflect-metadata": "^0.2.2"
|
|
69
73
|
},
|
|
70
74
|
"devDependencies": {}
|
|
@@ -1,4 +1,34 @@
|
|
|
1
|
-
import type
|
|
1
|
+
import { type Constructable, type FunctionType } from "../reflection/index.js";
|
|
2
|
+
/** Resolves to the scope that is resolving: inject it to resolve services later. */
|
|
3
|
+
export declare const LifetimeScopeToken: unique symbol;
|
|
4
|
+
export declare const ContainerMeta: {
|
|
5
|
+
injecttoken: string;
|
|
6
|
+
};
|
|
7
|
+
/**
|
|
8
|
+
* What a service is registered and resolved under, compared by identity: the class (or factory)
|
|
9
|
+
* itself, a symbol, or a string. A string never matches a class with that name, and two symbols
|
|
10
|
+
* with the same description are different keys.
|
|
11
|
+
*/
|
|
12
|
+
export type ServiceKey = string | symbol | Constructable | FunctionType;
|
|
13
|
+
export type InjectionMetadata = Map<number, InjectionToken>;
|
|
14
|
+
export type InjectionToken = {
|
|
15
|
+
/** The key to resolve; without one, the parameter's type is the key. */
|
|
16
|
+
key?: ServiceKey;
|
|
17
|
+
/** Pass `undefined` instead of throwing when nothing is registered for the key. */
|
|
18
|
+
optional?: boolean;
|
|
19
|
+
};
|
|
20
|
+
/**
|
|
21
|
+
* Bind a constructor parameter to a registration key. Keys match by identity: a class matches only
|
|
22
|
+
* itself (not a string of its name), and a symbol only itself. Prefer the class; use a symbol for an
|
|
23
|
+
* interface or several implementations. `@inject(SomeClass)` also keeps SomeClass's import, which
|
|
24
|
+
* a parameter used only as a type can lose (its run-time type then collapses to `Object`).
|
|
25
|
+
*/
|
|
26
|
+
export declare function inject(key: ServiceKey): (target: object, _propertyKey: string | symbol | undefined, idx: number) => void;
|
|
27
|
+
/**
|
|
28
|
+
* Mark a constructor parameter as optional: when nothing is registered for it, the container
|
|
29
|
+
* passes `undefined` (so a default value applies) instead of throwing.
|
|
30
|
+
*/
|
|
31
|
+
export declare function optional(): (target: object, _propertyKey: string | symbol | undefined, idx: number) => void;
|
|
2
32
|
export type ResolveRequest<T extends object = object> = string | symbol | Constructable<T>;
|
|
3
33
|
export type Scope = "single-instance" | "request" | "transient";
|
|
4
34
|
export interface ServiceProvider {
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import { type LifetimeScope } from "../composition/index.js";
|
|
2
|
+
import { type IConfigurationService } from "../configuration/index.js";
|
|
3
|
+
import type { HostedServiceHost } from "./hosted-service-host.js";
|
|
4
|
+
export declare class ApiConfiguration {
|
|
5
|
+
port: number;
|
|
6
|
+
}
|
|
7
|
+
export type AppServerStartOptions = {
|
|
8
|
+
port: number;
|
|
9
|
+
host?: string;
|
|
10
|
+
};
|
|
11
|
+
export type AppServerStartResponse = {
|
|
12
|
+
addresses: string[];
|
|
13
|
+
};
|
|
14
|
+
/** What serves traffic, if anything does. The HTTP provider is one; a worker has none. */
|
|
15
|
+
export interface AppServer {
|
|
16
|
+
start(options: AppServerStartOptions): Promise<AppServerStartResponse>;
|
|
17
|
+
stop(): Promise<unknown>;
|
|
18
|
+
}
|
|
19
|
+
export type StartOptions = {
|
|
20
|
+
port: number;
|
|
21
|
+
host?: string;
|
|
22
|
+
/**
|
|
23
|
+
* Signals that stop the app gracefully: stop accepting connections, let in-flight
|
|
24
|
+
* requests finish, stop hosted services, then dispose services. Default SIGTERM and SIGINT; `false` to
|
|
25
|
+
* handle signals yourself.
|
|
26
|
+
*/
|
|
27
|
+
shutdownSignals?: readonly NodeJS.Signals[] | false;
|
|
28
|
+
/** How long a signalled shutdown may take before the process exits with code 1. Default 10s. */
|
|
29
|
+
shutdownTimeoutMs?: number;
|
|
30
|
+
};
|
|
31
|
+
export declare class App {
|
|
32
|
+
private readonly container;
|
|
33
|
+
private configurationService?;
|
|
34
|
+
private server?;
|
|
35
|
+
private hostedServices?;
|
|
36
|
+
private _addresses;
|
|
37
|
+
private logger;
|
|
38
|
+
private disposing;
|
|
39
|
+
private disposingContainer;
|
|
40
|
+
private signalHandler;
|
|
41
|
+
private shutdownSignals;
|
|
42
|
+
constructor(container: LifetimeScope, configurationService?: IConfigurationService, server?: AppServer, hostedServices?: HostedServiceHost);
|
|
43
|
+
get addresses(): readonly string[];
|
|
44
|
+
start(options?: StartOptions): Promise<AppServerStartResponse | undefined>;
|
|
45
|
+
[Symbol.asyncDispose](): Promise<void>;
|
|
46
|
+
/** Stop the app. Calling it again (or from a signal) returns the same shutdown. */
|
|
47
|
+
dispose(): Promise<void>;
|
|
48
|
+
private stop;
|
|
49
|
+
private stopOnSignals;
|
|
50
|
+
private removeSignalHandlers;
|
|
51
|
+
private getPort;
|
|
52
|
+
}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import type { ContainerBuilder, IContainer } from "../composition/index.js";
|
|
2
|
+
import { type IConfigurationService } from "../configuration/index.js";
|
|
3
|
+
import type { Constructable } from "../reflection/index.js";
|
|
4
|
+
import { App } from "./app.js";
|
|
5
|
+
import type { HostedService } from "./hosted-service.js";
|
|
6
|
+
export type BuilderOptions = {
|
|
7
|
+
applicationName?: string;
|
|
8
|
+
};
|
|
9
|
+
/**
|
|
10
|
+
* A feature an app adds with `builder.use(...)`, such as `http(...)` or `config(...)`. A plugin is
|
|
11
|
+
* a plain function: it registers what it needs on the builder it gets.
|
|
12
|
+
*/
|
|
13
|
+
export type BuilderPlugin = (builder: Builder) => void;
|
|
14
|
+
export declare class Builder<T extends App = App> {
|
|
15
|
+
/**
|
|
16
|
+
* @param containerBuilder The container the app runs on: `new ServiceContainerBuilder()` from
|
|
17
|
+
* `@decohere/crucible`. It is an argument because `core` sits below the container that implements it.
|
|
18
|
+
*/
|
|
19
|
+
static create<T extends App = App>(containerBuilder: ContainerBuilder, options?: BuilderOptions): Builder<T>;
|
|
20
|
+
readonly containerBuilder: ContainerBuilder;
|
|
21
|
+
readonly applicationName?: string;
|
|
22
|
+
private readonly logger;
|
|
23
|
+
private userServices;
|
|
24
|
+
private preBuildSteps;
|
|
25
|
+
private postBuildSteps;
|
|
26
|
+
private readonly hostedServices;
|
|
27
|
+
constructor(containerBuilder: ContainerBuilder, options?: BuilderOptions);
|
|
28
|
+
use(plugin: BuilderPlugin): this;
|
|
29
|
+
withServices(userServices: (containerBuilder: ContainerBuilder) => void): Builder<T>;
|
|
30
|
+
/**
|
|
31
|
+
* Run {@link HostedService}s for the life of the app: started in this order before the
|
|
32
|
+
* server listens, stopped in reverse when the app stops (including SIGTERM and Flux reboots).
|
|
33
|
+
* Each is registered as a singleton, so other services can inject it by its class.
|
|
34
|
+
*/
|
|
35
|
+
withHostedService(...types: Constructable<HostedService>[]): Builder<T>;
|
|
36
|
+
registerPreBuildStep(step: (config: IConfigurationService, containerBuilder: ContainerBuilder) => Promise<void> | void): void;
|
|
37
|
+
registerPostBuildStep(step: (container: IContainer) => Promise<void> | void): void;
|
|
38
|
+
buildAndStart<T extends App>(type?: Constructable<T>): Promise<T | App>;
|
|
39
|
+
build<T extends App = App>(type?: Constructable<T>): Promise<T | App>;
|
|
40
|
+
private configureUserServices;
|
|
41
|
+
private runPreBuildSteps;
|
|
42
|
+
private runPostBuildSteps;
|
|
43
|
+
private configureApp;
|
|
44
|
+
private resolveApp;
|
|
45
|
+
}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
/** The {@link AppServer} the app starts last and stops first. Registered by a plugin such as `http`. */
|
|
2
|
+
export declare const AppServerToken: unique symbol;
|
|
3
|
+
export declare const HostedServiceHostToken: unique symbol;
|
|
4
|
+
export declare const ReadinessCheckToken: unique symbol;
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import type { IContainer } from "../composition/index.js";
|
|
2
|
+
import type { Constructable } from "../reflection/index.js";
|
|
3
|
+
import type { IReadinessCheck } from "./readiness.types.js";
|
|
4
|
+
import type { HostedService } from "./hosted-service.js";
|
|
5
|
+
/**
|
|
6
|
+
* Starts and stops the app's {@link HostedService}s. One per app; `Builder.withHostedService`
|
|
7
|
+
* adds the types and `App` drives it.
|
|
8
|
+
*/
|
|
9
|
+
export declare class HostedServiceHost {
|
|
10
|
+
private readonly logger;
|
|
11
|
+
private readonly types;
|
|
12
|
+
private readonly controller;
|
|
13
|
+
/** In start order; stopped in reverse. */
|
|
14
|
+
private readonly started;
|
|
15
|
+
private starting;
|
|
16
|
+
private stopping;
|
|
17
|
+
add(...types: Constructable<HostedService>[]): void;
|
|
18
|
+
get isEmpty(): boolean;
|
|
19
|
+
/**
|
|
20
|
+
* Start every service in registration order. If one throws, the ones already started are
|
|
21
|
+
* stopped and the error is rethrown. Stops launching more once {@link stop} has begun.
|
|
22
|
+
*/
|
|
23
|
+
start(container: IContainer): Promise<void>;
|
|
24
|
+
/** Abort the services' signal: background work should wind down. {@link stop} does this too. */
|
|
25
|
+
abort(): void;
|
|
26
|
+
/**
|
|
27
|
+
* Abort the signal, wait for a start still in progress, then stop the started services in
|
|
28
|
+
* reverse order. Every `stop()` runs even if one throws; the failures are rethrown after.
|
|
29
|
+
*/
|
|
30
|
+
stop(): Promise<void>;
|
|
31
|
+
/** The started services that report readiness, for `GET /ready`. */
|
|
32
|
+
readinessChecks(): IReadinessCheck[];
|
|
33
|
+
private startAll;
|
|
34
|
+
private stopAll;
|
|
35
|
+
/** Stop what is started, newest first. Takes each service off the list, so it runs once. */
|
|
36
|
+
private stopStarted;
|
|
37
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Work that runs for the life of the app outside a request: a feed, a poller, a queue consumer.
|
|
3
|
+
* Register it with `builder.withHostedService(Type)`; it is a singleton, so other services can
|
|
4
|
+
* inject it by its class.
|
|
5
|
+
*
|
|
6
|
+
* The app starts hosted services in registration order before the HTTP server listens, and stops
|
|
7
|
+
* them in reverse order when it stops (`app.dispose()`, SIGTERM or SIGINT, a Flux reboot).
|
|
8
|
+
*/
|
|
9
|
+
export interface HostedService {
|
|
10
|
+
/**
|
|
11
|
+
* Called once when the app starts, and awaited: a throw fails `app.start()`. Do what must be
|
|
12
|
+
* ready before traffic, then start long work (a first load that takes minutes, a timer) in
|
|
13
|
+
* the background and return. Waiting for it here keeps the HTTP server dark.
|
|
14
|
+
*
|
|
15
|
+
* `signal` is aborted as soon as the app starts stopping, before `stop()` is called, also
|
|
16
|
+
* while `start()` itself is still running. Stop background work and clear timers on it.
|
|
17
|
+
*/
|
|
18
|
+
start(signal: AbortSignal): Promise<void> | void;
|
|
19
|
+
/**
|
|
20
|
+
* Called once when the app stops, after the HTTP server has drained and before the container
|
|
21
|
+
* is disposed, so the services it uses (a DataSource) are still open. Wait here for the
|
|
22
|
+
* background work to finish. Optional: a service with nothing to wait for can rely on the
|
|
23
|
+
* signal, or on `Symbol.asyncDispose`, which the container calls later.
|
|
24
|
+
*/
|
|
25
|
+
stop?(): Promise<void> | void;
|
|
26
|
+
/**
|
|
27
|
+
* Readiness while the service is started but still warming up: throw until it can serve, and
|
|
28
|
+
* `GET /ready` answers 503 (`health()`). Optional.
|
|
29
|
+
*/
|
|
30
|
+
check?(): Promise<void>;
|
|
31
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A dependency probe run by `GET /ready`.
|
|
3
|
+
* Register instances under {@link ReadinessCheckToken} (multi-inject).
|
|
4
|
+
*/
|
|
5
|
+
export interface IReadinessCheck {
|
|
6
|
+
readonly name: string;
|
|
7
|
+
check(): Promise<void>;
|
|
8
|
+
}
|
|
9
|
+
export type ReadinessResult = {
|
|
10
|
+
ok: true;
|
|
11
|
+
} | {
|
|
12
|
+
ok: false;
|
|
13
|
+
failures: string[];
|
|
14
|
+
};
|