forked from nest-cloud/nestcloud
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathloadbalancer.ts
67 lines (57 loc) · 1.75 KB
/
loadbalancer.ts
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
import { ILoadbalancer, IServer } from '@nestcloud/common';
import { Server } from './server';
import { ServerState } from './server-state';
import { Rule } from './interfaces/rule.interface';
export class Loadbalancer implements ILoadbalancer {
constructor(
private readonly id: string,
private readonly name: string,
public servers: Server[],
private rule: Rule,
) {
this.servers = this.initialServers(this.servers);
}
public chooseService(): IServer {
if (!this.rule) {
throw new Error('The rule is not exist.');
}
this.rule.init(this);
return this.rule.choose();
}
public updateRule(rule: Rule) {
this.rule = rule;
this.rule.init(this);
}
public addServer(server: Server) {
if (server) {
this.servers.push(this.initialServer(server));
}
}
public removeServer(serverId: string) {
if (serverId) {
this.servers = this.servers.filter(server => server.id !== serverId);
}
}
public getServer(serverId: string): Server {
for (let i = 0; i < this.servers.length; i++) {
if (this.servers[i].id === serverId) {
return this.servers[i];
}
}
}
private initialServers(servers: Server[]): Server[] {
if (!servers) {
return [];
}
return servers.map(server => this.initialServer(server));
}
private initialServer(server: Server): Server {
if (!server.address || !server.port) {
throw new Error('Service does not has address or port');
}
if (!server.state) {
server.state = new ServerState();
}
return server;
}
}