Welcome to mirror list, hosted at ThFree Co, Russian Federation.

RoleAllocator.ts « src - github.com/jsxc/jsxc.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: b6f17cf6911e42d3786231a1e731568dc02aa9d4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
import Storage from './Storage';
import Client from './Client';
import Log from './util/Log';

const MASTER_KEY = 'master';
const SLAVE_KEY = 'slave';

const MASTER_CLASS = 'jsxc-master';
const SLAVE_CLASS = 'jsxc-slave';

const CLAIM_PREFIX = 'claim';
const CLAIM_SEP = '|';

const TIMEOUT_QUERY = 600;
const TIMEOUT_CLAIM = 600;
const TIMEOUT_MIN_OBSERVATION = 2000;
const INTERVAL_KEEPALIVE = 1000;

enum Role {
   Master,
   Slave,
   Master_Pending,
   Unknown,
}

export default class RoleAllocator {
   private storage: Storage;

   private role: Role = Role.Unknown;

   private resolveTimeout;

   private observationTimeout;

   private keepAliveInterval: number;

   private claimTimeout;

   private masterResolves = [];

   private slaveResolves = [];

   private slaveValue;

   private masterValue;

   private claim: number;

   private static instance: RoleAllocator;

   private constructor() {
      this.storage = Client.getStorage();

      this.storage.registerHook(MASTER_KEY, this.onMaster);
      this.storage.registerHook(SLAVE_KEY, this.onSlave);
   }

   public static get(): RoleAllocator {
      if (!RoleAllocator.instance) {
         RoleAllocator.instance = new RoleAllocator();
      }

      return RoleAllocator.instance;
   }

   public isMaster() {
      return this.role === Role.Master;
   }

   public masterExists() {
      return this.role !== Role.Unknown;
   }

   public waitUntilMaster() {
      return new Promise<void>(resolve => {
         if (this.role === Role.Master) {
            resolve();
         } else if (typeof this.storage.getItem(MASTER_KEY) === 'undefined') {
            this.startMaster();

            resolve();
         } else {
            this.masterResolves.push(resolve);

            if (this.role !== Role.Slave) {
               this.queryMaster();
            }
         }
      });
   }

   public waitUntilSlave() {
      return new Promise<void>(resolve => {
         if (this.role === Role.Slave) {
            resolve();
         } else {
            this.slaveResolves.push(resolve);
         }
      });
   }

   private onMaster = value => {
      if (this.masterValue === value) {
         return;
      }

      if (this.role === Role.Master_Pending && value.indexOf(CLAIM_PREFIX) === 0) {
         this.thereIsAnotherPotentialMaster(value);

         return;
      }

      if (this.role === Role.Unknown || this.role === Role.Master_Pending) {
         this.thereIsAMaster();
      }

      if (this.role === Role.Slave) {
         this.masterIsStillAlive();
      } else if (this.role === Role.Master) {
         Log.error('Something went wrong. We have another master.');

         this.stopKeepAliveSignal();

         window.location.reload();
      }
   };

   private thereIsAnotherPotentialMaster(value) {
      Log.debug('There is another potential master');

      let foreignClaim = parseFloat(value.split(CLAIM_SEP)[1]);

      if (foreignClaim > this.claim) {
         clearTimeout(this.claimTimeout);

         this.role = Role.Unknown;
         this.claim = undefined;
      }
   }

   private thereIsAMaster() {
      Log.debug('I am slave');

      this.role = Role.Slave;
      clearTimeout(this.resolveTimeout);

      this.resolveAllSlave();

      $('body').addClass(SLAVE_CLASS).removeClass(MASTER_CLASS);
   }

   private onSlave = value => {
      if (this.slaveValue === value) {
         return;
      }

      if (this.role === Role.Master) {
         this.stillAlive();
      }
   };

   private queryMaster() {
      Log.debug('query master');

      this.resolveTimeout = setTimeout(() => {
         if (this.role === Role.Unknown) {
            this.claimMaster();
         }
      }, TIMEOUT_QUERY);

      this.storage.setItem(SLAVE_KEY, (this.slaveValue = Math.random()));
   }

   private claimMaster = () => {
      Log.debug('Claim master');

      this.claimTimeout = setTimeout(() => {
         if (this.role === Role.Master_Pending) {
            this.startMaster();
         }
      }, TIMEOUT_CLAIM);

      this.role = Role.Master_Pending;
      this.claim = Math.random();

      this.storage.setItem(MASTER_KEY, (this.masterValue = `${CLAIM_PREFIX}${CLAIM_SEP}${this.claim}`));
   };

   private startMaster() {
      this.role = Role.Master;

      Log.debug('I am master');

      $('body').addClass(MASTER_CLASS).removeClass(SLAVE_CLASS);

      this.startKeepAliveSignal();

      this.resolveAllMaster();
   }

   private masterIsStillAlive() {
      clearTimeout(this.observationTimeout);

      let randomTime = Math.random() * 500;

      this.observationTimeout = setTimeout(this.masterProbablyDied, TIMEOUT_MIN_OBSERVATION + randomTime);
   }

   private masterProbablyDied = () => {
      this.role = Role.Unknown;
      this.queryMaster();
   };

   private startKeepAliveSignal() {
      this.stillAlive();

      this.keepAliveInterval = window.setInterval(this.stillAlive, INTERVAL_KEEPALIVE);
   }

   private stopKeepAliveSignal() {
      window.clearInterval(this.keepAliveInterval);
   }

   private resolveAllMaster() {
      this.resolveAll(this.masterResolves);
   }

   private resolveAllSlave() {
      this.resolveAll(this.slaveResolves);
   }

   private resolveAll(resolves) {
      for (let resolveIndex in resolves) {
         resolves[resolveIndex]();

         delete resolves[resolveIndex];
      }
   }

   private stillAlive = () => {
      this.storage.setItem(MASTER_KEY, (this.masterValue = Math.random()));
   };
}