Skip to content

Commit 8adf840

Browse files
authored
Merge pull request #1195 from danielpeintner/issue-1193
refactor: avoid starting servient multiple times
2 parents b77b16a + 16ec287 commit 8adf840

1 file changed

Lines changed: 22 additions & 1 deletion

File tree

packages/core/src/servient.ts

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,9 @@ export default class Servient {
3030
private things: Map<string, ExposedThing> = new Map<string, ExposedThing>();
3131
private credentialStore: Map<string, Array<unknown>> = new Map<string, Array<unknown>>();
3232

33+
#wotInstance?: typeof WoT;
34+
#shutdown = false;
35+
3336
/** add a new codec to support a mediatype; offered mediatypes are listed in TDs */
3437
public addMediaType(codec: ContentCodec, offered = false): void {
3538
ContentManager.addCodec(codec, offered);
@@ -210,18 +213,36 @@ export default class Servient {
210213

211214
// will return WoT object
212215
public async start(): Promise<typeof WoT> {
216+
if (this.#wotInstance !== undefined) {
217+
debug("Servient started already -> nop -> returning previous WoT implementation");
218+
return this.#wotInstance;
219+
}
220+
if (this.#shutdown) {
221+
throw Error("Servient cannot be started (again) since it was already stopped");
222+
}
223+
213224
const serverStatus: Array<Promise<void>> = [];
214225
this.servers.forEach((server) => serverStatus.push(server.start(this)));
215226
this.clientFactories.forEach((clientFactory) => clientFactory.init());
216227

217228
await Promise.all(serverStatus);
218-
return new WoTImpl(this);
229+
return (this.#wotInstance = new WoTImpl(this));
219230
}
220231

221232
public async shutdown(): Promise<void> {
233+
if (this.#wotInstance === undefined) {
234+
throw Error("Servient cannot be shutdown, wasn't even started");
235+
}
236+
if (this.#shutdown) {
237+
debug("Servient shutdown already -> nop");
238+
return;
239+
}
240+
222241
this.clientFactories.forEach((clientFactory) => clientFactory.destroy());
223242

224243
const promises = this.servers.map((server) => server.stop());
225244
await Promise.all(promises);
245+
this.#shutdown = true;
246+
this.#wotInstance = undefined; // clean-up reference
226247
}
227248
}

0 commit comments

Comments
 (0)