-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
639 lines (556 loc) · 16.5 KB
/
Copy pathindex.js
File metadata and controls
639 lines (556 loc) · 16.5 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
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
const express = require("express");
const { generateSlug } = require("random-word-slugs");
const { ECSClient, RunTaskCommand } = require("@aws-sdk/client-ecs");
// const Redis = require("ioredis");
const { Server } = require("socket.io");
const http = require("http");
const { PrismaClient } = require("@prisma/client");
const { createClient } = require("@clickhouse/client");
const { Kafka } = require("kafkajs");
const { v4: uuidv4 } = require("uuid");
const fs = require("fs");
const path = require("path");
const cors = require("cors");
const { exec } = require("child_process");
const bcrypt = require("bcrypt");
const bodyParser = require("body-parser");
const dotenv = require("dotenv");
const { isAuthenticatedUser } = require("./middlewares/AuthMiddleware");
const jwt = require("jsonwebtoken");
dotenv.config({});
const config = {
CLUSTER: process.env.AWS_CLUSTER_ARN,
TASK: process.env.AWS_TASK_DEF_ARN,
AWS_ACCESSKEYID: process.env.AWS_ACCESSKEYID,
AWS_SECRETACCESSKEY: process.env.AWS_SECRETACCESSKEY,
// redis
REDIS_HOST: process.env.REDIS_HOST,
REDIS_PORT: process.env.REDIS_PORT,
REDIS_PASSWORD: process.env.REDIS_PASSWORD,
//Click House
CLICK_HOUSE_URL: process.env.CLICK_HOUSE_URL,
CLICK_HOUSE_DB: process.env.CLICK_HOUSE_DB,
CLICK_HOUSE_USERNAME: process.env.CLICK_HOUSE_USERNAME,
CLICK_HOUSE_PASSWORD: process.env.CLICK_HOUSE_PASSWORD,
// Kafka
KAFKA_BROKER_URL: process.env.KAFKA_BROKER_URL,
KAFKA_USER_NAME: process.env.KAFKA_USER_NAME,
KAFKA_PASSWORD: process.env.KAFKA_PASSWORD,
// frontend
FRONTEND_URL: process.env.FRONTEND_URL,
FRONTEND_PROXY_URL: process.env.FRONTEND_PROXY_URL,
JWT_SECRET: process.env.JWT_SECRET,
};
const PORT = 9000;
const app = express();
// Create an HTTP server
const server = http.createServer(app);
// Initialize Socket.IO with the HTTP server
const io = new Server(server, {
cors: {
origin: "*",
methods: "*",
},
});
// const REDIS_URL = `rediss://${config.REDIS_PASSWORD}@${config.REDIS_HOST}:${config.REDIS_PORT}`;
// // redis Connection
// const subscriber = new Redis(REDIS_URL);
// Click House Connection
const clickhouseClient = createClient({
host: config.CLICK_HOUSE_URL,
database: config.CLICK_HOUSE_DB,
username: config.CLICK_HOUSE_USERNAME,
password: config.CLICK_HOUSE_PASSWORD,
});
// ECS Connection
const ecsClient = new ECSClient({
region: "ap-south-1",
credentials: {
accessKeyId: config.AWS_ACCESSKEYID,
secretAccessKey: config.AWS_SECRETACCESSKEY,
},
});
// Rrisma Connectin
const prisma = new PrismaClient({});
// Kafka Connection
const kafka = new Kafka({
clientId: `api-server`,
brokers: [config.KAFKA_BROKER_URL],
ssl: {
ca: [fs.readFileSync(path.join(__dirname, "kafka.pem"), "utf-8")],
},
sasl: {
username: config.KAFKA_USER_NAME,
password: config.KAFKA_PASSWORD,
mechanism: "plain",
},
});
// Kafka Consumer
const consumer = kafka.consumer({ groupId: "api-server-logs-consumer" });
// Middlewares
app.use(express.json());
app.use(
express.urlencoded({
extended: true,
})
);
app.use(
cors({
origin: config.FRONTEND_URL || "*",
})
);
// Redis Subscriber
// async function initRedisSubscribe() {
// console.log("Subscribed to logs....");
// subscriber.psubscribe("logs:*");
// // get on the Frontend :: logs:<PROJECT_SLUG>
// subscriber.on("pmessage", (pattern, channel, message) => {
// io.to(channel).emit("message", message);
// });
// }
// Kafka Consumer function
const logConsumer = kafka.consumer({ groupId: "log-group" });
async function initLogConsumer() {
await logConsumer.connect();
await logConsumer.subscribe({
topics: ["container-logs"],
fromBeginning: true,
});
await logConsumer.run({
eachBatch: async ({
batch,
heartbeat,
commitOffsetsIfNecessary,
resolveOffset,
}) => {
const messages = batch.messages;
console.log(`Received ${messages.length} log messages.`);
for (const message of messages) {
if (!message.value) continue;
const stringMessage = message.value.toString();
const { PROJECT_ID, DEPLOYEMENT_ID, log } = JSON.parse(stringMessage);
console.log({ log, DEPLOYEMENT_ID });
try {
const { query_id } = await clickhouseClient.insert({
table: "log_events",
values: [
{ event_id: uuidv4(), deployment_id: DEPLOYEMENT_ID, log },
],
format: "JSONEachRow",
});
console.log(query_id);
resolveOffset(message.offset);
await commitOffsetsIfNecessary(message.offset);
await heartbeat();
} catch (err) {
console.error("Error in log consumer: ", err);
}
}
},
});
}
// Visitor Count
const visitorConsumer = kafka.consumer({ groupId: "visitor-group" });
async function initVisitorConsumer() {
await visitorConsumer.connect();
await visitorConsumer.subscribe({
topics: ["visitor-counts"],
fromBeginning: true,
});
await visitorConsumer.run({
eachBatch: async ({
batch,
heartbeat,
commitOffsetsIfNecessary,
resolveOffset,
}) => {
const messages = batch.messages;
console.log(`Received ${messages.length} visitor count messages.`);
for (const message of messages) {
if (!message.value) continue;
const stringMessage = message.value.toString();
const { PROJECT_ID } = JSON.parse(stringMessage);
console.log({ PROJECT_ID });
// Get the current date in YYYY-MM-DD format
const currentDate = new Date().toISOString().split("T")[0];
try {
const { query_id } = await clickhouseClient.insert({
table: "visitor_counts",
values: [
{
project_id: PROJECT_ID,
visitor_count: 1,
date: currentDate,
},
],
format: "JSONEachRow",
});
console.log(`Inserted new record with query_id: ${query_id}`);
resolveOffset(message.offset);
await commitOffsetsIfNecessary(message.offset);
await heartbeat();
} catch (err) {
console.error("Error in visitor consumer: ", err);
}
}
},
});
}
// Routes
// register
app.post("/api/v1/register", async (req, res) => {
const { email, password, firstName, lastName } = req.body;
if (!email || !password || !firstName || !lastName) {
return res
.status(400)
.send({ success: false, message: "Please fill in all fields" });
}
const isUserExist = await prisma.user.findUnique({
where: {
email: email,
},
});
if (isUserExist) {
return res
.status(400)
.send({ success: false, message: "User already exist" });
}
const hashPassword = await bcrypt.hash(password, 10);
const user = await prisma.user.create({
data: {
email,
password: hashPassword,
firstName,
lastName,
},
});
res.status(200).send({
message: "User created successfully",
user,
});
});
// Login
app.post("/api/v1/login", async (req, res) => {
const { email, password } = req.body;
if (!email || !password) {
return res
.status(400)
.send({ success: false, message: "Please fill in all fields" });
}
// find the user
const user = await prisma.user.findUnique({
where: {
email: email,
},
});
if (!user) {
return res
.status(401)
.send({ success: false, message: "Invalid email or password" });
}
const isPasswordCorrect = await bcrypt.compare(password, user.password);
if (!isPasswordCorrect) {
return res
.status(401)
.send({ success: false, message: "Invalid email or password" });
}
const accessToken = jwt.sign(user, config.JWT_SECRET, { expiresIn: "1d" });
res.status(200).cookie("token", accessToken).send({
success: true,
message: "User login successfully",
user,
token: accessToken,
});
});
// Get prokects
app.get("/api/v1/get-projects", isAuthenticatedUser, async (req, res) => {
const projects = await prisma.project.findMany({
where: {
userId: req.user.id,
},
include: {
Deployement: {
select: {
status: true,
},
},
},
});
const formattedProjects = projects.map((project) => ({
...project,
status: project.Deployement[0]?.status || "NOT_STARTED",
}));
return res.status(200).send({
success: true,
message: "Projects retrieved successfully",
projects: formattedProjects,
});
});
// get the Single Project
app.get(
"/api/v1/get-single-project/:projectID",
isAuthenticatedUser,
async (req, res) => {
const { projectID } = req.params; // Use req.params for GET requests
try {
const project = await prisma.project.findUnique({
where: {
id: projectID,
userId: req.user.id,
},
});
if (!project) {
return res.status(404).send({
success: false,
message: "Project not found",
});
}
return res.status(200).send({
success: true,
message: "Project retrieved successfully",
project,
});
} catch (error) {
console.log(error);
return res.status(500).send({
success: false,
message: "An error occurred while retrieving the project",
error: error.message,
});
}
}
);
// get the Deployment id
app.get(
"/api/v1/get-deployment-id/:projectID",
isAuthenticatedUser,
async (req, res) => {
const { projectID } = req.params;
try {
const deployment = await prisma.deployement.findFirst({
where: {
projectId: projectID,
},
});
if (!deployment) {
return res.status(404).send({
success: false,
message: "Deployment Id not found",
});
}
return res.status(200).send({
success: true,
message: "Project retrieved successfully",
deploymentId: deployment.id,
});
} catch (error) {
console.log(error);
return res.status(500).send({
success: false,
message: "An error occurred while retrieving the project",
error: error.message,
});
}
}
);
// Create a Project
app.post("/api/v1/project", isAuthenticatedUser, async (req, res) => {
const { name, gitURL } = req.body;
const gitURLPattern = /^(https?:\/\/)?(www\.)?github\.com\/.+/i;
if (typeof name !== "string" || name.trim() === "") {
return res.status(400).send({
success: false,
message: "Invalid project name. It must be a non-empty string.",
});
}
// Validate the gitURL
if (
typeof gitURL !== "string" ||
gitURL.trim() === "" ||
!gitURLPattern.test(gitURL)
) {
return res.status(400).send({
success: false,
error:
"Invalid git URL. It must be a non-empty string starting with github.com.",
});
}
const project = await prisma.project.create({
data: {
name,
gitURL,
subDomain: generateSlug(),
userId: req.user.id,
},
});
return res.send({
success: true,
status: "success",
message: "Project created Succefully",
project,
});
});
// Deploy the Project
app.post("/api/v1/deploy", isAuthenticatedUser, async (req, res) => {
const { projectId } = req.body;
if (typeof projectId !== "string" || !projectId || projectId.trim() === "") {
return res
.status(400)
.send({ success: false, error: "Project ID is required." });
}
const project = await prisma.project.findUnique({
where: { id: projectId, userId: req.user.id },
});
if (!project) {
return res
.status(404)
.send({ success: false, error: "Project not found." });
}
// console.log("Project ", project);
// TODO => Check any Deployment is no running
const deployment = await prisma.deployement.create({
data: {
project: { connect: { id: projectId } },
status: "READY",
},
});
// console.log("Deployment ", deployment);
// Spin the container AWS
const command = new RunTaskCommand({
cluster: config.CLUSTER,
taskDefinition: config.TASK,
launchType: "FARGATE",
count: 1,
networkConfiguration: {
awsvpcConfiguration: {
assignPublicIp: "ENABLED",
subnets: [
"subnet-0f1c8efa3a40f272e",
"subnet-0b0d86a51a477985e",
"subnet-08d6adbe482395c1b",
],
securityGroups: ["sg-0eed262b572e26da8"],
},
},
overrides: {
containerOverrides: [
{
name: "builder-image",
environment: [
{ name: "GIT_REPOSITORY__URL", value: project.gitURL },
{ name: "PROJECT_ID", value: projectId },
{ name: "DEPLOYEMENT_ID", value: deployment.id },
{ name: "AWS_ACCESSKEYID", value: config.AWS_ACCESSKEYID },
{ name: "AWS_SECRETACCESSKEY", value: config.AWS_SECRETACCESSKEY },
// { name: "REDIS_HOST", value: config.REDIS_HOST },
// { name: "REDIS_PORT", value: config.REDIS_PORT },
// { name: "REDIS_PASSWORD", value: config.REDIS_PASSWORD },
{ name: "KAFKA_BROKER_URL", value: config.KAFKA_BROKER_URL },
{ name: "KAFKA_USER_NAME", value: config.KAFKA_USER_NAME },
{ name: "KAFKA_PASSWORD", value: config.KAFKA_PASSWORD },
],
},
],
},
});
await ecsClient.send(command);
// return res.json({
// status: "queued",
// data: { projectSlug, url: `http://${projectSlug}.localhost:8000` },
// });
return res.json({
success: true,
status: "queued",
message: "Deployed Succefully",
data: {
deploymentId: deployment.id,
url: `http://${project.subDomain}.${config.FRONTEND_PROXY_URL}`,
},
});
// Run the Docker image locally
// const command = `docker run -it -e GIT_REPOSITORY__URL=${project.gitURL} -e PROJECT_ID=${projectId} -e DEPLOYEMENT_ID=${deployment.id} -e AWS_ACCESSKEYID=${config.AWS_ACCESSKEYID} -e AWS_SECRETACCESSKEY=${config.AWS_SECRETACCESSKEY} -e KAFKA_BROKER_URL=${config.KAFKA_BROKER_URL} -e KAFKA_USER_NAME=${config.KAFKA_USER_NAME} -e KAFKA_PASSWORD=${config.KAFKA_PASSWORD} builder-server`;
// exec(command, (error, stdout, stderr) => {
// if (error) {
// console.error(`Error executing Docker run: ${error}`);
// return res.status(500).json({
// error: "Failed to run Docker image",
// details: stderr || stdout,
// });
// }
// console.log(`Docker run output: ${stdout}`);
// if (stderr) {
// console.error(`Docker run error: ${stderr}`);
// }
// // return res.json({
// // status: "queued",
// // data: { projectSlug, url: `http://${projectSlug}.localhost:8000` },
// // });
// return res.json({
// status: "queued",
// data: {
// deploymentId: deployment.id,
// url: `http://${project.subDomain}.${config.FRONTEND_PROXY_URL}`,
// },
// });
// });
});
// Get logs
app.get("/api/v1/logs/:id", isAuthenticatedUser, async (req, res) => {
const id = req.params.id; // Deployment ID
const logs = await clickhouseClient.query({
query: `SELECT event_id, deployment_id, log, timestamp from log_events where deployment_id = {deployment_id:String}`,
query_params: {
deployment_id: id,
},
format: "JSONEachRow",
});
const rawLogs = await logs.json();
return res.status(200).send({ success: true, logs: rawLogs });
});
// get the Visitors Count
app.get(
"/api/v1/visitor-count/:projectID",
isAuthenticatedUser,
async (req, res) => {
const { projectID } = req.params;
try {
const result = await clickhouseClient.query({
query: `
SELECT
date,
SUM(visitor_count) AS visitor_count
FROM
visitor_counts
WHERE
project_id = {projectID:String}
GROUP BY
date
ORDER BY
date DESC
LIMIT 15;
`,
query_params: { projectID },
format: "JSONEachRow",
});
const data = await result.json();
res.status(200).json(data);
} catch (err) {
console.error("Error fetching visitor data: ", err);
res.status(500).json({ error: "Failed to fetch visitor data" });
}
}
);
// Socket
io.on("connection", (socket) => {
console.log("Connection ", socket.id);
socket.on("subscribe", (channel) => {
socket.join(channel);
socket.emit("message", `Joined ${channel}`);
});
});
// initRedisSubscribe(); // For redis
initLogConsumer(); // Kafka
initVisitorConsumer();
server.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});