breejs / bree

Bree is a Node.js and JavaScript job task scheduler with worker threads, cron, Date, and human syntax. Built for @ladjs, @forwardemail, @spamscanner, @cabinjs.
https://jobscheduler.net
MIT License
2.96k stars 80 forks source link

[fix] Job using class function throws syntax error when run #245

Closed Gmanicus closed 3 months ago

Gmanicus commented 3 months ago

Describe the bug

Node.js version: 18.20.0

OS version: Ubuntu (Inside a Docker container)

Description: In case it helps, this is a Node Typescript project. Attempting to run a scheduled job with a class function given for its 'path' property throws a syntax error.

I am attempting to use Bree to schedule some external API calls that will collect data at repeated intervals. This works somewhat like so:

register(options) {
   // Set up the API collector instance...
   collector = new Collector(option)

   await this.bree.add({
         name: options.name,
         path: collector.runJob,
         ...options.job
  });
}

...

class Collector {
    ...
    async runJob() {
       // do stuff
   }
}

As you can see, I am creating instances of a class and attempting to use Bree to call the runJob() method on an automated schedule. I don't have a way to separate this process into different files.

Actual behavior

As soon as this job attempts to run, it throws a syntax error:

[worker eval]:1
(async runJob() {
       ^^^^^^

SyntaxError: Unexpected identifier
    at makeContextifyScript (node:internal/vm:122:14)
    at node:internal/process/execution:89:22
    at [worker eval]-wrapper:6:24
    at runScript (node:internal/process/execution:83:62)
    at evalScript (node:internal/process/execution:114:10)
    at MessagePort.<anonymous> (node:internal/main/worker_thread:166:9)
    at MessagePort.[nodejs.internal.kHybridDispatch] (node:internal/event_target:786:20)
    at MessagePort.exports.emitMessage (node:internal/per_context/messageport:23:28)

... I technically don't need this to be an async method, but attempting to remove that just throws on the next part:

[worker eval]:1
(runJob() {
          ^

SyntaxError: Unexpected token '{'
    at makeContextifyScript (node:internal/vm:122:14)
    ...

Expected behavior

The job successfully calls the runJob() method.

Code to reproduce

I can write up sample code to reproduce this if needed. The context of this particular error in somewhat deeply embedded and would take more time to get up and running rather than just creating a simple reproduction.

Checklist

Gmanicus commented 3 months ago

Did a more manual look through of the previously closed issues and found #170.

This is a limitation of Worker Threads and NodeJS so there isn't a lot we can do about it. you would need to define the function outside of a class or use a wrapper function to define and call the class.

I can probably do that.