Skip to content

Commit

Permalink
removed commented part from here
Browse files Browse the repository at this point in the history
  • Loading branch information
ayushhunt committed Dec 1, 2024
1 parent e886863 commit 194e07e
Show file tree
Hide file tree
Showing 2 changed files with 183 additions and 183 deletions.
166 changes: 83 additions & 83 deletions apps/triggers/src/db.status.ts
Original file line number Diff line number Diff line change
@@ -1,98 +1,98 @@
// import { cache } from "@repo/cache";
// import { logger, schedules, wait } from "@trigger.dev/sdk/v3";
// import { createClient } from '@supabase/supabase-js';
import { cache } from "@repo/cache";
import { logger, schedules, wait } from "@trigger.dev/sdk/v3";
import { createClient } from '@supabase/supabase-js';

// const supabaseUrl = process.env.SUPABASE_URL!;
// const supabaseKey = process.env.SUPABASE_KEY!;
// const db = createClient(supabaseUrl, supabaseKey);
const supabaseUrl = process.env.SUPABASE_URL!;
const supabaseKey = process.env.SUPABASE_KEY!;
const db = createClient(supabaseUrl, supabaseKey);

// export const dbStatusTask = schedules.task({
// id: "db-status",
// cron: "*/12 * * * *",
// maxDuration: 600,
// run: async (payload, { ctx }) => {
// const latencies: Record<string, number | null> = {};
// let totalLatency = 0;
// let operationCount = 0;
export const dbStatusTask = schedules.task({
id: "db-status",
cron: "*/12 * * * *",
maxDuration: 600,
run: async (payload, { ctx }) => {
const latencies: Record<string, number | null> = {};
let totalLatency = 0;
let operationCount = 0;

// const measureAndCacheLatency = async (operationName: string, operation: () => Promise<any>) => {
// const startTime = Date.now();
// try {
// await operation();
// const latency = Date.now() - startTime;
// latencies[operationName] = latency;
// totalLatency += latency;
// operationCount++;
const measureAndCacheLatency = async (operationName: string, operation: () => Promise<any>) => {
const startTime = Date.now();
try {
await operation();
const latency = Date.now() - startTime;
latencies[operationName] = latency;
totalLatency += latency;
operationCount++;

// logger.log(`Latency for ${operationName}`, { latency });
// } catch (error) {
// logger.error(`${operationName} failed`, { error });
// latencies[operationName] = null;
// }
// };
logger.log(`Latency for ${operationName}`, { latency });
} catch (error) {
logger.error(`${operationName} failed`, { error });
latencies[operationName] = null;
}
};

// const massOperationsCount = 100;
const massOperationsCount = 100;

// await measureAndCacheLatency("mass_create", async () => {
// const createPromises = Array.from({ length: massOperationsCount }, (_, i) =>
// db
// .from('triggers')
// .insert([{ id: `mass-${i}`, name: `Mass Test ${i}`, email: `mass${i}@test.com`, email_verified: true }])
// );
// await Promise.all(createPromises);
// });
await measureAndCacheLatency("mass_create", async () => {
const createPromises = Array.from({ length: massOperationsCount }, (_, i) =>
db
.from('triggers')
.insert([{ id: `mass-${i}`, name: `Mass Test ${i}`, email: `mass${i}@test.com`, email_verified: true }])
);
await Promise.all(createPromises);
});

// await wait.for({ seconds: 10 });
await wait.for({ seconds: 10 });

// await measureAndCacheLatency("mass_read", async () => {
// const { data, error } = await db
// .from('triggers')
// .select('*')
// if (error) {
// logger.error('Error fetching data:', { error });
// return null;
// }
// logger.log('Read data', { data });
// return data;
// });
await measureAndCacheLatency("mass_read", async () => {
const { data, error } = await db
.from('triggers')
.select('*')
if (error) {
logger.error('Error fetching data:', { error });
return null;
}
logger.log('Read data', { data });
return data;
});

// await wait.for({ seconds: 15 });
await wait.for({ seconds: 15 });

// await measureAndCacheLatency("mass_update", async () => {
// const updatePromises = Array.from({ length: massOperationsCount }, (_, i) =>
// db
// .from('triggers')
// .update({ name: `Updated Mass Test ${i}`, email_verified: false })
// .eq('id', `mass-${i}`)
// );
// await Promise.all(updatePromises);
// });
await measureAndCacheLatency("mass_update", async () => {
const updatePromises = Array.from({ length: massOperationsCount }, (_, i) =>
db
.from('triggers')
.update({ name: `Updated Mass Test ${i}`, email_verified: false })
.eq('id', `mass-${i}`)
);
await Promise.all(updatePromises);
});

// await wait.for({ seconds: 10 });
await wait.for({ seconds: 10 });

// await measureAndCacheLatency("mass_delete", async () => {
// const deletePromises = Array.from({ length: massOperationsCount }, (_, i) =>
// db
// .from('triggers')
// .delete()
// .eq('id', `mass-${i}`)
// );
// await Promise.all(deletePromises);
// });
await measureAndCacheLatency("mass_delete", async () => {
const deletePromises = Array.from({ length: massOperationsCount }, (_, i) =>
db
.from('triggers')
.delete()
.eq('id', `mass-${i}`)
);
await Promise.all(deletePromises);
});

// await wait.for({ seconds: 5 });
await wait.for({ seconds: 5 });

// const averageLatency = operationCount > 0 ? totalLatency / operationCount : null;
// const latencyRecord = {
// timestamp: new Date().toISOString(),
// latencies,
// totalLatency,
// operationCount,
// averageLatency,
// massOperationsCount,
// };
const averageLatency = operationCount > 0 ? totalLatency / operationCount : null;
const latencyRecord = {
timestamp: new Date().toISOString(),
latencies,
totalLatency,
operationCount,
averageLatency,
massOperationsCount,
};

// await cache.rpush("db-latency:history", JSON.stringify(latencyRecord));
// await cache.ltrim("db-latency:history", -120, -1);
// },
// });
await cache.rpush("db-latency:history", JSON.stringify(latencyRecord));
await cache.ltrim("db-latency:history", -120, -1);
},
});
200 changes: 100 additions & 100 deletions apps/triggers/src/site.status.ts
Original file line number Diff line number Diff line change
@@ -1,111 +1,111 @@
// import { cache } from "@repo/cache";
// import { logger, schedules } from "@trigger.dev/sdk/v3";
import { cache } from "@repo/cache";
import { logger, schedules } from "@trigger.dev/sdk/v3";

// const DISCORD_WEBHOOK_URL = process.env.DISCORD_WEBHOOK!;
// const LATENCY_THRESHOLD = 1000;
const DISCORD_WEBHOOK_URL = process.env.DISCORD_WEBHOOK!;
const LATENCY_THRESHOLD = 1000;

// export const siteStatusTask = schedules.task({
// id: "site-status",
// cron: "*/12 * * * *",
// maxDuration: 600,
// run: async () => {
// const urls = {
// WEB: "https://www.plura.pro",
// API: "https://api.plura.pro/api/health",
// APP: "https://app.plura.pro/events",
// };
export const siteStatusTask = schedules.task({
id: "site-status",
cron: "*/12 * * * *",
maxDuration: 600,
run: async () => {
const urls = {
WEB: "https://www.plura.pro",
API: "https://api.plura.pro/api/health",
APP: "https://app.plura.pro/events",
};

// const latencies: Record<string, number | null> = {};
// const statuses: Record<string, string | null> = {};
// let totalLatency = 0;
// let operationCount = 0;
const latencies: Record<string, number | null> = {};
const statuses: Record<string, string | null> = {};
let totalLatency = 0;
let operationCount = 0;

// for (const [name, url] of Object.entries(urls)) {
// const startTime = Date.now();
// try {
// const response = await fetch(url, { method: "GET" });
// const latency = Date.now() - startTime;
// latencies[name] = latency;
// statuses[name] = response.ok ? "UP" : `DOWN (Status ${response.status})`;
// totalLatency += latency;
// operationCount++;
for (const [name, url] of Object.entries(urls)) {
const startTime = Date.now();
try {
const response = await fetch(url, { method: "GET" });
const latency = Date.now() - startTime;
latencies[name] = latency;
statuses[name] = response.ok ? "UP" : `DOWN (Status ${response.status})`;
totalLatency += latency;
operationCount++;

// logger.log(`${name} is ${statuses[name]}`, { latency });
logger.log(`${name} is ${statuses[name]}`, { latency });

// // Send to Discord if the service is down or latency exceeds threshold
// if (!response.ok || latency > LATENCY_THRESHOLD) {
// await sendDiscordNotification(name, statuses[name], latency);
// }
// } catch (error: any) {
// latencies[name] = null;
// statuses[name] = `DOWN (Error: ${error.message})`;
// logger.error(`${name} check failed`, { error });
// await sendDiscordNotification(name, "DOWN", null, error.message);
// }
// }
// Send to Discord if the service is down or latency exceeds threshold
if (!response.ok || latency > LATENCY_THRESHOLD) {
await sendDiscordNotification(name, statuses[name], latency);
}
} catch (error: any) {
latencies[name] = null;
statuses[name] = `DOWN (Error: ${error.message})`;
logger.error(`${name} check failed`, { error });
await sendDiscordNotification(name, "DOWN", null, error.message);
}
}

// const averageLatency = operationCount > 0 ? totalLatency / operationCount : null;
// const statusRecord = {
// timestamp: new Date().toISOString(),
// latencies,
// statuses,
// totalLatency,
// operationCount,
// averageLatency,
// };
const averageLatency = operationCount > 0 ? totalLatency / operationCount : null;
const statusRecord = {
timestamp: new Date().toISOString(),
latencies,
statuses,
totalLatency,
operationCount,
averageLatency,
};

// // Push the status record to a list in Redis
// await cache.rpush("site-latency:history", JSON.stringify(statusRecord));
// await cache.ltrim("site-latency:history", -120, -1);
// },
// });
// Push the status record to a list in Redis
await cache.rpush("site-latency:history", JSON.stringify(statusRecord));
await cache.ltrim("site-latency:history", -120, -1);
},
});

// // Function to send notifications to Discord webhook
// async function sendDiscordNotification(
// serviceName: string,
// status: string | null,
// latency: number | null = null,
// error: string | null = null
// ) {
// const ROLE_ID = "1308042212319428668";
// const downMsg = `🚨 Service **${serviceName}** is experiencing issues!`;
// const upMsg = `📢 Service **${serviceName}** is having high latency!`;
// const NotifyMsg = status === "UP" ? upMsg : downMsg;
// const message = {
// content: `<@&${ROLE_ID}> ${NotifyMsg}`,
// embeds: [
// {
// title: `Status Alert for ${serviceName}`,
// description: `Service **${serviceName}** is currently **${status}**.`,
// color: status === "UP" ? 3066993 : 15158332, // Green for UP, Red for DOWN
// fields: [
// {
// name: "Latency",
// value: latency !== null ? `${latency} ms` : "N/A",
// inline: true,
// },
// {
// name: "Error",
// value: error || "None",
// inline: true,
// },
// ],
// timestamp: new Date().toISOString(),
// },
// ],
// };
// Function to send notifications to Discord webhook
async function sendDiscordNotification(
serviceName: string,
status: string | null,
latency: number | null = null,
error: string | null = null
) {
const ROLE_ID = "1308042212319428668";
const downMsg = `🚨 Service **${serviceName}** is experiencing issues!`;
const upMsg = `📢 Service **${serviceName}** is having high latency!`;
const NotifyMsg = status === "UP" ? upMsg : downMsg;
const message = {
content: `<@&${ROLE_ID}> ${NotifyMsg}`,
embeds: [
{
title: `Status Alert for ${serviceName}`,
description: `Service **${serviceName}** is currently **${status}**.`,
color: status === "UP" ? 3066993 : 15158332, // Green for UP, Red for DOWN
fields: [
{
name: "Latency",
value: latency !== null ? `${latency} ms` : "N/A",
inline: true,
},
{
name: "Error",
value: error || "None",
inline: true,
},
],
timestamp: new Date().toISOString(),
},
],
};

// try {
// await fetch(DISCORD_WEBHOOK_URL, {
// method: "POST",
// headers: {
// "Content-Type": "application/json",
// },
// body: JSON.stringify(message),
// });
// logger.log(`Notification sent to Discord for ${serviceName}`, { status, latency });
// } catch (notificationError) {
// logger.error("Failed to send notification to Discord", { notificationError });
// }
// }
try {
await fetch(DISCORD_WEBHOOK_URL, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(message),
});
logger.log(`Notification sent to Discord for ${serviceName}`, { status, latency });
} catch (notificationError) {
logger.error("Failed to send notification to Discord", { notificationError });
}
}

0 comments on commit 194e07e

Please sign in to comment.