UNPKG

@opengis/fastify-table

Version:

core-plugins

76 lines (75 loc) 2.73 kB
/* eslint-disable no-console */ 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 { cronList } = config; const rclient = getRedis(); async function runCron({ query, name }, pg = pgClients.client) { 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() { if (cronList?.length) { 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({ query, name }, pg); // interval setInterval(() => { runCron({ query, name }, pg); }, intervalMs); }, waitMs); }); } } export default plugin;