1 | import {CyclonNode, CyclonNodePointer} from 'cyclon.p2p';
|
2 | import {AsyncExecService, Logger} from 'cyclon.p2p-common';
|
3 | import {Channel} from 'cyclon.p2p-rtc-client/lib/Channel';
|
4 |
|
5 | const SHUFFLE_RESPONSE_TIMEOUT_MS: number = 30000;
|
6 |
|
7 | export class OutgoingShuffleState {
|
8 |
|
9 | private channelClosingTimeoutId?: number;
|
10 | private channel?: Channel;
|
11 |
|
12 | constructor(private readonly fromNode: CyclonNode,
|
13 | private readonly destinationNodePointer: CyclonNodePointer,
|
14 | private readonly shuffleSet: CyclonNodePointer[],
|
15 | private readonly asyncExecService: AsyncExecService,
|
16 | private readonly logger: Logger) {
|
17 | }
|
18 |
|
19 | |
20 |
|
21 |
|
22 | storeChannel(theChannel: Channel): void {
|
23 | this.channel = theChannel;
|
24 | }
|
25 |
|
26 | |
27 |
|
28 |
|
29 |
|
30 |
|
31 | sendShuffleRequest(): void {
|
32 | this.requireChannel().send("shuffleRequest", this.shuffleSet);
|
33 | this.logger.debug("Sent shuffle request to " + this.destinationNodePointer.id + " : " + JSON.stringify(this.shuffleSet));
|
34 | }
|
35 |
|
36 | |
37 |
|
38 |
|
39 | async processShuffleResponse(): Promise<void> {
|
40 | const shuffleResponseMessage = await this.requireChannel().receive("shuffleResponse", SHUFFLE_RESPONSE_TIMEOUT_MS);
|
41 | this.logger.debug("Received shuffle response from " + this.destinationNodePointer.id + " : " + JSON.stringify(shuffleResponseMessage));
|
42 | this.fromNode.handleShuffleResponse(this.destinationNodePointer, shuffleResponseMessage);
|
43 | }
|
44 |
|
45 | |
46 |
|
47 |
|
48 | async sendResponseAcknowledgement(): Promise<void> {
|
49 | await new Promise((resolve) => {
|
50 | this.requireChannel().send("shuffleResponseAcknowledgement");
|
51 |
|
52 |
|
53 |
|
54 |
|
55 | this.channelClosingTimeoutId = this.asyncExecService.setTimeout(() => {
|
56 | resolve();
|
57 | }, 3000);
|
58 | });
|
59 | }
|
60 |
|
61 | |
62 |
|
63 |
|
64 | close(): void {
|
65 | if(this.channel) {
|
66 | this.channel.close();
|
67 | }
|
68 | this.clearChannelClosingTimeout();
|
69 | }
|
70 |
|
71 | private clearChannelClosingTimeout(): void {
|
72 | if (this.channelClosingTimeoutId) {
|
73 | this.asyncExecService.clearTimeout(this.channelClosingTimeoutId);
|
74 | delete this.channelClosingTimeoutId;
|
75 | }
|
76 | }
|
77 |
|
78 | private requireChannel(): Channel {
|
79 | if (this.channel === undefined) {
|
80 | throw new Error("Channel must have been stored first!");
|
81 | }
|
82 | return this.channel;
|
83 | }
|
84 | }
|