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
23 changes: 22 additions & 1 deletion 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>>();

#startedWoT?: typeof WoT;
#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,36 @@ export default class Servient {

// will return WoT object
public async start(): Promise<typeof WoT> {
if (this.#startedWoT != null) {
debug("Servient started already -> nop -> returning previous WoT implementation");
return this.#startedWoT;
}
if (this.#shutdown) {
throw Error("Servient cannot be started (again) since it was already stopped");
}

const serverStatus: Array<Promise<void>> = [];
this.servers.forEach((server) => serverStatus.push(server.start(this)));
this.clientFactories.forEach((clientFactory) => clientFactory.init());

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

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

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

const promises = this.servers.map((server) => server.stop());
await Promise.all(promises);
this.#shutdown = true;
this.#startedWoT = undefined; // clean-up reference
}
}