@decohere/core 0.0.1-dev.20261120.333 → 0.0.1-dev.20261120.336

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.
@@ -15,7 +15,7 @@ function _ts_param(paramIndex, decorator) {
15
15
  import { scribe } from "@decohere/scribe";
16
16
  import { inject, LifetimeScopeToken, optional } from "../composition/index.js";
17
17
  import { ConfigurationServiceToken } from "../configuration/index.js";
18
- import { AppServerToken, HostedServiceHostToken, StartStepsToken } from "./const.js";
18
+ import { AppServerToken, HostedServiceHostToken } from "./const.js";
19
19
  const DEFAULT_PORT = 3000;
20
20
  const DEFAULT_SHUTDOWN_SIGNALS = [
21
21
  "SIGTERM",
@@ -41,7 +41,6 @@ export class App {
41
41
  configurationService;
42
42
  server;
43
43
  hostedServices;
44
- startSteps;
45
44
  _addresses = Array.of();
46
45
  logger = scribe.logger(App.name);
47
46
  disposing;
@@ -49,12 +48,11 @@ export class App {
49
48
  signalHandler;
50
49
  shutdownSignals = [];
51
50
  hostedStarting;
52
- constructor(container, configurationService, server, hostedServices, startSteps){
51
+ constructor(container, configurationService, server, hostedServices){
53
52
  this.container = container;
54
53
  this.configurationService = configurationService;
55
54
  this.server = server;
56
55
  this.hostedServices = hostedServices;
57
- this.startSteps = startSteps;
58
56
  }
59
57
  /**
60
58
  * The app's root container, for a tool or a test that builds the app to use its services
@@ -67,27 +65,27 @@ export class App {
67
65
  }
68
66
  async start(options) {
69
67
  this.logger.info("Starting app");
70
- for (const step of this.startSteps?.steps ?? []){
71
- await step(this.container);
72
- if (this.disposing != null) return undefined;
73
- }
68
+ const retry = options?.startRetry ?? {};
74
69
  if (options?.hostedServices === "after-listen") {
75
70
  const startResponse = await this.listen(options);
76
- if (this.disposing == null) this.hostedStarting = this.startHostedServicesAfterListen();
71
+ if (this.disposing == null) {
72
+ this.hostedStarting = this.startHostedServicesAfterListen(retry);
73
+ }
77
74
  return startResponse;
78
75
  }
79
76
  // Before the server, so a request never reaches a service that has not started.
80
- this.hostedStarting = this.startHostedServices();
77
+ this.hostedStarting = this.startHostedServices(retry);
81
78
  await this.hostedStarting;
82
79
  // The app was stopped while a hosted service was still starting.
83
80
  if (this.disposing != null) return undefined;
84
81
  return this.listen(options);
85
82
  }
86
83
  /**
87
- * Resolves once every hosted service has started, with how long each one took, in start order.
88
- * With `hostedServices: "after-listen"`, await it in `main.ts` after `start()`: a failure
89
- * rejects it, after the app has stopped. Left unawaited, that rejection is unhandled and ends
90
- * the process, as a failing `await app.start()` would.
84
+ * Resolves once every hosted service has started or is being retried, with how long each
85
+ * first start took, in start order. With `startRetry: false` and `hostedServices:
86
+ * "after-listen"`, await it in `main.ts` after `start()`: a failure rejects it, after the app
87
+ * has stopped. Left unawaited, that rejection is unhandled and ends the process, as a failing
88
+ * `await app.start()` would.
91
89
  */ hostedServicesStarted() {
92
90
  return this.hostedStarting ?? Promise.reject(new Error("hostedServicesStarted() before start()"));
93
91
  }
@@ -112,18 +110,24 @@ export class App {
112
110
  this.stopOnSignals(options);
113
111
  return startResponse;
114
112
  }
115
- async startHostedServices() {
113
+ async startHostedServices(retry) {
116
114
  const host = this.hostedServices;
117
115
  if (host == null || host.isEmpty) return [];
118
116
  const begun = performance.now();
119
- await host.start(this.container);
117
+ await host.start(this.container, retry);
120
118
  const timings = host.timings;
121
- this.logger.info(`Started ${timings.length} hosted services in ${Math.round(performance.now() - begun)} ms`);
119
+ const ms = Math.round(performance.now() - begun);
120
+ const retrying = timings.filter((t)=>!t.started).length;
121
+ const waiting = timings.length < host.size ? `; ${host.size - timings.length} waiting` : "";
122
+ this.logger.info(`Started ${timings.length - retrying} start steps and hosted services in ${ms} ms${retrying > 0 ? `; ${retrying} failed and are being retried` : ""}${waiting}`);
122
123
  return timings;
123
124
  }
124
- /** The server is already up, so a service that fails to start takes the app down with it. */ async startHostedServicesAfterListen() {
125
+ /**
126
+ * The server is already up. Without retries, a service that fails to start takes the app down
127
+ * with it.
128
+ */ async startHostedServicesAfterListen(retry) {
125
129
  try {
126
- return await this.startHostedServices();
130
+ return await this.startHostedServices(retry);
127
131
  } catch (startError) {
128
132
  try {
129
133
  await this.dispose();
@@ -202,14 +206,11 @@ App = _ts_decorate([
202
206
  _ts_param(2, optional()),
203
207
  _ts_param(3, inject(HostedServiceHostToken)),
204
208
  _ts_param(3, optional()),
205
- _ts_param(4, inject(StartStepsToken)),
206
- _ts_param(4, optional()),
207
209
  _ts_metadata("design:type", Function),
208
210
  _ts_metadata("design:paramtypes", [
209
211
  typeof LifetimeScope === "undefined" ? Object : LifetimeScope,
210
212
  typeof IConfigurationService === "undefined" ? Object : IConfigurationService,
211
213
  typeof AppServer === "undefined" ? Object : AppServer,
212
- typeof HostedServiceHost === "undefined" ? Object : HostedServiceHost,
213
- typeof StartSteps === "undefined" ? Object : StartSteps
214
+ typeof HostedServiceHost === "undefined" ? Object : HostedServiceHost
214
215
  ])
215
216
  ], App);
@@ -1,7 +1,7 @@
1
1
  import { scribe } from "@decohere/scribe";
2
2
  import { ConfigurationServiceToken } from "../configuration/index.js";
3
3
  import { App } from "./app.js";
4
- import { HostedServiceHostToken, StartStepsToken } from "./const.js";
4
+ import { HostedServiceHostToken } from "./const.js";
5
5
  import { HostedServiceHost } from "./hosted-service-host.js";
6
6
  export class Builder {
7
7
  /**
@@ -16,7 +16,6 @@ export class Builder {
16
16
  userServices = [];
17
17
  preBuildSteps = [];
18
18
  postBuildSteps = [];
19
- startSteps = [];
20
19
  hostedServices = new HostedServiceHost();
21
20
  constructor(containerBuilder, options){
22
21
  this.containerBuilder = containerBuilder;
@@ -46,12 +45,13 @@ export class Builder {
46
45
  this.postBuildSteps.push(step);
47
46
  }
48
47
  /**
49
- * Run `step` when the app starts, in registration order, before its hosted services start and
50
- * its server listens. For work that changes the world outside the process, such as bringing a
51
- * database's schema up to date: an app that is only built, by a tool or a test, does none of it.
52
- * A throw fails `app.start()`.
53
- */ registerStartStep(step) {
54
- this.startSteps.push(step);
48
+ * Run `step` when the app starts, in registration order, before its hosted services start. For
49
+ * work that changes the world outside the process, such as bringing a database's schema up to
50
+ * date: an app that is only built, by a tool or a test, does none of it. A throw is retried with
51
+ * the hosted services' backoff, and the hosted services wait until it succeeds (with
52
+ * `startRetry: false`, it fails `app.start()`). `name` is what logs and `/ready` call it.
53
+ */ registerStartStep(step, name) {
54
+ this.hostedServices.addStep(step, name);
55
55
  }
56
56
  async buildAndStart(type) {
57
57
  const app = await this.build(type);
@@ -91,9 +91,6 @@ export class Builder {
91
91
  }
92
92
  configureApp(type) {
93
93
  this.containerBuilder.registerSingleton(HostedServiceHostToken, this.hostedServices);
94
- this.containerBuilder.registerSingleton(StartStepsToken, {
95
- steps: this.startSteps
96
- });
97
94
  this.containerBuilder.registerSingleton(type ?? App);
98
95
  }
99
96
  resolveApp(container, type) {
@@ -1,4 +1,3 @@
1
1
  /** The {@link AppServer} the app starts last and stops first. Registered by a plugin such as `http`. */ export const AppServerToken = Symbol("AppServer");
2
2
  export const HostedServiceHostToken = Symbol("HostedServiceHost");
3
3
  export const ReadinessCheckToken = Symbol("ReadinessCheck");
4
- /** The {@link StartSteps} `App.start` runs before hosted services: `builder.registerStartStep`. */ export const StartStepsToken = Symbol("StartSteps");
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Something a request needs can't be reached right now: a database still connecting, or down
3
+ * while the app retries its start. HTTP answers `503 Service Unavailable`, without the reason,
4
+ * which is logged instead (it can name hosts).
5
+ */ export class DependencyUnavailableError extends Error {
6
+ dependency;
7
+ name = "DependencyUnavailableError";
8
+ /** `dependency` names what is missing, such as `data source "orders"`. */ constructor(dependency, reason, options){
9
+ super(reason == null ? `${dependency} is unavailable` : `${dependency} is unavailable: ${reason}`, options), this.dependency = dependency;
10
+ }
11
+ }
@@ -1,55 +1,86 @@
1
1
  import { scribe } from "@decohere/scribe";
2
+ const DEFAULT_RETRY_INITIAL_MS = 1_000;
3
+ const DEFAULT_RETRY_MAX_MS = 60_000;
2
4
  /**
3
- * Starts and stops the app's {@link HostedService}s. One per app; `Builder.withHostedService`
4
- * adds the types and `App` drives it.
5
+ * Starts and stops the app's start steps and {@link HostedService}s. One per app; the builder adds
6
+ * them (`registerStartStep`, `withHostedService`) and `App` drives it.
7
+ *
8
+ * Steps run first, in order, then services, in order. Either may throw: it is retried with
9
+ * backoff while the app runs. A failed step holds back everything after it until it succeeds,
10
+ * since what follows may need what it does (a database's migrations); a failed service holds back
11
+ * nothing.
5
12
  */ export class HostedServiceHost {
6
13
  logger = scribe.logger(HostedServiceHost.name);
14
+ steps = [];
7
15
  types = [];
8
16
  controller = new AbortController();
9
17
  /** In start order; stopped in reverse. */ started = [];
10
18
  _timings = [];
19
+ failing = new Map();
20
+ /** Background work (retries, and a start resumed after a step's retry), so a stop waits for it. */ background = new Set();
21
+ /** Starts running now: the first, and any resumed after a failed step's retry. */ running = 0;
11
22
  starting;
12
- startSettled = false;
13
23
  stopping;
14
24
  add(...types) {
15
25
  this.types.push(...types);
16
26
  }
27
+ /** Run `step` before every hosted service, after the steps added before it. */ addStep(step, name) {
28
+ const fallback = step.name || `start step ${this.steps.length + 1}`;
29
+ this.steps.push({
30
+ name: name ?? fallback,
31
+ run: step
32
+ });
33
+ }
34
+ /** How many steps and services there are. */ get size() {
35
+ return this.steps.length + this.types.length;
36
+ }
17
37
  get isEmpty() {
18
- return this.types.length === 0;
38
+ return this.types.length === 0 && this.steps.length === 0;
19
39
  }
20
40
  /**
21
- * Start every service in registration order. If one throws, the ones already started are
22
- * stopped and the error is rethrown. Stops launching more once {@link stop} has begun.
23
- */ start(container) {
24
- this.starting ??= this.startAll(container);
41
+ * Run the steps, then start the services, and resolve once each has started or, having thrown,
42
+ * is being retried in the background with `retry`'s backoff. With `retry: false`, a throw stops
43
+ * the services already started and is rethrown. Stops launching more once {@link stop} has
44
+ * begun.
45
+ */ start(container, retry = {}) {
46
+ this.starting ??= this.run(()=>this.startFrom(container, retry, 0));
25
47
  return this.starting;
26
48
  }
27
49
  /** Abort the services' signal: background work should wind down. {@link stop} does this too. */ abort() {
28
50
  this.controller.abort();
29
51
  }
30
52
  /**
31
- * Abort the signal, wait for a start still in progress, then stop the started services in
32
- * reverse order. Every `stop()` runs even if one throws; the failures are rethrown after.
53
+ * Abort the signal, wait for starts and retries still in progress, then stop the started
54
+ * services in reverse order. Every `stop()` runs even if one throws; the failures are rethrown
55
+ * after.
33
56
  */ stop() {
34
57
  this.stopping ??= this.stopAll();
35
58
  return this.stopping;
36
59
  }
37
- /** Each started service's start time, in start order. */ get timings() {
60
+ /** Each step's and service's first start, in start order. */ get timings() {
38
61
  return [
39
62
  ...this._timings
40
63
  ];
41
64
  }
42
65
  /**
43
66
  * For `GET /ready`: while a start is under way, one check that fails (the app listened before
44
- * its services started); then the started services that report readiness.
67
+ * its services started); one failing check per step or service being retried; then the
68
+ * started services that report readiness.
45
69
  */ readinessChecks() {
46
70
  const checks = [];
47
- if (this.starting != null && !this.startSettled) {
71
+ if (this.running > 0) {
48
72
  checks.push({
49
73
  name: "hosted services starting",
50
74
  check: ()=>Promise.reject(new Error("hosted services are still starting"))
51
75
  });
52
76
  }
77
+ for (const { name, error, waitMs } of this.failing.values()){
78
+ const reason = `failed to start, retrying within ${Math.round(waitMs * 1.2)} ms: ${describe(error)}`;
79
+ checks.push({
80
+ name,
81
+ check: ()=>Promise.reject(new Error(reason))
82
+ });
83
+ }
53
84
  for (const service of this.started){
54
85
  if (typeof service.check !== "function") continue;
55
86
  checks.push({
@@ -59,15 +90,35 @@ import { scribe } from "@decohere/scribe";
59
90
  }
60
91
  return checks;
61
92
  }
62
- async startAll(container) {
93
+ /** Counted in {@link running} while it runs, so `/ready` fails meanwhile. */ async run(start) {
94
+ this.running += 1;
63
95
  try {
64
- await this.startEach(container);
96
+ await start();
65
97
  } finally{
66
- this.startSettled = true;
98
+ this.running -= 1;
67
99
  }
68
100
  }
69
- async startEach(container) {
101
+ /** Run the steps from `stepIndex`, then start every service. */ async startFrom(container, retry, stepIndex) {
70
102
  const { signal } = this.controller;
103
+ for(let index = stepIndex; index < this.steps.length; index++){
104
+ if (signal.aborted) return;
105
+ const step = this.steps[index];
106
+ const begun = performance.now();
107
+ try {
108
+ await step.run(container);
109
+ } catch (error) {
110
+ this.record(step.name, begun, false);
111
+ if (retry === false) {
112
+ this.logger.error(`Start step ${step.name} failed`, error);
113
+ return this.failFast(error);
114
+ }
115
+ // What follows waits: it may need what this step does.
116
+ const resume = ()=>this.inBackground(this.run(()=>this.startFrom(container, retry, index + 1)));
117
+ this.retryLater(step, step.name, error, retry, ()=>step.run(container), resume);
118
+ return;
119
+ }
120
+ this.record(step.name, begun, true);
121
+ }
71
122
  for (const type of this.types){
72
123
  if (signal.aborted) return;
73
124
  const begun = performance.now();
@@ -75,26 +126,101 @@ import { scribe } from "@decohere/scribe";
75
126
  try {
76
127
  await service.start(signal);
77
128
  } catch (error) {
78
- this.logger.error(`Hosted service ${type.name} failed to start`, error);
79
- // Not stop(): it waits for this start to settle.
80
- this.controller.abort();
81
- await this.stopStarted().catch(()=>{});
82
- throw error;
129
+ this.record(type.name, begun, false);
130
+ if (retry === false) {
131
+ this.logger.error(`Hosted service ${type.name} failed to start`, error);
132
+ return this.failFast(error);
133
+ }
134
+ const attempt = ()=>service.start(signal);
135
+ // Pushed even if the app is stopping: the stop waits for this retry, then stops it.
136
+ const onStarted = ()=>this.started.push(service);
137
+ this.retryLater(service, type.name, error, retry, attempt, onStarted);
138
+ continue;
83
139
  }
84
140
  this.started.push(service);
85
- const ms = Math.round(performance.now() - begun);
86
- this._timings.push({
87
- name: type.name,
88
- ms
89
- });
90
- this.logger.debug(`Hosted service ${type.name} started in ${ms} ms`);
141
+ this.record(type.name, begun, true);
142
+ }
143
+ }
144
+ record(name, begun, started) {
145
+ const ms = Math.round(performance.now() - begun);
146
+ this._timings.push({
147
+ name,
148
+ ms,
149
+ started
150
+ });
151
+ if (started) this.logger.debug(`${name} started in ${ms} ms`);
152
+ }
153
+ /** Stop what started, then throw the start's error (with the stop's, if that failed too). */ async failFast(startError) {
154
+ // Not stop(): it waits for this start to settle.
155
+ this.controller.abort();
156
+ try {
157
+ await this.stopStarted();
158
+ } catch (stopError) {
159
+ throw new AggregateError([
160
+ startError,
161
+ stopError
162
+ ], "A hosted service failed to start, and stopping the ones already started failed too");
91
163
  }
164
+ throw startError;
165
+ }
166
+ /**
167
+ * Call `attempt` again with backoff until it succeeds, then `onStarted`. Listed in `/ready`
168
+ * meanwhile. Stops when the app stops.
169
+ */ retryLater(key, name, error, retry, attempt, onStarted) {
170
+ const { signal } = this.controller;
171
+ const maxMs = retry.maxMs ?? DEFAULT_RETRY_MAX_MS;
172
+ const initialMs = retry.initialMs ?? DEFAULT_RETRY_INITIAL_MS;
173
+ const failing = {
174
+ name,
175
+ error,
176
+ waitMs: initialMs
177
+ };
178
+ this.failing.set(key, failing);
179
+ this.logger.error(`${name} failed to start; retrying in about ${failing.waitMs} ms`, error);
180
+ const tryAgain = async ()=>{
181
+ try {
182
+ await attempt();
183
+ } catch (attemptError) {
184
+ failing.error = attemptError;
185
+ if (signal.aborted) {
186
+ this.failing.delete(key);
187
+ this.logger.warn(`${name} failed to start as the app stopped`, attemptError);
188
+ return;
189
+ }
190
+ failing.waitMs = Math.min(failing.waitMs * 2, maxMs);
191
+ this.logger.warn(`${name} still failing to start; retrying in about ${failing.waitMs} ms: ${describe(attemptError)}`);
192
+ schedule();
193
+ return;
194
+ }
195
+ this.failing.delete(key);
196
+ this.logger.info(`${name} started after retrying`);
197
+ onStarted();
198
+ };
199
+ const schedule = ()=>{
200
+ if (signal.aborted) return;
201
+ const cancel = ()=>clearTimeout(timer);
202
+ const timer = setTimeout(()=>{
203
+ signal.removeEventListener("abort", cancel);
204
+ this.inBackground(tryAgain());
205
+ }, failing.waitMs * (0.8 + Math.random() * 0.4));
206
+ signal.addEventListener("abort", cancel, {
207
+ once: true
208
+ });
209
+ };
210
+ schedule();
211
+ }
212
+ /** Track `work` so a stop waits for it. It must not reject: each caller handles its own errors. */ inBackground(work) {
213
+ this.background.add(work);
214
+ void work.finally(()=>this.background.delete(work));
92
215
  }
93
216
  async stopAll() {
94
217
  this.controller.abort();
218
+ this.failing.clear();
95
219
  await Promise.allSettled([
96
220
  this.starting
97
221
  ]);
222
+ // A retry that finishes now may resume a start, which adds more work: wait until none is left.
223
+ while(this.background.size > 0)await Promise.allSettled(this.background);
98
224
  await this.stopStarted();
99
225
  }
100
226
  /** Stop what is started, newest first. Takes each service off the list, so it runs once. */ async stopStarted() {
@@ -113,3 +239,6 @@ import { scribe } from "@decohere/scribe";
113
239
  }
114
240
  }
115
241
  }
242
+ function describe(error) {
243
+ return error instanceof Error ? error.message : String(error);
244
+ }
@@ -1,6 +1,7 @@
1
1
  export * from "./app.js";
2
2
  export * from "./builder.js";
3
3
  export * from "./const.js";
4
+ export * from "./dependency-unavailable.error.js";
4
5
  export * from "./hosted-service.js";
5
6
  export * from "./hosted-service-host.js";
6
7
  export * from "./readiness.types.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@decohere/core",
3
- "version": "0.0.1-dev.20261120.333",
3
+ "version": "0.0.1-dev.20261120.336",
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",
@@ -68,7 +68,7 @@
68
68
  "test": "echo \"Error: no test specified\" && exit 1"
69
69
  },
70
70
  "dependencies": {
71
- "@decohere/scribe": "0.0.1-dev.20261120.333",
71
+ "@decohere/scribe": "0.0.1-dev.20261120.336",
72
72
  "reflect-metadata": "^0.2.2"
73
73
  },
74
74
  "devDependencies": {}
@@ -1,7 +1,6 @@
1
1
  import { type IContainer, type LifetimeScope } from "../composition/index.js";
2
2
  import { type IConfigurationService } from "../configuration/index.js";
3
- import { type StartSteps } from "./const.js";
4
- import type { HostedServiceHost, HostedServiceStartTiming } from "./hosted-service-host.js";
3
+ import type { HostedServiceHost, HostedServiceStartTiming, StartRetry } from "./hosted-service-host.js";
5
4
  export declare class ApiConfiguration {
6
5
  static schema: {
7
6
  type: string;
@@ -40,20 +39,26 @@ export type StartOptions = {
40
39
  /** How long a signalled shutdown may take before the process exits with code 1. Default 10s. */
41
40
  shutdownTimeoutMs?: number;
42
41
  /**
43
- * When hosted services start. `"before-listen"` (default): `start()` resolves once every one
44
- * has started, and a failure rejects it. `"after-listen"`: the server listens first and they
45
- * start in the background, in the same order, while `GET /ready` answers 503; a failure stops
46
- * the app and rejects {@link App.hostedServicesStarted}. For a host with a start budget, such
47
- * as Cloud Run.
42
+ * When hosted services start. `"before-listen"` (default): `start()` resolves once each one
43
+ * has started or is being retried. `"after-listen"`: the server listens first and they start
44
+ * in the background, in the same order, while `GET /ready` answers 503. For a host with a
45
+ * start budget, such as Cloud Run.
48
46
  */
49
47
  hostedServices?: "before-listen" | "after-listen";
48
+ /**
49
+ * A hosted service whose `start()` throws is started again with this backoff (default 1 s
50
+ * doubling to 60 s) while the app runs, and `GET /ready` names it until it starts. `false` to
51
+ * fail fast instead, for a one-shot job: the services already started are stopped, and the
52
+ * error rejects `start()` (after-listen: it stops the app and rejects
53
+ * {@link App.hostedServicesStarted}).
54
+ */
55
+ startRetry?: StartRetry | false;
50
56
  };
51
57
  export declare class App {
52
58
  private readonly container;
53
59
  private configurationService?;
54
60
  private server?;
55
61
  private hostedServices?;
56
- private startSteps?;
57
62
  private _addresses;
58
63
  private logger;
59
64
  private disposing;
@@ -61,7 +66,7 @@ export declare class App {
61
66
  private signalHandler;
62
67
  private shutdownSignals;
63
68
  private hostedStarting;
64
- constructor(container: LifetimeScope, configurationService?: IConfigurationService, server?: AppServer, hostedServices?: HostedServiceHost, startSteps?: StartSteps);
69
+ constructor(container: LifetimeScope, configurationService?: IConfigurationService, server?: AppServer, hostedServices?: HostedServiceHost);
65
70
  /**
66
71
  * The app's root container, for a tool or a test that builds the app to use its services
67
72
  * without starting it: `decohere`'s db commands resolve its data sources' migrations here.
@@ -70,15 +75,19 @@ export declare class App {
70
75
  get addresses(): readonly string[];
71
76
  start(options?: StartOptions): Promise<AppServerStartResponse | undefined>;
72
77
  /**
73
- * Resolves once every hosted service has started, with how long each one took, in start order.
74
- * With `hostedServices: "after-listen"`, await it in `main.ts` after `start()`: a failure
75
- * rejects it, after the app has stopped. Left unawaited, that rejection is unhandled and ends
76
- * the process, as a failing `await app.start()` would.
78
+ * Resolves once every hosted service has started or is being retried, with how long each
79
+ * first start took, in start order. With `startRetry: false` and `hostedServices:
80
+ * "after-listen"`, await it in `main.ts` after `start()`: a failure rejects it, after the app
81
+ * has stopped. Left unawaited, that rejection is unhandled and ends the process, as a failing
82
+ * `await app.start()` would.
77
83
  */
78
84
  hostedServicesStarted(): Promise<readonly HostedServiceStartTiming[]>;
79
85
  private listen;
80
86
  private startHostedServices;
81
- /** The server is already up, so a service that fails to start takes the app down with it. */
87
+ /**
88
+ * The server is already up. Without retries, a service that fails to start takes the app down
89
+ * with it.
90
+ */
82
91
  private startHostedServicesAfterListen;
83
92
  [Symbol.asyncDispose](): Promise<void>;
84
93
  /** Stop the app. Calling it again (or from a signal) returns the same shutdown. */
@@ -24,7 +24,6 @@ export declare class Builder<T extends App = App> {
24
24
  private userServices;
25
25
  private preBuildSteps;
26
26
  private postBuildSteps;
27
- private readonly startSteps;
28
27
  private readonly hostedServices;
29
28
  constructor(containerBuilder: ContainerBuilder, options?: BuilderOptions);
30
29
  use(plugin: BuilderPlugin): this;
@@ -38,12 +37,13 @@ export declare class Builder<T extends App = App> {
38
37
  registerPreBuildStep(step: (config: IConfigurationService, containerBuilder: ContainerBuilder) => Promise<void> | void): void;
39
38
  registerPostBuildStep(step: (container: IContainer) => Promise<void> | void): void;
40
39
  /**
41
- * Run `step` when the app starts, in registration order, before its hosted services start and
42
- * its server listens. For work that changes the world outside the process, such as bringing a
43
- * database's schema up to date: an app that is only built, by a tool or a test, does none of it.
44
- * A throw fails `app.start()`.
40
+ * Run `step` when the app starts, in registration order, before its hosted services start. For
41
+ * work that changes the world outside the process, such as bringing a database's schema up to
42
+ * date: an app that is only built, by a tool or a test, does none of it. A throw is retried with
43
+ * the hosted services' backoff, and the hosted services wait until it succeeds (with
44
+ * `startRetry: false`, it fails `app.start()`). `name` is what logs and `/ready` call it.
45
45
  */
46
- registerStartStep(step: StartStep): void;
46
+ registerStartStep(step: StartStep, name?: string): void;
47
47
  buildAndStart<T extends App>(type?: Constructable<T>): Promise<T | App>;
48
48
  build<T extends App = App>(type?: Constructable<T>): Promise<T | App>;
49
49
  private configureUserServices;
@@ -3,10 +3,5 @@ import type { IContainer } from "../composition/index.js";
3
3
  export declare const AppServerToken: unique symbol;
4
4
  export declare const HostedServiceHostToken: unique symbol;
5
5
  export declare const ReadinessCheckToken: unique symbol;
6
- /** The {@link StartSteps} `App.start` runs before hosted services: `builder.registerStartStep`. */
7
- export declare const StartStepsToken: unique symbol;
8
- /** Work `App.start` does before hosted services start and the server listens. */
6
+ /** Work the app does when it starts, before its hosted services: `builder.registerStartStep`. */
9
7
  export type StartStep = (container: IContainer) => Promise<void> | void;
10
- export type StartSteps = {
11
- readonly steps: readonly StartStep[];
12
- };
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Something a request needs can't be reached right now: a database still connecting, or down
3
+ * while the app retries its start. HTTP answers `503 Service Unavailable`, without the reason,
4
+ * which is logged instead (it can name hosts).
5
+ */
6
+ export declare class DependencyUnavailableError extends Error {
7
+ readonly dependency: string;
8
+ readonly name = "DependencyUnavailableError";
9
+ /** `dependency` names what is missing, such as `data source "orders"`. */
10
+ constructor(dependency: string, reason?: string, options?: ErrorOptions);
11
+ }
@@ -1,49 +1,94 @@
1
1
  import type { IContainer } from "../composition/index.js";
2
2
  import type { Constructable } from "../reflection/index.js";
3
+ import type { StartStep } from "./const.js";
3
4
  import type { IReadinessCheck } from "./readiness.types.js";
4
5
  import type { HostedService } from "./hosted-service.js";
5
- /** How long one hosted service took to start: resolving it from the container plus its `start()`. */
6
+ /**
7
+ * How long one start step or hosted service took to start the first time: running the step, or
8
+ * resolving the service from the container plus its `start()`. `started` is false when that
9
+ * threw and it is being retried.
10
+ */
6
11
  export type HostedServiceStartTiming = {
7
12
  name: string;
8
13
  ms: number;
14
+ started: boolean;
9
15
  };
10
16
  /**
11
- * Starts and stops the app's {@link HostedService}s. One per app; `Builder.withHostedService`
12
- * adds the types and `App` drives it.
17
+ * How a start step or hosted service that throws is started again: after `initialMs` (default
18
+ * 1 s), doubling up to `maxMs` (default 60 s), each wait varied by ±20% so instances don't retry
19
+ * in step.
20
+ */
21
+ export type StartRetry = {
22
+ initialMs?: number;
23
+ maxMs?: number;
24
+ };
25
+ /**
26
+ * Starts and stops the app's start steps and {@link HostedService}s. One per app; the builder adds
27
+ * them (`registerStartStep`, `withHostedService`) and `App` drives it.
28
+ *
29
+ * Steps run first, in order, then services, in order. Either may throw: it is retried with
30
+ * backoff while the app runs. A failed step holds back everything after it until it succeeds,
31
+ * since what follows may need what it does (a database's migrations); a failed service holds back
32
+ * nothing.
13
33
  */
14
34
  export declare class HostedServiceHost {
15
35
  private readonly logger;
36
+ private readonly steps;
16
37
  private readonly types;
17
38
  private readonly controller;
18
39
  /** In start order; stopped in reverse. */
19
40
  private readonly started;
20
41
  private readonly _timings;
42
+ private readonly failing;
43
+ /** Background work (retries, and a start resumed after a step's retry), so a stop waits for it. */
44
+ private readonly background;
45
+ /** Starts running now: the first, and any resumed after a failed step's retry. */
46
+ private running;
21
47
  private starting;
22
- private startSettled;
23
48
  private stopping;
24
49
  add(...types: Constructable<HostedService>[]): void;
50
+ /** Run `step` before every hosted service, after the steps added before it. */
51
+ addStep(step: StartStep, name?: string): void;
52
+ /** How many steps and services there are. */
53
+ get size(): number;
25
54
  get isEmpty(): boolean;
26
55
  /**
27
- * Start every service in registration order. If one throws, the ones already started are
28
- * stopped and the error is rethrown. Stops launching more once {@link stop} has begun.
56
+ * Run the steps, then start the services, and resolve once each has started or, having thrown,
57
+ * is being retried in the background with `retry`'s backoff. With `retry: false`, a throw stops
58
+ * the services already started and is rethrown. Stops launching more once {@link stop} has
59
+ * begun.
29
60
  */
30
- start(container: IContainer): Promise<void>;
61
+ start(container: IContainer, retry?: StartRetry | false): Promise<void>;
31
62
  /** Abort the services' signal: background work should wind down. {@link stop} does this too. */
32
63
  abort(): void;
33
64
  /**
34
- * Abort the signal, wait for a start still in progress, then stop the started services in
35
- * reverse order. Every `stop()` runs even if one throws; the failures are rethrown after.
65
+ * Abort the signal, wait for starts and retries still in progress, then stop the started
66
+ * services in reverse order. Every `stop()` runs even if one throws; the failures are rethrown
67
+ * after.
36
68
  */
37
69
  stop(): Promise<void>;
38
- /** Each started service's start time, in start order. */
70
+ /** Each step's and service's first start, in start order. */
39
71
  get timings(): readonly HostedServiceStartTiming[];
40
72
  /**
41
73
  * For `GET /ready`: while a start is under way, one check that fails (the app listened before
42
- * its services started); then the started services that report readiness.
74
+ * its services started); one failing check per step or service being retried; then the
75
+ * started services that report readiness.
43
76
  */
44
77
  readinessChecks(): IReadinessCheck[];
45
- private startAll;
46
- private startEach;
78
+ /** Counted in {@link running} while it runs, so `/ready` fails meanwhile. */
79
+ private run;
80
+ /** Run the steps from `stepIndex`, then start every service. */
81
+ private startFrom;
82
+ private record;
83
+ /** Stop what started, then throw the start's error (with the stop's, if that failed too). */
84
+ private failFast;
85
+ /**
86
+ * Call `attempt` again with backoff until it succeeds, then `onStarted`. Listed in `/ready`
87
+ * meanwhile. Stops when the app stops.
88
+ */
89
+ private retryLater;
90
+ /** Track `work` so a stop waits for it. It must not reject: each caller handles its own errors. */
91
+ private inBackground;
47
92
  private stopAll;
48
93
  /** Stop what is started, newest first. Takes each service off the list, so it runs once. */
49
94
  private stopStarted;
@@ -8,8 +8,9 @@
8
8
  */
9
9
  export interface HostedService {
10
10
  /**
11
- * Called once when the app starts, and awaited: a throw fails `app.start()` (after-listen: it
12
- * stops the app and rejects `app.hostedServicesStarted()`). Do what must be
11
+ * Called when the app starts, and awaited. A throw is logged and `start()` is called again on
12
+ * the same instance with backoff, while `GET /ready` fails (with `startRetry: false`, a throw
13
+ * fails `app.start()` instead), so it must be safe to call again after it threw. Do what must be
13
14
  * ready before traffic, then start long work (a first load that takes minutes, a timer) in
14
15
  * the background and return. Waiting for it here keeps the HTTP server dark.
15
16
  *
@@ -1,6 +1,7 @@
1
1
  export * from "./app.js";
2
2
  export * from "./builder.js";
3
3
  export * from "./const.js";
4
+ export * from "./dependency-unavailable.error.js";
4
5
  export * from "./hosted-service.js";
5
6
  export * from "./hosted-service-host.js";
6
7
  export * from "./readiness.types.js";