Skip to content

Commit 1a3fddd

Browse files
committed
handle goodbye in close
1 parent 9623e0f commit 1a3fddd

2 files changed

Lines changed: 45 additions & 3 deletions

File tree

lib/session.ts

Lines changed: 44 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -18,11 +18,12 @@ import {
1818
Event as EventMsg,
1919
Unsubscribe, UnsubscribeFields,
2020
Unsubscribed,
21-
Error, ErrorFields
21+
Error, ErrorFields,
22+
Goodbye, GoodbyeFields
2223
} from "wampproto";
2324

2425
import {wampErrorString} from "./helpers";
25-
import {ERROR_RUNTIME_ERROR} from "./wamp";
26+
import {ERROR_RUNTIME_ERROR, CLOSE_CLOSE_REALM} from "./wamp";
2627
import {ApplicationError, ProtocolError} from "./exception";
2728
import {
2829
IBaseSession,
@@ -58,6 +59,20 @@ export class Session {
5859
private _subscriptions: Map<number, (event: Event) => void> = new Map();
5960
private _unsubscribeRequests: Map<number, UnsubscribeRequest> = new Map();
6061

62+
private _goodbyeRequest = (() => {
63+
let resolve!: () => void;
64+
let isCompleted = false;
65+
const promise = new Promise<void>((res) => {
66+
resolve = () => {
67+
if (!isCompleted) {
68+
isCompleted = true;
69+
res();
70+
}
71+
};
72+
});
73+
return { promise, resolve, isCompleted };
74+
})();
75+
6176
constructor(baseSession: IBaseSession) {
6277
this._baseSession = baseSession;
6378
this._wampSession = new WAMPSession(baseSession.serializer());
@@ -75,7 +90,21 @@ export class Session {
7590
}
7691

7792
async close(): Promise<void> {
78-
await this._baseSession.close();
93+
const goodbye = new Goodbye(new GoodbyeFields({}, CLOSE_CLOSE_REALM));
94+
const data = this._wampSession.sendMessage(goodbye)
95+
this._baseSession.send(data)
96+
97+
return Promise.race([
98+
this._goodbyeRequest.promise,
99+
new Promise<void>((resolve) =>
100+
setTimeout(async () => {
101+
await this._baseSession.close();
102+
resolve();
103+
}, 10_000)
104+
)
105+
]).finally(async () => {
106+
await this._baseSession.close();
107+
});
79108
}
80109

81110
isConnected(): boolean {
@@ -204,11 +233,23 @@ export class Session {
204233
default:
205234
throw new ProtocolError(wampErrorString(message));
206235
}
236+
} else if (message instanceof Goodbye) {
237+
this.markDisconnected()
207238
} else {
208239
throw new ProtocolError(`Unexpected message type ${typeof message}`);
209240
}
210241
}
211242

243+
private markDisconnected() {
244+
if (!this.isConnected()) {
245+
return
246+
}
247+
248+
if (this._goodbyeRequest && !this._goodbyeRequest.isCompleted) {
249+
this._goodbyeRequest.resolve();
250+
}
251+
}
252+
212253
async call(
213254
procedure: string,
214255
args?: any[] | null,

lib/wamp.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,2 @@
1+
export const CLOSE_CLOSE_REALM = "wamp.close.close_realm"
12
export const ERROR_RUNTIME_ERROR = "wamp.error.runtime_error"

0 commit comments

Comments
 (0)