-
Notifications
You must be signed in to change notification settings - Fork 148
Expand file tree
/
Copy pathserver.ts
More file actions
160 lines (138 loc) · 3.95 KB
/
server.ts
File metadata and controls
160 lines (138 loc) · 3.95 KB
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
import { Client } from '@temporalio/client';
import { Worker } from '@temporalio/worker';
import { randomUUID } from 'crypto';
import http from 'http';
import { nanoid } from 'nanoid';
import { createActivities } from './activities';
import { Hub } from './hub';
import { chatRoomWorkflow, Event, newEventSignal } from './workflows';
const temporalClient = new Client();
const serverTaskQueue = randomUUID();
const hub = new Hub();
// handleEvents adds the incoming conection as a client in the Hub
function handleEvents(req: http.IncomingMessage, res: http.ServerResponse) {
const headers = {
'Content-Type': 'text/event-stream',
Connection: 'keep-alive',
'Cache-Control': 'no-cache',
};
res.writeHead(200, headers);
const qs = new URL(req.url || '', `http://${req.headers.host}`);
const clientId = qs.searchParams.get('client_id') || nanoid();
const roomId = qs.searchParams.get('room_id') || 'default';
hub.addClient({
id: clientId,
roomId,
res,
});
req.on('close', () => {
hub.removeClient(clientId);
});
temporalClient.workflow
.signalWithStart<typeof chatRoomWorkflow, [Event]>(chatRoomWorkflow, {
args: [
{
roomId,
},
],
signal: newEventSignal,
signalArgs: [
{
type: 'join',
data: {
clientId,
},
},
],
workflowId: `room:${roomId}`,
taskQueue: serverTaskQueue,
})
.catch((err) => {
console.error(err);
res.end('{"ok": false}');
});
}
function handlePushEvents(req: http.IncomingMessage, res: http.ServerResponse) {
const headers = {
'Content-Type': 'text/event-stream',
Connection: 'keep-alive',
'Cache-Control': 'no-cache',
};
const qs = new URL(req.url || '', `http://${req.headers.host}`);
const clientId = qs.searchParams.get('client_id') || nanoid();
const roomId = qs.searchParams.get('room_id') || 'default';
const message = qs.searchParams.get('message') || 'hey wtf';
temporalClient.workflow
.signalWithStart<typeof chatRoomWorkflow, [Event]>(chatRoomWorkflow, {
args: [
{
roomId,
},
],
signal: newEventSignal,
signalArgs: [
{
type: 'message',
data: {
message,
clientId,
},
},
],
workflowId: `room:${roomId}`,
taskQueue: serverTaskQueue,
})
.then(() => {
res.writeHead(200, headers);
res.end('{"ok": true}');
})
.catch(() => {
res.writeHead(500, headers);
res.end('{"ok": false}');
});
}
// handleHealth works as a simple health check
function handleHealth(_req: http.IncomingMessage, res: http.ServerResponse) {
const headers = {
'Content-Type': 'application/json',
Connection: 'keep-alive',
'Cache-Control': 'no-cache',
};
res.writeHead(200, headers);
res.end('{"ok": true}');
}
async function main() {
const server = http.createServer((req, res) => {
if (req.method === 'GET' && req.url?.includes('/events')) {
handleEvents(req, res);
return;
}
if (req.method === 'POST' && req.url?.includes('/events')) {
handlePushEvents(req, res);
return;
}
handleHealth(req, res);
});
const activities = createActivities(hub);
// every server will have two components:
// - an http listener
// - a temporal worker that is able to broadcast messages to it's own connection list through SSE
const worker = await Worker.create({
activities,
workflowsPath: require.resolve('./workflows'),
taskQueue: serverTaskQueue,
});
const serverP = new Promise((resolve, reject) => {
const port = process.env['PORT'] || 3000;
server.listen(port, () => {
console.log(`🚀 :: server is listening on port ${port}`);
});
server.on('error', reject);
server.on('close', resolve);
});
await Promise.all([worker.run(), serverP]);
}
main().catch((err) => {
console.error(err);
process.exit(1);
});