Merge pull request #26 from aki-0421/wait-until

Add WaitUntil
This commit is contained in:
syumai 2023-03-29 21:06:36 +09:00 committed by GitHub
commit 49bfbf6625
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
9 changed files with 118 additions and 0 deletions

18
cloudflare/context.go Normal file
View File

@ -0,0 +1,18 @@
package cloudflare
import (
"context"
"syscall/js"
"github.com/syumai/workers/cloudflare/internal/cfruntimecontext"
"github.com/syumai/workers/internal/jsutil"
)
func WaitUntil(ctx context.Context, task func()) {
executionContext := cfruntimecontext.GetExecutionContext(ctx)
executionContext.Call("waitUntil", jsutil.NewPromise(js.FuncOf(func(this js.Value, args []js.Value) any {
task()
return nil
})))
}

1
examples/wait-until/.gitignore vendored Normal file
View File

@ -0,0 +1 @@
dist

View File

@ -0,0 +1,12 @@
.PHONY: dev
dev:
wrangler dev
.PHONY: build
build:
mkdir -p dist
tinygo build -o ./dist/app.wasm -target wasm ./...
.PHONY: publish
publish:
wrangler publish

View File

@ -0,0 +1,25 @@
# wait-until
* Executes a task in worker even after the server has returned the response.
* This example executes 5-second task after responding and outputs the console log.
## Document
* https://developers.cloudflare.com/workers/runtime-apis/fetch-event/#waituntil
## 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
```

View File

@ -0,0 +1,7 @@
module github.com/syumai/hello
go 1.18
require github.com/syumai/workers v0.0.0
replace github.com/syumai/workers => ../../

View File

@ -0,0 +1,2 @@
github.com/syumai/workers v0.1.0 h1:z5QfQR2X+PCKzom7RodpI5J4D5YF7NT7Qwzb9AM9dgY=
github.com/syumai/workers v0.1.0/go.mod h1:alXIDhTyeTwSzh0ZgQ3cb9HQPyyYfIejupE4Z3efr14=

View File

@ -0,0 +1,25 @@
package main
import (
"fmt"
"net/http"
"time"
"github.com/syumai/workers"
"github.com/syumai/workers/cloudflare"
)
func main() {
handler := http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
cloudflare.WaitUntil(req.Context(), func() {
for i := 0; i < 5; i++ {
time.Sleep(time.Second)
}
fmt.Println("5-second task completed")
})
w.Write([]byte("http response done"))
})
workers.Serve(handler)
}

View File

@ -0,0 +1,22 @@
import "../assets/polyfill_performance.js";
import "../assets/wasm_exec.js";
import mod from "./dist/app.wasm";
const go = new Go();
const readyPromise = new Promise((resolve) => {
globalThis.ready = resolve;
});
const load = WebAssembly.instantiate(mod, go.importObject).then((instance) => {
go.run(instance);
return instance;
});
export default {
async fetch(req, env, ctx) {
await load;
await readyPromise;
return handleRequest(req, { env, ctx });
}
}

View File

@ -0,0 +1,6 @@
name = "wait-until"
main = "./worker.mjs"
compatibility_date = "2023-02-24"
[build]
command = "make build"