Skip to content

Commit

Permalink
Merge pull request #1195 from danielpeintner/issue-1193
Browse files Browse the repository at this point in the history
refactor: avoid starting servient multiple times
  • Loading branch information
relu91 authored Jan 11, 2024
2 parents b77b16a + 16ec287 commit 8adf840
Showing 1 changed file with 22 additions and 1 deletion.
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>>();

#wotInstance?: 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.#wotInstance !== undefined) {
debug("Servient started already -> nop -> returning previous WoT implementation");
return this.#wotInstance;
}
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.#wotInstance = new WoTImpl(this));
}

public async shutdown(): Promise<void> {
if (this.#wotInstance === 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.#wotInstance = undefined; // clean-up reference
}
}

0 comments on commit 8adf840

Please sign in to comment.