-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
363 lines (329 loc) · 11.4 KB
/
server.js
File metadata and controls
363 lines (329 loc) · 11.4 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
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
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
const WebSocket = require("ws");
const amqp = require("amqplib");
const PORT = process.env.PORT || 3008;
const RABBITMQ_HOST = process.env.RABBITMQ_HOST || "rabbitmq";
const RABBITMQ_PORT = process.env.RABBITMQ_PORT || 5672;
const RABBITMQ_USER = process.env.RABBITMQ_USER || "admin";
const RABBITMQ_PASS = process.env.RABBITMQ_PASS || "admin";
let rabbitmqConnection = null;
let rabbitmqChannel = null;
const wss = new WebSocket.Server({ port: PORT });
// Connect to RabbitMQ
async function connectRabbitMQ() {
try {
const connectionString = `amqp://${RABBITMQ_USER}:${RABBITMQ_PASS}@${RABBITMQ_HOST}:${RABBITMQ_PORT}`;
rabbitmqConnection = await amqp.connect(connectionString);
rabbitmqChannel = await rabbitmqConnection.createChannel();
console.log("Connected to RabbitMQ");
// Set up exchanges
await rabbitmqChannel.assertExchange("booking.events", "topic", {
durable: true,
});
await rabbitmqChannel.assertExchange("resource.events", "topic", {
durable: true,
});
await rabbitmqChannel.assertExchange("policy.events", "topic", {
durable: true,
});
// Listen for booking events (from booking.events exchange)
const bookingQueue = "realtime.booking";
await rabbitmqChannel.assertQueue(bookingQueue, { durable: false });
await rabbitmqChannel.bindQueue(
bookingQueue,
"booking.events",
"booking.created"
);
await rabbitmqChannel.bindQueue(
bookingQueue,
"booking.events",
"booking.updated"
);
await rabbitmqChannel.bindQueue(
bookingQueue,
"booking.events",
"booking.canceled"
);
await rabbitmqChannel.bindQueue(
bookingQueue,
"booking.events",
"booking.checked_in"
);
// Listen for resource events (from resource.events exchange)
const resourceQueue = "realtime.resource";
await rabbitmqChannel.assertQueue(resourceQueue, { durable: false });
await rabbitmqChannel.bindQueue(
resourceQueue,
"resource.events",
"resource.created"
);
await rabbitmqChannel.bindQueue(
resourceQueue,
"resource.events",
"resource.updated"
);
await rabbitmqChannel.bindQueue(
resourceQueue,
"resource.events",
"resource.deleted"
);
// Listen for policy events (from policy.events exchange)
const policyQueue = "realtime.policy";
await rabbitmqChannel.assertQueue(policyQueue, { durable: false });
await rabbitmqChannel.bindQueue(
policyQueue,
"policy.events",
"policy.created"
);
await rabbitmqChannel.bindQueue(
policyQueue,
"policy.events",
"policy.updated"
);
await rabbitmqChannel.bindQueue(
policyQueue,
"policy.events",
"policy.deleted"
);
// Consume booking messages and broadcast to WebSocket clients
rabbitmqChannel.consume(bookingQueue, (msg) => {
if (msg) {
try {
const content = JSON.parse(msg.content.toString());
const routingKey = msg.fields.routingKey || "";
// Determine event type based on routing key or content
let eventType = "availability_update";
if (
routingKey.includes("booking.created") ||
content.eventType === "booking.created"
) {
eventType = "booking_created";
} else if (
routingKey.includes("booking.canceled") ||
routingKey.includes("booking.cancelled") ||
content.eventType === "booking.canceled" ||
content.eventType === "booking.cancelled"
) {
eventType = "booking_cancelled";
} else if (
routingKey.includes("booking.updated") ||
content.eventType === "booking.updated"
) {
eventType = "booking_updated";
}
// Extract fields from booking content
const bookingId = content.id || content.bookingId;
const userId = content.userId;
const resourceId = content.resourceId;
const bookingStatus = content.status;
// Broadcast booking event (for realtime provider to handle)
broadcastToClients({
type: eventType,
bookingId: bookingId,
userId: userId,
resourceId: resourceId,
status: bookingStatus,
data: content,
event: routingKey,
});
// Also broadcast availability update for resource status changes
if (resourceId) {
// Ensure resourceId is a number
const resourceIdNum =
typeof resourceId === "string"
? parseInt(resourceId, 10)
: resourceId;
// Determine availability status based on booking status or event type
let status = "available";
if (
eventType === "booking_created" ||
eventType === "booking_updated" ||
bookingStatus === "CONFIRMED" ||
bookingStatus === "CHECKED_IN"
) {
status = "unavailable";
} else if (
eventType === "booking_cancelled" ||
bookingStatus === "CANCELED" ||
bookingStatus === "NO_SHOW"
) {
status = "available";
}
console.log(
`Broadcasting availability update: resourceId=${resourceIdNum}, status=${status}, event=${routingKey}`
);
broadcastToClients({
type: "availability_update",
resourceId: resourceIdNum,
status: status,
bookingId: bookingId,
event: routingKey,
timestamp: content.timestamp || new Date().toISOString(),
});
}
rabbitmqChannel.ack(msg);
} catch (error) {
console.error("Error processing booking message:", error);
rabbitmqChannel.nack(msg, false, false);
}
}
});
// Consume resource messages and broadcast to WebSocket clients
// Note: WebSockets are primarily for availability status updates
// Resource creation/deletion should use refresh button instead
rabbitmqChannel.consume(resourceQueue, (msg) => {
if (msg) {
try {
const content = JSON.parse(msg.content.toString());
const routingKey = msg.fields.routingKey;
// Handle resource status updates (availability changes)
if (routingKey === "resource.updated") {
const resourceId = content.id;
const status = content.status
? content.status.toLowerCase()
: "available";
console.log(
`Broadcasting resource status update: id=${resourceId}, status=${status}`
);
// Send availability_update for status changes
broadcastToClients({
type: "availability_update",
resourceId: resourceId,
status: status,
event: routingKey,
});
} else if (routingKey === "resource.created") {
// Broadcast resource creation to all clients
console.log(
`Broadcasting resource.created event: id=${content.id}, name=${content.name}`
);
broadcastToClients({
type: "resource_created",
resource: content,
event: routingKey,
});
} else if (routingKey === "resource.deleted") {
// Broadcast resource deletion to all clients
const resourceId = typeof content === "object" ? content.id : content;
console.log(`Broadcasting resource.deleted event: id=${resourceId}`);
broadcastToClients({
type: "resource_deleted",
resourceId: resourceId,
event: routingKey,
});
}
rabbitmqChannel.ack(msg);
} catch (error) {
console.error("Error processing resource message:", error);
rabbitmqChannel.nack(msg, false, false);
}
}
});
// Consume policy messages and broadcast to WebSocket clients
rabbitmqChannel.consume(policyQueue, (msg) => {
if (msg) {
try {
const content = JSON.parse(msg.content.toString());
const routingKey = msg.fields.routingKey;
console.log(
`Broadcasting policy event: ${routingKey}, id=${content.id || content}`
);
if (routingKey === "policy.created") {
broadcastToClients({
type: "policy_created",
policy: content,
event: routingKey,
});
} else if (routingKey === "policy.updated") {
broadcastToClients({
type: "policy_updated",
policy: content,
event: routingKey,
});
} else if (routingKey === "policy.deleted") {
const policyId = typeof content === "object" ? content.id : content;
broadcastToClients({
type: "policy_deleted",
policyId: policyId,
event: routingKey,
});
}
rabbitmqChannel.ack(msg);
} catch (error) {
console.error("Error processing policy message:", error);
rabbitmqChannel.nack(msg, false, false);
}
}
});
} catch (error) {
console.error("Failed to connect to RabbitMQ:", error.message);
// Retry connection after 5 seconds
setTimeout(connectRabbitMQ, 5000);
}
}
// Broadcast message to all connected WebSocket clients
function broadcastToClients(data) {
const message = JSON.stringify(data);
let sentCount = 0;
wss.clients.forEach((client) => {
if (client.readyState === WebSocket.OPEN) {
try {
client.send(message);
sentCount++;
} catch (error) {
console.error("Error sending message to client:", error);
}
}
});
console.log(`Broadcasted to ${sentCount} client(s): ${message}`);
}
// Handle WebSocket connections
wss.on("connection", (ws, req) => {
console.log(
`New WebSocket client connected from ${req.socket.remoteAddress}`
);
// Send welcome message
ws.send(
JSON.stringify({
type: "connected",
message: "Connected to realtime gateway",
})
);
console.log("Sent welcome message to client");
// Handle incoming messages from client
ws.on("message", (message) => {
try {
const data = JSON.parse(message.toString());
// Handle subscription requests (support both 'topic' and 'event' fields)
if (data.type === "subscribe" && (data.topic || data.event)) {
const topic = data.topic || data.event;
console.log(`Client subscribed to: ${topic}`);
ws.send(
JSON.stringify({
type: "subscribed",
topic: topic,
})
);
}
} catch (error) {
console.error("Error parsing client message:", error);
}
});
// Handle client disconnect
ws.on("close", () => {
console.log("WebSocket client disconnected");
});
ws.on("error", (error) => {
console.error("WebSocket error:", error);
});
});
// Start server
console.log(`Realtime Gateway WebSocket server starting on port ${PORT}...`);
connectRabbitMQ();
// Graceful shutdown
process.on("SIGTERM", async () => {
console.log("SIGTERM received, shutting down gracefully...");
wss.close();
if (rabbitmqChannel) await rabbitmqChannel.close();
if (rabbitmqConnection) await rabbitmqConnection.close();
process.exit(0);
});