Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: avoid starting servient multiple times #1195

Merged
merged 7 commits into from
Jan 11, 2024
16 changes: 16 additions & 0 deletions packages/core/src/servient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,9 @@ export default class Servient {
private things: Map<string, ExposedThing> = new Map<string, ExposedThing>();
private credentialStore: Map<string, Array<unknown>> = new Map<string, Array<unknown>>();

#started = false;
#shutdown = false;

/** add a new codec to support a mediatype; offered mediatypes are listed in TDs */
public addMediaType(codec: ContentCodec, offered = false): void {
ContentManager.addCodec(codec, offered);
Expand Down Expand Up @@ -210,18 +213,31 @@ export default class Servient {

// will return WoT object
public async start(): Promise<typeof WoT> {
if (this.#started) {
throw Error("Servient started already");
}
const serverStatus: Array<Promise<void>> = [];
this.servers.forEach((server) => serverStatus.push(server.start(this)));
this.clientFactories.forEach((clientFactory) => clientFactory.init());

await Promise.all(serverStatus);
this.#started = true;
return new WoTImpl(this);
}

public async shutdown(): Promise<void> {
if (!this.#started) {
debug("Servient cannot be shutdown, wasn't even started");
return;
}
if (this.#shutdown) {
throw Error("Servient shutdown already");
}

this.clientFactories.forEach((clientFactory) => clientFactory.destroy());

const promises = this.servers.map((server) => server.stop());
await Promise.all(promises);
this.#shutdown = true;
}
}