Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
# Stage 1: Builder
FROM node:20-bullseye-slim AS builder
FROM node:22-bookworm-slim AS builder

# Install prerequisites
RUN apt-get update && apt-get install -y curl unzip build-essential pkg-config libssl-dev
Expand Down Expand Up @@ -27,7 +27,7 @@ RUN mkdir -p ./src/database/sqlite
RUN if [ ! -f ./src/database/sqlite/*.sqlite ]; then bun db:push; fi

# Stage 2: Release
FROM node:20-bullseye-slim AS release
FROM node:22-bookworm-slim AS release
WORKDIR /usr/src/Yuuko

# Install production dependencies and CA certificates
Expand Down
400 changes: 142 additions & 258 deletions bun.lock

Large diffs are not rendered by default.

38 changes: 22 additions & 16 deletions eslint.config.js
Original file line number Diff line number Diff line change
@@ -1,17 +1,23 @@
import antfu from '@antfu/eslint-config'
import { FlatCompat } from '@eslint/eslintrc'
import antfu from "@antfu/eslint-config";

const compat = new FlatCompat()

export default antfu(
{
ignores: ['n/prefer-global/process'],
},

...compat.config({
extends: [
'eslint:recommended',
],
}),

)
export default antfu({
stylistic: false,
ignores: ["n/prefer-global/process"],
perfectionist: false,
typescript: {
tsconfigPath: "tsconfig.json",
tsconfigRootDir: import.meta.dirname,
overrides: {
"ts/no-floating-promises": "error",
"ts/no-misused-promises": "error",
"ts/await-thenable": "error",
"ts/consistent-type-definitions": "off",
"import/consistent-type-specifier-style": "off",
},
},
rules: {
"ts/strict-boolean-expressions": "off",
"ts/no-non-null-asserted-optional-chain": "off",
"antfu/no-top-level-await": "off",
},
});
8 changes: 4 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,8 @@
"start:prod": "NODE_ENV=production bun run ./src/app.ts",
"test": "echo \"Error: no test specified\" && exit 1",
"format": "prettier --write .",
"lint": "eslint .",
"lint:fix": "eslint . --fix",
"lint": "eslint ./src",
"lint:fix": "eslint ./src --fix",
"module:build": "sh ./src/modules/build.sh",
"gen:gql": "graphql-codegen",
"gen:queries": "bun run ./src/scripts/genQueries.ts",
Expand All @@ -43,7 +43,7 @@
"zod": "^4.3.6"
},
"devDependencies": {
"@antfu/eslint-config": "^8.1.1",
"@antfu/eslint-config": "^9.5.1",
"@graphql-codegen/cli": "^6.2.1",
"@graphql-codegen/typescript": "^5.0.9",
"@graphql-codegen/typescript-operations": "^5.0.9",
Expand All @@ -57,7 +57,7 @@
"drizzle-kit": "^0.31.10",
"eslint": "^10.2.0",
"prettier": "^3.8.1",
"prettier-eslint": "^16.4.2",
"prettier-eslint": "^17.1.2",
"typescript": "^6.0.2"
}
}
2 changes: 1 addition & 1 deletion src/api.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
import { startApi } from "#api/index";

startApi();
await startApi();
2 changes: 1 addition & 1 deletion src/api/controllers/global.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ export const api = new Elysia({
security: [{ BearerAuth: [] }],
},
beforeHandle({ set, headers }) {
if (!headers.authorization || !env().TRUSTED_USERS.includes(headers.authorization)) {
if (!headers.authorization || !env.TRUSTED_USERS.includes(headers.authorization)) {
set.status = 401;
return { message: "Unauthorized" };
}
Expand Down
11 changes: 7 additions & 4 deletions src/api/controllers/info.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { Elysia, t } from "elysia";
import { db, tables } from "#database/db";
import { getStats } from "#utils/botStats";
import { srcPath } from "#utils/paths";
import { LogEntrySchema } from "#src/utils/logger";
import { LogEntrySchema, type LogEntry } from "#src/utils/logger";

export const infoController = new Elysia({
prefix: "/info",
Expand All @@ -15,6 +15,7 @@ export const infoController = new Elysia({
({ set }) => {
set.headers["content-type"] = "application/json";
set.status = 200;

return readLogFile();
},
{
Expand Down Expand Up @@ -65,7 +66,7 @@ export const infoController = new Elysia({
async ({ set }) => {
set.headers["content-type"] = "application/json";
set.status = 200;
return await getStats();
return getStats();
},
{
detail: {
Expand All @@ -82,8 +83,10 @@ export const infoController = new Elysia({

);

function readLogFile() {
function readLogFile(): LogEntry[] {
const logPath = srcPath("logging", "logs.json");
if (!fs.existsSync(logPath)) return [];

const lines = fs.readFileSync(logPath, "utf-8").split("\n").filter(Boolean);
return lines.map((line) => JSON.parse(line));
return lines.map((line) => JSON.parse(line) as LogEntry);
}
7 changes: 3 additions & 4 deletions src/api/controllers/trigger.controller.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { execSync, spawnSync } from "child_process";
import { execSync } from "node:child_process";
import fs from "node:fs";
import { Elysia, t } from "elysia";
import { db, sqlite, tables } from "#database/db";
import fs from "fs";
import { srcPath } from "#utils/paths";

export const triggerController = new Elysia({
Expand All @@ -11,7 +11,6 @@ export const triggerController = new Elysia({
.post(
"/restart",
async ({ set }) => {
const update = spawnSync("sh", ["update.sh"]);
sqlite.close();
set.status = 202;
return { message: "Successfully restarted the bot!" };
Expand All @@ -24,7 +23,7 @@ export const triggerController = new Elysia({
},
afterHandle() {
execSync('pm2 restart "Yuuko Production"', { encoding: "utf-8" });
setTimeout(() => execSync('pm2 restart "Yuuko Production API"', { encoding: "utf-8" }), 500);
setTimeout(execSync, 500, 'pm2 restart "Yuuko Production API"', { encoding: "utf-8" });
},
response: {
202: t.Object({ message: t.String() }),
Expand Down
2 changes: 1 addition & 1 deletion src/api/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { env } from "#env";
import { logger } from "#src/utils/logger";

export async function startApi() {
const port = env().API_PORT;
const port = env.API_PORT;

await RSA.loadKeys();

Expand Down
17 changes: 11 additions & 6 deletions src/app.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import process from "node:process";
import dotenvFlow from "dotenv-flow";
import { db, sqlite, tables } from "#database/db";
import { Client } from "#structures/index";
Expand All @@ -23,12 +24,12 @@ process.on("SIGINT", () => {
async function start(token: string | undefined) {
await RSA.loadKeys();
await registerEvents(client);
await runChecks(client);
await runChecks();

client.login(token);
await client.login(token);
await updateBotStats(client);

env().UPTIME = Date.now();
env.UPTIME = Date.now();
}

async function initializeWorkerDB() {
Expand All @@ -48,18 +49,19 @@ async function initializeWorkerDB() {
.where(eq(tables.workerEvents.type, "SYNC"));
}

await start(env().TOKEN);
await start(env.TOKEN);
await initializeWorkerDB();

workerManager.onmessage = async (e) => {
workerManager.onmessage = async (e: MessageEvent<WorkerResponseUnion>) => {
if (!e.data.type) return;
const data = e.data as WorkerResponseUnion;
const data = e.data;

switch (data.type) {
case 'LOG': {
logger.log(data.level, data.text);
break;
}

case "SYNC": {
await db.update(tables.workerEvents)
.set({ updatedAt: sql`current_timestamp` })
Expand All @@ -68,5 +70,8 @@ workerManager.onmessage = async (e) => {
await syncAnilistUsers(data);
break;
}

case "REMINDER":
break;
}
};
15 changes: 8 additions & 7 deletions src/caching/redis.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import { createClient } from "redis";
import { env } from "#env";
import { logger } from "#src/utils/logger";
import { handleAsync } from "#src/utils";

const host = env().NODE_ENV === "docker" ? "dragonfly" : "localhost";
const host = env.NODE_ENV === "docker" ? "dragonfly" : "localhost";

export const redis = createClient({
socket: {
Expand All @@ -15,11 +16,11 @@ redis.on("error", (err) => {
logger.error(err);
});

redis.on("connect", () => {
redis.on("connect", handleAsync(async () => {
logger.info(`Connected to ${host}!`);
redis.set("test", "test");
});
await redis.set("test", "test");
}));

(async () => {
redis.connect();
})();
handleAsync((async () => {
await redis.connect();
}))();
47 changes: 25 additions & 22 deletions src/checks/run.ts
Original file line number Diff line number Diff line change
@@ -1,26 +1,28 @@
import fs from 'node:fs'
import { Client, type Check } from "#structures/index";
import path from 'node:path';
import type { Check } from "#structures/index";
import { srcPath } from "#utils/paths";
import { logger } from "#src/utils/logger";

export async function runChecks(client: Client) {
export async function runChecks() {
// Flatten the array of checks
const checks: Check[] = (
await Promise.all(
fs
.readdirSync(srcPath("checks"))
.filter(file => file.endsWith('.ts') && file !== 'run.ts')
.map(async (file) => {
const check = await import(srcPath("checks", file))
return check.default
}),
)
).flat()
const checksPath = srcPath("checks");
const checkFiles = fs.readdirSync(checksPath).filter((file) => file.endsWith(".ts"));

const checks: Check[] = [];

for (const file of checkFiles) {
const filePath = path.join(checksPath, file);
const module = await import(filePath) as { default: Check };

checks.push(module.default);
}

logger.info("Running checks", { type: "check", total: checks.length });

for (const check of checks) {
try {
check.run()
await check.run()
logger.info("Check passed", { type: "check", name: check.name, optional: check.optional });
}
catch (e) {
Expand All @@ -35,7 +37,7 @@ export async function runChecks(client: Client) {
else {
throw new Error(`Critical check "${check.name}" failed
> Purpose: ${check.description}
> Why: ${e}
> Why: ${serializeError(e)}
`)
}
}
Expand All @@ -44,13 +46,14 @@ export async function runChecks(client: Client) {
logger.info("Checks passed!");
}

function serializeError(e: unknown) {
function serializeError(e: unknown): string {
if (e instanceof Error) {
return {
message: e.message,
stack: e.stack,
name: e.name,
};
return e.stack ?? e.message;
}

if (typeof e === "object" && e !== null) {
return JSON.stringify(e);
}
return e;

return String(e);
}
1 change: 1 addition & 0 deletions src/checks/verifyEnv.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { Check } from '#structures/index'
import process from 'node:process';

const tokenCheck = new Check({
name: 'Token Check',
Expand Down
2 changes: 1 addition & 1 deletion src/checks/verifyModules.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import fs from 'fs'
import fs from 'node:fs'
import { Check } from '#structures/index'
import { suffix } from "bun:ffi";
import { srcPath } from '#utils/paths'
Expand Down
2 changes: 1 addition & 1 deletion src/checks/verifyRSA.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import fs from 'fs'
import fs from 'node:fs'
import { RSA } from '#utils/rsaEncryption'
import { Check } from '#structures/index'
import { srcPath } from '#utils/paths'
Expand Down
Loading
Loading