revising cron modules and better error messages

This commit is contained in:
Jacob Nguyen
2024-07-04 19:18:52 -05:00
parent 92ca9eb859
commit c252854954
15 changed files with 148 additions and 105 deletions

View File

@@ -67,8 +67,8 @@ export async function makeDependencies (conf: ValidDependencyConfig) {
container.addSingleton('@sern/errors', new __Services.DefaultErrorHandling);
container.addSingleton('@sern/modules', new Map);
container.addSingleton('@sern/emitter', new EventEmitter)
container.addWiredSingleton('@sern/cron',
(deps) => new __Services.Cron(deps as unknown as Dependencies))
container.addWiredSingleton('@sern/scheduler',
(deps) => new __Services.CronScheduler(deps as unknown as Dependencies))
conf(dependencyBuilder(container));
await container.ready();
}

View File

@@ -39,10 +39,8 @@ export const Presence = {
* @example
* ```ts
* Presence.of({
* activities: [
* { name: "Chilling out" }
* ]
* }).once() // Sets the presence once, with what's provided in '.of()'
* activities: [{ name: "Chilling out" }]
* }).once() // Sets the presence once, with what's provided in '.of()'
* ```
*/
once: () => root
@@ -50,7 +48,7 @@ export const Presence = {
}
}
export declare namespace Presence {
type Config<T extends (keyof Dependencies)[]> = {
export type Config<T extends (keyof Dependencies)[]> = {
inject?: [...T]
execute: (...v: IntoDependencies<T>) => Presence.Result;

43
src/core/schedule.ts Normal file
View File

@@ -0,0 +1,43 @@
import { CronJob } from 'cron';
export class TaskScheduler {
private __tasks: Map<string, CronJob> = new Map();
scheduleTask(taskName: string, cronExpression: string, task: () => void): boolean {
if (this.__tasks.has(taskName)) {
return false;
}
try {
const job = new CronJob(cronExpression, task);
job.start();
this.__tasks.set(taskName, job);
return true;
} catch (error) {
return false;
}
}
private stopTask(taskName: string): boolean {
const job = this.__tasks.get(taskName);
if (job) {
job.stop();
this.__tasks.delete(taskName);
return true;
}
return false;
}
private restartTask(taskName: string): boolean {
const job = this.__tasks.get(taskName);
if (job) {
job.start();
return true;
}
return false;
}
tasks(): string[] {
return Array.from(this.__tasks.keys());
}
}

View File

@@ -1,8 +1,6 @@
import type { LogPayload, Logging, ErrorHandling, Emitter } from '../interfaces';
import { AnyFunction, UnpackedDependencies } from '../../types/utility';
import cron from 'node-cron'
import type { CronEventCommand, Module } from '../../types/core-modules'
import { EventType } from './enums';
/**
* @internal
* @since 2.0.0
@@ -42,48 +40,30 @@ export class DefaultLogging implements Logging {
}
}
export class Cron implements Emitter {
export class CronScheduler {
tasks: string[] = [];
modules: Map<string, CronEventCommand> = new Map();
constructor(private deps: UnpackedDependencies) {}
private sanityCheck(eventName: string | symbol) : asserts eventName is string {
if(typeof eventName === 'symbol') throw Error("Cron cannot add symbol based listener")
}
addCronModule(module: Module) {
if(module.type !== EventType.Cron) {
throw Error("Can only add cron modules");
}
//@ts-ignore
if(!cron.validate(module.pattern)) {
throw Error("Invalid cron expression while adding " + module.name)
}
(module as CronEventCommand)
this.modules.set(module.name!, module as CronEventCommand);
}
addListener(eventName: string | symbol, listener: AnyFunction): this {
this.sanityCheck(eventName);
const retrievedModule = this.modules.get(eventName);
if(!retrievedModule) throw Error("Adding task: module " +eventName +"was not found");
const { pattern, name, runOnInit, timezone } = retrievedModule;
cron.schedule(pattern,
(date) => listener({ date, deps: this.deps }),
{ name, runOnInit, timezone, scheduled: true });
return this;
}
removeListener(eventName: string | symbol, listener: AnyFunction) {
this.sanityCheck(eventName);
const retrievedModule = this.modules.get(eventName);
if(!retrievedModule) throw Error("Removing cron: module " +eventName +"was not found");
const task = cron.getTasks().get(retrievedModule.name!)
if(!task) throw Error("Finding cron task with"+ retrievedModule.name + " not found");
task.stop();
return this;
}
emit(eventName: string | symbol, ...payload: any[]): boolean {
this.sanityCheck(eventName);
const retrievedModule = this.modules.get(eventName);
if(!retrievedModule) throw Error("Removing cron: module " +eventName +"was not found");
const task= cron.getTasks().get(retrievedModule.name!)
return task?.emit(eventName, payload) ?? false;
}
// addListener(eventName: string | symbol, listener: AnyFunction): this {
// const retrievedModule = this.modules.get(eventName);
// if(!retrievedModule) throw Error("Adding task: module " +eventName +"was not found");
// const { pattern, name, runOnInit, timezone } = retrievedModule;
// cron.schedule(pattern,
// (date) => listener({ date, deps: this.deps }),
// { name, runOnInit, timezone, scheduled: true });
// return this;
// }
// removeListener(eventName: string | symbol, listener: AnyFunction) {
// const retrievedModule = this.modules.get(eventName);
// if(!retrievedModule) throw Error("Removing cron: module " +eventName +"was not found");
// const task = cron.getTasks().get(retrievedModule.name!)
// if(!task) throw Error("Finding cron task with"+ retrievedModule.name + " not found");
// task.stop();
// return this;
// }
// emit(eventName: string | symbol, ...payload: any[]): boolean {
// const retrievedModule = this.modules.get(eventName);
// if(!retrievedModule) throw Error("Removing cron: module " +eventName +"was not found");
// const task= cron.getTasks().get(retrievedModule.name!)
// return task?.emit(eventName, payload) ?? false;
// }
}

View File

@@ -58,7 +58,6 @@ export enum EventType {
* Could be for example, `process` events, database events
*/
External,
Cron
}
/**