interface with db

This commit is contained in:
2025-01-12 01:14:50 -05:00
parent f02676ba2e
commit 07ab1fb40d
13 changed files with 366 additions and 29 deletions

196
src/DB.ts Normal file
View File

@@ -0,0 +1,196 @@
import { Sequelize, DataTypes, Op, } from 'sequelize';
import type { ModelStatic, Filterable } from 'sequelize';
interface DBConfig {
db?: string;
user?: string;
password?: string;
host?: string;
port?: number;
}
const MONTH = 1000 * 60 * 60 * 24 * 24;
const FRESH = {
[Op.or]: [
{ startTime: { [Op.gt]: new Date(Date.now() - MONTH) } },
{ startTime: { [Op.is]: null } }
]
}
const SELECT = ['id', 'repo', 'commit', 'distro', 'startTime', 'endTime', 'status'];
class DB {
private build: ModelStatic<any>;
private sequelize: Sequelize;
constructor(config: DBConfig = {}) {
this.sequelize = new Sequelize(config.db || 'archery', config.user || 'archery', config.password || '', {
host: config.host || 'localhost',
port: config.port || 5432,
dialect: 'postgres'
});
this.build = this.sequelize.define('builds', {
id: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true
},
repo: {
type: DataTypes.STRING,
allowNull: false
},
commit: {
type: DataTypes.STRING,
allowNull: true
},
patch: {
type: DataTypes.TEXT,
allowNull: true
},
distro: {
type: DataTypes.STRING,
allowNull: false
},
startTime: {
type: DataTypes.DATE,
allowNull: true
},
endTime: {
type: DataTypes.DATE,
allowNull: true
},
status: {
type: DataTypes.ENUM('queued', 'running', 'cancelled', 'success', 'error'),
allowNull: false,
defaultValue: 'queued'
},
pid: {
type: DataTypes.INTEGER,
allowNull: true
},
log: {
type: DataTypes.TEXT,
allowNull: true
}
});
this.build.sync();
}
public async createBuild(repo: string, commit: string, patch: string, distro: string): Promise<number> {
const buildRec = await this.build.create({
repo,
commit: commit || null,
patch: patch || null,
distro
});
return buildRec.id;
}
public async startBuild(id: number, pid: number): Promise<void> {
await this.build.update({
startTime: new Date(),
status: 'running',
pid,
log: ''
}, {
where: {
id
}
});
}
public async finishBuild(id: number, status: string): Promise<void> {
await this.build.update({
endTime: new Date(),
status
}, {
where: {
id
}
});
}
public async appendLog(id: number, log: string): Promise<void> {
await this.build.update({
log: Sequelize.literal(`log || '${log}'`)
}, {
where: {
id
}
});
}
public async getBuild(id: number): Promise<any> {
return await this.build.findByPk(id);
}
public async getBuilds(): Promise<any> {
return await this.build.findAll({
attributes: SELECT,
order: [['id', 'DESC']],
where: FRESH,
});
}
public async getBuildsByStatus(status: string): Promise<any> {
return await this.build.findAll({
attributes: SELECT,
order: [['id', 'DESC']],
where: {
...FRESH,
status
}
});
}
public async getBuildsByDistro(distro: string): Promise<any> {
return await this.build.findAll({
attributes: SELECT,
order: [['id', 'DESC']],
where: {
...FRESH,
distro
}
});
}
public async getBuildsBy(filterable: Filterable): Promise<any> {
return await this.build.findAll({
attributes: SELECT,
order: [['id', 'DESC']],
where: {
...FRESH,
...filterable
}
});
}
public async searchBuilds(query: string): Promise<any> {
return await this.build.findAll({
attributes: SELECT,
order: [['id', 'DESC']],
where: {
[Op.or]: [
{ repo: { [Op.iLike]: `%${query}%` } }
]
},
limit: 100
});
}
public async cleanup(): Promise<void> {
await this.build.destroy({
where: {
startTime: { [Op.lt]: new Date(Date.now() - MONTH * 6) }
}
});
}
public async close(): Promise<void> {
await this.sequelize.close();
}
}
export default DB;
export { DB };
export type { DBConfig };

View File

@@ -2,6 +2,8 @@ import * as http from "http";
import crypto from 'crypto';
import type { Express } from "express";
import express, { application } from 'express';
import bodyParser from "body-parser";
import type { DB } from "./DB.ts";
interface WebConfig {
port?: number;
@@ -16,6 +18,7 @@ function notStupidParseInt(v: string | undefined): number {
class Web {
private _webserver: http.Server | null = null;
private db: DB;
constructor(options: WebConfig = {}) {
const app: Express = express();
@@ -25,6 +28,8 @@ class Web {
app.set('view engine', 'ejs');
app.set('view options', { outputFunctionName: 'echo' });
app.use('/assets', express.static('assets', { maxAge: '30 days' }));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use((_req, res, next) => {
crypto.randomBytes(32, (err, randomBytes) => {
if (err) {
@@ -37,18 +42,26 @@ class Web {
});
});
app.get('/', (_, res) => {
res.render('index', {
page: {
title: 'Archery',
titlesuffix: 'Dashboard',
description: 'PKGBUILD central'
}
});
app.get('/', async (req, res) => {
try {
const builds = await this.db.getBuildsBy(req.query);
res.render('index', {
page: {
title: 'Archery',
titlesuffix: 'Dashboard',
description: 'PKGBUILD central'
},
builds
});
}
catch (err) {
console.error(err);
res.sendStatus(400);
}
});
app.get('/build/?', (_, res) => {
res.render('build', {
res.render('build-new', {
page: {
title: 'Archery',
titlesuffix: 'New Build',
@@ -57,6 +70,36 @@ class Web {
});
});
app.post('/build/?', async (req, res) => {
const build = await this.db.createBuild(req.body.repo, req.body.commit || null, req.body.patch || null, req.body.distro);
res.redirect(`/build/${build}`);
});
app.get('/build/:num/?', async (req, res) => {
const build = await this.db.getBuild(parseInt(req.params.num));
if (!build) {
res.sendStatus(404);
return;
}
res.render('build', {
page: {
title: 'Archery',
titlesuffix: `Build #${req.params.num}`,
description: `Building ${build.repo} on ${build.distro}`
},
build
});
});
app.get('/build/:num/logs/?', async (req, res) => {
const build = await this.db.getBuild(parseInt(req.params.num));
if (!build) {
res.sendStatus(404);
return;
}
res.set('Content-Type', 'text/plain').send(build.log);
});
app.get('/healthcheck', (_, res) => {
res.send('Healthy');
});
@@ -69,6 +112,12 @@ class Web {
this._webserver.close();
}
}
setDB = (db: DB) => {
this.db = db;
}
}
export default Web;
export default Web;
export { Web };
export type { WebConfig };

View File

@@ -1,9 +1,23 @@
import fs from 'fs';
import path from 'path';
import Web from './Web.ts';
import { Web } from './Web.ts';
import { DB } from './DB.ts';
import type { WebConfig } from './Web.ts';
import type { DBConfig } from './DB.ts';
const config = JSON.parse(await fs.promises.readFile(process.env.config || path.join('config', 'config.json'), 'utf-8'));
interface compositeConfig {
web?: WebConfig,
db?: DBConfig
}
const web = new Web(config);
const config: compositeConfig = JSON.parse(await fs.promises.readFile(process.env.config || path.join('config', 'config.json'), 'utf-8'));
process.on('SIGTERM', web.close);
const web = new Web(config.web);
await new Promise((resolve) => setTimeout(resolve, 1500));
const db = new DB(config.db);
web.setDB(db);
process.on('SIGTERM', () => {
web.close();
db.close();
});