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

Remove dependencies on Context #102

Merged
merged 5 commits into from
Apr 16, 2024
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
3 changes: 1 addition & 2 deletions _examples/cache/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,6 @@ func (rw *responseWriter) ToHTTPResponse() *http.Response {
}

func handler(w http.ResponseWriter, req *http.Request) {
ctx := req.Context()
rw := responseWriter{ResponseWriter: w}
c := cache.New()

Expand All @@ -64,7 +63,7 @@ func handler(w http.ResponseWriter, req *http.Request) {
rw.Write([]byte(text))

// Create cache
cloudflare.WaitUntil(ctx, func() {
cloudflare.WaitUntil(func() {
err := c.Put(req, rw.ToHTTPResponse())
if err != nil {
fmt.Println(err)
Expand Down
2 changes: 1 addition & 1 deletion _examples/d1-blog-server/app/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ func NewArticleHandler() http.Handler {
func (h *articleHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
// initialize DB.
// D1 connector requires request's context to initialize DB.
c, err := d1.OpenConnector(req.Context(), "BlogDB")
c, err := d1.OpenConnector("BlogDB")
if err != nil {
h.handleErr(w, http.StatusInternalServerError, fmt.Sprintf("failed to initialize DB: %v", err))
}
Expand Down
5 changes: 2 additions & 3 deletions _examples/durable-object-counter/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,10 @@ func main() {
workers.Serve(&MyHandler{})
}

type MyHandler struct {}
type MyHandler struct{}

func (_ *MyHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
COUNTER, err := cloudflare.NewDurableObjectNamespace(req.Context(), "COUNTER")
COUNTER, err := cloudflare.NewDurableObjectNamespace("COUNTER")
if err != nil {
panic(err)
}
Expand All @@ -38,4 +38,3 @@ func (_ *MyHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {

w.Write([]byte("Durable object 'A' count: " + string(count)))
}

2 changes: 1 addition & 1 deletion _examples/env/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import (

func main() {
handler := http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
fmt.Fprintf(w, "MY_ENV: %s", cloudflare.Getenv(req.Context(), "MY_ENV"))
fmt.Fprintf(w, "MY_ENV: %s", cloudflare.Getenv("MY_ENV"))
})
workers.Serve(handler)
}
2 changes: 1 addition & 1 deletion _examples/fetch-event/go.mod
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
module github.com/syumai/workers/_examples/hello
module github.com/syumai/workers/_examples/fetch-event

go 1.21.3

Expand Down
6 changes: 2 additions & 4 deletions _examples/fetch-event/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,10 @@ import (
)

func handler(w http.ResponseWriter, req *http.Request) {
ctx := req.Context()

cloudflare.PassThroughOnException(ctx)
cloudflare.PassThroughOnException()

// logging after responding
cloudflare.WaitUntil(ctx, func() {
cloudflare.WaitUntil(func() {
for i := 0; i < 5; i++ {
time.Sleep(time.Second)
}
Expand Down
2 changes: 1 addition & 1 deletion _examples/kv-counter/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ func main() {
}

// initialize KV namespace instance
kv, err := cloudflare.NewKVNamespace(req.Context(), counterNamespace)
kv, err := cloudflare.NewKVNamespace(counterNamespace)
if err != nil {
fmt.Fprintf(os.Stderr, "failed to init KV: %v", err)
os.Exit(1)
Expand Down
6 changes: 3 additions & 3 deletions _examples/mysql-blog-server/app/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,13 +27,13 @@ func NewArticleHandler() http.Handler {

func (h *articleHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
// initialize DB.
mysql.RegisterDialContext("tcp", func(_ context.Context, addr string) (net.Conn, error) {
return sockets.Connect(req.Context(), addr, &sockets.SocketOptions{
mysql.RegisterDialContext("tcp", func(ctx context.Context, addr string) (net.Conn, error) {
return sockets.Connect(ctx, addr, &sockets.SocketOptions{
SecureTransport: sockets.SecureTransportOff,
})
})
db, err := sql.Open("mysql",
cloudflare.Getenv(req.Context(), "MYSQL_DSN"))
cloudflare.Getenv("MYSQL_DSN"))
if err != nil {
log.Fatalf("failed to connect: %v", err)
}
Expand Down
19 changes: 9 additions & 10 deletions _examples/r2-image-server/main.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package main

import (
"context"
"fmt"
"io"
"log"
Expand All @@ -24,12 +23,12 @@ func handleErr(w http.ResponseWriter, msg string, err error) {

type server struct{}

func (s *server) bucket(ctx context.Context) (*cloudflare.R2Bucket, error) {
return cloudflare.NewR2Bucket(ctx, bucketName)
func (s *server) bucket() (*cloudflare.R2Bucket, error) {
return cloudflare.NewR2Bucket(bucketName)
}

func (s *server) post(w http.ResponseWriter, req *http.Request, key string) {
bucket, err := s.bucket(req.Context())
bucket, err := s.bucket()
if err != nil {
handleErr(w, "failed to initialize R2Bucket\n", err)
return
Expand Down Expand Up @@ -61,9 +60,9 @@ func (s *server) post(w http.ResponseWriter, req *http.Request, key string) {
w.Write([]byte("successfully uploaded image"))
}

func (s *server) get(w http.ResponseWriter, req *http.Request, key string) {
func (s *server) get(w http.ResponseWriter, key string) {
// get image object from R2
bucket, err := s.bucket(req.Context())
bucket, err := s.bucket()
if err != nil {
handleErr(w, "failed to initialize R2Bucket\n", err)
return
Expand All @@ -88,9 +87,9 @@ func (s *server) get(w http.ResponseWriter, req *http.Request, key string) {
io.Copy(w, imgObj.Body)
}

func (s *server) delete(w http.ResponseWriter, req *http.Request, key string) {
func (s *server) delete(w http.ResponseWriter, key string) {
// delete image object from R2
bucket, err := s.bucket(req.Context())
bucket, err := s.bucket()
if err != nil {
handleErr(w, "failed to initialize R2Bucket\n", err)
return
Expand All @@ -107,10 +106,10 @@ func (s *server) ServeHTTP(w http.ResponseWriter, req *http.Request) {
key := strings.TrimPrefix(req.URL.Path, "/")
switch req.Method {
case "GET":
s.get(w, req, key)
s.get(w, key)
return
case "DELETE":
s.delete(w, req, key)
s.delete(w, key)
return
case "POST":
s.post(w, req, key)
Expand Down
2 changes: 1 addition & 1 deletion _examples/r2-image-viewer/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ func handleErr(w http.ResponseWriter, msg string, err error) {
// This example is based on implementation in syumai/workers-playground
// - https://github.com/syumai/workers-playground/blob/e32881648ccc055e3690a0d9c750a834261c333e/r2-image-viewer/src/index.ts#L30
func handler(w http.ResponseWriter, req *http.Request) {
bucket, err := cloudflare.NewR2Bucket(req.Context(), bucketName)
bucket, err := cloudflare.NewR2Bucket(bucketName)
if err != nil {
handleErr(w, "failed to get R2Bucket\n", err)
return
Expand Down
2 changes: 1 addition & 1 deletion _examples/service-bindings/go.mod
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
module github.com/syumai/workers/_examples/fetch
module github.com/syumai/workers/_examples/service-bindings

go 1.21.3

Expand Down
3 changes: 1 addition & 2 deletions _examples/service-bindings/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,7 @@ import (

func main() {
handler := http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
ctx := req.Context()
bind := cloudflare.GetBinding(ctx, "hello")
bind := cloudflare.GetBinding("hello")
fc := fetch.NewClient(fetch.WithBinding(bind))

hc := fc.HTTPClient(fetch.RedirectModeFollow)
Expand Down
7 changes: 3 additions & 4 deletions cloudflare/cron/scheduler.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@ type Task func(ctx context.Context) error

var scheduledTask Task

func runScheduler(eventObj js.Value, runtimeCtxObj js.Value) error {
ctx := runtimecontext.New(context.Background(), eventObj, runtimeCtxObj)
func runScheduler(eventObj js.Value) error {
ctx := runtimecontext.New(context.Background(), eventObj)
if err := scheduledTask(ctx); err != nil {
return err
}
Expand All @@ -27,13 +27,12 @@ func init() {
panic(fmt.Errorf("invalid number of arguments given to runScheduler: %d", len(args)))
}
eventObj := args[0]
runtimeCtxObj := jsutil.RuntimeContext
var cb js.Func
cb = js.FuncOf(func(_ js.Value, pArgs []js.Value) any {
defer cb.Release()
resolve := pArgs[0]
go func() {
err := runScheduler(eventObj, runtimeCtxObj)
err := runScheduler(eventObj)
if err != nil {
panic(err)
}
Expand Down
4 changes: 2 additions & 2 deletions cloudflare/d1/connector.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,8 @@ var (

// OpenConnector returns Connector of D1.
// This method checks DB existence. If DB was not found, this function returns error.
func OpenConnector(ctx context.Context, name string) (driver.Connector, error) {
v := cfruntimecontext.MustGetRuntimeContextEnv(ctx).Get(name)
func OpenConnector(name string) (driver.Connector, error) {
v := cfruntimecontext.MustGetRuntimeContextEnv().Get(name)
if v.IsUndefined() {
return nil, ErrDatabaseNotFound
}
Expand Down
5 changes: 2 additions & 3 deletions cloudflare/dostub.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package cloudflare

import (
"context"
"fmt"
"net/http"
"syscall/js"
Expand All @@ -20,8 +19,8 @@ type DurableObjectNamespace struct {
//
// This binding must be defined in the `wrangler.toml` file. The method will
// return an `error` when there is no binding defined by `varName`.
func NewDurableObjectNamespace(ctx context.Context, varName string) (*DurableObjectNamespace, error) {
inst := cfruntimecontext.MustGetRuntimeContextEnv(ctx).Get(varName)
func NewDurableObjectNamespace(varName string) (*DurableObjectNamespace, error) {
inst := cfruntimecontext.MustGetRuntimeContextEnv().Get(varName)
if inst.IsUndefined() {
return nil, fmt.Errorf("%s is undefined", varName)
}
Expand Down
9 changes: 4 additions & 5 deletions cloudflare/env.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package cloudflare

import (
"context"
"syscall/js"

"github.com/syumai/workers/cloudflare/internal/cfruntimecontext"
Expand All @@ -10,13 +9,13 @@ import (
// Getenv gets a value of an environment variable.
// - https://developers.cloudflare.com/workers/platform/environment-variables/
// - This function panics when a runtime context is not found.
func Getenv(ctx context.Context, name string) string {
return cfruntimecontext.MustGetRuntimeContextEnv(ctx).Get(name).String()
func Getenv(name string) string {
return cfruntimecontext.MustGetRuntimeContextEnv().Get(name).String()
}

// GetBinding gets a value of an environment binding.
// - https://developers.cloudflare.com/workers/platform/bindings/about-service-bindings/
// - This function panics when a runtime context is not found.
func GetBinding(ctx context.Context, name string) js.Value {
return cfruntimecontext.MustGetRuntimeContextEnv(ctx).Get(name)
func GetBinding(name string) js.Value {
return cfruntimecontext.MustGetRuntimeContextEnv().Get(name)
}
9 changes: 4 additions & 5 deletions cloudflare/fetchevent.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package cloudflare

import (
"context"
"syscall/js"

"github.com/syumai/workers/cloudflare/internal/cfruntimecontext"
Expand All @@ -11,8 +10,8 @@ import (
// WaitUntil extends the lifetime of the "fetch" event.
// It accepts an asynchronous task which the Workers runtime will execute before the handler terminates but without blocking the response.
// see: https://developers.cloudflare.com/workers/runtime-apis/fetch-event/#waituntil
func WaitUntil(ctx context.Context, task func()) {
exCtx := cfruntimecontext.MustGetExecutionContext(ctx)
func WaitUntil(task func()) {
exCtx := cfruntimecontext.MustGetExecutionContext()
exCtx.Call("waitUntil", jsutil.NewPromise(js.FuncOf(func(this js.Value, pArgs []js.Value) any {
resolve := pArgs[0]
go func() {
Expand All @@ -26,8 +25,8 @@ func WaitUntil(ctx context.Context, task func()) {
// PassThroughOnException prevents a runtime error response when the Worker script throws an unhandled exception.
// Instead, the request forwards to the origin server as if it had not gone through the worker.
// see: https://developers.cloudflare.com/workers/runtime-apis/fetch-event/#passthroughonexception
func PassThroughOnException(ctx context.Context) {
exCtx := cfruntimecontext.MustGetExecutionContext(ctx)
func PassThroughOnException() {
exCtx := cfruntimecontext.MustGetExecutionContext()
jsutil.AwaitPromise(jsutil.NewPromise(js.FuncOf(func(this js.Value, pArgs []js.Value) any {
resolve := pArgs[0]
go func() {
Expand Down
19 changes: 9 additions & 10 deletions cloudflare/internal/cfruntimecontext/cfruntimecontext.go
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
package cfruntimecontext

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

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

/**
Expand All @@ -23,21 +22,21 @@ import (

// MustGetRuntimeContextEnv gets object which holds environment variables bound to Cloudflare worker.
// - see: https://github.com/cloudflare/workers-types/blob/c8d9533caa4415c2156d2cf1daca75289d01ae70/index.d.ts#L566
func MustGetRuntimeContextEnv(ctx context.Context) js.Value {
return MustGetRuntimeContextValue(ctx, "env")
func MustGetRuntimeContextEnv() js.Value {
return MustGetRuntimeContextValue("env")
}

// MustGetExecutionContext gets ExecutionContext object from context.
// - see: https://github.com/cloudflare/workers-types/blob/c8d9533caa4415c2156d2cf1daca75289d01ae70/index.d.ts#L567
// - see also: https://github.com/cloudflare/workers-types/blob/c8d9533caa4415c2156d2cf1daca75289d01ae70/index.d.ts#L554
func MustGetExecutionContext(ctx context.Context) js.Value {
return MustGetRuntimeContextValue(ctx, "ctx")
func MustGetExecutionContext() js.Value {
return MustGetRuntimeContextValue("ctx")
}

// MustGetRuntimeContextValue gets value for specified key from RuntimeContext.
// - if the value is undefined, this function panics.
func MustGetRuntimeContextValue(ctx context.Context, key string) js.Value {
val, err := GetRuntimeContextValue(ctx, key)
func MustGetRuntimeContextValue(key string) js.Value {
val, err := GetRuntimeContextValue(key)
if err != nil {
panic(err)
}
Expand All @@ -48,8 +47,8 @@ var ErrValueNotFound = errors.New("execution context value for specified key not

// GetRuntimeContextValue gets value for specified key from RuntimeContext.
// - if the value is undefined, return error.
func GetRuntimeContextValue(ctx context.Context, key string) (js.Value, error) {
runtimeObj := runtimecontext.MustExtractRuntimeObj(ctx)
func GetRuntimeContextValue(key string) (js.Value, error) {
runtimeObj := jsutil.RuntimeContext
v := runtimeObj.Get(key)
if v.IsUndefined() {
return js.Value{}, ErrValueNotFound
Expand Down
5 changes: 2 additions & 3 deletions cloudflare/kv.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package cloudflare

import (
"context"
"fmt"
"io"
"syscall/js"
Expand All @@ -21,8 +20,8 @@ type KVNamespace struct {
// - variable name must be defined in wrangler.toml as kv_namespace's binding.
// - if the given variable name doesn't exist on runtime context, returns error.
// - This function panics when a runtime context is not found.
func NewKVNamespace(ctx context.Context, varName string) (*KVNamespace, error) {
inst := cfruntimecontext.MustGetRuntimeContextEnv(ctx).Get(varName)
func NewKVNamespace(varName string) (*KVNamespace, error) {
inst := cfruntimecontext.MustGetRuntimeContextEnv().Get(varName)
if inst.IsUndefined() {
return nil, fmt.Errorf("%s is undefined", varName)
}
Expand Down
5 changes: 2 additions & 3 deletions cloudflare/r2bucket.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package cloudflare

import (
"context"
"fmt"
"io"
"syscall/js"
Expand All @@ -22,8 +21,8 @@ type R2Bucket struct {
// - see example: https://github.com/syumai/workers/tree/main/_examples/r2-image-viewer
// - if the given variable name doesn't exist on runtime context, returns error.
// - This function panics when a runtime context is not found.
func NewR2Bucket(ctx context.Context, varName string) (*R2Bucket, error) {
inst := cfruntimecontext.MustGetRuntimeContextEnv(ctx).Get(varName)
func NewR2Bucket(varName string) (*R2Bucket, error) {
inst := cfruntimecontext.MustGetRuntimeContextEnv().Get(varName)
if inst.IsUndefined() {
return nil, fmt.Errorf("%s is undefined", varName)
}
Expand Down
2 changes: 1 addition & 1 deletion cloudflare/sockets/connect.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ type SocketOptions struct {
const defaultDeadline = 999999 * time.Hour

func Connect(ctx context.Context, addr string, opts *SocketOptions) (net.Conn, error) {
connect, err := cfruntimecontext.GetRuntimeContextValue(ctx, "connect")
connect, err := cfruntimecontext.GetRuntimeContextValue("connect")
if err != nil {
return nil, err
}
Expand Down
Loading
Loading