core

package
v2.2.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 2, 2026 License: MIT Imports: 10 Imported by: 0

Documentation

Index

Constants

View Source
const MaxKVValueSize = 1 << 20

MaxKVValueSize is the maximum size of a KV value (1 MB).

View Source
const MaxLogEntries = 1000
View Source
const MaxLogMessageSize = 4096

Variables

This section is empty.

Functions

func AddLog

func AddLog(id uint64, level, message string)

AddLog appends a log entry to the request state identified by id.

func BoolToInt

func BoolToInt(b bool) int

BoolToInt converts a bool to 1 (true) or 0 (false) for JS interop, since some JS engines cannot marshal Go bool return values directly.

func CallFetchCancel

func CallFetchCancel(reqID uint64, fetchID string)

CallFetchCancel calls the cancel function for the given fetch, if present.

func DecodeCursor

func DecodeCursor(cursor string) int

DecodeCursor decodes a base64-encoded cursor to an integer offset.

func EncodeCursor

func EncodeCursor(offset int) string

EncodeCursor encodes an integer offset to a base64 cursor string.

func ImportCryptoKey

func ImportCryptoKey(reqID uint64, hashAlgo string, data []byte) int

ImportCryptoKey stores key material scoped to the request and returns its ID.

func ImportCryptoKeyFull

func ImportCryptoKeyFull(reqID uint64, entry *CryptoKeyEntry) int

ImportCryptoKeyFull stores a complete CryptoKeyEntry and returns its ID.

func JsEscape

func JsEscape(s string) string

JsEscape escapes a string for safe embedding in JavaScript source code.

func NewRequestState

func NewRequestState(maxFetches int, env *Env) uint64

NewRequestState creates a new request state and returns its unique ID.

func ParseReqID

func ParseReqID(s string) uint64

ParseReqID parses a request ID string to uint64.

func RegisterFetchCancel

func RegisterFetchCancel(reqID uint64, cancel context.CancelFunc) string

RegisterFetchCancel stores a cancel function for an in-flight fetch and returns the unique fetchID string key.

func RemoveFetchCancel

func RemoveFetchCancel(reqID uint64, fetchID string) context.CancelFunc

RemoveFetchCancel removes and returns the cancel function for a fetch.

Types

type AssetsFetcher

type AssetsFetcher interface {
	Fetch(req *WorkerRequest) (*WorkerResponse, error)
}

AssetsFetcher is implemented by the static pipeline to handle env.ASSETS.fetch().

type BinaryTransferer

type BinaryTransferer interface {
	// ReadBinaryFromJS reads binary data from a JS buffer stored at the
	// given global variable name and returns it as Go bytes.
	ReadBinaryFromJS(globalName string) ([]byte, error)

	// WriteBinaryToJS writes Go bytes into a JS ArrayBuffer at the given
	// global variable name.
	WriteBinaryToJS(globalName string, data []byte) error

	// BinaryMode returns the JS buffer type to use for binary transfer:
	// "sab" for SharedArrayBuffer (V8), "ab" for ArrayBuffer (QuickJS).
	BinaryMode() string
}

BinaryTransferer is an optional interface that JSRuntime implementations can provide for efficient binary data transfer between Go and JS. V8 implements this using SharedArrayBuffer; QuickJS uses direct ArrayBuffer access via the libquickjs C API.

type CacheEntry

type CacheEntry struct {
	Status    int
	Headers   string
	Body      []byte
	ExpiresAt *time.Time
}

CacheEntry represents a cached HTTP response.

type CacheStore

type CacheStore interface {
	Match(cacheName, url string) (*CacheEntry, error)
	Put(cacheName, url string, status int, headers string, body []byte, ttl *int) error
	Delete(cacheName, url string) (bool, error)
}

CacheStore backs the Cache API (site-scoped).

type CryptoKeyEntry

type CryptoKeyEntry struct {
	Data        []byte // Raw key bytes (symmetric keys)
	HashAlgo    string // Associated hash algorithm
	AlgoName    string // Algorithm name (HMAC, AES-GCM, ECDSA, AES-CBC)
	KeyType     string // "secret", "public", "private"
	NamedCurve  string // For EC keys: "P-256", "P-384"
	EcKey       any    // *ecdsa.PrivateKey or *ecdsa.PublicKey
	Extractable bool   // WebCrypto extractable flag
}

CryptoKeyEntry holds imported key material and its associated hash algorithm.

func GetCryptoKey

func GetCryptoKey(reqID uint64, keyID int) *CryptoKeyEntry

GetCryptoKey retrieves key material scoped to the request.

type D1ExecResult

type D1ExecResult struct {
	Columns []string        `json:"columns"`
	Rows    [][]interface{} `json:"rows"`
	Meta    D1Meta          `json:"meta"`
}

D1ExecResult holds the result of executing a SQL statement.

type D1Meta

type D1Meta struct {
	ChangedDB   bool  `json:"changed_db"`
	Changes     int64 `json:"changes"`
	LastRowID   int64 `json:"last_row_id"`
	RowsRead    int   `json:"rows_read"`
	RowsWritten int   `json:"rows_written"`
}

D1Meta holds metadata about a D1 query execution.

type D1Store

type D1Store interface {
	Exec(sql string, bindings []interface{}) (*D1ExecResult, error)
	Close() error
}

D1Store backs a single D1 database binding.

type DurableObjectStore

type DurableObjectStore interface {
	Get(namespace, objectID, key string) (string, error)
	GetMulti(namespace, objectID string, keys []string) (map[string]string, error)
	Put(namespace, objectID, key, valueJSON string) error
	PutMulti(namespace, objectID string, entries map[string]string) error
	Delete(namespace, objectID, key string) error
	DeleteMulti(namespace, objectID string, keys []string) (int, error)
	DeleteAll(namespace, objectID string) error
	List(namespace, objectID, prefix string, limit int, reverse bool) ([]KVPair, error)
}

DurableObjectStore backs Durable Object storage.

type EngineBackend

type EngineBackend interface {
	Execute(siteID, deployKey string, env *Env, req *WorkerRequest) *WorkerResult
	ExecuteScheduled(siteID, deployKey string, env *Env, cron string) *WorkerResult
	ExecuteTail(siteID, deployKey string, env *Env, events []TailEvent) *WorkerResult
	ExecuteFunction(siteID, deployKey string, env *Env, fnName string, args ...any) *WorkerResult
	EnsureSource(siteID, deployKey string) error
	CompileAndCache(siteID, deployKey string, source string) ([]byte, error)
	InvalidatePool(siteID, deployKey string)
	Shutdown()
	SetDispatcher(d WorkerDispatcher)
	MaxResponseBytes() int
}

EngineBackend is the interface that engine implementations (QuickJS, V8) must satisfy. The root worker.Engine facade delegates to one of these based on build tags.

type EngineConfig

type EngineConfig struct {
	PoolSize         int // number of JS runtime instances per site pool
	MemoryLimitMB    int // per-runtime memory limit
	ExecutionTimeout int // milliseconds before worker is terminated
	MaxFetchRequests int // max outbound fetches per request
	FetchTimeoutSec  int // per-fetch timeout in seconds
	MaxResponseBytes int // max response body size
	MaxScriptSizeKB  int // max bundled script size
}

EngineConfig holds runtime configuration for the worker engine.

type Env

type Env struct {
	Vars    map[string]string
	Secrets map[string]string

	// Opt-in bindings — nil means disabled
	KV              map[string]KVStore
	Cache           CacheStore
	Storage         map[string]R2Store
	Queues          map[string]QueueSender
	D1Bindings      map[string]string  // binding name -> database ID
	D1              map[string]D1Store // binding name -> D1Store (opened by engine)
	DurableObjects  map[string]DurableObjectStore
	ServiceBindings map[string]ServiceBindingConfig

	// CustomBindings allows downstream users to add arbitrary bindings
	// to the env object. Each function is called per-request and its
	// returned value is set on env under the map key name.
	CustomBindings map[string]EnvBindingFunc

	// D1 configuration
	D1DataDir string

	// Runtime references
	Assets     AssetsFetcher
	Dispatcher WorkerDispatcher // set by Engine before execution
	SiteID     string           // site isolation key
	// contains filtered or unexported fields
}

Env holds all bindings passed to the worker as the second argument.

func (*Env) InitRuntime

func (env *Env) InitRuntime(dispatcher WorkerDispatcher, siteID string)

InitRuntime sets Dispatcher and SiteID if not already set. Safe to call concurrently from multiple goroutines.

type EnvBindingFunc

type EnvBindingFunc func(rt JSRuntime) (any, error)

EnvBindingFunc creates a JS binding to be set on the worker's env object. It receives the JSRuntime for the current execution. The returned value is a basic Go type (string, int, float64, bool, nil) that is set on the env object via SetGlobal. For complex objects, use rt.Eval() to construct them in JS-land and return nil.

type JSRuntime

type JSRuntime interface {
	// Eval evaluates JavaScript source and discards the result.
	Eval(js string) error

	// EvalString evaluates JavaScript and returns the result as a Go string.
	EvalString(js string) (string, error)

	// EvalBool evaluates JavaScript and returns the result as a Go bool.
	EvalBool(js string) (bool, error)

	// EvalInt evaluates JavaScript and returns the result as a Go int.
	EvalInt(js string) (int, error)

	// RegisterFunc registers a Go function as a global JavaScript function.
	// The function's Go types are automatically marshaled to/from JS types.
	// On error return, the JS wrapper throws a TypeError instead of
	// returning an array.
	RegisterFunc(name string, fn any) error

	// SetGlobal sets a global variable on the JS context. Basic Go types
	// (string, int, float64, bool) are auto-converted to JS types.
	SetGlobal(name string, value any) error

	// RunMicrotasks pumps the microtask queue (Promise callbacks, etc.).
	// V8: PerformMicrotaskCheckpoint, QuickJS: ExecutePendingJob loop.
	RunMicrotasks()
}

JSRuntime abstracts the JavaScript engine (V8 or QuickJS) behind a common interface used by shared setup functions in internal/webapi and the shared event loop in internal/eventloop.

type KVListResult

type KVListResult struct {
	Keys         []map[string]interface{}
	ListComplete bool
	Cursor       string // base64-encoded offset, empty when list is complete
}

KVListResult holds the result of a List operation with pagination info.

type KVPair

type KVPair struct {
	Key   string
	Value string
}

KVPair represents a key-value pair from Durable Object storage.

type KVStore

type KVStore interface {
	Get(key string) (*string, error)
	GetWithMetadata(key string) (*KVValueWithMetadata, error)
	Put(key, value string, metadata *string, ttl *int) error
	Delete(key string) error
	List(prefix string, limit int, cursor string) (*KVListResult, error)
}

KVStore backs a single KV namespace.

type KVValueWithMetadata

type KVValueWithMetadata struct {
	Value    string
	Metadata *string
}

KVValueWithMetadata holds a value and its associated metadata.

type LogEntry

type LogEntry struct {
	Level   string    `json:"level"`
	Message string    `json:"message"`
	Time    time.Time `json:"time"`
}

LogEntry is a single console.log/warn/error captured from a worker.

type QueueMessageInput

type QueueMessageInput struct {
	Body        string
	ContentType string
}

QueueMessageInput represents a message to be sent to a queue.

type QueueSender

type QueueSender interface {
	Send(body, contentType string) (string, error)
	SendBatch(messages []QueueMessageInput) ([]string, error)
}

QueueSender backs queue message production for a single queue.

type R2ListOptions

type R2ListOptions struct {
	Prefix    string
	Delimiter string
	Cursor    string
	Limit     int
}

R2ListOptions configures an R2 list operation.

type R2ListResult

type R2ListResult struct {
	Objects           []R2Object
	Truncated         bool
	Cursor            string
	DelimitedPrefixes []string
}

R2ListResult holds the result of an R2 list operation.

type R2Object

type R2Object struct {
	Key            string
	Size           int64
	ContentType    string
	ETag           string
	LastModified   time.Time
	CustomMetadata map[string]string
}

R2Object holds metadata about an R2/S3-compatible object.

type R2PutOptions

type R2PutOptions struct {
	ContentType    string
	CustomMetadata map[string]string
}

R2PutOptions configures an R2 put operation.

type R2Store

type R2Store interface {
	Get(key string) ([]byte, *R2Object, error)
	Put(key string, data []byte, opts R2PutOptions) (*R2Object, error)
	Delete(keys []string) error
	Head(key string) (*R2Object, error)
	List(opts R2ListOptions) (*R2ListResult, error)
	PresignedGetURL(key string, expiry time.Duration) (string, error)
	PublicURL(key string) (string, error)
}

R2Store backs R2-compatible object storage for a single bucket.

type RequestState

type RequestState struct {
	Logs       []LogEntry
	FetchCount int
	MaxFetches int
	Env        *Env
	CryptoKeys map[int]*CryptoKeyEntry
	NextKeyID  int

	// WebSocket bridge state (set when status 101 response is returned).
	// Typed as any to avoid importing coder/websocket in core.
	WsConn   any // *websocket.Conn
	WsMu     sync.Mutex
	WsClosed bool

	// DigestStream state: per-request hash instances keyed by stream ID.
	DigestStreams map[string]hash.Hash
	NextDigestID  int64

	// TCP socket state: per-request TCP connections keyed by socket ID.
	TcpSockets      map[string]net.Conn
	NextTCPSocketID int64

	// In-flight fetch cancellation: maps fetchID -> cancel function.
	FetchCancels map[string]context.CancelFunc
	NextFetchID  int64
	// contains filtered or unexported fields
}

RequestState holds per-request mutable state (logs, fetch counter, env, crypto keys). The engine sets it before calling into JS and clears it after.

func ClearRequestState

func ClearRequestState(id uint64) *RequestState

ClearRequestState removes the state for the given request ID and returns it. It cleans up all per-request resources by running registered cleanup functions, cancelling in-flight fetches, and closing TCP sockets.

func GetRequestState

func GetRequestState(id uint64) *RequestState

GetRequestState returns the state for the given request ID, or nil.

func (*RequestState) GetExt

func (rs *RequestState) GetExt(key string) any

GetExt retrieves a value from the extension map.

func (*RequestState) RegisterCleanup

func (rs *RequestState) RegisterCleanup(fn func())

RegisterCleanup adds a cleanup function to be called when the request state is cleared. Cleanups are called in reverse registration order.

func (*RequestState) SetExt

func (rs *RequestState) SetExt(key string, val any)

SetExt stores a value in the extension map under the given key.

type ServiceBindingConfig

type ServiceBindingConfig struct {
	TargetSiteID    string
	TargetDeployKey string
}

ServiceBindingConfig identifies a target worker for service bindings.

type SourceLoader

type SourceLoader interface {
	GetWorkerScript(siteID, deployKey string) (string, error)
}

SourceLoader retrieves worker JS source code.

type TailEvent

type TailEvent struct {
	ScriptName string     `json:"scriptName"`
	Logs       []LogEntry `json:"logs"`
	Exceptions []string   `json:"exceptions"`
	Outcome    string     `json:"outcome"`
	Timestamp  time.Time  `json:"timestamp"`
}

TailEvent represents a log event forwarded to a tail worker.

type WebSocketBridger

type WebSocketBridger interface {
	Bridge(ctx context.Context, httpConn *websocket.Conn)
}

WebSocketBridger is implemented by engine-specific WebSocket handlers. Consumers call Bridge to relay messages between an HTTP WebSocket connection and the JS runtime.

type WorkerDispatcher

type WorkerDispatcher interface {
	Execute(siteID, deployKey string, env *Env, req *WorkerRequest) *WorkerResult
}

WorkerDispatcher executes a worker (used by service bindings to dispatch to other workers without a direct Engine dependency).

type WorkerRequest

type WorkerRequest struct {
	Method  string
	URL     string
	Headers map[string]string
	Body    []byte
}

WorkerRequest represents an incoming HTTP request to a worker.

type WorkerResponse

type WorkerResponse struct {
	StatusCode   int
	Headers      map[string]string
	Body         []byte
	HasWebSocket bool // true when status is 101 and webSocket was set
}

WorkerResponse represents the HTTP response from a worker.

type WorkerResult

type WorkerResult struct {
	Response  *WorkerResponse
	Logs      []LogEntry
	Error     error
	Duration  time.Duration
	WebSocket WebSocketBridger // engine-specific WebSocket handler
	Data      string           // JSON-serialized return value from ExecuteFunction
}

WorkerResult wraps a response with execution metadata.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL