Files
EasyTier/easytier-go/internal/engine/dataplane.go
T
KKRainbow f26c2aa147 feat(wasi): run EasyTier core on Cloudflare Workers and browsers (#2548)
* fix(core): normalize secure keys for TOML instances

* feat(wasi): run core behind Cloudflare WebSockets

Introduce the Cloudflare Worker WASI host that runs the EasyTier core
behind host-upgraded WebSockets.

- Worker package scaffold (wrangler Durable Object, build-wasm script,
  vitest config) and core-runtime/websocket-host/data-plane runtime.
- WASI host WebSocket tunnel ABI (imports, adapter, runtime exports)
  with bounded receive memory and bounded admission queue.
- Route host sockets through the portable listener plan
  (HostListenerRegistration, listener queue, admission handler split).
- Build the WASM guest with the aes-gcm feature so secure peer
  sessions have their cipher available.

* feat(wasi): add outbound browser client runtime

Add the outbound-only WASI runtime and browser connector host so
browser pages can dial EasyTier peers through WebSocket relays.

- CoreConnectivityMode::{OutboundOnly, InboundOnly} gating for
  listeners, discovery, and direct connectivity modules.
- ExternalTunnelConnector plumbing through composite/connector_host/
  manual for browser WebSocket dials.
- Browser/Node smoke entries with shared helpers
  (smoke-shared.ts).

* feat(wasi): extend browser data plane with TCP half-close

Add the data-plane pieces the browser runtime needs for full-duplex
TCP streams behind host WebSockets:

- Guest TCP shutdown_write operation with submit/take ABI pair
  (DATA_PLANE_ABI_VERSION 3 -> 4) and smoltcp half-close support.
- Worker data-plane TCP listener/stream plumbing and core-runtime
  listener registration.
- Unit coverage for the new session ops and listener wiring.

* refactor(wasi): make host tunnel ABI transport-neutral

Replace WebSocket-specific core and WASI boundaries with a
message-oriented Host Tunnel interface. Keep WebSocket framing and text
rejection in the Cloudflare host while preserving payload boundaries,
ownership, cancellation, backpressure, and EOF behavior.

Rename feature flags and guest imports and exports to the Host Tunnel
ABI. Update both Worker profiles, tests, and architecture documentation.

* feat(web): split WASI hosts into publishable npm packages

Extract the shared JSPI, WASI, Host Tunnel, and data-plane runtime
into @easytier/runtime. Keep ABI handles, guest memory, TOML, and
operation broker details behind its adapter entry point.

Add typed, auto-starting @easytier/browser and factory-based
@easytier/cloudflare packages. Ship a matching Wasm profile with
each platform package and validate its capabilities before packing.

Persist Cloudflare instance identity in Durable Object storage,
centralize WebSocket admission ownership, and add package-level
coverage for the public interfaces.

* fix(web): make public packages portable

Embed the browser Wasm artifact in the published JavaScript entry
point. This lets esbuild consumers bundle the package without an asset
loader or a copied file.

Return Cloudflare's nominal Durable Object base type and document the
named subclass export required by generated Wrangler bindings.

* docs(web): add public package walkthrough

Expand both package READMEs with installation, configuration, local
validation, health checks, and deployment instructions.

Add a standalone Vite and Wrangler example that imports only the
public Browser and Cloudflare entries. Generate Worker bindings from
configuration and keep local secrets outside version control.

* chore(go): import EasyTier Go host

Add the standalone Go host runtime as a monorepo subtree without
carrying its development branch ancestry.

Preserve its API, tests, examples, generated protobuf bindings, and
embedded WASI artifacts.

* refactor(hosts): colocate Go and JavaScript runtimes

Move the browser, Cloudflare, shared runtime, and web example into
the easytier-js subtree. Update workspace metadata, build paths, and
documentation for the new layout.

Adopt github.com/EasyTier/EasyTier/easytier-go as the Go module path.
Resolve artifact and protobuf generation from the enclosing monorepo.

* build(web): isolate JavaScript host workspace

Keep public browser and Cloudflare packages outside the legacy frontend
workspace so root installs and cross-platform builds do not pull workerd.

Make each package build generate its required WASI artifact from a clean
checkout. Add a dedicated workflow that runs the same install and check
commands documented for contributors.

Move JavaScript dependencies into a scoped lockfile and restore the root
workspace lockfile to its pre-host state.
2026-09-06 13:35:02 +08:00

511 lines
12 KiB
Go

package engine
import (
"context"
"errors"
"fmt"
"math"
"net"
"net/netip"
"os"
"syscall"
"time"
"github.com/EasyTier/EasyTier/easytier-go/internal/coreabi"
)
const dataPlaneCompletionBatch = 64
type dataPlaneCore interface {
SubmitTCPConnect(
context.Context,
netip.AddrPort,
uint64,
) (coreabi.OperationID, error)
SubmitTCPBind(
context.Context,
uint16,
uint64,
) (coreabi.OperationID, error)
SubmitTCPAccept(
context.Context,
coreabi.ResourceID,
uint64,
) (coreabi.OperationID, error)
SubmitTCPRead(
context.Context,
coreabi.ResourceID,
uint32,
) (coreabi.OperationID, error)
SubmitTCPWrite(
context.Context,
coreabi.ResourceID,
[]byte,
) (coreabi.OperationID, error)
SubmitUDPBind(
context.Context,
uint16,
uint64,
) (coreabi.OperationID, error)
SubmitUDPReceive(
context.Context,
coreabi.ResourceID,
uint32,
) (coreabi.OperationID, error)
SubmitUDPSend(
context.Context,
coreabi.ResourceID,
netip.AddrPort,
[]byte,
) (coreabi.OperationID, error)
SetResourceDeadline(
context.Context,
coreabi.ResourceID,
coreabi.DeadlineDirection,
uint64,
) error
DrainCompletions(context.Context, uint32) ([]coreabi.Completion, error)
TakeResult(
context.Context,
coreabi.Completion,
) (coreabi.OperationResult, error)
CancelOperation(context.Context, coreabi.OperationID) error
CloseResource(context.Context, coreabi.ResourceID) error
}
type dataPlaneCommandKind uint8
const (
dataPlaneSubmit dataPlaneCommandKind = iota + 1
dataPlaneCancel
dataPlaneCloseResource
dataPlaneSetDeadline
)
type dataPlaneCommand struct {
kind dataPlaneCommandKind
operation coreabi.OperationID
resource coreabi.ResourceID
direction coreabi.DeadlineDirection
deadline time.Time
submit func(context.Context, dataPlaneCore) (coreabi.OperationID, error)
opKind coreabi.OperationKind
response chan dataPlaneCommandResponse
}
type dataPlaneCommandResponse struct {
ticket operationTicket
outcome operationOutcome
completed bool
err error
}
type operationTicket struct {
id coreabi.OperationID
result <-chan operationOutcome
}
type operationOutcome struct {
result coreabi.OperationResult
err error
}
type pendingOperation struct {
kind coreabi.OperationKind
result chan operationOutcome
}
func (instance *Instance) performOperation(
ctx context.Context,
kind coreabi.OperationKind,
submit func(context.Context, dataPlaneCore) (coreabi.OperationID, error),
) (coreabi.OperationResult, error) {
if ctx == nil {
return coreabi.OperationResult{}, fmt.Errorf(
"submit EasyTier data plane operation with nil context",
)
}
response := make(chan dataPlaneCommandResponse, 1)
request := dataPlaneCommand{
kind: dataPlaneSubmit,
submit: submit,
opKind: kind,
response: response,
}
select {
case instance.dataPlaneCommands <- request:
case <-instance.done:
return coreabi.OperationResult{}, net.ErrClosed
case <-instance.closeRequested:
return coreabi.OperationResult{}, net.ErrClosed
case <-ctx.Done():
return coreabi.OperationResult{}, ctx.Err()
}
var ticket operationTicket
select {
case submitted := <-response:
if submitted.err != nil {
return coreabi.OperationResult{}, mapDataPlaneError(submitted.err)
}
if submitted.completed {
return submitted.outcome.result, mapDataPlaneError(submitted.outcome.err)
}
ticket = submitted.ticket
case <-instance.done:
return coreabi.OperationResult{}, net.ErrClosed
case <-instance.closeRequested:
return coreabi.OperationResult{}, net.ErrClosed
case <-ctx.Done():
// The driver may already have submitted the operation. Wait for its
// response so that cancellation always targets the actual operation.
select {
case submitted := <-response:
if submitted.err != nil {
return coreabi.OperationResult{}, mapDataPlaneError(submitted.err)
}
if submitted.completed {
return submitted.outcome.result, mapDataPlaneError(
submitted.outcome.err,
)
}
ticket = submitted.ticket
case <-instance.done:
return coreabi.OperationResult{}, net.ErrClosed
case <-instance.closeRequested:
return coreabi.OperationResult{}, net.ErrClosed
}
return instance.cancelAndWait(ctx, ticket)
}
select {
case outcome := <-ticket.result:
return outcome.result, mapDataPlaneError(outcome.err)
case <-ctx.Done():
return instance.cancelAndWait(ctx, ticket)
case <-instance.done:
return coreabi.OperationResult{}, net.ErrClosed
case <-instance.closeRequested:
return coreabi.OperationResult{}, net.ErrClosed
}
}
func (instance *Instance) cancelAndWait(
cancelled context.Context,
ticket operationTicket,
) (coreabi.OperationResult, error) {
response := make(chan dataPlaneCommandResponse, 1)
request := dataPlaneCommand{
kind: dataPlaneCancel,
operation: ticket.id,
response: response,
}
select {
case instance.dataPlaneCommands <- request:
case outcome := <-ticket.result:
return outcome.result, mapDataPlaneError(outcome.err)
case <-instance.done:
return coreabi.OperationResult{}, net.ErrClosed
case <-instance.closeRequested:
return coreabi.OperationResult{}, net.ErrClosed
}
select {
case result := <-response:
if result.err != nil {
return coreabi.OperationResult{}, mapDataPlaneError(result.err)
}
case outcome := <-ticket.result:
return cancelledOutcome(cancelled, outcome)
case <-instance.done:
return coreabi.OperationResult{}, net.ErrClosed
case <-instance.closeRequested:
return coreabi.OperationResult{}, net.ErrClosed
}
select {
case outcome := <-ticket.result:
return cancelledOutcome(cancelled, outcome)
case <-instance.done:
return coreabi.OperationResult{}, net.ErrClosed
case <-instance.closeRequested:
return coreabi.OperationResult{}, net.ErrClosed
}
}
func cancelledOutcome(
cancelled context.Context,
outcome operationOutcome,
) (coreabi.OperationResult, error) {
var dataPlaneErr *coreabi.DataPlaneError
if errors.As(outcome.err, &dataPlaneErr) &&
dataPlaneErr.Kind == coreabi.ErrorCancelled {
return coreabi.OperationResult{}, cancelled.Err()
}
return outcome.result, mapDataPlaneError(outcome.err)
}
func (instance *Instance) closeDataPlaneResource(
resource coreabi.ResourceID,
) error {
response := make(chan dataPlaneCommandResponse, 1)
request := dataPlaneCommand{
kind: dataPlaneCloseResource,
resource: resource,
response: response,
}
select {
case instance.dataPlaneCommands <- request:
case <-instance.done:
return net.ErrClosed
case <-instance.closeRequested:
return net.ErrClosed
}
select {
case result := <-response:
return mapDataPlaneError(result.err)
case <-instance.done:
return net.ErrClosed
case <-instance.closeRequested:
return net.ErrClosed
}
}
func (instance *Instance) setDataPlaneResourceDeadline(
resource coreabi.ResourceID,
direction coreabi.DeadlineDirection,
deadline time.Time,
) error {
response := make(chan dataPlaneCommandResponse, 1)
request := dataPlaneCommand{
kind: dataPlaneSetDeadline,
resource: resource,
direction: direction,
deadline: deadline,
response: response,
}
select {
case instance.dataPlaneCommands <- request:
case <-instance.done:
return net.ErrClosed
case <-instance.closeRequested:
return net.ErrClosed
}
select {
case result := <-response:
return mapDataPlaneError(result.err)
case <-instance.done:
return net.ErrClosed
case <-instance.closeRequested:
return net.ErrClosed
}
}
func (instance *Instance) handleDataPlaneCommand(
request dataPlaneCommand,
) dataPlaneCommandResponse {
instance.host.guestMu.Lock()
defer instance.host.guestMu.Unlock()
switch request.kind {
case dataPlaneSubmit:
operation, err := request.submit(instance.ctx, instance.dataPlane)
if err != nil {
return dataPlaneCommandResponse{err: err}
}
result := make(chan operationOutcome, 1)
instance.pendingOperations[operation] = &pendingOperation{
kind: request.opKind,
result: result,
}
return dataPlaneCommandResponse{ticket: operationTicket{
id: operation,
result: result,
}}
case dataPlaneCancel:
if _, exists := instance.pendingOperations[request.operation]; !exists {
return dataPlaneCommandResponse{}
}
return dataPlaneCommandResponse{
err: instance.dataPlane.CancelOperation(
instance.ctx,
request.operation,
),
}
case dataPlaneCloseResource:
return dataPlaneCommandResponse{
err: instance.dataPlane.CloseResource(
instance.ctx,
request.resource,
),
}
case dataPlaneSetDeadline:
return dataPlaneCommandResponse{
err: instance.dataPlane.SetResourceDeadline(
instance.ctx,
request.resource,
request.direction,
resourceDeadlineTimeoutMillis(request.deadline),
),
}
default:
return dataPlaneCommandResponse{
err: fmt.Errorf("unknown data plane command %d", request.kind),
}
}
}
func (instance *Instance) drainDataPlaneCompletions() (bool, error) {
if instance.dataPlane == nil || len(instance.pendingOperations) == 0 {
return false, nil
}
completions, err := instance.dataPlane.DrainCompletions(
instance.ctx,
dataPlaneCompletionBatch,
)
if err != nil {
return false, err
}
for _, completion := range completions {
pending := instance.pendingOperations[completion.Operation]
if pending == nil {
return false, fmt.Errorf(
"EasyTier completed unknown data plane operation %d",
completion.Operation,
)
}
if pending.kind != completion.Kind {
return false, fmt.Errorf(
"EasyTier completed operation %d as kind %d, want %d",
completion.Operation,
completion.Kind,
pending.kind,
)
}
result, resultErr := instance.dataPlane.TakeResult(
instance.ctx,
completion,
)
if err := validateCompletionResult(completion, resultErr); err != nil {
return false, err
}
delete(instance.pendingOperations, completion.Operation)
pending.result <- operationOutcome{result: result, err: resultErr}
}
return len(completions) == dataPlaneCompletionBatch, nil
}
func validateCompletionResult(
completion coreabi.Completion,
resultErr error,
) error {
var dataPlaneErr *coreabi.DataPlaneError
if completion.Status == coreabi.ErrorNone {
if resultErr != nil {
return fmt.Errorf(
"take successful data plane operation %d: %w",
completion.Operation,
resultErr,
)
}
return nil
}
if !errors.As(resultErr, &dataPlaneErr) {
return fmt.Errorf(
"take failed data plane operation %d with status %d: %w",
completion.Operation,
completion.Status,
resultErr,
)
}
if dataPlaneErr.Kind != completion.Status {
return fmt.Errorf(
"data plane operation %d status %d disagrees with result %d",
completion.Operation,
completion.Status,
dataPlaneErr.Kind,
)
}
return nil
}
func (instance *Instance) failPendingOperations(err error) {
for operation, pending := range instance.pendingOperations {
pending.result <- operationOutcome{err: err}
delete(instance.pendingOperations, operation)
}
}
func timeoutFromDeadline(deadline time.Time) (uint64, error) {
if deadline.IsZero() {
return math.MaxUint64, nil
}
remaining := time.Until(deadline)
if remaining <= 0 {
return 0, os.ErrDeadlineExceeded
}
millis := remaining / time.Millisecond
if remaining%time.Millisecond != 0 {
millis++
}
return uint64(millis), nil
}
func resourceDeadlineTimeoutMillis(deadline time.Time) uint64 {
if deadline.IsZero() {
return math.MaxUint64
}
remaining := time.Until(deadline)
if remaining <= 0 {
return 0
}
millis := remaining / time.Millisecond
if remaining%time.Millisecond != 0 {
millis++
}
return uint64(millis)
}
func contextTimeoutMillis(ctx context.Context) (uint64, error) {
if err := ctx.Err(); err != nil {
return 0, err
}
deadline, exists := ctx.Deadline()
if !exists {
return math.MaxUint64, nil
}
return timeoutFromDeadline(deadline)
}
func mapDataPlaneError(err error) error {
if err == nil {
return nil
}
var dataPlaneErr *coreabi.DataPlaneError
if !errors.As(err, &dataPlaneErr) {
return err
}
switch dataPlaneErr.Kind {
case coreabi.ErrorCancelled:
return context.Canceled
case coreabi.ErrorDeadlineExceeded:
return os.ErrDeadlineExceeded
case coreabi.ErrorInstanceStopped, coreabi.ErrorHandleClosed:
return net.ErrClosed
case coreabi.ErrorNoOverlayRoute, coreabi.ErrorPathNotReady:
return syscall.ENETUNREACH
case coreabi.ErrorAddressFamilyUnsupported:
return syscall.EAFNOSUPPORT
case coreabi.ErrorAddressInUse:
return syscall.EADDRINUSE
case coreabi.ErrorConnectionRefused:
return syscall.ECONNREFUSED
case coreabi.ErrorNetworkChanged:
return syscall.ENETRESET
case coreabi.ErrorResourceLimit:
return syscall.ENOBUFS
case coreabi.ErrorBufferTooSmall:
return syscall.EMSGSIZE
default:
return err
}
}