-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.ts
163 lines (133 loc) · 4.59 KB
/
index.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
153
154
155
156
157
158
159
160
161
162
163
// @ts-ignore
import { STATUS_CODE } from 'https://deno.land/std/http/status.ts';
console.log('main function started');
// log system memory usage every 30s
// setInterval(() => console.log(EdgeRuntime.systemMemoryInfo()), 30 * 1000);
Deno.serve(async (req: Request) => {
const headers = new Headers({
'Content-Type': 'application/json',
});
const url = new URL(req.url);
const { pathname } = url;
// handle health checks
if (pathname === '/_internal/health') {
return new Response(
JSON.stringify({ 'message': 'ok' }),
{
status: STATUS_CODE.OK,
headers,
},
);
}
if (pathname === '/_internal/metric') {
const metric = await EdgeRuntime.getRuntimeMetrics();
return Response.json(metric);
}
// NOTE: You can test WebSocket in the main worker by uncommenting below.
// if (pathname === '/_internal/ws') {
// const upgrade = req.headers.get("upgrade") || "";
// if (upgrade.toLowerCase() != "websocket") {
// return new Response("request isn't trying to upgrade to websocket.");
// }
// const { socket, response } = Deno.upgradeWebSocket(req);
// socket.onopen = () => console.log("socket opened");
// socket.onmessage = (e) => {
// console.log("socket message:", e.data);
// socket.send(new Date().toString());
// };
// socket.onerror = e => console.log("socket errored:", e.message);
// socket.onclose = () => console.log("socket closed");
// return response; // 101 (Switching Protocols)
// }
const path_parts = pathname.split('/');
const service_name = path_parts[1];
if (!service_name || service_name === '') {
const error = { msg: 'missing function name in request' };
return new Response(
JSON.stringify(error),
{ status: STATUS_CODE.BadRequest, headers: { 'Content-Type': 'application/json' } },
);
}
const servicePath = `./examples/${service_name}`;
// console.error(`serving the request with ${servicePath}`);
const createWorker = async () => {
const memoryLimitMb = 150;
const workerTimeoutMs = 5 * 60 * 1000;
const noModuleCache = false;
// you can provide an import map inline
// const inlineImportMap = {
// imports: {
// "std/": "https://deno.land/[email protected]/",
// "cors": "./examples/_shared/cors.ts"
// }
// }
// const importMapPath = `data:${encodeURIComponent(JSON.stringify(importMap))}?${encodeURIComponent('/home/deno/functions/test')}`;
const importMapPath = null;
const envVarsObj = Deno.env.toObject();
const envVars = Object.keys(envVarsObj).map((k) => [k, envVarsObj[k]]);
const forceCreate = false;
const netAccessDisabled = false;
// load source from an eszip
//const maybeEszip = await Deno.readFile('./bin.eszip');
//const maybeEntrypoint = 'file:///src/index.ts';
// const maybeEntrypoint = 'file:///src/index.ts';
// or load module source from an inline module
// const maybeModuleCode = 'Deno.serve((req) => new Response("Hello from Module Code"));';
//
const cpuTimeSoftLimitMs = 10000;
const cpuTimeHardLimitMs = 20000;
return await EdgeRuntime.userWorkers.create({
servicePath,
memoryLimitMb,
workerTimeoutMs,
noModuleCache,
importMapPath,
envVars,
forceCreate,
netAccessDisabled,
cpuTimeSoftLimitMs,
cpuTimeHardLimitMs,
// maybeEszip,
// maybeEntrypoint,
// maybeModuleCode,
});
};
const callWorker = async () => {
try {
// If a worker for the given service path already exists,
// it will be reused by default.
// Update forceCreate option in createWorker to force create a new worker for each request.
const worker = await createWorker();
const controller = new AbortController();
const signal = controller.signal;
// Optional: abort the request after a timeout
//setTimeout(() => controller.abort(), 2 * 60 * 1000);
return await worker.fetch(req, { signal });
} catch (e) {
console.error(e);
if (e instanceof Deno.errors.WorkerRequestCancelled) {
headers.append('Connection', 'close');
// XXX(Nyannyacha): I can't think right now how to re-poll
// inside the worker pool without exposing the error to the
// surface.
// It is satisfied when the supervisor that handled the original
// request terminated due to reaches such as CPU time limit or
// Wall-clock limit.
//
// The current request to the worker has been canceled due to
// some internal reasons. We should repoll the worker and call
// `fetch` again.
// return await callWorker();
}
const error = { msg: e.toString() };
return new Response(
JSON.stringify(error),
{
status: STATUS_CODE.InternalServerError,
headers,
},
);
}
};
return callWorker();
});