-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.ts
262 lines (225 loc) · 6.91 KB
/
server.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
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
import { grantOrThrow } from "https://deno.land/[email protected]/permissions/mod.ts";
import { createHttpError } from "https://deno.land/x/[email protected]/httpError.ts";
import {
Application,
NativeRequest,
Router,
RouterContext,
Status,
} from "https://deno.land/x/[email protected]/mod.ts";
import {
BroadcastChannel,
isBroadcastSendMode,
} from "async_channels/broadcast.ts";
import { AbortedError, Channel } from "async_channels/channel.ts";
type Message = { topic: string; payload: Blob };
const router = new Router();
const exchanges = new Map<string, BroadcastChannel<Message, string>>();
interface ExchangeRequestBody {
name: string;
sendMode: string;
}
router.post("/api/exchanges", async (ctx: RouterContext) => {
const body = ctx.request.body();
ctx.assert(body.type === "json", Status.BadRequest, "JSON body expected");
const data = await body.value as ExchangeRequestBody;
ctx.assert(data.name !== undefined, Status.BadRequest);
ctx.assert(
!exchanges.has(data.name),
Status.Conflict,
"Exchange already exists",
);
const sendMode = data.sendMode || "ReturnImmediately";
if (!isBroadcastSendMode(sendMode)) {
throw createHttpError(Status.BadRequest, "Invalid sendMode");
}
exchanges.set(
data.name,
new BroadcastChannel((msg) => msg.topic, {
sendMode,
debugExtra: { exchange: data.name },
}),
);
ctx.response.status = Status.Created;
ctx.response.body = { name: data.name, sendMode };
});
type TopicTuple = [string, string];
const queues = new Map<
string,
[Channel<Message>, Map<TopicTuple, () => void>]
>();
interface QueueConf {
name: string;
bufferSize?: number;
topics: TopicTuple[];
}
// Create a Queue
router.post("/api/queues", async (ctx: RouterContext) => {
const body = ctx.request.body();
ctx.assert(
body.type === "json",
Status.BadRequest,
"body must be a valid JSON",
);
const conf = await body.value as QueueConf;
ctx.assert(
conf.name !== undefined,
Status.BadRequest,
"missing queue id",
);
ctx.assert(
!queues.has(conf.name),
Status.Conflict,
"queue already exists",
);
ctx.assert(
typeof conf === "object",
Status.BadRequest,
"body must be a JSON object",
);
const ch = new Channel<Message>(conf.bufferSize, {
debugExtra: { queue: conf.name },
});
const unsubscribeFns = new Map(
conf.topics?.map(([exchangeName, topic]) => {
return [[exchangeName, topic], subscribe(ch, exchangeName, topic)] as [
TopicTuple,
() => void,
];
}),
);
queues.set(conf.name, [ch, unsubscribeFns]);
ctx.response.status = Status.Created;
ctx.response.body = {
name: conf.name,
topics: conf.topics,
bufferSize: conf.bufferSize,
};
});
function subscribe(
ch: Channel<Message>,
exchangeName: string,
topic: string,
) {
const exchange = exchanges.get(exchangeName);
if (!exchange) return () => {};
const [sub, unsubscribe] = exchange.subscribe(topic);
(async () => {
for await (const msg of sub) {
await ch.send(msg);
}
})().catch((err) => console.error("caught error in subscription loop", err))
.finally(() => ch.close());
return unsubscribe;
}
router.put("/api/subscribe/:queue", async (ctx: RouterContext) => {
const body = ctx.request.body();
ctx.assert(
body.type === "json",
Status.BadRequest,
"body must be a valid JSON",
);
const conf = await body.value as Pick<QueueConf, "topics">;
ctx.assert(Array.isArray(conf.topics), Status.BadRequest);
ctx.assert(
conf.topics.every((x) => Array.isArray(x) && x.length === 2),
Status.BadRequest,
);
ctx.assert(ctx.params.queue !== undefined, Status.BadRequest);
const maybeQueue = queues.get(ctx.params.queue);
ctx.assert(maybeQueue, Status.NotFound, "Queue not found");
const [queue, unsubscribeFns] = maybeQueue;
for (const [exchangeName, topic] of conf.topics) {
const exchange = exchanges.get(exchangeName);
if (!exchange) continue;
if (unsubscribeFns.has([exchangeName, topic])) continue;
unsubscribeFns.set(
[exchangeName, topic],
subscribe(queue, exchangeName, topic),
);
}
queues.set(ctx.params.queue, [queue, unsubscribeFns]);
});
router.put("/api/unsubscribe/:queue", async (ctx: RouterContext) => {
const body = ctx.request.body();
ctx.assert(
body.type === "json",
Status.BadRequest,
"body must be a valid JSON",
);
const conf = await body.value as Pick<QueueConf, "topics">;
ctx.assert(Array.isArray(conf.topics), Status.BadRequest);
ctx.assert(
conf.topics.every((x) => Array.isArray(x) && x.length === 2),
Status.BadRequest,
);
ctx.assert(ctx.params.queue !== undefined, Status.BadRequest);
const maybeQueue = queues.get(ctx.params.queue);
ctx.assert(maybeQueue, Status.NotFound, "Queue not found");
const [queue, unsubscribeFns] = maybeQueue;
for (const [exchangeName, topic] of conf.topics) {
const unsubscribeFn = unsubscribeFns.get([exchangeName, topic]);
if (!unsubscribeFn) continue;
unsubscribeFns.delete([exchangeName, topic]);
unsubscribeFn();
}
queues.set(ctx.params.queue, [queue, unsubscribeFns]);
});
// Send a message on a topic.
router.put("/api/topics/:exchange/:topic", async (ctx: RouterContext) => {
ctx.assert(ctx.params.topic !== undefined, Status.BadRequest);
ctx.assert(ctx.params.exchange !== undefined, Status.BadRequest);
const exchange = exchanges.get(ctx.params.exchange);
ctx.assert(
exchange !== undefined,
Status.NotFound,
"No exchange found with that identifier.",
);
const body = ctx.request.body();
await exchange.send({ topic: ctx.params.topic, payload: await body.value });
ctx.response.status = Status.Accepted;
});
// Get a message from the queue.
router.get("/api/queues/:name", async (ctx: RouterContext) => {
ctx.assert(
ctx.request.accepts("application/json"),
Status.UnsupportedMediaType,
);
ctx.assert(
ctx.params.name !== undefined,
Status.BadRequest,
"missing queue name",
);
const queueTuple = queues.get(ctx.params.name);
ctx.assert(
queueTuple,
Status.NotFound,
"Queue not found",
);
const ctrl = new AbortController();
(ctx.request.originalRequest as NativeRequest).donePromise.then(() => {
ctrl.abort();
});
const [queue] = queueTuple;
try {
const [msg, ok] = await queue.get(ctrl);
ctx.assert(ok, Status.Gone, "queue is closed");
ctx.response.body = JSON.stringify(msg);
} catch (e) {
if (!(e instanceof AbortedError)) {
throw createHttpError(
Status.InternalServerError,
e instanceof Error ? e.message : String(e),
);
}
console.log("client aborted");
}
ctx.response.status = Status.Accepted;
});
const app = new Application();
app.use(router.routes());
app.use(router.allowedMethods());
await grantOrThrow({ name: "env", variable: "MQ_PORT" });
const port = parseInt(Deno.env.get("MQ_PORT") || "8000");
console.log(`Listening on port: ${port}`);
await app.listen({ port });