diff --git a/packages/core/src/servient.ts b/packages/core/src/servient.ts index 627e3d4f7..1a9111dfc 100644 --- a/packages/core/src/servient.ts +++ b/packages/core/src/servient.ts @@ -30,6 +30,9 @@ export default class Servient { private things: Map = new Map(); private credentialStore: Map> = new Map>(); + #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); @@ -210,18 +213,36 @@ export default class Servient { // will return WoT object public async start(): Promise { + 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> = []; 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 { + 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 } }