Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Scheduled worker #45

Merged
merged 2 commits into from
Apr 30, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions cmd/workers-assets-gen/assets/common/shim.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -22,3 +22,8 @@ export async function fetch(req, env, ctx) {
await run();
return handleRequest(req, { env, ctx });
}

export async function scheduled(event, env, ctx) {
await run();
return runScheduler(event, { env, ctx });
}
2 changes: 1 addition & 1 deletion cmd/workers-assets-gen/assets/common/worker.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,4 @@ import mod from "./app.wasm";

imports.init(mod);

export default { fetch: imports.fetch }
export default { fetch: imports.fetch, scheduled: imports.scheduled }
84 changes: 84 additions & 0 deletions cron.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
package workers

import (
"context"
"errors"
"fmt"
"syscall/js"
"time"

"github.com/syumai/workers/internal/jsutil"
"github.com/syumai/workers/internal/runtimecontext"
)

// CronEvent represents information about the Cron that invoked this worker.
type CronEvent struct {
// Type string
Cron string
ScheduledTime time.Time
}

// toGo converts JS Object to CronEvent
func (ce *CronEvent) toGo(obj js.Value) error {
if obj.IsUndefined() {
return errors.New("event is null")
}
cronVal := obj.Get("cron").String()
ce.Cron = cronVal
scheduledTimeVal := obj.Get("scheduledTime").Float()
ce.ScheduledTime = time.Unix(int64(scheduledTimeVal)/1000, 0).UTC()

return nil
}

type CronFunc func(ctx context.Context, event CronEvent) error

var cronTask CronFunc

// ScheduleTask sets the CronFunc to be executed
func ScheduleTask(task CronFunc) {
cronTask = task
jsutil.Global.Call("ready")
select {}
}

func runScheduler(eventObj js.Value, runtimeCtxObj js.Value) error {
ctx := runtimecontext.New(context.Background(), runtimeCtxObj)
event := CronEvent{}
err := event.toGo(eventObj)
if err != nil {
return err
}
err = cronTask(ctx, event)
if err != nil {
return err
}
return nil
}

func init() {
runSchedulerCallback := js.FuncOf(func(_ js.Value, args []js.Value) any {
if len(args) != 2 {
panic(fmt.Errorf("invalid number of arguments given to runScheduler: %d", len(args)))
}
event := args[0]
runtimeCtx := args[1]

var cb js.Func
cb = js.FuncOf(func(_ js.Value, pArgs []js.Value) any {
defer cb.Release()
resolve := pArgs[0]
go func() {
err := runScheduler(event, runtimeCtx)
if err != nil {
panic(err)
}
resolve.Invoke(js.Undefined())
}()
return js.Undefined()
})

return jsutil.NewPromise(cb)
})
jsutil.Global.Set("runScheduler", runSchedulerCallback)
}
1 change: 1 addition & 0 deletions examples/cron/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
build
12 changes: 12 additions & 0 deletions examples/cron/Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
.PHONY: dev
dev:
wrangler dev

.PHONY: build
build:
go run ../../cmd/workers-assets-gen
tinygo build -o ./build/app.wasm -target wasm ./...

.PHONY: publish
publish:
wrangler publish
20 changes: 20 additions & 0 deletions examples/cron/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# [Cron](https://developers.cloudflare.com/workers/platform/triggers/cron-triggers/)

* Create a worker to be triggered by Cron.

## Development

### Requirements

This project requires these tools to be installed globally.

* wrangler
* tinygo

### Commands

```
make dev # run dev server
make build # build Go Wasm binary
make publish # publish worker
```
7 changes: 7 additions & 0 deletions examples/cron/go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
module github.com/syumai/workers/examples/scheduled

go 1.18

require github.com/syumai/workers v0.0.0

replace github.com/syumai/workers => ../../
Empty file added examples/cron/go.sum
Empty file.
24 changes: 24 additions & 0 deletions examples/cron/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package main

import (
"context"
"errors"
"fmt"

"github.com/syumai/workers"
"github.com/syumai/workers/cloudflare"
)

func task(ctx context.Context, event workers.CronEvent) error {
fmt.Println(cloudflare.Getenv(ctx, "HELLO"))

if event.ScheduledTime.Minute()%2 == 0 {
return errors.New("even numbers cause errors")
}

return nil
}

func main() {
workers.ScheduleTask(task)
}
13 changes: 13 additions & 0 deletions examples/cron/wrangler.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
name = "scheduled"
main = "./build/worker.mjs"
compatibility_date = "2023-02-24"
workers_dev = false

[vars]
HELLO = "hello, world!"

[triggers]
crons = ["* * * * *"]

[build]
command = "make build"