Skip to content

Commit

Permalink
feat: instrument tracing on commands
Browse files Browse the repository at this point in the history
  • Loading branch information
aldy505 committed Dec 31, 2023
1 parent 3f85d42 commit 485bc4f
Show file tree
Hide file tree
Showing 18 changed files with 254 additions and 29 deletions.
10 changes: 10 additions & 0 deletions .idea/.gitignore

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

9 changes: 9 additions & 0 deletions .idea/bot.iml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

63 changes: 63 additions & 0 deletions .idea/codeStyles/Project.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 5 additions & 0 deletions .idea/codeStyles/codeStyleConfig.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 6 additions & 0 deletions .idea/inspectionProfiles/Project_Default.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 6 additions & 0 deletions .idea/jsLibraryMappings.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

11 changes: 11 additions & 0 deletions .idea/misc.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 8 additions & 0 deletions .idea/modules.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 6 additions & 0 deletions .idea/vcs.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

54 changes: 47 additions & 7 deletions src/app.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import { memoryUsage } from "process";
import { fork } from "child_process";
import { memoryUsage } from "node:process";
import { fork } from "node:child_process";
import { Telegraf } from "telegraf";
import dotenv from "dotenv";
import mongoose from "mongoose";
import Datastore from "@teknologi-umum/nedb-promises";
import * as Sentry from "@sentry/node";

import { sentry, terminal, logger } from "#utils/logger/index.js";
import { terminal, logger } from "#utils/logger/index.js";
import { pathTo } from "#utils/path.js";

import * as poll from "#services/poll/index.js";
Expand All @@ -25,9 +26,24 @@ import * as analytics from "#services/analytics/index.js";
import * as news from "#services/news/index.js";
import * as qr from "#services/qr/index.js";
import * as pesto from "#services/pesto/index.js";
import { getCommandName } from "#utils/command.js";

dotenv.config({ path: pathTo(import.meta.url, "../.env") });


Sentry.init({
dsn: process.env.SENTRY_DSN,
enabled: process.env.NODE_ENV === "production",
environment: process.env.NODE_ENV,
sampleRate: 1.0,
tracesSampleRate: 0.2,
integrations: [
new Sentry.Integrations.Http({ tracing: true }),
new Sentry.Integrations.Undici(),
...Sentry.autoDiscoverNodePerformanceMonitoringIntegrations()
]
});

const bot = new Telegraf(process.env.BOT_TOKEN);
const cache = Datastore.create();
const mongo = mongoose.createConnection(String(process.env.MONGO_URL), {
Expand All @@ -37,11 +53,12 @@ const mongo = mongoose.createConnection(String(process.env.MONGO_URL), {
// Fork processes
const hackernewsFork = fork(pathTo(import.meta.url, "./hackernews.js"), { detached: true });

function terminate(caller) {
async function terminate(caller) {
const t = Date.now();
mongo.close();
bot.stop(caller);
hackernewsFork.kill();
await mongo.close();
await Sentry.flush();
terminal.info(`${caller}: ${Date.now() - t}ms`);
}

Expand All @@ -58,6 +75,29 @@ async function main() {
return;
}

// TODO: Move this somewhere else
const validCommands = ["blidingej", "covid", "devread", "dukun", "eval", "laodeai", "news", "hilih", "joke", "kktbsys", "yntks", "homework", "illuminati", "c", "cpp", "clisp", "dotnet", "go", "java", "js", "julia", "lua", "php", "python", "ruby", "sqlite3", "ts", "v", "brainfuck", "qr", "quote", "search", "snap"];
if (ctx.updateType === "message") {
const command = getCommandName(ctx);
if (command === "" || !validCommands.includes(command)) {
next();
return;
}

Sentry.startSpan({
name: command,
op: "bot.update",
data: {
from_username: ctx.from.username,
chat_type: ctx.message.chat.type,
chat_title: ctx.message.chat.title
}
}, () => {
next();
});
return;
}

next();
});

Expand All @@ -83,11 +123,11 @@ async function main() {
.filter((v) => Array.isArray(v))
.flat();

bot.telegram.setMyCommands(commands);
await bot.telegram.setMyCommands(commands);

bot.catch(async (error, context) => {
try {
sentry.captureException(error, (scope) => {
Sentry.captureException(error, (scope) => {
scope.setContext("chat", {
chat_id: context.message.chat.id,
chat_title: context.message.chat.title,
Expand Down
4 changes: 2 additions & 2 deletions src/hackernews.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { Telegraf } from "telegraf";
import dotenv from "dotenv";
import * as Sentry from "@sentry/node";
import { pathTo } from "#utils/path.js";
import { run } from "#services/hackernews/index.js";
import { sentry } from "#utils/logger/index.js";

dotenv.config({ path: pathTo(import.meta.url, "../.env") });

Expand All @@ -19,7 +19,7 @@ for (;;) {
// eslint-disable-next-line no-await-in-loop
await run(bot)
.catch((error) => {
sentry.captureException(error);
Sentry.captureException(error);
})
.finally(() => {
done = true;
Expand Down
6 changes: 3 additions & 3 deletions src/services/meme/index.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import got, { TimeoutError } from "got";
import * as Sentry from "@sentry/node";
import { randomNumber } from "carret";
import { DEFAULT_HEADERS } from "#utils/http.js";
import { isBigGroup, isHomeGroup } from "#utils/home.js";
import { logger } from "#utils/logger/logtail.js";
import { sentry } from "#utils/logger/index.js";

/**
* Send memes..
Expand Down Expand Up @@ -125,15 +125,15 @@ export function register(bot, cache) {
});
} catch (error) {
if (error instanceof TimeoutError) {
sentry.addBreadcrumb({
Sentry.addBreadcrumb({
type: "default",
level: "warning",
category: "http.request",
message: "HTTP request timeout",
data: error
});

sentry.captureException(error, {
Sentry.captureException(error, {
level: "warning",
extra: {
chat: {
Expand Down
4 changes: 2 additions & 2 deletions src/services/qr/index.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import QRCode from "qrcode";
import { getCommandArgs } from "#utils/command.js";
import { logger } from "#utils/logger/logtail.js";
import { sentry } from "#utils/logger/index.js";
import * as Sentry from "@sentry/node";

/**
* Handling /qr command
Expand Down Expand Up @@ -36,7 +36,7 @@ async function qr(context) {
"Oppss.. Service sedang error.."
);

sentry.captureException(err, {
Sentry.getCurrentHub().captureException(err, {
level: "warning",
extra: {
chat: {
Expand Down
7 changes: 4 additions & 3 deletions src/services/snap/index.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { logger, sentry } from "#utils/logger/index.js";
import * as Sentry from "@sentry/node";
import { logger } from "#utils/logger/index.js";
import { getCommandArgs } from "#utils/command.js";
import { terminal } from "#utils/logger/terminal.js";
import { generateImage } from "./utils.js";
Expand Down Expand Up @@ -101,15 +102,15 @@ async function snap(context) {
}

if (err instanceof TimeoutError) {
sentry.addBreadcrumb({
Sentry.getCurrentHub().addBreadcrumb({
type: "default",
level: "warning",
category: "http.request",
message: "HTTP request timeout",
data: err
});

sentry.captureException(err, {
Sentry.getCurrentHub().captureException(err, {
level: "warning",
extra: {
chat: {
Expand Down
26 changes: 26 additions & 0 deletions src/utils/command.js
Original file line number Diff line number Diff line change
Expand Up @@ -49,3 +49,29 @@ export const getCommandArgs = (cmd, context) => {

return context.message.text;
};

/**
* Get command name from given context
* @param {import("telegraf").Context} context - The Telegraf context
* @return {string} command argument, empty string if context is not a command
*/
export const getCommandName = (context) => {
if (context === undefined || context === null) {
return "";
}

const text = context.message.text;
if (text && !text.startsWith("/")) {
return "";
}

const command = text
.substring(1)
.split(/\s/)
.at(0);
if (command === undefined) {
return "";
}

Check warning on line 74 in src/utils/command.js

View check run for this annotation

Codecov / codecov/patch

src/utils/command.js#L73-L74

Added lines #L73 - L74 were not covered by tests

return command.replace(`@${context.me}`, "");
};
1 change: 0 additions & 1 deletion src/utils/logger/index.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,2 @@
export * from "./logtail.js";
export * from "./sentry.js";
export * from "./terminal.js";
10 changes: 0 additions & 10 deletions src/utils/logger/sentry.js

This file was deleted.

Loading

0 comments on commit 485bc4f

Please sign in to comment.