This repository has been archived by the owner on Feb 2, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.ts
152 lines (114 loc) · 3.46 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
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
import { serve, ServerRequest, readAll } from "./deps.ts";
async function callDocker(path: string, payload: object, json: boolean = true): Promise<object> {
const response = await fetch(`http://localhost:4444/v1.41/${path}`, {
method: "POST",
headers: {
"Content-Type": "application/json",
"Host": "localhost"
},
body: JSON.stringify(payload)
});
if(json === true) {
return await response.json();
} else {
return await response.arrayBuffer();
}
}
interface Image {
tag: string;
repo: string;
org: string;
}
function imageToString(image: Image): string {
return `${image.org}/${image.repo}:${image.tag}`;
}
const portMap: { [key: string]: Promise<number>; } = {};
function parseHost(host: string): Image {
const [ tag, repo, org ] = host.split(".");
return { tag, repo, org };
}
async function pullImage(image: Image) {
await callDocker(`images/create?fromImage=${imageToString(image)}`, {}, false);
}
async function createContainer(image: Image, port: number): Promise<string> {
interface createContainerResponse {
Id: string;
}
const response: createContainerResponse = await callDocker("containers/create", {
Image: `${image.org}/${image.repo}:${image.tag}`,
HostConfig: {
PortBindings: {
"80/tcp": [
{ HostPort: port.toString() }
]
}
}
}) as createContainerResponse;
if(typeof response.Id !== "string") {
throw new Error("failed to create container, responded with no `ID`");
}
return response.Id;
}
async function startContainer(container: string): Promise<void> {
await callDocker(`containers/${container}/start`, {}, false);
}
async function ensureContainerRunning(request: ServerRequest): Promise<void> {
const host = request.headers.get("host");
if(typeof host !== "string") {
throw new Error("host cannot be undefined");
}
const image = parseHost(host);
if(!(portMap[imageToString(image)] instanceof Promise)) {
portMap[imageToString(image)] = (async () => {
const port = 5000 + Math.floor(Math.random() * 1000);
await pullImage(image);
const id = await createContainer(image, port);
console.log({ id });
await startContainer(id);
console.log("container started");
await new Promise(r => setTimeout(r, 500));
return port;
})() as Promise<number>;
}
}
async function proxyRequest(request: ServerRequest): Promise<void> {
const host = request.headers.get("host");
if(typeof host !== "string") {
throw new Error("host cannot be undefined");
}
const port = await portMap[imageToString(parseHost(host))];
const url = `http://127.0.0.1:${port}${request.url}`;
console.log(request.headers);
const res = await fetch(url, {
method: request.method,
headers: request.headers,
body: !([ "GET", "HEAD" ].includes(request.method)) ? await readAll(request.body) : null
});
const body = new Uint8Array(await res.arrayBuffer());
const responseHeaders = new Headers();
console.log({
resHeaders: res.headers
})
// copy specified headers from fetch response to server response
for(const header of [
"Set-Cookie",
"Content-Type"
]) {
if(res.headers.has(header)) {
const value = res.headers.get(header) as string;
responseHeaders.append(header, value);
}
}
request.respond({
body,
headers: responseHeaders
});
}
async function handleRequest(request: ServerRequest): Promise<void> {
await ensureContainerRunning(request);
await proxyRequest(request);
}
const server = serve({ port: 3000 });
for await (const request of server) {
handleRequest(request);
}