netzo / fresh-netzo

Full-stack Deno Fresh meta-framework for building business web apps like internal tools, dashboards, admin panels and automated workflows.
https://netzo.io
MIT License
52 stars 2 forks source link

[modules] add `crons` modules #57

Closed miguelrk closed 8 months ago

miguelrk commented 11 months ago

Add cron utility to wrap around Deno.cron and reflect that to a monitoring UI by stubbing Deno.cron with an ES Proxy to proxy the executions and update netzo. This should work as long as the Deno.cron is used in the top-module level, which is already a requirement for it to work.

// from https://github.com/timfish/sentry-javascript/blob/feat/deno-cron/packages/deno/src/integrations/deno-cron.ts

Deno.cron = new Proxy(Deno.cron, {
  apply(target, thisArg, argArray: CronParams) {
    const [monitorSlug, schedule, opt1, opt2] = argArray
    let options: CronOptions | undefined
    let fn: CronFn

    if (typeof opt1 === 'function' && typeof opt2 !== 'function') {
      fn = opt1
      options = opt2
    }
    else if (typeof opt1 !== 'function' && typeof opt2 === 'function') {
      fn = opt2
      options = opt1
    }

    async function cronCalled(): Promise<void> {
      await withMonitor(monitorSlug, async () => fn(), {
        schedule: { type: 'crontab', value: schedule },
        // (minutes) so 12 hours - just a very high arbitrary number since we don't know the actual duration of the users cron job
        maxRuntime: 60 * 12,
      })
    }

    return target.call(thisArg, monitorSlug, schedule, options || {}, cronCalled)
  },
})
miguelrk commented 8 months ago

Closing as completed