@opengis/fastify-table
Version:
core-plugins
77 lines (61 loc) • 2.5 kB
JavaScript
import { createHash } from 'node:crypto';
import config from '../../../config.js';
import getPG from '../pg/funcs/getPG.js';
import pgClients from '../pg/pgClients.js';
import getRedis from '../redis/funcs/getRedis.js';
import logger from '../logger/getLogger.js';
import interval2ms from './funcs/interval2ms.js';
const rclient = getRedis();
async function runCron({
pg = pgClients.client, query, name,
}) {
const db = pg?.options?.database;
// verifyUnique
const key = `cron:unique:${name}`;
const unique = config.redis ? await rclient.setnx(key, 1) : null;
const ttl = config.redis ? await rclient.ttl(key) : -1;
if (!unique && ttl !== -1) {
// if (config.trace) console.log(name, db, query, 'skip unique');
return;
}
if (config.redis) {
await rclient.expire(key, 20);
}
try {
if (!pg.pk && config.pg) { await pg.init(); }
if (config.trace) console.time(`${db}:${query}`);
const { command, rows = [], rowCount } = pg?.pk ? await pg.query(query) : {};
if (config.trace) console.timeEnd(`${db}:${query}`);
logger.file('cron', { db, name, result: { command, rows, rowCount } });
}
catch (err) {
if (config.trace) console.error(name, err.toString());
logger.file('cron/error', { db, name, error: err.toString() });
logger.error(err);
}
}
async function plugin(fastify) {
if (config.cronList?.length) {
config.cronList?.filter?.(el => el.query && !el.disabled)?.forEach?.((el, idx) => {
const { interval, db, query } = el;
const name = createHash('md5').update(`${config.port || 3000}:${db}:${query}`).digest('hex');
const pg = getPG(db);
if (config.trace) console.log('cron-list: init', db, idx);
const [waitMs, intervalMs] = interval2ms[typeof interval](interval);
if (intervalMs < 1000) {
if (config.trace) console.error('cron-list: skip too small interval', db, idx);
logger.file('cron', { name, error: `interval ${interval} too small` });
return;
}
// setTimeout to w8 for the time to start
setTimeout(() => {
runCron({ pg, query, name });
// interval
setInterval(() => {
runCron({ pg, query, name });
}, intervalMs);
}, waitMs);
});
}
}
export default plugin;