-
Notifications
You must be signed in to change notification settings - Fork 6
/
Hub.ts
52 lines (48 loc) · 1.69 KB
/
Hub.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
import { Config, FileData } from "./types.ts";
import { Peer } from "./Peer.ts";
import { PeerStorage } from "./PeerStorage.ts";
import { PeerCouchDB } from "./PeerCouchDB.ts";
export class Hub {
conf: Config;
peers = [] as Peer[];
constructor(conf: Config) {
this.conf = conf;
}
start() {
for (const p of this.peers) {
p.stop();
}
this.peers = [];
for (const peer of this.conf.peers) {
if (peer.type == "couchdb") {
const p = new PeerCouchDB(peer, this.dispatch.bind(this));
this.peers.push(p);
} else if (peer.type == "storage") {
const p = new PeerStorage(peer, this.dispatch.bind(this));
this.peers.push(p);
} else {
throw new Error(`Unexpected Peer type: ${(peer as any)?.name} - ${(peer as any)?.type}`);
}
}
for (const p of this.peers) {
p.start();
}
}
async dispatch(source: Peer, path: string, data: FileData | false) {
for (const peer of this.peers) {
if (peer !== source && (source.config.group ?? "") === (peer.config.group ?? "")) {
let ret = false;
if (data === false) {
ret = await peer.delete(path);
} else {
ret = await peer.put(path, data);
}
// if (ret) {
// // Logger(` ${data === false ? "-x->" : "--->"} ${peer.config.name} ${path} `)
// } else {
// // Logger(` ${peer.config.name} ignored ${path} `)
// }
}
}
}
}