-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.ts
65 lines (53 loc) · 1.58 KB
/
main.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
import { serve } from "https://deno.land/std/http/server.ts";
import nodeIDS from "./servers.ts";
type Database = Map<string, string>;
function getOwnerForKey(key: string) {
return nodeIDS[key.length % nodeIDS.length];
}
async function startServer(port: number) {
const server = serve({ port });
const nodeId = port;
console.log(`http://localhost:${port}/`);
let db: Database = new Map();
const decoder = new TextDecoder("utf-8");
async function store(key: string, value: string) {
const ownerID = getOwnerForKey(key);
if (nodeId === ownerID) {
return db.set(key, value);
} else {
const response = await fetch(`http://localhost:${ownerID}${key}`, {
method: "POST",
body: value,
});
return await response.text();
}
}
async function lookup(key: string): Promise<string> {
const ownerID = getOwnerForKey(key);
if (nodeId === ownerID) {
return db.get(key) || "";
} else {
const response = await fetch(`http://localhost:${ownerID}${key}`);
return await response.text();
}
}
for await (const req of server) {
const key = req.url;
switch (req.method) {
case "POST": {
const body = decoder.decode(await Deno.readAll(req.body));
await store(key, body);
console.log("store", { nodeId, db });
req.respond({ body: "ok" });
break;
}
case "GET": {
console.log("query", { nodeId, key });
const value = await lookup(key);
req.respond({ body: value });
break;
}
}
}
}
nodeIDS.forEach(startServer);