Skip to content

An open-source, faster Devin alternative

TypeScript

scale

motatoes4bec751d9e2e
diff --git a/Makefile b/Makefile
index b34b598d..4fb3d50c 100644
--- a/Makefile
+++ b/Makefile
@@ -14,19 +14,92 @@ build: build-server build-worker
## build-server: Build the control plane server
build-server:
- go build -o $(BUILD_DIR)/$(BINARY_SERVER) ./cmd/server
+ CGO_ENABLED=1 go build -o $(BUILD_DIR)/$(BINARY_SERVER) ./cmd/server
## build-worker: Build the sandbox worker
build-worker:
- go build -o $(BUILD_DIR)/$(BINARY_WORKER) ./cmd/worker
+ CGO_ENABLED=1 go build -o $(BUILD_DIR)/$(BINARY_WORKER) ./cmd/worker
-## run: Run the server in combined mode
-run: build-server
- OPENSANDBOX_MODE=combined $(BUILD_DIR)/$(BINARY_SERVER)
+## --- Local Testing (3 tiers) ---
-## run-dev: Run the server with no auth for development
+## run-dev: Tier 1 - Combined mode, no auth, no PG/NATS (simplest)
run-dev: build-server
- OPENSANDBOX_MODE=combined OPENSANDBOX_API_KEY= $(BUILD_DIR)/$(BINARY_SERVER)
+ OPENSANDBOX_MODE=combined \
+ OPENSANDBOX_API_KEY= \
+ OPENSANDBOX_DATA_DIR=/tmp/opensandbox-data \
+ $(BUILD_DIR)/$(BINARY_SERVER)
+
+## run: Tier 1 - Combined mode with static API key
+run: build-server
+ OPENSANDBOX_MODE=combined \
+ OPENSANDBOX_API_KEY=test-key \
+ OPENSANDBOX_DATA_DIR=/tmp/opensandbox-data \
+ $(BUILD_DIR)/$(BINARY_SERVER)
+
+## run-pg: Tier 2 - Combined mode with PostgreSQL (requires: make infra-up)
+run-pg: build-server
+ OPENSANDBOX_MODE=combined \
+ OPENSANDBOX_API_KEY=test-key \
+ OPENSANDBOX_JWT_SECRET=dev-secret-change-me \
+ OPENSANDBOX_DATABASE_URL="postgres://opensandbox:opensandbox@localhost:5432/opensandbox?sslmode=disable" \
+ OPENSANDBOX_DATA_DIR=/tmp/opensandbox-data \
+ OPENSANDBOX_HTTP_ADDR=http://localhost:8080 \
+ $(BUILD_DIR)/$(BINARY_SERVER)
+
+## run-full-server: Tier 3 - Control plane only (requires: make infra-up)
+run-full-server: build-server
+ OPENSANDBOX_MODE=server \
+ OPENSANDBOX_PORT=8080 \
+ OPENSANDBOX_API_KEY=test-key \
+ OPENSANDBOX_JWT_SECRET=dev-secret-change-me \
+ OPENSANDBOX_DATABASE_URL="postgres://opensandbox:opensandbox@localhost:5432/opensandbox?sslmode=disable" \
+ OPENSANDBOX_NATS_URL=nats://localhost:4222 \
+ OPENSANDBOX_REGION=local \
+ OPENSANDBOX_WORKER_ID=cp-local-1 \
+ OPENSANDBOX_HTTP_ADDR=http://localhost:8080 \
+ OPENSANDBOX_DATA_DIR=/tmp/opensandbox-data \
+ $(BUILD_DIR)/$(BINARY_SERVER)
+
+## run-full-worker: Tier 3 - Worker only (requires: make infra-up)
+run-full-worker: build-worker
+ OPENSANDBOX_MODE=worker \
+ OPENSANDBOX_PORT=8081 \
+ OPENSANDBOX_JWT_SECRET=dev-secret-change-me \
+ OPENSANDBOX_NATS_URL=nats://localhost:4222 \
+ OPENSANDBOX_REGION=local \
+ OPENSANDBOX_WORKER_ID=w-local-1 \
+ OPENSANDBOX_HTTP_ADDR=http://localhost:8081 \
+ OPENSANDBOX_DATA_DIR=/tmp/opensandbox-worker-data \
+ $(BUILD_DIR)/$(BINARY_WORKER)
+
+## --- Infrastructure ---
+
+## infra-up: Start PostgreSQL + NATS via Docker Compose
+infra-up:
+ docker compose -f deploy/docker-compose.yml up -d
+ @echo "Waiting for PostgreSQL..."
+ @until docker compose -f deploy/docker-compose.yml exec -T postgres pg_isready -U opensandbox 2>/dev/null; do sleep 1; done
+ @echo "Infrastructure ready: PostgreSQL :5432, NATS :4222"
+
+## infra-down: Stop infrastructure
+infra-down:
+ docker compose -f deploy/docker-compose.yml down
+
+## infra-reset: Stop infrastructure and delete volumes
+infra-reset:
+ docker compose -f deploy/docker-compose.yml down -v
+
+## seed: Create a test org and API key in PostgreSQL (requires: make infra-up)
+seed:
+ @docker compose -f deploy/docker-compose.yml exec -T postgres psql -U opensandbox -d opensandbox -c " \
+ INSERT INTO orgs (name, slug) VALUES ('Test Org', 'test-org') ON CONFLICT (slug) DO NOTHING; \
+ INSERT INTO api_keys (org_id, key_hash, key_prefix, name) \
+ SELECT id, encode(sha256('test-key'::bytea), 'hex'), 'test-key', 'Dev Key' \
+ FROM orgs WHERE slug = 'test-org' \
+ ON CONFLICT (key_hash) DO NOTHING; \
+ " 2>/dev/null && echo "Seeded: org=test-org, api_key=test-key" || echo "Seed failed (run migrations first by starting the server)"
+
+## --- Standard ---
## test: Run all tests
test:
@@ -52,6 +125,13 @@ tidy:
## clean: Remove build artifacts
clean:
rm -rf $(BUILD_DIR)
+ rm -rf /tmp/opensandbox-data /tmp/opensandbox-worker-data
+
+## proto: Regenerate protobuf/gRPC code
+proto:
+ protoc --go_out=. --go_opt=paths=source_relative \
+ --go-grpc_out=. --go-grpc_opt=paths=source_relative \
+ proto/worker/worker.proto
## docker-server: Build server Docker image
docker-server:
diff --git a/cmd/server/main.go b/cmd/server/main.go
index d3f571e4..50e206ef 100644
--- a/cmd/server/main.go
+++ b/cmd/server/main.go
@@ -10,7 +10,9 @@ import (
"syscall"
"github.com/opensandbox/opensandbox/internal/api"
+ "github.com/opensandbox/opensandbox/internal/auth"
"github.com/opensandbox/opensandbox/internal/config"
+ "github.com/opensandbox/opensandbox/internal/db"
"github.com/opensandbox/opensandbox/internal/podman"
"github.com/opensandbox/opensandbox/internal/sandbox"
"github.com/opensandbox/opensandbox/internal/template"
@@ -48,10 +50,64 @@ func main() {
registry := template.NewRegistry()
builder := template.NewBuilder(podmanClient, registry)
+ // Build server options
+ opts := &api.ServerOpts{
+ Mode: cfg.Mode,
+ WorkerID: cfg.WorkerID,
+ Region: cfg.Region,
+ HTTPAddr: cfg.HTTPAddr,
+ }
+
+ // Initialize PostgreSQL if configured
+ if cfg.DatabaseURL != "" {
+ store, err := db.NewStore(ctx, cfg.DatabaseURL)
+ if err != nil {
+ log.Fatalf("failed to connect to database: %v", err)
+ }
+ defer store.Close()
+
+ log.Println("opensandbox: running database migrations...")
+ if err := store.Migrate(ctx); err != nil {
+ log.Fatalf("failed to run migrations: %v", err)
+ }
+ log.Println("opensandbox: database migrations complete")
+
+ opts.Store = store
+ } else {
+ log.Println("opensandbox: no DATABASE_URL configured, running without PostgreSQL")
+ }
+
+ // Initialize JWT issuer if configured
+ if cfg.JWTSecret != "" {
+ opts.JWTIssuer = auth.NewJWTIssuer(cfg.JWTSecret)
+ log.Println("opensandbox: JWT issuer configured")
+ }
+
+ // Initialize per-sandbox SQLite manager
+ sandboxDBMgr := sandbox.NewSandboxDBManager(cfg.DataDir)
+ defer sandboxDBMgr.Close()
+ opts.SandboxDBs = sandboxDBMgr
+ log.Printf("opensandbox: SQLite data directory: %s", cfg.DataDir)
+
// Create API server
- server := api.NewServer(mgr, ptyMgr, cfg.APIKey)
+ server := api.NewServer(mgr, ptyMgr, cfg.APIKey, opts)
server.SetTemplateDeps(registry, builder)
+ // Start NATS sync consumer if both PG and NATS are configured
+ if opts.Store != nil && cfg.NATSURL != "" {
+ consumer, err := db.NewSyncConsumer(opts.Store, cfg.NATSURL)
+ if err != nil {
+ log.Printf("opensandbox: NATS sync consumer not available: %v (continuing without)", err)
+ } else {
+ if err := consumer.Start(); err != nil {
+ log.Printf("opensandbox: failed to start NATS sync consumer: %v", err)
+ } else {
+ defer consumer.Stop()
+ log.Println("opensandbox: NATS sync consumer started")
+ }
+ }
+ }
+
// Graceful shutdown
quit := make(chan os.Signal, 1)
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
diff --git a/cmd/worker/main.go b/cmd/worker/main.go
index 79e0a945..faeb8355 100644
--- a/cmd/worker/main.go
+++ b/cmd/worker/main.go
@@ -2,16 +2,28 @@ package main
import (
"context"
+ "fmt"
"log"
"os"
+ "os/exec"
"os/signal"
"syscall"
+ "github.com/opensandbox/opensandbox/internal/auth"
+ "github.com/opensandbox/opensandbox/internal/config"
+ "github.com/opensandbox/opensandbox/internal/metrics"
"github.com/opensandbox/opensandbox/internal/podman"
+ "github.com/opensandbox/opensandbox/internal/sandbox"
+ "github.com/opensandbox/opensandbox/internal/worker"
)
func main() {
- log.Println("opensandbox-worker: starting...")
+ cfg, err := config.Load()
+ if err != nil {
+ log.Fatalf("failed to load config: %v", err)
+ }
+
+ log.Printf("opensandbox-worker: starting (id=%s, region=%s)...", cfg.WorkerID, cfg.Region)
client, err := podman.NewClient()
if err != nil {
@@ -25,14 +37,90 @@ func main() {
}
log.Printf("opensandbox-worker: using podman %s", version)
- // TODO: Start gRPC server for control plane communication
- // For now, the worker functionality is embedded in the server (combined mode)
- log.Println("opensandbox-worker: running in standalone mode (gRPC server not yet implemented)")
- log.Println("opensandbox-worker: use --mode=combined on the server for single-machine deployment")
+ // Pre-pull common template images
+ log.Println("opensandbox-worker: pre-pulling template images...")
+ images := []string{
+ "docker.io/library/ubuntu:22.04",
+ "docker.io/library/python:3.12-slim",
+ "docker.io/library/node:20-slim",
+ }
+ for _, img := range images {
+ exists, _ := client.ImageExists(ctx, img)
+ if !exists {
+ log.Printf("opensandbox-worker: pulling %s...", img)
+ if err := client.PullImage(ctx, img); err != nil {
+ log.Printf("opensandbox-worker: warning: failed to pull %s: %v", img, err)
+ }
+ }
+ }
+
+ // Initialize sandbox manager
+ mgr := sandbox.NewManager(client)
+ defer mgr.Close()
+
+ // Initialize PTY manager
+ podmanPath, _ := exec.LookPath("podman")
+ ptyMgr := sandbox.NewPTYManager(podmanPath, client.AuthFile())
+ defer ptyMgr.CloseAll()
+
+ // Initialize per-sandbox SQLite manager
+ sandboxDBMgr := sandbox.NewSandboxDBManager(cfg.DataDir)
+ defer sandboxDBMgr.Close()
+
+ // JWT issuer for validating sandbox tokens
+ if cfg.JWTSecret == "" {
+ log.Fatalf("OPENSANDBOX_JWT_SECRET is required for worker mode")
+ }
+ jwtIssuer := auth.NewJWTIssuer(cfg.JWTSecret)
+
+ // Start Prometheus metrics server on :9091
+ metricsSrv := metrics.StartMetricsServer(":9091")
+ defer metricsSrv.Close()
+ log.Println("opensandbox-worker: metrics server started on :9091")
+
+ // Start gRPC server for control plane communication
+ grpcServer := worker.NewGRPCServer(mgr, ptyMgr, sandboxDBMgr)
+ grpcAddr := ":9090"
+ log.Printf("opensandbox-worker: starting gRPC server on %s", grpcAddr)
+ go func() {
+ if err := grpcServer.Start(grpcAddr); err != nil {
+ log.Printf("gRPC server error: %v", err)
+ }
+ }()
+
+ // Start HTTP server for direct SDK access
+ httpServer := worker.NewHTTPServer(mgr, ptyMgr, jwtIssuer, sandboxDBMgr)
+ httpAddr := fmt.Sprintf(":%d", cfg.Port)
+ log.Printf("opensandbox-worker: starting HTTP server on %s", httpAddr)
+ go func() {
+ if err := httpServer.Start(httpAddr); err != nil {
+ log.Printf("HTTP server error: %v", err)
+ }
+ }()
+
+ // Start NATS event publisher if configured
+ if cfg.NATSURL != "" {
+ pub, err := worker.NewEventPublisher(cfg.NATSURL, cfg.Region, cfg.WorkerID, sandboxDBMgr)
+ if err != nil {
+ log.Printf("opensandbox-worker: NATS not available: %v (continuing without event sync)", err)
+ } else {
+ pub.Start()
+ pub.StartHeartbeat(func() (int, int, float64, float64) {
+ // TODO: get actual stats from sandbox manager
+ return 50, 0, 0.0, 0.0
+ })
+ defer pub.Stop()
+ log.Println("opensandbox-worker: NATS event publisher started")
+ }
+ }
quit := make(chan os.Signal, 1)
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
<-quit
log.Println("opensandbox-worker: shutting down...")
+ grpcServer.Stop()
+ if err := httpServer.Close(); err != nil {
+ log.Printf("error closing HTTP server: %v", err)
+ }
}
diff --git a/deploy/Dockerfile.server b/deploy/Dockerfile.server
index 1119711f..51719413 100644
--- a/deploy/Dockerfile.server
+++ b/deploy/Dockerfile.server
@@ -1,11 +1,11 @@
-FROM golang:1.22-bookworm AS builder
+FROM golang:1.23-bookworm AS builder
WORKDIR /app
COPY go.mod go.sum ./
RUN go mod download
COPY . .
-RUN CGO_ENABLED=0 go build -o /opensandbox-server ./cmd/server
+RUN CGO_ENABLED=1 go build -o /opensandbox-server ./cmd/server
FROM debian:bookworm-slim
diff --git a/deploy/Dockerfile.worker b/deploy/Dockerfile.worker
index 1c2ba682..098a262a 100644
--- a/deploy/Dockerfile.worker
+++ b/deploy/Dockerfile.worker
@@ -1,11 +1,11 @@
-FROM golang:1.22-bookworm AS builder
+FROM golang:1.23-bookworm AS builder
WORKDIR /app
COPY go.mod go.sum ./
RUN go mod download
COPY . .
-RUN CGO_ENABLED=0 go build -o /opensandbox-worker ./cmd/worker
+RUN CGO_ENABLED=1 go build -o /opensandbox-worker ./cmd/worker
FROM ubuntu:22.04
@@ -20,10 +20,5 @@ RUN apt-get update && apt-get install -y --no-install-recommends \
COPY --from=builder /opensandbox-worker /usr/local/bin/opensandbox-worker
-# Pre-pull default template images
-RUN podman pull docker.io/library/ubuntu:22.04 && \
- podman pull docker.io/library/python:3.12-slim && \
- podman pull docker.io/library/node:20-slim || true
-
-EXPOSE 9090
+EXPOSE 8080 9090 9091
CMD ["opensandbox-worker"]
diff --git a/deploy/docker-compose.yml b/deploy/docker-compose.yml
new file mode 100644
index 00000000..a53e7cf0
--- /dev/null
+++ b/deploy/docker-compose.yml
@@ -0,0 +1,34 @@
+version: "3.9"
+
+# Full local stack: PostgreSQL + NATS + Control Plane + Worker
+# Usage: cd deploy && docker compose up
+
+services:
+ postgres:
+ image: postgres:16-alpine
+ environment:
+ POSTGRES_DB: opensandbox
+ POSTGRES_USER: opensandbox
+ POSTGRES_PASSWORD: opensandbox
+ ports:
+ - "5432:5432"
+ volumes:
+ - pg_data:/var/lib/postgresql/data
+ healthcheck:
+ test: ["CMD-SHELL", "pg_isready -U opensandbox"]
+ interval: 5s
+ timeout: 5s
+ retries: 5
+
+ nats:
+ image: nats:2-alpine
+ command: ["--jetstream", "--store_dir=/data"]
+ ports:
+ - "4222:4222"
+ - "8222:8222" # monitoring
+ volumes:
+ - nats_data:/data
+
+volumes:
+ pg_data:
+ nats_data:
diff --git a/deploy/fly-worker.toml b/deploy/fly-worker.toml
new file mode 100644
index 00000000..0de00d14
--- /dev/null
+++ b/deploy/fly-worker.toml
@@ -0,0 +1,43 @@
+app = "opensandbox-worker"
+primary_region = "iad"
+
+[build]
+ dockerfile = "Dockerfile.worker"
+
+# HTTP service for direct SDK access
+[http_service]
+ internal_port = 8080
+ force_https = true
+ auto_stop_machines = false
+ auto_start_machines = true
+ min_machines_running = 1
+
+# gRPC service for control plane communication
+[[services]]
+ protocol = "tcp"
+ internal_port = 9090
+ [[services.ports]]
+ port = 9090
+ handlers = ["tls"]
+
+# Metrics endpoint
+[[services]]
+ protocol = "tcp"
+ internal_port = 9091
+ [[services.ports]]
+ port = 9091
+
+[env]
+ OPENSANDBOX_MODE = "worker"
+ OPENSANDBOX_PORT = "8080"
+ OPENSANDBOX_REGION = "iad"
+ OPENSANDBOX_DATA_DIR = "/data/sandboxes"
+
+[mounts]
+ source = "sandbox_data"
+ destination = "/data/sandboxes"
+
+[[vm]]
+ cpu_kind = "shared"
+ cpus = 2
+ memory_mb = 2048
diff --git a/deploy/fly.toml b/deploy/fly.toml
index 74f19ef8..cb1b50ab 100644
--- a/deploy/fly.toml
+++ b/deploy/fly.toml
@@ -14,3 +14,7 @@ primary_region = "iad"
[env]
OPENSANDBOX_MODE = "server"
OPENSANDBOX_PORT = "8080"
+ OPENSANDBOX_REGION = "iad"
+ OPENSANDBOX_WORKER_ID = "cp-iad-1"
+ OPENSANDBOX_HTTP_ADDR = "https://opensandbox.fly.dev"
+ # DATABASE_URL, JWT_SECRET, NATS_URL set via fly secrets
diff --git a/deploy/grafana/dashboards/opensandbox-overview.json b/deploy/grafana/dashboards/opensandbox-overview.json
new file mode 100644
index 00000000..ed08a664
--- /dev/null
+++ b/deploy/grafana/dashboards/opensandbox-overview.json
@@ -0,0 +1,128 @@
+{
+ "dashboard": {
+ "title": "OpenSandbox Overview",
+ "uid": "opensandbox-overview",
+ "panels": [
+ {
+ "title": "Active Sandboxes",
+ "type": "stat",
+ "gridPos": {"h": 4, "w": 6, "x": 0, "y": 0},
+ "targets": [
+ {
+ "expr": "sum(opensandbox_sandboxes_active)",
+ "legendFormat": "Total Active"
+ }
+ ]
+ },
+ {
+ "title": "Active Sandboxes by Region",
+ "type": "timeseries",
+ "gridPos": {"h": 8, "w": 12, "x": 0, "y": 4},
+ "targets": [
+ {
+ "expr": "sum by (region) (opensandbox_sandboxes_active)",
+ "legendFormat": "{{region}}"
+ }
+ ]
+ },
+ {
+ "title": "Sandbox Create Latency",
+ "type": "timeseries",
+ "gridPos": {"h": 8, "w": 12, "x": 12, "y": 4},
+ "targets": [
+ {
+ "expr": "histogram_quantile(0.95, sum(rate(opensandbox_sandbox_create_duration_seconds_bucket[5m])) by (le, region))",
+ "legendFormat": "p95 {{region}}"
+ },
+ {
+ "expr": "histogram_quantile(0.50, sum(rate(opensandbox_sandbox_create_duration_seconds_bucket[5m])) by (le, region))",
+ "legendFormat": "p50 {{region}}"
+ }
+ ]
+ },
+ {
+ "title": "Worker Utilization",
+ "type": "gauge",
+ "gridPos": {"h": 4, "w": 6, "x": 6, "y": 0},
+ "targets": [
+ {
+ "expr": "avg(opensandbox_worker_utilization)",
+ "legendFormat": "Avg Utilization"
+ }
+ ]
+ },
+ {
+ "title": "Workers by Region & Status",
+ "type": "table",
+ "gridPos": {"h": 4, "w": 12, "x": 12, "y": 0},
+ "targets": [
+ {
+ "expr": "opensandbox_workers_total",
+ "legendFormat": "{{region}} {{status}}"
+ }
+ ]
+ },
+ {
+ "title": "Command Execution Latency",
+ "type": "timeseries",
+ "gridPos": {"h": 8, "w": 12, "x": 0, "y": 12},
+ "targets": [
+ {
+ "expr": "histogram_quantile(0.95, sum(rate(opensandbox_exec_duration_seconds_bucket[5m])) by (le))",
+ "legendFormat": "p95"
+ },
+ {
+ "expr": "histogram_quantile(0.50, sum(rate(opensandbox_exec_duration_seconds_bucket[5m])) by (le))",
+ "legendFormat": "p50"
+ }
+ ]
+ },
+ {
+ "title": "Active PTY Sessions",
+ "type": "timeseries",
+ "gridPos": {"h": 8, "w": 12, "x": 12, "y": 12},
+ "targets": [
+ {
+ "expr": "sum by (region) (opensandbox_pty_sessions_active)",
+ "legendFormat": "{{region}}"
+ }
+ ]
+ },
+ {
+ "title": "HTTP Request Rate",
+ "type": "timeseries",
+ "gridPos": {"h": 8, "w": 12, "x": 0, "y": 20},
+ "targets": [
+ {
+ "expr": "sum(rate(opensandbox_http_requests_total[5m])) by (method, path)",
+ "legendFormat": "{{method}} {{path}}"
+ }
+ ]
+ },
+ {
+ "title": "SQLite Sync Lag",
+ "type": "timeseries",
+ "gridPos": {"h": 8, "w": 12, "x": 12, "y": 20},
+ "targets": [
+ {
+ "expr": "opensandbox_sqlite_sync_lag_seconds",
+ "legendFormat": "{{worker_id}}"
+ }
+ ]
+ },
+ {
+ "title": "Scale Events",
+ "type": "timeseries",
+ "gridPos": {"h": 8, "w": 24, "x": 0, "y": 28},
+ "targets": [
+ {
+ "expr": "sum(rate(opensandbox_scale_events_total[5m])) by (region, direction)",
+ "legendFormat": "{{region}} {{direction}}"
+ }
+ ]
+ }
+ ],
+ "time": {"from": "now-1h", "to": "now"},
+ "refresh": "10s"
+ }
+}
diff --git a/deploy/prometheus/prometheus.yml b/deploy/prometheus/prometheus.yml
new file mode 100644
index 00000000..cd8feef6
--- /dev/null
+++ b/deploy/prometheus/prometheus.yml
@@ -0,0 +1,24 @@
+global:
+ scrape_interval: 15s
+ evaluation_interval: 15s
+
+scrape_configs:
+ # Control plane metrics
+ - job_name: 'opensandbox-cp'
+ static_configs:
+ - targets: ['opensandbox.internal:8080']
+ metrics_path: '/metrics'
+
+ # Worker metrics (auto-discovered via DNS)
+ - job_name: 'opensandbox-workers'
+ dns_sd_configs:
+ - names:
+ - '_prometheus._tcp.opensandbox-worker.internal'
+ type: SRV
+ refresh_interval: 30s
+ # Fallback to static for local development
+ static_configs:
+ - targets: ['localhost:9091']
+ labels:
+ region: 'local'
+ worker_id: 'w-local-1'
diff --git a/go.mod b/go.mod
index 2c21135a..3694356a 100644
--- a/go.mod
+++ b/go.mod
@@ -1,24 +1,45 @@
module github.com/opensandbox/opensandbox
-go 1.22
+go 1.23.0
require (
+ github.com/creack/pty v1.1.24
+ github.com/golang-jwt/jwt/v5 v5.2.1
github.com/google/uuid v1.6.0
github.com/gorilla/websocket v1.5.3
+ github.com/jackc/pgx/v5 v5.7.2
github.com/labstack/echo/v4 v4.12.0
+ github.com/mattn/go-sqlite3 v1.14.24
+ github.com/nats-io/nats.go v1.48.0
+ github.com/prometheus/client_golang v1.20.5
+ google.golang.org/grpc v1.69.4
+ google.golang.org/protobuf v1.36.3
)
require (
- github.com/creack/pty v1.1.24 // indirect
+ github.com/beorn7/perks v1.0.1 // indirect
+ github.com/cespare/xxhash/v2 v2.3.0 // indirect
github.com/golang-jwt/jwt v3.2.2+incompatible // indirect
+ github.com/jackc/pgpassfile v1.0.0 // indirect
+ github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
+ github.com/jackc/puddle/v2 v2.2.2 // indirect
+ github.com/klauspost/compress v1.18.0 // indirect
github.com/labstack/gommon v0.4.2 // indirect
github.com/mattn/go-colorable v0.1.13 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
+ github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
+ github.com/nats-io/nkeys v0.4.11 // indirect
+ github.com/nats-io/nuid v1.0.1 // indirect
+ github.com/prometheus/client_model v0.6.1 // indirect
+ github.com/prometheus/common v0.55.0 // indirect
+ github.com/prometheus/procfs v0.15.1 // indirect
github.com/valyala/bytebufferpool v1.0.0 // indirect
github.com/valyala/fasttemplate v1.2.2 // indirect
- golang.org/x/crypto v0.31.0 // indirect
+ golang.org/x/crypto v0.37.0 // indirect
golang.org/x/net v0.33.0 // indirect
- golang.org/x/sys v0.28.0 // indirect
- golang.org/x/text v0.21.0 // indirect
+ golang.org/x/sync v0.13.0 // indirect
+ golang.org/x/sys v0.32.0 // indirect
+ golang.org/x/text v0.24.0 // indirect
golang.org/x/time v0.8.0 // indirect
+ google.golang.org/genproto/googleapis/rpc v0.0.0-20241015192408-796eee8c2d53 // indirect
)
diff --git a/go.sum b/go.sum
index 91d85a05..ee40f693 100644
--- a/go.sum
+++ b/go.sum
@@ -1,13 +1,40 @@
+github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=
+github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw=
+github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
+github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
github.com/creack/pty v1.1.24 h1:bJrF4RRfyJnbTJqzRLHzcGaZK1NeM5kTC9jGgovnR1s=
github.com/creack/pty v1.1.24/go.mod h1:08sCNb52WyoAwi2QDyzUCTgcvVFhUzewun7wtTfvcwE=
+github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
+github.com/go-logr/logr v1.4.2 h1:6pFjapn8bFcIbiKo3XT4j/BhANplGihG6tvd+8rYgrY=
+github.com/go-logr/logr v1.4.2/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
+github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
+github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
github.com/golang-jwt/jwt v3.2.2+incompatible h1:IfV12K8xAKAnZqdXVzCZ+TOjboZ2keLg81eXfW3O+oY=
github.com/golang-jwt/jwt v3.2.2+incompatible/go.mod h1:8pz2t5EyA70fFQQSrl6XZXzqecmYZeUEB8OUGHkxJ+I=
+github.com/golang-jwt/jwt/v5 v5.2.1 h1:OuVbFODueb089Lh128TAcimifWaLhJwVflnrgM17wHk=
+github.com/golang-jwt/jwt/v5 v5.2.1/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk=
+github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=
+github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=
+github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
+github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
+github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
+github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
+github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
+github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
+github.com/jackc/pgx/v5 v5.7.2 h1:mLoDLV6sonKlvjIEsV56SkWNCnuNv531l94GaIzO+XI=
+github.com/jackc/pgx/v5 v5.7.2/go.mod h1:ncY89UGWxg82EykZUwSpUKEfccBGGYq1xjrOpsbsfGQ=
+github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo=
+github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
+github.com/klauspost/compress v1.18.0 h1:c/Cqfb0r+Yi+JtIEq73FWXVkRonBlf0CRNYc8Zttxdo=
+github.com/klauspost/compress v1.18.0/go.mod h1:2Pp+KzxcywXVXMr50+X0Q/Lsb43OQHYWRCY2AiWywWQ=
+github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc=
+github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw=
github.com/labstack/echo/v4 v4.12.0 h1:IKpw49IMryVB2p1a4dzwlhP1O2Tf2E0Ir/450lH+kI0=
github.com/labstack/echo/v4 v4.12.0/go.mod h1:UP9Cr2DJXbOK3Kr9ONYzNowSh7HP0aG0ShAyycHSJvM=
github.com/labstack/gommon v0.4.2 h1:F8qTUNXgG1+6WQmqoUWnz8WiEU60mXVVw0P4ht1WRA0=
@@ -17,25 +44,66 @@ github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovk
github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
+github.com/mattn/go-sqlite3 v1.14.24 h1:tpSp2G2KyMnnQu99ngJ47EIkWVmliIizyZBfPrBWDRM=
+github.com/mattn/go-sqlite3 v1.14.24/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=
+github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA=
+github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ=
+github.com/nats-io/nats.go v1.48.0 h1:pSFyXApG+yWU/TgbKCjmm5K4wrHu86231/w84qRVR+U=
+github.com/nats-io/nats.go v1.48.0/go.mod h1:iRWIPokVIFbVijxuMQq4y9ttaBTMe0SFdlZfMDd+33g=
+github.com/nats-io/nkeys v0.4.11 h1:q44qGV008kYd9W1b1nEBkNzvnWxtRSQ7A8BoqRrcfa0=
+github.com/nats-io/nkeys v0.4.11/go.mod h1:szDimtgmfOi9n25JpfIdGw12tZFYXqhGxjhVxsatHVE=
+github.com/nats-io/nuid v1.0.1 h1:5iA8DT8V7q8WK2EScv2padNa/rTESc1KdnPw4TC2paw=
+github.com/nats-io/nuid v1.0.1/go.mod h1:19wcPz3Ph3q0Jbyiqsd0kePYG7A95tJPxeL+1OSON2c=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
-github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk=
-github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
+github.com/prometheus/client_golang v1.20.5 h1:cxppBPuYhUnsO6yo/aoRol4L7q7UFfdm+bR9r+8l63Y=
+github.com/prometheus/client_golang v1.20.5/go.mod h1:PIEt8X02hGcP8JWbeHyeZ53Y/jReSnHgO035n//V5WE=
+github.com/prometheus/client_model v0.6.1 h1:ZKSh/rekM+n3CeS952MLRAdFwIKqeY8b62p8ais2e9E=
+github.com/prometheus/client_model v0.6.1/go.mod h1:OrxVMOVHjw3lKMa8+x6HeMGkHMQyHDk9E3jmP2AmGiY=
+github.com/prometheus/common v0.55.0 h1:KEi6DK7lXW/m7Ig5i47x0vRzuBsHuvJdi5ee6Y3G1dc=
+github.com/prometheus/common v0.55.0/go.mod h1:2SECS4xJG1kd8XF9IcM1gMX6510RAEL65zxzNImwdc8=
+github.com/prometheus/procfs v0.15.1 h1:YagwOFzUgYfKKHX6Dr+sHT7km/hxC76UB0learggepc=
+github.com/prometheus/procfs v0.15.1/go.mod h1:fB45yRUv8NstnjriLhBQLuOUt+WW4BsoGhij/e3PBqk=
+github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
+github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
+github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
+github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
+github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw=
github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc=
github.com/valyala/fasttemplate v1.2.2 h1:lxLXG0uE3Qnshl9QyaK6XJxMXlQZELvChBOCmQD0Loo=
github.com/valyala/fasttemplate v1.2.2/go.mod h1:KHLXt3tVN2HBp8eijSv/kGJopbvo7S+qRAEEKiv+SiQ=
-golang.org/x/crypto v0.31.0 h1:ihbySMvVjLAeSH1IbfcRTkD/iNscyz8rGzjF/E5hV6U=
-golang.org/x/crypto v0.31.0/go.mod h1:kDsLvtWBEx7MV9tJOj9bnXsPbxwJQ6csT/x4KIN4Ssk=
+go.opentelemetry.io/otel v1.31.0 h1:NsJcKPIW0D0H3NgzPDHmo0WW6SptzPdqg/L1zsIm2hY=
+go.opentelemetry.io/otel v1.31.0/go.mod h1:O0C14Yl9FgkjqcCZAsE053C13OaddMYr/hz6clDkEJE=
+go.opentelemetry.io/otel/metric v1.31.0 h1:FSErL0ATQAmYHUIzSezZibnyVlft1ybhy4ozRPcF2fE=
+go.opentelemetry.io/otel/metric v1.31.0/go.mod h1:C3dEloVbLuYoX41KpmAhOqNriGbA+qqH6PQ5E5mUfnY=
+go.opentelemetry.io/otel/sdk v1.31.0 h1:xLY3abVHYZ5HSfOg3l2E5LUj2Cwva5Y7yGxnSW9H5Gk=
+go.opentelemetry.io/otel/sdk v1.31.0/go.mod h1:TfRbMdhvxIIr/B2N2LQW2S5v9m3gOQ/08KsbbO5BPT0=
+go.opentelemetry.io/otel/sdk/metric v1.31.0 h1:i9hxxLJF/9kkvfHppyLL55aW7iIJz4JjxTeYusH7zMc=
+go.opentelemetry.io/otel/sdk/metric v1.31.0/go.mod h1:CRInTMVvNhUKgSAMbKyTMxqOBC0zgyxzW55lZzX43Y8=
+go.opentelemetry.io/otel/trace v1.31.0 h1:ffjsj1aRouKewfr85U2aGagJ46+MvodynlQ1HYdmJys=
+go.opentelemetry.io/otel/trace v1.31.0/go.mod h1:TXZkRk7SM2ZQLtR6eoAWQFIHPvzQ06FJAsO1tJg480A=
+golang.org/x/crypto v0.37.0 h1:kJNSjF/Xp7kU0iB2Z+9viTPMW4EqqsrywMXLJOOsXSE=
+golang.org/x/crypto v0.37.0/go.mod h1:vg+k43peMZ0pUMhYmVAWysMK35e6ioLh3wB8ZCAfbVc=
golang.org/x/net v0.33.0 h1:74SYHlV8BIgHIFC/LrYkOGIwL19eTYXQ5wc6TBuO36I=
golang.org/x/net v0.33.0/go.mod h1:HXLR5J+9DxmrqMwG9qjGCxZ+zKXxBru04zlTvWlWuN4=
+golang.org/x/sync v0.13.0 h1:AauUjRAJ9OSnvULf/ARrrVywoJDy0YS2AwQ98I37610=
+golang.org/x/sync v0.13.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA=
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
-golang.org/x/sys v0.28.0 h1:Fksou7UEQUWlKvIdsqzJmUmCX3cZuD2+P3XyyzwMhlA=
-golang.org/x/sys v0.28.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
-golang.org/x/text v0.21.0 h1:zyQAAkrwaneQ066sspRyJaG9VNi/YJ1NfzcGB3hZ/qo=
-golang.org/x/text v0.21.0/go.mod h1:4IBbMaMmOPCJ8SecivzSH54+73PCFmPWxNTLm+vZkEQ=
+golang.org/x/sys v0.32.0 h1:s77OFDvIQeibCmezSnk/q6iAfkdiQaJi4VzroCFrN20=
+golang.org/x/sys v0.32.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
+golang.org/x/text v0.24.0 h1:dd5Bzh4yt5KYA8f9CJHCP4FB4D51c2c6JvN37xJJkJ0=
+golang.org/x/text v0.24.0/go.mod h1:L8rBsPeo2pSS+xqN0d5u2ikmjtmoJbDBT1b7nHvFCdU=
golang.org/x/time v0.8.0 h1:9i3RxcPv3PZnitoVGMPDKZSq1xW1gK1Xy3ArNOGZfEg=
golang.org/x/time v0.8.0/go.mod h1:3BpzKBy/shNhVucY/MWOyx10tF3SFh9QdLuxbVysPQM=
+google.golang.org/genproto/googleapis/rpc v0.0.0-20241015192408-796eee8c2d53 h1:X58yt85/IXCx0Y3ZwN6sEIKZzQtDEYaBWrDvErdXrRE=
+google.golang.org/genproto/googleapis/rpc v0.0.0-20241015192408-796eee8c2d53/go.mod h1:GX3210XPVPUjJbTUbvwI8f2IpZDMZuPJWDzDuebbviI=
+google.golang.org/grpc v1.69.4 h1:MF5TftSMkd8GLw/m0KM6V8CMOCY6NZ1NQDPGFgbTt4A=
+google.golang.org/grpc v1.69.4/go.mod h1:vyjdE6jLBI76dgpDojsFGNaHlxdjXN9ghpnd2o7JGZ4=
+google.golang.org/protobuf v1.36.3 h1:82DV7MYdb8anAVi3qge1wSnMDrnKK7ebr+I0hHRN1BU=
+google.golang.org/protobuf v1.36.3/go.mod h1:9fA7Ob0pmnwhb644+1+CVWFRbNajQ6iRojtC/QF5bRE=
+gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
+gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
diff --git a/internal/api/commands.go b/internal/api/commands.go
index 57cb7762..92a3674c 100644
--- a/internal/api/commands.go
+++ b/internal/api/commands.go
@@ -2,6 +2,7 @@ package api
import (
"net/http"
+ "time"
"github.com/labstack/echo/v4"
"github.com/opensandbox/opensandbox/pkg/types"
@@ -23,12 +24,25 @@ func (s *Server) runCommand(c echo.Context) error {
})
}
+ start := time.Now()
result, err := s.manager.Exec(c.Request().Context(), id, cfg)
+ durationMs := int(time.Since(start).Milliseconds())
+
if err != nil {
return c.JSON(http.StatusInternalServerError, map[string]string{
"error": err.Error(),
})
}
+ // Log command to per-sandbox SQLite
+ if s.sandboxDBs != nil {
+ sdb, dbErr := s.sandboxDBs.Get(id)
+ if dbErr == nil {
+ stdoutLen := len(result.Stdout)
+ stderrLen := len(result.Stderr)
+ _ = sdb.LogCommand(cfg.Command, cfg.Args, cfg.Cwd, result.ExitCode, durationMs, stdoutLen, stderrLen)
+ }
+ }
+
return c.JSON(http.StatusOK, result)
}
diff --git a/internal/api/router.go b/internal/api/router.go
index 5b782e25..417f5de8 100644
--- a/internal/api/router.go
+++ b/internal/api/router.go
@@ -6,6 +6,7 @@ import (
"github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
"github.com/opensandbox/opensandbox/internal/auth"
+ "github.com/opensandbox/opensandbox/internal/db"
"github.com/opensandbox/opensandbox/internal/sandbox"
)
@@ -15,10 +16,28 @@ type Server struct {
manager *sandbox.Manager
ptyManager *sandbox.PTYManager
templates *templateDeps
+ store *db.Store // nil in combined/dev mode without PG
+ jwtIssuer *auth.JWTIssuer // nil if JWT not configured
+ mode string // "server", "worker", "combined"
+ workerID string // this worker's ID
+ region string // this worker's region
+ httpAddr string // public HTTP address for direct access
+ sandboxDBs *sandbox.SandboxDBManager // per-sandbox SQLite manager
+}
+
+// ServerOpts holds optional dependencies for the API server.
+type ServerOpts struct {
+ Store *db.Store
+ JWTIssuer *auth.JWTIssuer
+ Mode string // "server", "worker", "combined"
+ WorkerID string
+ Region string
+ HTTPAddr string
+ SandboxDBs *sandbox.SandboxDBManager
}
// NewServer creates a new API server with all routes configured.
-func NewServer(mgr *sandbox.Manager, ptyMgr *sandbox.PTYManager, apiKey string) *Server {
+func NewServer(mgr *sandbox.Manager, ptyMgr *sandbox.PTYManager, apiKey string, opts *ServerOpts) *Server {
e := echo.New()
e.HideBanner = true
e.HidePort = true
@@ -29,6 +48,16 @@ func NewServer(mgr *sandbox.Manager, ptyMgr *sandbox.PTYManager, apiKey string)
ptyManager: ptyMgr,
}
+ if opts != nil {
+ s.store = opts.Store
+ s.jwtIssuer = opts.JWTIssuer
+ s.mode = opts.Mode
+ s.workerID = opts.WorkerID
+ s.region = opts.Region
+ s.httpAddr = opts.HTTPAddr
+ s.sandboxDBs = opts.SandboxDBs
+ }
+
// Global middleware
e.Use(middleware.Recover())
e.Use(middleware.Logger())
@@ -42,7 +71,7 @@ func NewServer(mgr *sandbox.Manager, ptyMgr *sandbox.PTYManager, apiKey string)
// API routes (with auth)
api := e.Group("")
- api.Use(auth.APIKeyMiddleware(apiKey))
+ api.Use(auth.PGAPIKeyMiddleware(s.store, apiKey))
// Sandbox lifecycle
api.POST("/sandboxes", s.createSandbox)
@@ -72,6 +101,9 @@ func NewServer(mgr *sandbox.Manager, ptyMgr *sandbox.PTYManager, apiKey string)
api.GET("/templates/:name", s.getTemplate)
api.DELETE("/templates/:name", s.deleteTemplate)
+ // Session history (requires PG)
+ api.GET("/sessions", s.listSessions)
+
return s
}
@@ -84,3 +116,8 @@ func (s *Server) Start(addr string) error {
func (s *Server) Close() error {
return s.echo.Close()
}
+
+// Echo returns the underlying echo instance for reuse (e.g., worker HTTP server).
+func (s *Server) Echo() *echo.Echo {
+ return s.echo
+}
diff --git a/internal/api/sandbox.go b/internal/api/sandbox.go
index 8a4a5399..c8e071a7 100644
--- a/internal/api/sandbox.go
+++ b/internal/api/sandbox.go
@@ -1,9 +1,12 @@
package api
import (
+ "encoding/json"
"net/http"
+ "time"
"github.com/labstack/echo/v4"
+ "github.com/opensandbox/opensandbox/internal/auth"
"github.com/opensandbox/opensandbox/pkg/types"
)
@@ -15,13 +18,75 @@ func (s *Server) createSandbox(c echo.Context) error {
})
}
- sb, err := s.manager.Create(c.Request().Context(), cfg)
+ ctx := c.Request().Context()
+
+ // Check org quota if PG is available
+ orgID, hasOrg := auth.GetOrgID(c)
+ if hasOrg && s.store != nil {
+ org, err := s.store.GetOrg(ctx, orgID)
+ if err == nil {
+ count, err := s.store.CountActiveSandboxes(ctx, orgID)
+ if err == nil && count >= org.MaxConcurrentSandboxes {
+ return c.JSON(http.StatusTooManyRequests, map[string]string{
+ "error": "concurrent sandbox limit reached",
+ })
+ }
+ }
+ }
+
+ sb, err := s.manager.Create(ctx, cfg)
if err != nil {
return c.JSON(http.StatusInternalServerError, map[string]string{
"error": err.Error(),
})
}
+ // Initialize per-sandbox SQLite if available
+ if s.sandboxDBs != nil {
+ sdb, err := s.sandboxDBs.Get(sb.ID)
+ if err == nil {
+ _ = sdb.LogEvent("created", map[string]string{
+ "sandbox_id": sb.ID,
+ "template": cfg.Template,
+ })
+ }
+ }
+
+ // Issue sandbox-scoped JWT and connectURL only in server mode (separate worker).
+ // In combined mode the SDK already talks to the right server, so no redirect needed.
+ if s.jwtIssuer != nil && s.mode == "server" {
+ timeout := cfg.Timeout
+ if timeout <= 0 {
+ timeout = 300
+ }
+ token, err := s.jwtIssuer.IssueSandboxToken(orgID, sb.ID, s.workerID, time.Duration(timeout)*time.Second)
+ if err == nil {
+ sb.Token = token
+ }
+ if s.httpAddr != "" {
+ sb.ConnectURL = s.httpAddr
+ }
+ }
+
+ // Write session record to PG if available
+ if s.store != nil && hasOrg {
+ cfgJSON, _ := json.Marshal(cfg)
+ metadataJSON, _ := json.Marshal(cfg.Metadata)
+ region := s.region
+ if region == "" {
+ region = "local"
+ }
+ workerID := s.workerID
+ if workerID == "" {
+ workerID = "w-local-1"
+ }
+ template := cfg.Template
+ if template == "" {
+ template = "base"
+ }
+ _, _ = s.store.CreateSandboxSession(ctx, sb.ID, orgID, nil, template, region, workerID, cfgJSON, metadataJSON)
+ }
+
return c.JSON(http.StatusCreated, sb)
}
@@ -35,6 +100,19 @@ func (s *Server) getSandbox(c echo.Context) error {
})
}
+ // Attach connectURL for discovery only in server mode (separate worker)
+ if s.jwtIssuer != nil && s.httpAddr != "" && s.mode == "server" {
+ sb.ConnectURL = s.httpAddr
+
+ orgID, hasOrg := auth.GetOrgID(c)
+ if hasOrg {
+ token, err := s.jwtIssuer.IssueSandboxToken(orgID, id, s.workerID, 24*time.Hour)
+ if err == nil {
+ sb.Token = token
+ }
+ }
+ }
+
return c.JSON(http.StatusOK, sb)
}
@@ -47,6 +125,16 @@ func (s *Server) killSandbox(c echo.Context) error {
})
}
+ // Update session in PG
+ if s.store != nil {
+ _ = s.store.UpdateSandboxSessionStatus(c.Request().Context(), id, "stopped", nil)
+ }
+
+ // Clean up SQLite
+ if s.sandboxDBs != nil {
+ _ = s.sandboxDBs.Remove(id)
+ }
+
return c.NoContent(http.StatusNoContent)
}
@@ -85,3 +173,29 @@ func (s *Server) setTimeout(c echo.Context) error {
return c.NoContent(http.StatusNoContent)
}
+
+// listSessions returns session history from PostgreSQL.
+func (s *Server) listSessions(c echo.Context) error {
+ if s.store == nil {
+ return c.JSON(http.StatusServiceUnavailable, map[string]string{
+ "error": "session history requires database configuration",
+ })
+ }
+
+ orgID, ok := auth.GetOrgID(c)
+ if !ok {
+ return c.JSON(http.StatusUnauthorized, map[string]string{
+ "error": "org context required",
+ })
+ }
+
+ status := c.QueryParam("status")
+ sessions, err := s.store.ListSandboxSessions(c.Request().Context(), orgID, status, 100, 0)
+ if err != nil {
+ return c.JSON(http.StatusInternalServerError, map[string]string{
+ "error": err.Error(),
+ })
+ }
+
+ return c.JSON(http.StatusOK, sessions)
+}
diff --git a/internal/auth/jwt.go b/internal/auth/jwt.go
new file mode 100644
index 00000000..99bcbed0
--- /dev/null
+++ b/internal/auth/jwt.go
@@ -0,0 +1,66 @@
+package auth
+
+import (
+ "fmt"
+ "time"
+
+ "github.com/golang-jwt/jwt/v5"
+ "github.com/google/uuid"
+)
+
+// SandboxClaims are the JWT claims for sandbox-scoped access tokens.
+type SandboxClaims struct {
+ jwt.RegisteredClaims
+ OrgID uuid.UUID `json:"org_id"`
+ SandboxID string `json:"sandbox_id"`
+ WorkerID string `json:"worker_id"`
+}
+
+// JWTIssuer creates sandbox-scoped JWTs.
+type JWTIssuer struct {
+ secret []byte
+}
+
+// NewJWTIssuer creates a new JWT issuer with the given shared secret.
+func NewJWTIssuer(secret string) *JWTIssuer {
+ return &JWTIssuer{secret: []byte(secret)}
+}
+
+// IssueSandboxToken creates a JWT for direct worker access.
+func (j *JWTIssuer) IssueSandboxToken(orgID uuid.UUID, sandboxID, workerID string, ttl time.Duration) (string, error) {
+ now := time.Now()
+ claims := SandboxClaims{
+ RegisteredClaims: jwt.RegisteredClaims{
+ Subject: orgID.String(),
+ IssuedAt: jwt.NewNumericDate(now),
+ ExpiresAt: jwt.NewNumericDate(now.Add(ttl)),
+ Issuer: "opensandbox",
+ },
+ OrgID: orgID,
+ SandboxID: sandboxID,
+ WorkerID: workerID,
+ }
+
+ token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
+ return token.SignedString(j.secret)
+}
+
+// ValidateSandboxToken parses and validates a sandbox-scoped JWT.
+func (j *JWTIssuer) ValidateSandboxToken(tokenStr string) (*SandboxClaims, error) {
+ token, err := jwt.ParseWithClaims(tokenStr, &SandboxClaims{}, func(t *jwt.Token) (interface{}, error) {
+ if _, ok := t.Method.(*jwt.SigningMethodHMAC); !ok {
+ return nil, fmt.Errorf("unexpected signing method: %v", t.Header["alg"])
+ }
+ return j.secret, nil
+ })
+ if err != nil {
+ return nil, fmt.Errorf("invalid token: %w", err)
+ }
+
+ claims, ok := token.Claims.(*SandboxClaims)
+ if !ok || !token.Valid {
+ return nil, fmt.Errorf("invalid token claims")
+ }
+
+ return claims, nil
+}
diff --git a/internal/auth/middleware.go b/internal/auth/middleware.go
new file mode 100644
index 00000000..63b4885c
--- /dev/null
+++ b/internal/auth/middleware.go
@@ -0,0 +1,114 @@
+package auth
+
+import (
+ "net/http"
+ "strings"
+
+ "github.com/google/uuid"
+ "github.com/labstack/echo/v4"
+ "github.com/opensandbox/opensandbox/internal/db"
+)
+
+type contextKey string
+
+const (
+ // ContextKeyOrgID is the echo context key for the authenticated org ID.
+ ContextKeyOrgID contextKey = "org_id"
+)
+
+// SetOrgID stores the org ID in the echo context.
+func SetOrgID(c echo.Context, orgID uuid.UUID) {
+ c.Set(string(ContextKeyOrgID), orgID)
+}
+
+// GetOrgID retrieves the org ID from the echo context.
+func GetOrgID(c echo.Context) (uuid.UUID, bool) {
+ v := c.Get(string(ContextKeyOrgID))
+ if v == nil {
+ return uuid.Nil, false
+ }
+ id, ok := v.(uuid.UUID)
+ return id, ok
+}
+
+// PGAPIKeyMiddleware validates API keys against PostgreSQL.
+// Falls back to static API key comparison if store is nil (combined/dev mode).
+func PGAPIKeyMiddleware(store *db.Store, staticKey string) echo.MiddlewareFunc {
+ return func(next echo.HandlerFunc) echo.HandlerFunc {
+ return func(c echo.Context) error {
+ // Try static API key first (backward compat for combined mode)
+ if staticKey != "" && store == nil {
+ return APIKeyMiddleware(staticKey)(next)(c)
+ }
+
+ // Get API key from header or query
+ key := c.Request().Header.Get("X-API-Key")
+ if key == "" {
+ key = c.QueryParam("api_key")
+ }
+
+ // If no key and no store, pass through (dev mode)
+ if key == "" && store == nil && staticKey == "" {
+ return next(c)
+ }
+
+ if key == "" {
+ return c.JSON(http.StatusUnauthorized, map[string]string{
+ "error": "missing API key",
+ })
+ }
+
+ // Validate against PG if store is available
+ if store != nil {
+ orgID, err := store.ValidateAPIKey(c.Request().Context(), key)
+ if err != nil {
+ return c.JSON(http.StatusForbidden, map[string]string{
+ "error": "invalid API key",
+ })
+ }
+ SetOrgID(c, orgID)
+ return next(c)
+ }
+
+ // Fall back to static key comparison
+ return APIKeyMiddleware(staticKey)(next)(c)
+ }
+ }
+}
+
+// SandboxJWTMiddleware validates sandbox-scoped JWTs for direct worker access.
+// It verifies the token and checks that the sandbox_id in the token matches the :id URL param.
+func SandboxJWTMiddleware(jwtIssuer *JWTIssuer) echo.MiddlewareFunc {
+ return func(next echo.HandlerFunc) echo.HandlerFunc {
+ return func(c echo.Context) error {
+ authHeader := c.Request().Header.Get("Authorization")
+ if authHeader == "" || !strings.HasPrefix(authHeader, "Bearer ") {
+ return c.JSON(http.StatusUnauthorized, map[string]string{
+ "error": "missing or invalid Authorization header",
+ })
+ }
+
+ tokenStr := strings.TrimPrefix(authHeader, "Bearer ")
+ claims, err := jwtIssuer.ValidateSandboxToken(tokenStr)
+ if err != nil {
+ return c.JSON(http.StatusForbidden, map[string]string{
+ "error": "invalid token: " + err.Error(),
+ })
+ }
+
+ // Verify sandbox ID matches URL parameter
+ urlSandboxID := c.Param("id")
+ if urlSandboxID != "" && claims.SandboxID != urlSandboxID {
+ return c.JSON(http.StatusForbidden, map[string]string{
+ "error": "token not valid for this sandbox",
+ })
+ }
+
+ SetOrgID(c, claims.OrgID)
+ c.Set("sandbox_id", claims.SandboxID)
+ c.Set("worker_id", claims.WorkerID)
+
+ return next(c)
+ }
+ }
+}
diff --git a/internal/auth/workos.go b/internal/auth/workos.go
new file mode 100644
index 00000000..6e338c01
--- /dev/null
+++ b/internal/auth/workos.go
@@ -0,0 +1,160 @@
+package auth
+
+import (
+ "context"
+ "crypto/rand"
+ "encoding/hex"
+ "fmt"
+ "log"
+ "net/http"
+ "strings"
+
+ "github.com/google/uuid"
+ "github.com/labstack/echo/v4"
+ "github.com/opensandbox/opensandbox/internal/db"
+)
+
+// WorkOSConfig holds WorkOS integration settings.
+type WorkOSConfig struct {
+ APIKey string
+ ClientID string
+}
+
+// WorkOSMiddleware validates WorkOS session tokens for dashboard access.
+// It checks for a session cookie or Authorization header, validates with WorkOS,
+// and provisions orgs/users in the local database on first login.
+type WorkOSMiddleware struct {
+ config WorkOSConfig
+ store *db.Store
+}
+
+// NewWorkOSMiddleware creates WorkOS session middleware.
+func NewWorkOSMiddleware(config WorkOSConfig, store *db.Store) *WorkOSMiddleware {
+ return &WorkOSMiddleware{config: config, store: store}
+}
+
+// Middleware returns the Echo middleware function.
+func (w *WorkOSMiddleware) Middleware() echo.MiddlewareFunc {
+ return func(next echo.HandlerFunc) echo.HandlerFunc {
+ return func(c echo.Context) error {
+ // Skip if WorkOS is not configured
+ if w.config.APIKey == "" {
+ return next(c)
+ }
+
+ // Extract session token from cookie or header
+ sessionToken := ""
+ if cookie, err := c.Cookie("workos_session"); err == nil {
+ sessionToken = cookie.Value
+ }
+ if sessionToken == "" {
+ auth := c.Request().Header.Get("Authorization")
+ if strings.HasPrefix(auth, "Bearer wos_") {
+ sessionToken = strings.TrimPrefix(auth, "Bearer ")
+ }
+ }
+
+ if sessionToken == "" {
+ return c.JSON(http.StatusUnauthorized, map[string]string{
+ "error": "authentication required",
+ })
+ }
+
+ // Validate session with WorkOS
+ user, err := w.validateSession(c.Request().Context(), sessionToken)
+ if err != nil {
+ return c.JSON(http.StatusUnauthorized, map[string]string{
+ "error": "invalid session: " + err.Error(),
+ })
+ }
+
+ // Set org context
+ SetOrgID(c, user.OrgID)
+ c.Set("user_id", user.ID)
+ c.Set("user_email", user.Email)
+
+ return next(c)
+ }
+ }
+}
+
+// WorkOSUser represents a validated WorkOS user.
+type WorkOSUser struct {
+ ID uuid.UUID
+ OrgID uuid.UUID
+ Email string
+ Name string
+}
+
+// validateSession validates a WorkOS session token.
+// In production, this calls the WorkOS API. For now, it's a placeholder.
+func (w *WorkOSMiddleware) validateSession(ctx context.Context, token string) (*WorkOSUser, error) {
+ // TODO: Implement actual WorkOS API call:
+ // POST https://api.workos.com/user_management/sessions/authenticate
+ // with { session_token: token, client_id: w.config.ClientID }
+ // This returns user info including email, org membership, etc.
+ _ = token
+ return nil, fmt.Errorf("WorkOS session validation not yet implemented")
+}
+
+// ProvisionOrgAndUser creates or fetches an org and user based on WorkOS data.
+// Called on first login to auto-provision local records.
+func (w *WorkOSMiddleware) ProvisionOrgAndUser(ctx context.Context, email, name, orgName string) (*WorkOSUser, error) {
+ if w.store == nil {
+ return nil, fmt.Errorf("database not configured")
+ }
+
+ // Check if user exists
+ existingUser, err := w.store.GetUserByEmail(ctx, email)
+ if err == nil {
+ return &WorkOSUser{
+ ID: existingUser.ID,
+ OrgID: existingUser.OrgID,
+ Email: existingUser.Email,
+ Name: existingUser.Name,
+ }, nil
+ }
+
+ // Create org (slug from org name)
+ slug := strings.ToLower(strings.ReplaceAll(orgName, " ", "-"))
+ org, err := w.store.GetOrgBySlug(ctx, slug)
+ if err != nil {
+ org, err = w.store.CreateOrg(ctx, orgName, slug)
+ if err != nil {
+ return nil, fmt.Errorf("failed to create org: %w", err)
+ }
+ log.Printf("workos: provisioned new org: %s (%s)", org.Name, org.ID)
+
+ // Generate a default API key for the new org
+ apiKey, err := GenerateAPIKey()
+ if err == nil {
+ hash := db.HashAPIKey(apiKey)
+ prefix := apiKey[:8]
+ _, _ = w.store.CreateAPIKey(ctx, org.ID, nil, hash, prefix, "Default", []string{"sandbox:*"})
+ log.Printf("workos: created default API key for org %s: %s...", org.Slug, prefix)
+ }
+ }
+
+ // Create user
+ user, err := w.store.CreateUser(ctx, org.ID, email, name, "admin")
+ if err != nil {
+ return nil, fmt.Errorf("failed to create user: %w", err)
+ }
+ log.Printf("workos: provisioned new user: %s (%s)", user.Email, user.ID)
+
+ return &WorkOSUser{
+ ID: user.ID,
+ OrgID: user.OrgID,
+ Email: user.Email,
+ Name: user.Name,
+ }, nil
+}
+
+// GenerateAPIKey generates a new plaintext API key with the osb_ prefix.
+func GenerateAPIKey() (string, error) {
+ bytes := make([]byte, 32)
+ if _, err := rand.Read(bytes); err != nil {
+ return "", err
+ }
+ return "osb_" + hex.EncodeToString(bytes), nil
+}
diff --git a/internal/compute/fly.go b/internal/compute/fly.go
index b36a622b..5c2cfcd0 100644
--- a/internal/compute/fly.go
+++ b/internal/compute/fly.go
@@ -160,6 +160,15 @@ func (p *FlyPool) HealthCheck(ctx context.Context, machineID string) error {
return nil
}
+func (p *FlyPool) SupportedRegions(_ context.Context) ([]string, error) {
+ return []string{"iad", "ams", "lhr", "sjc", "nrt", "syd", "cdg", "fra"}, nil
+}
+
+func (p *FlyPool) DrainMachine(ctx context.Context, machineID string) error {
+ // Stop the machine gracefully (Fly will drain connections)
+ return p.StopMachine(ctx, machineID)
+}
+
func (p *FlyPool) machineAction(ctx context.Context, machineID, method, action string) error {
url := fmt.Sprintf("%s/apps/%s/machines/%s%s", flyAPIBase, p.appName, machineID, action)
req, err := http.NewRequestWithContext(ctx, method, url, nil)
diff --git a/internal/compute/local.go b/internal/compute/local.go
index 3a1cb9e6..c227256c 100644
--- a/internal/compute/local.go
+++ b/internal/compute/local.go
@@ -51,3 +51,11 @@ func (p *LocalPool) ListMachines(_ context.Context) ([]*Machine, error) {
func (p *LocalPool) HealthCheck(_ context.Context, _ string) error {
return nil // Local machine is always healthy
}
+
+func (p *LocalPool) SupportedRegions(_ context.Context) ([]string, error) {
+ return []string{"local"}, nil
+}
+
+func (p *LocalPool) DrainMachine(_ context.Context, _ string) error {
+ return fmt.Errorf("cannot drain local machine")
+}
diff --git a/internal/compute/pool.go b/internal/compute/pool.go
index eaed0186..944d49af 100644
--- a/internal/compute/pool.go
+++ b/internal/compute/pool.go
@@ -5,7 +5,8 @@ import "context"
// Machine represents a worker machine in the compute pool.
type Machine struct {
ID string `json:"id"`
- Addr string `json:"addr"` // internal address (host:port)
+ Addr string `json:"addr"` // internal address (host:port) for gRPC
+ HTTPAddr string `json:"httpAddr"` // public HTTP address for direct SDK access
Region string `json:"region"`
Status string `json:"status"` // "running", "stopped", "creating"
Capacity int `json:"capacity"` // max sandboxes
@@ -27,4 +28,6 @@ type Pool interface {
StopMachine(ctx context.Context, machineID string) error
ListMachines(ctx context.Context) ([]*Machine, error)
HealthCheck(ctx context.Context, machineID string) error
+ SupportedRegions(ctx context.Context) ([]string, error)
+ DrainMachine(ctx context.Context, machineID string) error
}
diff --git a/internal/compute/router.go b/internal/compute/router.go
index 44c58b2b..637166f2 100644
--- a/internal/compute/router.go
+++ b/internal/compute/router.go
@@ -52,6 +52,39 @@ func (r *Router) Assign(ctx context.Context, sandboxID string) (*Machine, error)
return best, nil
}
+// AssignInRegion picks the least-loaded machine in a specific region.
+func (r *Router) AssignInRegion(ctx context.Context, sandboxID, region string) (*Machine, error) {
+ machines, err := r.pool.ListMachines(ctx)
+ if err != nil {
+ return nil, fmt.Errorf("failed to list machines: %w", err)
+ }
+
+ var best *Machine
+ for _, m := range machines {
+ if m.Status != "running" {
+ continue
+ }
+ if region != "" && m.Region != region {
+ continue
+ }
+ remaining := m.Capacity - m.Current
+ if best == nil || remaining > (best.Capacity-best.Current) {
+ best = m
+ }
+ }
+
+ if best == nil {
+ return nil, fmt.Errorf("no available machines in region %s", region)
+ }
+
+ r.mu.Lock()
+ r.mapping[sandboxID] = best.ID
+ best.Current++
+ r.mu.Unlock()
+
+ return best, nil
+}
+
// Lookup returns the machine that hosts a given sandbox.
func (r *Router) Lookup(sandboxID string) (string, error) {
r.mu.RLock()
diff --git a/internal/config/config.go b/internal/config/config.go
index 0c4095d2..974ad413 100644
--- a/internal/config/config.go
+++ b/internal/config/config.go
@@ -13,6 +13,25 @@ type Config struct {
WorkerAddr string
Mode string // "server", "worker", "combined"
LogLevel string
+
+ // Database
+ DatabaseURL string // PostgreSQL connection string
+ DataDir string // Local data directory for SQLite files
+
+ // Auth
+ JWTSecret string // Shared secret for sandbox-scoped JWTs
+
+ // NATS
+ NATSURL string // NATS server URL
+
+ // Worker identity
+ Region string // Region identifier (e.g., "iad", "ams")
+ WorkerID string // Unique worker ID (e.g., "w-iad-1")
+ HTTPAddr string // Public HTTP address for direct SDK access
+
+ // WorkOS
+ WorkOSAPIKey string
+ WorkOSClientID string
}
// Load reads configuration from environment variables with sensible defaults.
@@ -23,6 +42,17 @@ func Load() (*Config, error) {
WorkerAddr: envOrDefault("OPENSANDBOX_WORKER_ADDR", "localhost:9090"),
Mode: envOrDefault("OPENSANDBOX_MODE", "combined"),
LogLevel: envOrDefault("OPENSANDBOX_LOG_LEVEL", "info"),
+
+ DatabaseURL: os.Getenv("OPENSANDBOX_DATABASE_URL"),
+ DataDir: envOrDefault("OPENSANDBOX_DATA_DIR", "/data/sandboxes"),
+ JWTSecret: os.Getenv("OPENSANDBOX_JWT_SECRET"),
+ NATSURL: envOrDefault("OPENSANDBOX_NATS_URL", "nats://localhost:4222"),
+ Region: envOrDefault("OPENSANDBOX_REGION", "local"),
+ WorkerID: envOrDefault("OPENSANDBOX_WORKER_ID", "w-local-1"),
+ HTTPAddr: envOrDefault("OPENSANDBOX_HTTP_ADDR", "http://localhost:8080"),
+
+ WorkOSAPIKey: os.Getenv("WORKOS_API_KEY"),
+ WorkOSClientID: os.Getenv("WORKOS_CLIENT_ID"),
}
if portStr := os.Getenv("OPENSANDBOX_PORT"); portStr != "" {
diff --git a/internal/controlplane/scaler.go b/internal/controlplane/scaler.go
new file mode 100644
index 00000000..1f80d17e
--- /dev/null
+++ b/internal/controlplane/scaler.go
@@ -0,0 +1,125 @@
+package controlplane
+
+import (
+ "context"
+ "log"
+ "sync"
+ "time"
+
+ "github.com/opensandbox/opensandbox/internal/compute"
+)
+
+const (
+ scaleUpThreshold = 0.70 // Scale up when utilization > 70%
+ scaleDownThreshold = 0.30 // Scale down when utilization < 30%
+ minWorkersPerRegion = 1
+ scaleCheckInterval = 10 * time.Second
+)
+
+// Scaler manages autoscaling of workers via the compute Pool.
+type Scaler struct {
+ pool compute.Pool
+ registry *WorkerRegistry
+ image string // worker Docker image
+ stop chan struct{}
+ wg sync.WaitGroup
+}
+
+// NewScaler creates a new autoscaling controller.
+func NewScaler(pool compute.Pool, registry *WorkerRegistry, workerImage string) *Scaler {
+ return &Scaler{
+ pool: pool,
+ registry: registry,
+ image: workerImage,
+ stop: make(chan struct{}),
+ }
+}
+
+// Start begins the autoscaling loop.
+func (s *Scaler) Start() {
+ s.wg.Add(1)
+ go func() {
+ defer s.wg.Done()
+ ticker := time.NewTicker(scaleCheckInterval)
+ defer ticker.Stop()
+
+ for {
+ select {
+ case <-ticker.C:
+ s.evaluate()
+ case <-s.stop:
+ return
+ }
+ }
+ }()
+ log.Println("scaler: autoscaling controller started")
+}
+
+// Stop stops the autoscaling loop.
+func (s *Scaler) Stop() {
+ close(s.stop)
+ s.wg.Wait()
+}
+
+func (s *Scaler) evaluate() {
+ ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
+ defer cancel()
+
+ regions := s.registry.Regions()
+ for _, region := range regions {
+ s.evaluateRegion(ctx, region)
+ }
+}
+
+func (s *Scaler) evaluateRegion(ctx context.Context, region string) {
+ workers := s.registry.GetWorkersByRegion(region)
+ utilization := s.registry.RegionUtilization(region)
+
+ if utilization > scaleUpThreshold {
+ log.Printf("scaler: region %s utilization %.1f%% > %.0f%%, scaling up", region, utilization*100, scaleUpThreshold*100)
+ s.scaleUp(ctx, region)
+ } else if utilization < scaleDownThreshold && len(workers) > minWorkersPerRegion {
+ log.Printf("scaler: region %s utilization %.1f%% < %.0f%%, scaling down", region, utilization*100, scaleDownThreshold*100)
+ s.scaleDown(ctx, region, workers)
+ }
+}
+
+func (s *Scaler) scaleUp(ctx context.Context, region string) {
+ opts := compute.MachineOpts{
+ Region: region,
+ Image: s.image,
+ }
+
+ machine, err := s.pool.CreateMachine(ctx, opts)
+ if err != nil {
+ log.Printf("scaler: failed to create machine in %s: %v", region, err)
+ return
+ }
+
+ log.Printf("scaler: created machine %s in %s (addr=%s)", machine.ID, region, machine.Addr)
+}
+
+func (s *Scaler) scaleDown(ctx context.Context, region string, workers []*WorkerInfo) {
+ // Find the least-loaded worker to drain
+ var target *WorkerInfo
+ for _, w := range workers {
+ if target == nil || w.Current < target.Current {
+ target = w
+ }
+ }
+
+ if target == nil {
+ return
+ }
+
+ log.Printf("scaler: draining worker %s in %s (current=%d)", target.ID, region, target.Current)
+
+ if err := s.pool.DrainMachine(ctx, target.ID); err != nil {
+ log.Printf("scaler: failed to drain machine %s: %v", target.ID, err)
+ return
+ }
+
+ if err := s.pool.DestroyMachine(ctx, target.ID); err != nil {
+ log.Printf("scaler: failed to destroy machine %s: %v", target.ID, err)
+ }
+}
diff --git a/internal/controlplane/server.go b/internal/controlplane/server.go
new file mode 100644
index 00000000..5294d9eb
--- /dev/null
+++ b/internal/controlplane/server.go
@@ -0,0 +1,273 @@
+package controlplane
+
+import (
+ "context"
+ "encoding/json"
+ "log"
+ "net/http"
+ "time"
+
+ "github.com/labstack/echo/v4"
+ "github.com/labstack/echo/v4/middleware"
+ "google.golang.org/grpc"
+ "google.golang.org/grpc/credentials/insecure"
+
+ "github.com/opensandbox/opensandbox/internal/auth"
+ "github.com/opensandbox/opensandbox/internal/db"
+ pb "github.com/opensandbox/opensandbox/proto/worker"
+)
+
+// Server is the control plane API server.
+type Server struct {
+ echo *echo.Echo
+ store *db.Store
+ jwtIssuer *auth.JWTIssuer
+ registry *WorkerRegistry
+}
+
+// NewServer creates a new control plane server.
+func NewServer(store *db.Store, jwtIssuer *auth.JWTIssuer, registry *WorkerRegistry, apiKey string) *Server {
+ e := echo.New()
+ e.HideBanner = true
+ e.HidePort = true
+
+ s := &Server{
+ echo: e,
+ store: store,
+ jwtIssuer: jwtIssuer,
+ registry: registry,
+ }
+
+ // Global middleware
+ e.Use(middleware.Recover())
+ e.Use(middleware.Logger())
+ e.Use(middleware.CORS())
+ e.Use(middleware.RequestID())
+
+ // Health check
+ e.GET("/health", func(c echo.Context) error {
+ return c.JSON(http.StatusOK, map[string]string{"status": "ok", "role": "controlplane"})
+ })
+
+ // Auth middleware
+ api := e.Group("")
+ api.Use(auth.PGAPIKeyMiddleware(store, apiKey))
+
+ // Sandbox lifecycle (control plane only handles create/destroy/discover)
+ api.POST("/sandboxes", s.createSandbox)
+ api.GET("/sandboxes/:id", s.discoverSandbox)
+ api.DELETE("/sandboxes/:id", s.destroySandbox)
+
+ // Session history (global queries from PG)
+ api.GET("/sessions", s.listSessions)
+
+ // Workers
+ api.GET("/workers", s.listWorkers)
+
+ return s
+}
+
+// Start starts the HTTP server.
+func (s *Server) Start(addr string) error {
+ return s.echo.Start(addr)
+}
+
+// Close shuts down the server.
+func (s *Server) Close() error {
+ return s.echo.Close()
+}
+
+func (s *Server) createSandbox(c echo.Context) error {
+ var req struct {
+ TemplateID string `json:"templateID"`
+ Timeout int `json:"timeout"`
+ Region string `json:"region"`
+ Envs map[string]string `json:"envs"`
+ MemoryMB int `json:"memoryMB"`
+ CpuCount int `json:"cpuCount"`
+ Metadata map[string]string `json:"metadata"`
+ NetworkEnabled bool `json:"networkEnabled"`
+ }
+ if err := c.Bind(&req); err != nil {
+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "invalid request: " + err.Error()})
+ }
+
+ orgID, ok := auth.GetOrgID(c)
+ if !ok {
+ return c.JSON(http.StatusUnauthorized, map[string]string{"error": "auth required"})
+ }
+
+ // Check org quota
+ org, err := s.store.GetOrg(c.Request().Context(), orgID)
+ if err != nil {
+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": "org not found"})
+ }
+ count, err := s.store.CountActiveSandboxes(c.Request().Context(), orgID)
+ if err == nil && count >= org.MaxConcurrentSandboxes {
+ return c.JSON(http.StatusTooManyRequests, map[string]string{"error": "concurrent sandbox limit reached"})
+ }
+
+ // Select region (explicit, or from Fly-Region header, or default)
+ region := req.Region
+ if region == "" {
+ region = c.Request().Header.Get("Fly-Region")
+ }
+ if region == "" {
+ region = "iad" // default
+ }
+
+ // Select least-loaded worker in region
+ worker := s.registry.GetLeastLoadedWorker(region)
+ if worker == nil {
+ return c.JSON(http.StatusServiceUnavailable, map[string]string{"error": "no workers available in region " + region})
+ }
+
+ // Call gRPC CreateSandbox on the worker
+ ctx, cancel := context.WithTimeout(c.Request().Context(), 10*time.Second)
+ defer cancel()
+
+ conn, err := grpc.NewClient(worker.GRPCAddr, grpc.WithTransportCredentials(insecure.NewCredentials()))
+ if err != nil {
+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": "failed to connect to worker"})
+ }
+ defer conn.Close()
+
+ client := pb.NewSandboxWorkerClient(conn)
+ grpcResp, err := client.CreateSandbox(ctx, &pb.CreateSandboxRequest{
+ Template: req.TemplateID,
+ Timeout: int32(req.Timeout),
+ Envs: req.Envs,
+ MemoryMb: int32(req.MemoryMB),
+ CpuCount: int32(req.CpuCount),
+ NetworkEnabled: req.NetworkEnabled,
+ })
+ if err != nil {
+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": "worker create failed: " + err.Error()})
+ }
+
+ // Insert session record into PG
+ template := req.TemplateID
+ if template == "" {
+ template = "base"
+ }
+ cfgJSON, _ := json.Marshal(req)
+ metadataJSON, _ := json.Marshal(req.Metadata)
+ _, _ = s.store.CreateSandboxSession(ctx, grpcResp.SandboxId, orgID, nil, template, region, worker.ID, cfgJSON, metadataJSON)
+
+ // Issue sandbox-scoped JWT
+ timeout := req.Timeout
+ if timeout <= 0 {
+ timeout = 300
+ }
+ token, err := s.jwtIssuer.IssueSandboxToken(orgID, grpcResp.SandboxId, worker.ID, time.Duration(timeout)*time.Second)
+ if err != nil {
+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": "failed to issue token"})
+ }
+
+ return c.JSON(http.StatusCreated, map[string]interface{}{
+ "sandboxID": grpcResp.SandboxId,
+ "connectURL": worker.HTTPAddr,
+ "token": token,
+ "status": grpcResp.Status,
+ "region": region,
+ "workerID": worker.ID,
+ })
+}
+
+func (s *Server) discoverSandbox(c echo.Context) error {
+ sandboxID := c.Param("id")
+
+ session, err := s.store.GetSandboxSession(c.Request().Context(), sandboxID)
+ if err != nil {
+ return c.JSON(http.StatusNotFound, map[string]string{"error": "sandbox not found"})
+ }
+
+ // Look up worker address
+ worker := s.registry.GetWorker(session.WorkerID)
+ connectURL := ""
+ if worker != nil {
+ connectURL = worker.HTTPAddr
+ }
+
+ orgID, _ := auth.GetOrgID(c)
+
+ // Issue a new token for reconnection
+ token := ""
+ if s.jwtIssuer != nil {
+ t, err := s.jwtIssuer.IssueSandboxToken(orgID, sandboxID, session.WorkerID, 24*time.Hour)
+ if err == nil {
+ token = t
+ }
+ }
+
+ return c.JSON(http.StatusOK, map[string]interface{}{
+ "sandboxID": sandboxID,
+ "connectURL": connectURL,
+ "token": token,
+ "status": session.Status,
+ "region": session.Region,
+ "workerID": session.WorkerID,
+ "startedAt": session.StartedAt,
+ "template": session.Template,
+ })
+}
+
+func (s *Server) destroySandbox(c echo.Context) error {
+ sandboxID := c.Param("id")
+
+ session, err := s.store.GetSandboxSession(c.Request().Context(), sandboxID)
+ if err != nil {
+ return c.JSON(http.StatusNotFound, map[string]string{"error": "sandbox not found"})
+ }
+
+ // Get worker gRPC address
+ worker := s.registry.GetWorker(session.WorkerID)
+ if worker == nil {
+ // Worker is down, just mark as error
+ _ = s.store.UpdateSandboxSessionStatus(c.Request().Context(), sandboxID, "error", strPtr("worker unreachable"))
+ return c.NoContent(http.StatusNoContent)
+ }
+
+ // Call gRPC DestroySandbox
+ ctx, cancel := context.WithTimeout(c.Request().Context(), 10*time.Second)
+ defer cancel()
+
+ conn, err := grpc.NewClient(worker.GRPCAddr, grpc.WithTransportCredentials(insecure.NewCredentials()))
+ if err != nil {
+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": "failed to connect to worker"})
+ }
+ defer conn.Close()
+
+ client := pb.NewSandboxWorkerClient(conn)
+ if _, err := client.DestroySandbox(ctx, &pb.DestroySandboxRequest{SandboxId: sandboxID}); err != nil {
+ log.Printf("controlplane: gRPC destroy failed: %v", err)
+ }
+
+ _ = s.store.UpdateSandboxSessionStatus(c.Request().Context(), sandboxID, "stopped", nil)
+
+ return c.NoContent(http.StatusNoContent)
+}
+
+func (s *Server) listSessions(c echo.Context) error {
+ orgID, ok := auth.GetOrgID(c)
+ if !ok {
+ return c.JSON(http.StatusUnauthorized, map[string]string{"error": "auth required"})
+ }
+
+ status := c.QueryParam("status")
+ sessions, err := s.store.ListSandboxSessions(c.Request().Context(), orgID, status, 100, 0)
+ if err != nil {
+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})
+ }
+
+ return c.JSON(http.StatusOK, sessions)
+}
+
+func (s *Server) listWorkers(c echo.Context) error {
+ workers := s.registry.GetAllWorkers()
+ return c.JSON(http.StatusOK, workers)
+}
+
+func strPtr(s string) *string {
+ return &s
+}
diff --git a/internal/controlplane/worker_registry.go b/internal/controlplane/worker_registry.go
new file mode 100644
index 00000000..6330214b
--- /dev/null
+++ b/internal/controlplane/worker_registry.go
@@ -0,0 +1,226 @@
+package controlplane
+
+import (
+ "encoding/json"
+ "log"
+ "sync"
+ "time"
+
+ "github.com/nats-io/nats.go"
+)
+
+// WorkerInfo represents a registered worker.
+type WorkerInfo struct {
+ ID string `json:"worker_id"`
+ Region string `json:"region"`
+ GRPCAddr string `json:"grpc_addr"`
+ HTTPAddr string `json:"http_addr"`
+ Capacity int `json:"capacity"`
+ Current int `json:"current"`
+ CPUPct float64 `json:"cpu_pct"`
+ MemPct float64 `json:"mem_pct"`
+ LastSeen time.Time `json:"-"`
+ MissedBeats int `json:"-"`
+}
+
+// WorkerRegistry tracks live workers from NATS heartbeats.
+type WorkerRegistry struct {
+ mu sync.RWMutex
+ workers map[string]*WorkerInfo // worker ID -> info
+ nc *nats.Conn
+ sub *nats.Subscription
+ stop chan struct{}
+
+ onWorkerDown func(workerID string) // callback when worker is marked down
+}
+
+// NewWorkerRegistry creates a worker registry that subscribes to NATS heartbeats.
+func NewWorkerRegistry(natsURL string) (*WorkerRegistry, error) {
+ nc, err := nats.Connect(natsURL,
+ nats.RetryOnFailedConnect(true),
+ nats.MaxReconnects(-1),
+ nats.ReconnectWait(2*time.Second),
+ )
+ if err != nil {
+ return nil, err
+ }
+
+ return &WorkerRegistry{
+ workers: make(map[string]*WorkerInfo),
+ nc: nc,
+ stop: make(chan struct{}),
+ }, nil
+}
+
+// OnWorkerDown sets a callback for when a worker is detected as down.
+func (r *WorkerRegistry) OnWorkerDown(fn func(workerID string)) {
+ r.onWorkerDown = fn
+}
+
+// Start begins listening for heartbeats and checking for stale workers.
+func (r *WorkerRegistry) Start() error {
+ sub, err := r.nc.Subscribe("workers.heartbeat.>", r.handleHeartbeat)
+ if err != nil {
+ return err
+ }
+ r.sub = sub
+
+ // Stale worker checker
+ go func() {
+ ticker := time.NewTicker(10 * time.Second)
+ defer ticker.Stop()
+ for {
+ select {
+ case <-ticker.C:
+ r.checkStaleWorkers()
+ case <-r.stop:
+ return
+ }
+ }
+ }()
+
+ log.Println("worker_registry: listening for heartbeats")
+ return nil
+}
+
+// Stop stops the registry.
+func (r *WorkerRegistry) Stop() {
+ close(r.stop)
+ if r.sub != nil {
+ r.sub.Unsubscribe()
+ }
+ r.nc.Close()
+}
+
+// GetWorkersByRegion returns healthy workers in a region, sorted by available capacity.
+func (r *WorkerRegistry) GetWorkersByRegion(region string) []*WorkerInfo {
+ r.mu.RLock()
+ defer r.mu.RUnlock()
+
+ var result []*WorkerInfo
+ for _, w := range r.workers {
+ if w.Region == region && w.MissedBeats < 3 {
+ result = append(result, w)
+ }
+ }
+ return result
+}
+
+// GetLeastLoadedWorker returns the worker with the most remaining capacity in a region.
+func (r *WorkerRegistry) GetLeastLoadedWorker(region string) *WorkerInfo {
+ workers := r.GetWorkersByRegion(region)
+ if len(workers) == 0 {
+ return nil
+ }
+
+ var best *WorkerInfo
+ for _, w := range workers {
+ remaining := w.Capacity - w.Current
+ if best == nil || remaining > (best.Capacity-best.Current) {
+ best = w
+ }
+ }
+ return best
+}
+
+// GetAllWorkers returns all known workers.
+func (r *WorkerRegistry) GetAllWorkers() []*WorkerInfo {
+ r.mu.RLock()
+ defer r.mu.RUnlock()
+
+ result := make([]*WorkerInfo, 0, len(r.workers))
+ for _, w := range r.workers {
+ result = append(result, w)
+ }
+ return result
+}
+
+// GetWorker returns info for a specific worker.
+func (r *WorkerRegistry) GetWorker(workerID string) *WorkerInfo {
+ r.mu.RLock()
+ defer r.mu.RUnlock()
+ return r.workers[workerID]
+}
+
+// RegionUtilization returns the average utilization for a region.
+func (r *WorkerRegistry) RegionUtilization(region string) float64 {
+ workers := r.GetWorkersByRegion(region)
+ if len(workers) == 0 {
+ return 0
+ }
+
+ var totalCap, totalCur int
+ for _, w := range workers {
+ totalCap += w.Capacity
+ totalCur += w.Current
+ }
+ if totalCap == 0 {
+ return 0
+ }
+ return float64(totalCur) / float64(totalCap)
+}
+
+// Regions returns all known regions.
+func (r *WorkerRegistry) Regions() []string {
+ r.mu.RLock()
+ defer r.mu.RUnlock()
+
+ regionSet := make(map[string]struct{})
+ for _, w := range r.workers {
+ regionSet[w.Region] = struct{}{}
+ }
+
+ regions := make([]string, 0, len(regionSet))
+ for region := range regionSet {
+ regions = append(regions, region)
+ }
+ return regions
+}
+
+func (r *WorkerRegistry) handleHeartbeat(msg *nats.Msg) {
+ var hb WorkerInfo
+ if err := json.Unmarshal(msg.Data, &hb); err != nil {
+ return
+ }
+
+ r.mu.Lock()
+ defer r.mu.Unlock()
+
+ existing, ok := r.workers[hb.ID]
+ if ok {
+ existing.Current = hb.Current
+ existing.Capacity = hb.Capacity
+ existing.CPUPct = hb.CPUPct
+ existing.MemPct = hb.MemPct
+ existing.LastSeen = time.Now()
+ existing.MissedBeats = 0
+ if hb.GRPCAddr != "" {
+ existing.GRPCAddr = hb.GRPCAddr
+ }
+ if hb.HTTPAddr != "" {
+ existing.HTTPAddr = hb.HTTPAddr
+ }
+ } else {
+ hb.LastSeen = time.Now()
+ r.workers[hb.ID] = &hb
+ log.Printf("worker_registry: new worker registered: %s (region=%s)", hb.ID, hb.Region)
+ }
+}
+
+func (r *WorkerRegistry) checkStaleWorkers() {
+ r.mu.Lock()
+ defer r.mu.Unlock()
+
+ for id, w := range r.workers {
+ if time.Since(w.LastSeen) > 15*time.Second {
+ w.MissedBeats++
+ if w.MissedBeats >= 3 {
+ log.Printf("worker_registry: worker %s marked as down (missed %d heartbeats)", id, w.MissedBeats)
+ delete(r.workers, id)
+ if r.onWorkerDown != nil {
+ go r.onWorkerDown(id)
+ }
+ }
+ }
+ }
+}
diff --git a/internal/db/migrations/001_initial.down.sql b/internal/db/migrations/001_initial.down.sql
new file mode 100644
index 00000000..5df4f04b
--- /dev/null
+++ b/internal/db/migrations/001_initial.down.sql
@@ -0,0 +1,8 @@
+DROP TABLE IF EXISTS templates;
+DROP TABLE IF EXISTS workers;
+DROP TABLE IF EXISTS pty_session_logs;
+DROP TABLE IF EXISTS command_logs;
+DROP TABLE IF EXISTS sandbox_sessions;
+DROP TABLE IF EXISTS api_keys;
+DROP TABLE IF EXISTS users;
+DROP TABLE IF EXISTS orgs;
diff --git a/internal/db/migrations/001_initial.up.sql b/internal/db/migrations/001_initial.up.sql
new file mode 100644
index 00000000..db91cb48
--- /dev/null
+++ b/internal/db/migrations/001_initial.up.sql
@@ -0,0 +1,106 @@
+-- Organizations
+CREATE TABLE orgs (
+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
+ name TEXT NOT NULL,
+ slug TEXT NOT NULL UNIQUE,
+ plan TEXT NOT NULL DEFAULT 'free',
+ max_concurrent_sandboxes INT NOT NULL DEFAULT 5,
+ max_sandbox_timeout_sec INT NOT NULL DEFAULT 3600,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
+);
+
+-- Users
+CREATE TABLE users (
+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
+ org_id UUID NOT NULL REFERENCES orgs(id),
+ email TEXT NOT NULL UNIQUE,
+ name TEXT,
+ role TEXT NOT NULL DEFAULT 'member',
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now()
+);
+
+-- API Keys
+CREATE TABLE api_keys (
+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
+ org_id UUID NOT NULL REFERENCES orgs(id),
+ created_by UUID REFERENCES users(id),
+ key_hash TEXT NOT NULL UNIQUE,
+ key_prefix TEXT NOT NULL,
+ name TEXT NOT NULL,
+ scopes TEXT[] NOT NULL DEFAULT '{sandbox:*}',
+ last_used TIMESTAMPTZ,
+ expires_at TIMESTAMPTZ,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now()
+);
+CREATE INDEX idx_api_keys_hash ON api_keys(key_hash);
+
+-- Sandbox Sessions
+CREATE TABLE sandbox_sessions (
+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
+ sandbox_id TEXT NOT NULL,
+ org_id UUID NOT NULL REFERENCES orgs(id),
+ user_id UUID REFERENCES users(id),
+ template TEXT NOT NULL,
+ region TEXT NOT NULL,
+ worker_id TEXT NOT NULL,
+ status TEXT NOT NULL DEFAULT 'running',
+ config JSONB NOT NULL DEFAULT '{}',
+ metadata JSONB,
+ started_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ stopped_at TIMESTAMPTZ,
+ error_msg TEXT
+);
+CREATE INDEX idx_sessions_org ON sandbox_sessions(org_id, status);
+CREATE INDEX idx_sessions_sandbox ON sandbox_sessions(sandbox_id);
+
+-- Command Logs (populated from NATS sync)
+CREATE TABLE command_logs (
+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
+ sandbox_id TEXT NOT NULL,
+ command TEXT NOT NULL,
+ args TEXT[],
+ cwd TEXT,
+ exit_code INT,
+ duration_ms INT,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now()
+);
+CREATE INDEX idx_cmd_logs_sandbox ON command_logs(sandbox_id, created_at);
+
+-- PTY Session Logs (populated from NATS sync)
+CREATE TABLE pty_session_logs (
+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
+ sandbox_id TEXT NOT NULL,
+ pty_session_id TEXT NOT NULL,
+ started_at TIMESTAMPTZ NOT NULL,
+ ended_at TIMESTAMPTZ,
+ bytes_in BIGINT DEFAULT 0,
+ bytes_out BIGINT DEFAULT 0
+);
+
+-- Worker Registry
+CREATE TABLE workers (
+ id TEXT PRIMARY KEY,
+ region TEXT NOT NULL,
+ grpc_addr TEXT NOT NULL,
+ http_addr TEXT NOT NULL,
+ capacity INT NOT NULL,
+ current_count INT NOT NULL DEFAULT 0,
+ status TEXT NOT NULL DEFAULT 'healthy',
+ last_heartbeat TIMESTAMPTZ,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now()
+);
+CREATE INDEX idx_workers_region ON workers(region, status);
+
+-- Templates
+CREATE TABLE templates (
+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
+ org_id UUID REFERENCES orgs(id),
+ name TEXT NOT NULL,
+ tag TEXT NOT NULL DEFAULT 'latest',
+ image_ref TEXT NOT NULL,
+ dockerfile TEXT,
+ is_public BOOLEAN NOT NULL DEFAULT false,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ UNIQUE(org_id, name, tag)
+);
diff --git a/internal/db/store.go b/internal/db/store.go
new file mode 100644
index 00000000..090fa8ef
--- /dev/null
+++ b/internal/db/store.go
@@ -0,0 +1,454 @@
+package db
+
+import (
+ "context"
+ "crypto/sha256"
+ "embed"
+ "encoding/hex"
+ "encoding/json"
+ "fmt"
+ "time"
+
+ "github.com/google/uuid"
+ "github.com/jackc/pgx/v5"
+ "github.com/jackc/pgx/v5/pgxpool"
+)
+
+//go:embed migrations/*.sql
+var migrationsFS embed.FS
+
+// Store provides data access to the global PostgreSQL database.
+type Store struct {
+ pool *pgxpool.Pool
+}
+
+// NewStore creates a new Store with a connection pool.
+func NewStore(ctx context.Context, databaseURL string) (*Store, error) {
+ pool, err := pgxpool.New(ctx, databaseURL)
+ if err != nil {
+ return nil, fmt.Errorf("failed to connect to database: %w", err)
+ }
+ if err := pool.Ping(ctx); err != nil {
+ pool.Close()
+ return nil, fmt.Errorf("failed to ping database: %w", err)
+ }
+ return &Store{pool: pool}, nil
+}
+
+// Close closes the connection pool.
+func (s *Store) Close() {
+ s.pool.Close()
+}
+
+// Migrate runs database migrations.
+func (s *Store) Migrate(ctx context.Context) error {
+ // Create migrations tracking table
+ _, err := s.pool.Exec(ctx, `
+ CREATE TABLE IF NOT EXISTS schema_migrations (
+ version INT PRIMARY KEY,
+ applied_at TIMESTAMPTZ NOT NULL DEFAULT now()
+ )
+ `)
+ if err != nil {
+ return fmt.Errorf("failed to create migrations table: %w", err)
+ }
+
+ // Check current version
+ var currentVersion int
+ err = s.pool.QueryRow(ctx, `SELECT COALESCE(MAX(version), 0) FROM schema_migrations`).Scan(&currentVersion)
+ if err != nil {
+ return fmt.Errorf("failed to get current migration version: %w", err)
+ }
+
+ // Apply migration 1 if not applied
+ if currentVersion < 1 {
+ sql, err := migrationsFS.ReadFile("migrations/001_initial.up.sql")
+ if err != nil {
+ return fmt.Errorf("failed to read migration file: %w", err)
+ }
+ tx, err := s.pool.Begin(ctx)
+ if err != nil {
+ return fmt.Errorf("failed to begin transaction: %w", err)
+ }
+ defer tx.Rollback(ctx)
+
+ if _, err := tx.Exec(ctx, string(sql)); err != nil {
+ return fmt.Errorf("failed to apply migration 001: %w", err)
+ }
+ if _, err := tx.Exec(ctx, `INSERT INTO schema_migrations (version) VALUES (1)`); err != nil {
+ return fmt.Errorf("failed to record migration 001: %w", err)
+ }
+ if err := tx.Commit(ctx); err != nil {
+ return fmt.Errorf("failed to commit migration 001: %w", err)
+ }
+ }
+
+ return nil
+}
+
+// --- Org operations ---
+
+type Org struct {
+ ID uuid.UUID `json:"id"`
+ Name string `json:"name"`
+ Slug string `json:"slug"`
+ Plan string `json:"plan"`
+ MaxConcurrentSandboxes int `json:"maxConcurrentSandboxes"`
+ MaxSandboxTimeoutSec int `json:"maxSandboxTimeoutSec"`
+ CreatedAt time.Time `json:"createdAt"`
+ UpdatedAt time.Time `json:"updatedAt"`
+}
+
+func (s *Store) CreateOrg(ctx context.Context, name, slug string) (*Org, error) {
+ org := &Org{}
+ err := s.pool.QueryRow(ctx,
+ `INSERT INTO orgs (name, slug) VALUES ($1, $2)
+ RETURNING id, name, slug, plan, max_concurrent_sandboxes, max_sandbox_timeout_sec, created_at, updated_at`,
+ name, slug,
+ ).Scan(&org.ID, &org.Name, &org.Slug, &org.Plan, &org.MaxConcurrentSandboxes,
+ &org.MaxSandboxTimeoutSec, &org.CreatedAt, &org.UpdatedAt)
+ if err != nil {
+ return nil, fmt.Errorf("failed to create org: %w", err)
+ }
+ return org, nil
+}
+
+func (s *Store) GetOrg(ctx context.Context, id uuid.UUID) (*Org, error) {
+ org := &Org{}
+ err := s.pool.QueryRow(ctx,
+ `SELECT id, name, slug, plan, max_concurrent_sandboxes, max_sandbox_timeout_sec, created_at, updated_at
+ FROM orgs WHERE id = $1`, id,
+ ).Scan(&org.ID, &org.Name, &org.Slug, &org.Plan, &org.MaxConcurrentSandboxes,
+ &org.MaxSandboxTimeoutSec, &org.CreatedAt, &org.UpdatedAt)
+ if err != nil {
+ return nil, fmt.Errorf("org not found: %w", err)
+ }
+ return org, nil
+}
+
+func (s *Store) GetOrgBySlug(ctx context.Context, slug string) (*Org, error) {
+ org := &Org{}
+ err := s.pool.QueryRow(ctx,
+ `SELECT id, name, slug, plan, max_concurrent_sandboxes, max_sandbox_timeout_sec, created_at, updated_at
+ FROM orgs WHERE slug = $1`, slug,
+ ).Scan(&org.ID, &org.Name, &org.Slug, &org.Plan, &org.MaxConcurrentSandboxes,
+ &org.MaxSandboxTimeoutSec, &org.CreatedAt, &org.UpdatedAt)
+ if err != nil {
+ return nil, fmt.Errorf("org not found: %w", err)
+ }
+ return org, nil
+}
+
+// --- User operations ---
+
+type User struct {
+ ID uuid.UUID `json:"id"`
+ OrgID uuid.UUID `json:"orgId"`
+ Email string `json:"email"`
+ Name string `json:"name"`
+ Role string `json:"role"`
+ CreatedAt time.Time `json:"createdAt"`
+}
+
+func (s *Store) CreateUser(ctx context.Context, orgID uuid.UUID, email, name, role string) (*User, error) {
+ user := &User{}
+ err := s.pool.QueryRow(ctx,
+ `INSERT INTO users (org_id, email, name, role) VALUES ($1, $2, $3, $4)
+ RETURNING id, org_id, email, name, role, created_at`,
+ orgID, email, name, role,
+ ).Scan(&user.ID, &user.OrgID, &user.Email, &user.Name, &user.Role, &user.CreatedAt)
+ if err != nil {
+ return nil, fmt.Errorf("failed to create user: %w", err)
+ }
+ return user, nil
+}
+
+func (s *Store) GetUserByEmail(ctx context.Context, email string) (*User, error) {
+ user := &User{}
+ err := s.pool.QueryRow(ctx,
+ `SELECT id, org_id, email, name, role, created_at FROM users WHERE email = $1`, email,
+ ).Scan(&user.ID, &user.OrgID, &user.Email, &user.Name, &user.Role, &user.CreatedAt)
+ if err != nil {
+ return nil, fmt.Errorf("user not found: %w", err)
+ }
+ return user, nil
+}
+
+// --- API Key operations ---
+
+type APIKey struct {
+ ID uuid.UUID `json:"id"`
+ OrgID uuid.UUID `json:"orgId"`
+ CreatedBy *uuid.UUID `json:"createdBy,omitempty"`
+ KeyPrefix string `json:"keyPrefix"`
+ Name string `json:"name"`
+ Scopes []string `json:"scopes"`
+ LastUsed *time.Time `json:"lastUsed,omitempty"`
+ ExpiresAt *time.Time `json:"expiresAt,omitempty"`
+ CreatedAt time.Time `json:"createdAt"`
+}
+
+// HashAPIKey returns the SHA-256 hash of a plaintext API key.
+func HashAPIKey(key string) string {
+ h := sha256.Sum256([]byte(key))
+ return hex.EncodeToString(h[:])
+}
+
+func (s *Store) CreateAPIKey(ctx context.Context, orgID uuid.UUID, createdBy *uuid.UUID, keyHash, keyPrefix, name string, scopes []string) (*APIKey, error) {
+ apiKey := &APIKey{}
+ err := s.pool.QueryRow(ctx,
+ `INSERT INTO api_keys (org_id, created_by, key_hash, key_prefix, name, scopes)
+ VALUES ($1, $2, $3, $4, $5, $6)
+ RETURNING id, org_id, created_by, key_prefix, name, scopes, created_at`,
+ orgID, createdBy, keyHash, keyPrefix, name, scopes,
+ ).Scan(&apiKey.ID, &apiKey.OrgID, &apiKey.CreatedBy, &apiKey.KeyPrefix, &apiKey.Name,
+ &apiKey.Scopes, &apiKey.CreatedAt)
+ if err != nil {
+ return nil, fmt.Errorf("failed to create API key: %w", err)
+ }
+ return apiKey, nil
+}
+
+// ValidateAPIKey looks up an API key by hash and returns the associated org ID.
+func (s *Store) ValidateAPIKey(ctx context.Context, keyPlaintext string) (uuid.UUID, error) {
+ hash := HashAPIKey(keyPlaintext)
+ var orgID uuid.UUID
+ var expiresAt *time.Time
+ err := s.pool.QueryRow(ctx,
+ `SELECT org_id, expires_at FROM api_keys WHERE key_hash = $1`, hash,
+ ).Scan(&orgID, &expiresAt)
+ if err != nil {
+ return uuid.Nil, fmt.Errorf("invalid API key")
+ }
+ if expiresAt != nil && expiresAt.Before(time.Now()) {
+ return uuid.Nil, fmt.Errorf("API key expired")
+ }
+ // Update last_used
+ _, _ = s.pool.Exec(ctx, `UPDATE api_keys SET last_used = now() WHERE key_hash = $1`, hash)
+ return orgID, nil
+}
+
+func (s *Store) ListAPIKeys(ctx context.Context, orgID uuid.UUID) ([]APIKey, error) {
+ rows, err := s.pool.Query(ctx,
+ `SELECT id, org_id, created_by, key_prefix, name, scopes, last_used, expires_at, created_at
+ FROM api_keys WHERE org_id = $1 ORDER BY created_at DESC`, orgID)
+ if err != nil {
+ return nil, fmt.Errorf("failed to list API keys: %w", err)
+ }
+ defer rows.Close()
+
+ var keys []APIKey
+ for rows.Next() {
+ var k APIKey
+ if err := rows.Scan(&k.ID, &k.OrgID, &k.CreatedBy, &k.KeyPrefix, &k.Name,
+ &k.Scopes, &k.LastUsed, &k.ExpiresAt, &k.CreatedAt); err != nil {
+ return nil, err
+ }
+ keys = append(keys, k)
+ }
+ return keys, nil
+}
+
+func (s *Store) DeleteAPIKey(ctx context.Context, id uuid.UUID) error {
+ _, err := s.pool.Exec(ctx, `DELETE FROM api_keys WHERE id = $1`, id)
+ return err
+}
+
+// --- Sandbox Session operations ---
+
+type SandboxSession struct {
+ ID uuid.UUID `json:"id"`
+ SandboxID string `json:"sandboxId"`
+ OrgID uuid.UUID `json:"orgId"`
+ UserID *uuid.UUID `json:"userId,omitempty"`
+ Template string `json:"template"`
+ Region string `json:"region"`
+ WorkerID string `json:"workerId"`
+ Status string `json:"status"`
+ Config json.RawMessage `json:"config"`
+ Metadata json.RawMessage `json:"metadata,omitempty"`
+ StartedAt time.Time `json:"startedAt"`
+ StoppedAt *time.Time `json:"stoppedAt,omitempty"`
+ ErrorMsg *string `json:"errorMsg,omitempty"`
+}
+
+func (s *Store) CreateSandboxSession(ctx context.Context, sandboxID string, orgID uuid.UUID, userID *uuid.UUID, template, region, workerID string, config, metadata json.RawMessage) (*SandboxSession, error) {
+ session := &SandboxSession{}
+ err := s.pool.QueryRow(ctx,
+ `INSERT INTO sandbox_sessions (sandbox_id, org_id, user_id, template, region, worker_id, config, metadata)
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
+ RETURNING id, sandbox_id, org_id, user_id, template, region, worker_id, status, config, metadata, started_at`,
+ sandboxID, orgID, userID, template, region, workerID, config, metadata,
+ ).Scan(&session.ID, &session.SandboxID, &session.OrgID, &session.UserID, &session.Template,
+ &session.Region, &session.WorkerID, &session.Status, &session.Config, &session.Metadata, &session.StartedAt)
+ if err != nil {
+ return nil, fmt.Errorf("failed to create sandbox session: %w", err)
+ }
+ return session, nil
+}
+
+func (s *Store) UpdateSandboxSessionStatus(ctx context.Context, sandboxID, status string, errorMsg *string) error {
+ var query string
+ var args []interface{}
+ if status == "stopped" || status == "error" {
+ query = `UPDATE sandbox_sessions SET status = $1, stopped_at = now(), error_msg = $2 WHERE sandbox_id = $3 AND status = 'running'`
+ args = []interface{}{status, errorMsg, sandboxID}
+ } else {
+ query = `UPDATE sandbox_sessions SET status = $1 WHERE sandbox_id = $2 AND status = 'running'`
+ args = []interface{}{status, sandboxID}
+ }
+ _, err := s.pool.Exec(ctx, query, args...)
+ if err != nil {
+ return fmt.Errorf("failed to update sandbox session: %w", err)
+ }
+ return nil
+}
+
+func (s *Store) GetSandboxSession(ctx context.Context, sandboxID string) (*SandboxSession, error) {
+ session := &SandboxSession{}
+ err := s.pool.QueryRow(ctx,
+ `SELECT id, sandbox_id, org_id, user_id, template, region, worker_id, status, config, metadata, started_at, stopped_at, error_msg
+ FROM sandbox_sessions WHERE sandbox_id = $1 ORDER BY started_at DESC LIMIT 1`, sandboxID,
+ ).Scan(&session.ID, &session.SandboxID, &session.OrgID, &session.UserID, &session.Template,
+ &session.Region, &session.WorkerID, &session.Status, &session.Config, &session.Metadata,
+ &session.StartedAt, &session.StoppedAt, &session.ErrorMsg)
+ if err != nil {
+ return nil, fmt.Errorf("sandbox session not found: %w", err)
+ }
+ return session, nil
+}
+
+func (s *Store) ListSandboxSessions(ctx context.Context, orgID uuid.UUID, status string, limit, offset int) ([]SandboxSession, error) {
+ var rows pgx.Rows
+ var err error
+ if status != "" {
+ rows, err = s.pool.Query(ctx,
+ `SELECT id, sandbox_id, org_id, user_id, template, region, worker_id, status, config, metadata, started_at, stopped_at, error_msg
+ FROM sandbox_sessions WHERE org_id = $1 AND status = $2 ORDER BY started_at DESC LIMIT $3 OFFSET $4`,
+ orgID, status, limit, offset)
+ } else {
+ rows, err = s.pool.Query(ctx,
+ `SELECT id, sandbox_id, org_id, user_id, template, region, worker_id, status, config, metadata, started_at, stopped_at, error_msg
+ FROM sandbox_sessions WHERE org_id = $1 ORDER BY started_at DESC LIMIT $2 OFFSET $3`,
+ orgID, limit, offset)
+ }
+ if err != nil {
+ return nil, fmt.Errorf("failed to list sandbox sessions: %w", err)
+ }
+ defer rows.Close()
+
+ var sessions []SandboxSession
+ for rows.Next() {
+ var sess SandboxSession
+ if err := rows.Scan(&sess.ID, &sess.SandboxID, &sess.OrgID, &sess.UserID, &sess.Template,
+ &sess.Region, &sess.WorkerID, &sess.Status, &sess.Config, &sess.Metadata,
+ &sess.StartedAt, &sess.StoppedAt, &sess.ErrorMsg); err != nil {
+ return nil, err
+ }
+ sessions = append(sessions, sess)
+ }
+ return sessions, nil
+}
+
+func (s *Store) CountActiveSandboxes(ctx context.Context, orgID uuid.UUID) (int, error) {
+ var count int
+ err := s.pool.QueryRow(ctx,
+ `SELECT COUNT(*) FROM sandbox_sessions WHERE org_id = $1 AND status = 'running'`, orgID,
+ ).Scan(&count)
+ return count, err
+}
+
+// --- Command Log operations (for NATS sync consumer) ---
+
+type CommandLog struct {
+ ID uuid.UUID `json:"id"`
+ SandboxID string `json:"sandboxId"`
+ Command string `json:"command"`
+ Args []string `json:"args,omitempty"`
+ Cwd string `json:"cwd,omitempty"`
+ ExitCode *int `json:"exitCode,omitempty"`
+ DurationMs *int `json:"durationMs,omitempty"`
+ CreatedAt time.Time `json:"createdAt"`
+}
+
+func (s *Store) InsertCommandLog(ctx context.Context, sandboxID, command string, args []string, cwd string, exitCode, durationMs *int) error {
+ _, err := s.pool.Exec(ctx,
+ `INSERT INTO command_logs (sandbox_id, command, args, cwd, exit_code, duration_ms)
+ VALUES ($1, $2, $3, $4, $5, $6)`,
+ sandboxID, command, args, cwd, exitCode, durationMs)
+ return err
+}
+
+func (s *Store) InsertCommandLogBatch(ctx context.Context, logs []CommandLog) error {
+ if len(logs) == 0 {
+ return nil
+ }
+ batch := &pgx.Batch{}
+ for _, l := range logs {
+ batch.Queue(
+ `INSERT INTO command_logs (sandbox_id, command, args, cwd, exit_code, duration_ms, created_at)
+ VALUES ($1, $2, $3, $4, $5, $6, $7)`,
+ l.SandboxID, l.Command, l.Args, l.Cwd, l.ExitCode, l.DurationMs, l.CreatedAt)
+ }
+ br := s.pool.SendBatch(ctx, batch)
+ defer br.Close()
+ for range logs {
+ if _, err := br.Exec(); err != nil {
+ return fmt.Errorf("failed to insert command log batch: %w", err)
+ }
+ }
+ return nil
+}
+
+// --- Worker Registry operations ---
+
+type Worker struct {
+ ID string `json:"id"`
+ Region string `json:"region"`
+ GRPCAddr string `json:"grpcAddr"`
+ HTTPAddr string `json:"httpAddr"`
+ Capacity int `json:"capacity"`
+ CurrentCount int `json:"currentCount"`
+ Status string `json:"status"`
+ LastHeartbeat *time.Time `json:"lastHeartbeat,omitempty"`
+ CreatedAt time.Time `json:"createdAt"`
+}
+
+func (s *Store) UpsertWorker(ctx context.Context, w *Worker) error {
+ _, err := s.pool.Exec(ctx,
+ `INSERT INTO workers (id, region, grpc_addr, http_addr, capacity, current_count, status, last_heartbeat)
+ VALUES ($1, $2, $3, $4, $5, $6, $7, now())
+ ON CONFLICT (id) DO UPDATE SET
+ current_count = EXCLUDED.current_count,
+ status = EXCLUDED.status,
+ last_heartbeat = now()`,
+ w.ID, w.Region, w.GRPCAddr, w.HTTPAddr, w.Capacity, w.CurrentCount, w.Status)
+ return err
+}
+
+func (s *Store) ListHealthyWorkers(ctx context.Context, region string) ([]Worker, error) {
+ rows, err := s.pool.Query(ctx,
+ `SELECT id, region, grpc_addr, http_addr, capacity, current_count, status, last_heartbeat, created_at
+ FROM workers WHERE region = $1 AND status = 'healthy'
+ ORDER BY (capacity - current_count) DESC`, region)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+
+ var workers []Worker
+ for rows.Next() {
+ var w Worker
+ if err := rows.Scan(&w.ID, &w.Region, &w.GRPCAddr, &w.HTTPAddr, &w.Capacity, &w.CurrentCount,
+ &w.Status, &w.LastHeartbeat, &w.CreatedAt); err != nil {
+ return nil, err
+ }
+ workers = append(workers, w)
+ }
+ return workers, nil
+}
+
+// Pool returns the underlying pgx pool for advanced use cases.
+func (s *Store) Pool() *pgxpool.Pool {
+ return s.pool
+}
diff --git a/internal/db/sync_consumer.go b/internal/db/sync_consumer.go
new file mode 100644
index 00000000..dc0a12c5
--- /dev/null
+++ b/internal/db/sync_consumer.go
@@ -0,0 +1,187 @@
+package db
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "log"
+ "sync"
+ "time"
+
+ "github.com/nats-io/nats.go"
+)
+
+// SyncConsumer reads sandbox events from NATS JetStream and writes them to PostgreSQL.
+type SyncConsumer struct {
+ store *Store
+ nc *nats.Conn
+ js nats.JetStreamContext
+ sub *nats.Subscription
+ stop chan struct{}
+ wg sync.WaitGroup
+}
+
+// NATSEvent is the event payload from workers.
+type NATSEvent struct {
+ Type string `json:"type"`
+ SandboxID string `json:"sandbox_id"`
+ WorkerID string `json:"worker_id"`
+ Region string `json:"region"`
+ Payload json.RawMessage `json:"payload"`
+ Timestamp time.Time `json:"timestamp"`
+}
+
+// NewSyncConsumer creates a new NATS-to-PG sync consumer.
+func NewSyncConsumer(store *Store, natsURL string) (*SyncConsumer, error) {
+ nc, err := nats.Connect(natsURL,
+ nats.RetryOnFailedConnect(true),
+ nats.MaxReconnects(-1),
+ nats.ReconnectWait(2*time.Second),
+ )
+ if err != nil {
+ return nil, fmt.Errorf("failed to connect to NATS: %w", err)
+ }
+
+ js, err := nc.JetStream()
+ if err != nil {
+ nc.Close()
+ return nil, fmt.Errorf("failed to get JetStream context: %w", err)
+ }
+
+ // Ensure the stream exists
+ _, _ = js.AddStream(&nats.StreamConfig{
+ Name: "SANDBOX_EVENTS",
+ Subjects: []string{"sandbox.events.>"},
+ MaxAge: 7 * 24 * time.Hour,
+ })
+
+ return &SyncConsumer{
+ store: store,
+ nc: nc,
+ js: js,
+ stop: make(chan struct{}),
+ }, nil
+}
+
+// Start begins consuming events from NATS and writing to PG.
+func (c *SyncConsumer) Start() error {
+ // Subscribe to all sandbox events with a durable consumer
+ sub, err := c.js.Subscribe("sandbox.events.>", c.handleMessage,
+ nats.Durable("pg-sync-consumer"),
+ nats.AckExplicit(),
+ nats.MaxAckPending(256),
+ )
+ if err != nil {
+ return fmt.Errorf("failed to subscribe: %w", err)
+ }
+ c.sub = sub
+ log.Println("sync_consumer: subscribed to sandbox.events.>")
+
+ // Also subscribe to worker heartbeats (regular NATS, not JetStream)
+ c.wg.Add(1)
+ go func() {
+ defer c.wg.Done()
+ heartbeatSub, err := c.nc.Subscribe("workers.heartbeat.>", c.handleHeartbeat)
+ if err != nil {
+ log.Printf("sync_consumer: failed to subscribe to heartbeats: %v", err)
+ return
+ }
+ defer heartbeatSub.Unsubscribe()
+ <-c.stop
+ }()
+
+ return nil
+}
+
+// Stop stops the consumer.
+func (c *SyncConsumer) Stop() {
+ close(c.stop)
+ if c.sub != nil {
+ c.sub.Unsubscribe()
+ }
+ c.wg.Wait()
+ c.nc.Close()
+}
+
+func (c *SyncConsumer) handleMessage(msg *nats.Msg) {
+ var event NATSEvent
+ if err := json.Unmarshal(msg.Data, &event); err != nil {
+ log.Printf("sync_consumer: failed to unmarshal event: %v", err)
+ msg.Ack()
+ return
+ }
+
+ switch event.Type {
+ case "command":
+ c.handleCommandEvent(event)
+ case "pty_start", "pty_end":
+ c.handlePTYEvent(event)
+ case "created", "destroyed":
+ log.Printf("sync_consumer: lifecycle event %s for sandbox %s", event.Type, event.SandboxID)
+ default:
+ log.Printf("sync_consumer: unknown event type %s for sandbox %s", event.Type, event.SandboxID)
+ }
+
+ msg.Ack()
+}
+
+func (c *SyncConsumer) handleCommandEvent(event NATSEvent) {
+ var payload struct {
+ SandboxID string `json:"sandbox_id"`
+ Command string `json:"command"`
+ Args []string `json:"args"`
+ Cwd string `json:"cwd"`
+ ExitCode *int `json:"exit_code"`
+ DurationMs *int `json:"duration_ms"`
+ }
+ if err := json.Unmarshal(event.Payload, &payload); err != nil {
+ log.Printf("sync_consumer: failed to unmarshal command payload: %v", err)
+ return
+ }
+
+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+ defer cancel()
+
+ if err := c.store.InsertCommandLog(
+ ctx, event.SandboxID, payload.Command, payload.Args, payload.Cwd,
+ payload.ExitCode, payload.DurationMs,
+ ); err != nil {
+ log.Printf("sync_consumer: failed to insert command log: %v", err)
+ }
+}
+
+func (c *SyncConsumer) handlePTYEvent(event NATSEvent) {
+ log.Printf("sync_consumer: PTY event %s for sandbox %s", event.Type, event.SandboxID)
+}
+
+func (c *SyncConsumer) handleHeartbeat(msg *nats.Msg) {
+ var heartbeat struct {
+ WorkerID string `json:"worker_id"`
+ Region string `json:"region"`
+ GRPCAddr string `json:"grpc_addr"`
+ HTTPAddr string `json:"http_addr"`
+ Capacity int `json:"capacity"`
+ Current int `json:"current"`
+ CPUPct float64 `json:"cpu_pct"`
+ MemPct float64 `json:"mem_pct"`
+ }
+ if err := json.Unmarshal(msg.Data, &heartbeat); err != nil {
+ return
+ }
+
+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+ defer cancel()
+
+ worker := &Worker{
+ ID: heartbeat.WorkerID,
+ Region: heartbeat.Region,
+ GRPCAddr: heartbeat.GRPCAddr,
+ HTTPAddr: heartbeat.HTTPAddr,
+ Capacity: heartbeat.Capacity,
+ CurrentCount: heartbeat.Current,
+ Status: "healthy",
+ }
+ if err := c.store.UpsertWorker(ctx, worker); err != nil {
+ log.Printf("sync_consumer: failed to upsert worker: %v", err)
+ }
+}
diff --git a/internal/metrics/metrics.go b/internal/metrics/metrics.go
new file mode 100644
index 00000000..722da2a5
--- /dev/null
+++ b/internal/metrics/metrics.go
@@ -0,0 +1,188 @@
+package metrics
+
+import (
+ "net/http"
+ "strconv"
+ "time"
+
+ "github.com/labstack/echo/v4"
+ "github.com/prometheus/client_golang/prometheus"
+ "github.com/prometheus/client_golang/prometheus/promhttp"
+)
+
+// Worker metrics
+var (
+ SandboxesActive = prometheus.NewGaugeVec(
+ prometheus.GaugeOpts{
+ Name: "opensandbox_sandboxes_active",
+ Help: "Number of currently active sandboxes",
+ },
+ []string{"region", "worker_id", "template"},
+ )
+
+ SandboxCreateDuration = prometheus.NewHistogramVec(
+ prometheus.HistogramOpts{
+ Name: "opensandbox_sandbox_create_duration_seconds",
+ Help: "Time to create a sandbox",
+ Buckets: []float64{0.1, 0.25, 0.5, 1.0, 2.0, 5.0, 10.0},
+ },
+ []string{"region", "template"},
+ )
+
+ ExecDuration = prometheus.NewHistogramVec(
+ prometheus.HistogramOpts{
+ Name: "opensandbox_exec_duration_seconds",
+ Help: "Time to execute a command in a sandbox",
+ Buckets: []float64{0.01, 0.05, 0.1, 0.5, 1.0, 5.0, 30.0, 60.0},
+ },
+ []string{"region"},
+ )
+
+ PTYSessionsActive = prometheus.NewGaugeVec(
+ prometheus.GaugeOpts{
+ Name: "opensandbox_pty_sessions_active",
+ Help: "Number of active PTY sessions",
+ },
+ []string{"region", "worker_id"},
+ )
+
+ WorkerUtilization = prometheus.NewGaugeVec(
+ prometheus.GaugeOpts{
+ Name: "opensandbox_worker_utilization",
+ Help: "Worker utilization (0-1)",
+ },
+ []string{"region", "worker_id"},
+ )
+
+ PodmanOpDuration = prometheus.NewHistogramVec(
+ prometheus.HistogramOpts{
+ Name: "opensandbox_podman_op_duration_seconds",
+ Help: "Time for podman operations",
+ Buckets: []float64{0.01, 0.05, 0.1, 0.5, 1.0, 5.0},
+ },
+ []string{"operation"},
+ )
+
+ DirectConnectionsActive = prometheus.NewGaugeVec(
+ prometheus.GaugeOpts{
+ Name: "opensandbox_direct_connections_active",
+ Help: "Number of active direct SDK connections to worker",
+ },
+ []string{"region", "worker_id"},
+ )
+
+ SQLiteSyncLag = prometheus.NewGaugeVec(
+ prometheus.GaugeOpts{
+ Name: "opensandbox_sqlite_sync_lag_seconds",
+ Help: "Time since last NATS sync",
+ },
+ []string{"region", "worker_id"},
+ )
+)
+
+// Control plane metrics
+var (
+ HTTPRequestsTotal = prometheus.NewCounterVec(
+ prometheus.CounterOpts{
+ Name: "opensandbox_http_requests_total",
+ Help: "Total HTTP requests",
+ },
+ []string{"method", "path", "status"},
+ )
+
+ SandboxCreatesTotal = prometheus.NewCounterVec(
+ prometheus.CounterOpts{
+ Name: "opensandbox_sandbox_creates_total",
+ Help: "Total sandbox creations",
+ },
+ []string{"region", "template", "status"},
+ )
+
+ AuthAttemptsTotal = prometheus.NewCounterVec(
+ prometheus.CounterOpts{
+ Name: "opensandbox_auth_attempts_total",
+ Help: "Total auth attempts",
+ },
+ []string{"type", "result"},
+ )
+
+ WorkersTotal = prometheus.NewGaugeVec(
+ prometheus.GaugeOpts{
+ Name: "opensandbox_workers_total",
+ Help: "Number of workers",
+ },
+ []string{"region", "status"},
+ )
+
+ ScaleEventsTotal = prometheus.NewCounterVec(
+ prometheus.CounterOpts{
+ Name: "opensandbox_scale_events_total",
+ Help: "Total scaling events",
+ },
+ []string{"region", "direction"},
+ )
+)
+
+func init() {
+ // Register all metrics
+ prometheus.MustRegister(
+ SandboxesActive,
+ SandboxCreateDuration,
+ ExecDuration,
+ PTYSessionsActive,
+ WorkerUtilization,
+ PodmanOpDuration,
+ DirectConnectionsActive,
+ SQLiteSyncLag,
+ HTTPRequestsTotal,
+ SandboxCreatesTotal,
+ AuthAttemptsTotal,
+ WorkersTotal,
+ ScaleEventsTotal,
+ )
+}
+
+// Handler returns an HTTP handler for the /metrics endpoint.
+func Handler() http.Handler {
+ return promhttp.Handler()
+}
+
+// EchoMiddleware returns Echo middleware that instruments HTTP requests.
+func EchoMiddleware() echo.MiddlewareFunc {
+ return func(next echo.HandlerFunc) echo.HandlerFunc {
+ return func(c echo.Context) error {
+ start := time.Now()
+ err := next(c)
+ duration := time.Since(start)
+
+ status := c.Response().Status
+ if err != nil {
+ if he, ok := err.(*echo.HTTPError); ok {
+ status = he.Code
+ }
+ }
+
+ HTTPRequestsTotal.WithLabelValues(
+ c.Request().Method,
+ c.Path(),
+ strconv.Itoa(status),
+ ).Inc()
+
+ _ = duration // Could add request duration histogram here
+ return err
+ }
+ }
+}
+
+// StartMetricsServer starts a standalone HTTP server serving /metrics on the given address.
+func StartMetricsServer(addr string) *http.Server {
+ mux := http.NewServeMux()
+ mux.Handle("/metrics", Handler())
+ srv := &http.Server{Addr: addr, Handler: mux}
+ go func() {
+ if err := srv.ListenAndServe(); err != http.ErrServerClosed {
+ // Log but don't crash — metrics are non-critical
+ }
+ }()
+ return srv
+}
diff --git a/internal/sandbox/sqlite.go b/internal/sandbox/sqlite.go
new file mode 100644
index 00000000..a515927b
--- /dev/null
+++ b/internal/sandbox/sqlite.go
@@ -0,0 +1,319 @@
+package sandbox
+
+import (
+ "database/sql"
+ "encoding/json"
+ "fmt"
+ "os"
+ "path/filepath"
+ "sync"
+ "time"
+
+ _ "github.com/mattn/go-sqlite3"
+)
+
+const sqliteSchema = `
+CREATE TABLE IF NOT EXISTS command_log (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ command TEXT NOT NULL,
+ args TEXT,
+ cwd TEXT,
+ exit_code INTEGER,
+ duration_ms INTEGER,
+ stdout_len INTEGER,
+ stderr_len INTEGER,
+ created_at TEXT NOT NULL DEFAULT (datetime('now'))
+);
+
+CREATE TABLE IF NOT EXISTS pty_sessions (
+ id TEXT PRIMARY KEY,
+ started_at TEXT NOT NULL DEFAULT (datetime('now')),
+ ended_at TEXT,
+ bytes_in INTEGER DEFAULT 0,
+ bytes_out INTEGER DEFAULT 0
+);
+
+CREATE TABLE IF NOT EXISTS events (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ type TEXT NOT NULL,
+ payload TEXT,
+ synced INTEGER DEFAULT 0,
+ created_at TEXT NOT NULL DEFAULT (datetime('now'))
+);
+
+CREATE INDEX IF NOT EXISTS idx_events_unsynced ON events(synced) WHERE synced = 0;
+`
+
+// SandboxDB manages the per-sandbox SQLite database.
+type SandboxDB struct {
+ db *sql.DB
+ sandboxID string
+}
+
+// OpenSandboxDB opens (or creates) the SQLite database for a sandbox.
+func OpenSandboxDB(dataDir, sandboxID string) (*SandboxDB, error) {
+ dir := filepath.Join(dataDir, sandboxID)
+ if err := os.MkdirAll(dir, 0755); err != nil {
+ return nil, fmt.Errorf("failed to create sandbox data dir: %w", err)
+ }
+
+ dbPath := filepath.Join(dir, "state.db")
+ db, err := sql.Open("sqlite3", dbPath+"?_journal_mode=WAL&_busy_timeout=5000")
+ if err != nil {
+ return nil, fmt.Errorf("failed to open sqlite: %w", err)
+ }
+
+ if _, err := db.Exec(sqliteSchema); err != nil {
+ db.Close()
+ return nil, fmt.Errorf("failed to apply sqlite schema: %w", err)
+ }
+
+ return &SandboxDB{db: db, sandboxID: sandboxID}, nil
+}
+
+// Close closes the database connection.
+func (s *SandboxDB) Close() error {
+ return s.db.Close()
+}
+
+// LogCommand records a command execution.
+func (s *SandboxDB) LogCommand(command string, args []string, cwd string, exitCode, durationMs, stdoutLen, stderrLen int) error {
+ argsJSON, _ := json.Marshal(args)
+ _, err := s.db.Exec(
+ `INSERT INTO command_log (command, args, cwd, exit_code, duration_ms, stdout_len, stderr_len) VALUES (?, ?, ?, ?, ?, ?, ?)`,
+ command, string(argsJSON), cwd, exitCode, durationMs, stdoutLen, stderrLen)
+ if err != nil {
+ return fmt.Errorf("failed to log command: %w", err)
+ }
+
+ // Also insert an event for NATS sync
+ payload, _ := json.Marshal(map[string]interface{}{
+ "sandbox_id": s.sandboxID,
+ "command": command,
+ "args": args,
+ "cwd": cwd,
+ "exit_code": exitCode,
+ "duration_ms": durationMs,
+ })
+ _, err = s.db.Exec(
+ `INSERT INTO events (type, payload) VALUES ('command', ?)`, string(payload))
+ return err
+}
+
+// LogPTYStart records a PTY session start.
+func (s *SandboxDB) LogPTYStart(sessionID string) error {
+ _, err := s.db.Exec(`INSERT INTO pty_sessions (id) VALUES (?)`, sessionID)
+ if err != nil {
+ return err
+ }
+ payload, _ := json.Marshal(map[string]interface{}{
+ "sandbox_id": s.sandboxID,
+ "session_id": sessionID,
+ })
+ _, err = s.db.Exec(`INSERT INTO events (type, payload) VALUES ('pty_start', ?)`, string(payload))
+ return err
+}
+
+// LogPTYEnd records a PTY session end.
+func (s *SandboxDB) LogPTYEnd(sessionID string, bytesIn, bytesOut int64) error {
+ _, err := s.db.Exec(
+ `UPDATE pty_sessions SET ended_at = datetime('now'), bytes_in = ?, bytes_out = ? WHERE id = ?`,
+ bytesIn, bytesOut, sessionID)
+ if err != nil {
+ return err
+ }
+ payload, _ := json.Marshal(map[string]interface{}{
+ "sandbox_id": s.sandboxID,
+ "session_id": sessionID,
+ "bytes_in": bytesIn,
+ "bytes_out": bytesOut,
+ })
+ _, err = s.db.Exec(`INSERT INTO events (type, payload) VALUES ('pty_end', ?)`, string(payload))
+ return err
+}
+
+// LogEvent records a generic event.
+func (s *SandboxDB) LogEvent(eventType string, payload interface{}) error {
+ data, _ := json.Marshal(payload)
+ _, err := s.db.Exec(`INSERT INTO events (type, payload) VALUES (?, ?)`, eventType, string(data))
+ return err
+}
+
+// Event represents an unsynced event.
+type Event struct {
+ ID int64
+ Type string
+ Payload string
+ CreatedAt string
+}
+
+// GetUnsyncedEvents returns events that haven't been synced to NATS yet.
+func (s *SandboxDB) GetUnsyncedEvents(limit int) ([]Event, error) {
+ rows, err := s.db.Query(
+ `SELECT id, type, payload, created_at FROM events WHERE synced = 0 ORDER BY id ASC LIMIT ?`, limit)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+
+ var events []Event
+ for rows.Next() {
+ var e Event
+ if err := rows.Scan(&e.ID, &e.Type, &e.Payload, &e.CreatedAt); err != nil {
+ return nil, err
+ }
+ events = append(events, e)
+ }
+ return events, nil
+}
+
+// MarkEventsSynced marks the given event IDs as synced.
+func (s *SandboxDB) MarkEventsSynced(ids []int64) error {
+ if len(ids) == 0 {
+ return nil
+ }
+ tx, err := s.db.Begin()
+ if err != nil {
+ return err
+ }
+ defer tx.Rollback()
+
+ stmt, err := tx.Prepare(`UPDATE events SET synced = 1 WHERE id = ?`)
+ if err != nil {
+ return err
+ }
+ defer stmt.Close()
+
+ for _, id := range ids {
+ if _, err := stmt.Exec(id); err != nil {
+ return err
+ }
+ }
+ return tx.Commit()
+}
+
+// RemoveSandboxData removes the SQLite database directory for a sandbox.
+func RemoveSandboxData(dataDir, sandboxID string) error {
+ dir := filepath.Join(dataDir, sandboxID)
+ return os.RemoveAll(dir)
+}
+
+// SandboxDBManager manages SQLite databases for all sandboxes on a worker.
+type SandboxDBManager struct {
+ dataDir string
+ mu sync.RWMutex
+ dbs map[string]*SandboxDB
+}
+
+// NewSandboxDBManager creates a new SandboxDB manager.
+func NewSandboxDBManager(dataDir string) *SandboxDBManager {
+ return &SandboxDBManager{
+ dataDir: dataDir,
+ dbs: make(map[string]*SandboxDB),
+ }
+}
+
+// Get returns the SandboxDB for a given sandbox, creating it if necessary.
+func (m *SandboxDBManager) Get(sandboxID string) (*SandboxDB, error) {
+ m.mu.RLock()
+ if db, ok := m.dbs[sandboxID]; ok {
+ m.mu.RUnlock()
+ return db, nil
+ }
+ m.mu.RUnlock()
+
+ m.mu.Lock()
+ defer m.mu.Unlock()
+
+ // Double-check after acquiring write lock
+ if db, ok := m.dbs[sandboxID]; ok {
+ return db, nil
+ }
+
+ db, err := OpenSandboxDB(m.dataDir, sandboxID)
+ if err != nil {
+ return nil, err
+ }
+ m.dbs[sandboxID] = db
+ return db, nil
+}
+
+// Remove closes and removes the database for a sandbox.
+func (m *SandboxDBManager) Remove(sandboxID string) error {
+ m.mu.Lock()
+ db, ok := m.dbs[sandboxID]
+ delete(m.dbs, sandboxID)
+ m.mu.Unlock()
+
+ if ok {
+ db.Close()
+ }
+ return RemoveSandboxData(m.dataDir, sandboxID)
+}
+
+// AllUnsyncedEvents collects unsynced events from all sandbox databases.
+func (m *SandboxDBManager) AllUnsyncedEvents(limitPerDB int) (map[string][]Event, error) {
+ m.mu.RLock()
+ defer m.mu.RUnlock()
+
+ result := make(map[string][]Event)
+ for id, db := range m.dbs {
+ events, err := db.GetUnsyncedEvents(limitPerDB)
+ if err != nil {
+ continue // Skip errored DBs, log in production
+ }
+ if len(events) > 0 {
+ result[id] = events
+ }
+ }
+ return result, nil
+}
+
+// MarkSynced marks events as synced in the given sandbox's database.
+func (m *SandboxDBManager) MarkSynced(sandboxID string, ids []int64) error {
+ m.mu.RLock()
+ db, ok := m.dbs[sandboxID]
+ m.mu.RUnlock()
+ if !ok {
+ return fmt.Errorf("sandbox %s not found", sandboxID)
+ }
+ return db.MarkEventsSynced(ids)
+}
+
+// Close closes all open databases.
+func (m *SandboxDBManager) Close() {
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ for _, db := range m.dbs {
+ db.Close()
+ }
+ m.dbs = make(map[string]*SandboxDB)
+}
+
+// GetAllUnsyncedEventsFlat returns all unsynced events across all sandboxes as a flat list
+// with sandbox ID attached, useful for the NATS event publisher.
+type SandboxEvent struct {
+ SandboxID string
+ Event Event
+ Timestamp time.Time
+}
+
+func (m *SandboxDBManager) GetAllUnsyncedEventsFlat(limitPerDB int) ([]SandboxEvent, error) {
+ grouped, err := m.AllUnsyncedEvents(limitPerDB)
+ if err != nil {
+ return nil, err
+ }
+
+ var flat []SandboxEvent
+ for sandboxID, events := range grouped {
+ for _, e := range events {
+ ts, _ := time.Parse("2006-01-02 15:04:05", e.CreatedAt)
+ flat = append(flat, SandboxEvent{
+ SandboxID: sandboxID,
+ Event: e,
+ Timestamp: ts,
+ })
+ }
+ }
+ return flat, nil
+}
diff --git a/internal/worker/event_publisher.go b/internal/worker/event_publisher.go
new file mode 100644
index 00000000..812885ee
--- /dev/null
+++ b/internal/worker/event_publisher.go
@@ -0,0 +1,177 @@
+package worker
+
+import (
+ "encoding/json"
+ "fmt"
+ "log"
+ "sync"
+ "time"
+
+ "github.com/nats-io/nats.go"
+ "github.com/opensandbox/opensandbox/internal/sandbox"
+)
+
+// EventPublisher publishes sandbox events from local SQLite to NATS JetStream.
+type EventPublisher struct {
+ nc *nats.Conn
+ js nats.JetStreamContext
+ sandboxDBs *sandbox.SandboxDBManager
+ region string
+ workerID string
+ stop chan struct{}
+ wg sync.WaitGroup
+}
+
+// NATSEvent is the JSON payload published to NATS.
+type NATSEvent struct {
+ Type string `json:"type"`
+ SandboxID string `json:"sandbox_id"`
+ WorkerID string `json:"worker_id"`
+ Region string `json:"region"`
+ Payload json.RawMessage `json:"payload"`
+ Timestamp time.Time `json:"timestamp"`
+}
+
+// NewEventPublisher creates a new NATS event publisher.
+func NewEventPublisher(natsURL, region, workerID string, sandboxDBs *sandbox.SandboxDBManager) (*EventPublisher, error) {
+ nc, err := nats.Connect(natsURL,
+ nats.RetryOnFailedConnect(true),
+ nats.MaxReconnects(-1),
+ nats.ReconnectWait(2*time.Second),
+ )
+ if err != nil {
+ return nil, fmt.Errorf("failed to connect to NATS: %w", err)
+ }
+
+ js, err := nc.JetStream()
+ if err != nil {
+ nc.Close()
+ return nil, fmt.Errorf("failed to get JetStream context: %w", err)
+ }
+
+ // Ensure the stream exists
+ _, err = js.AddStream(&nats.StreamConfig{
+ Name: "SANDBOX_EVENTS",
+ Subjects: []string{"sandbox.events.>"},
+ MaxAge: 7 * 24 * time.Hour, // Retain for 7 days
+ })
+ if err != nil {
+ // Stream may already exist, that's OK
+ log.Printf("event_publisher: stream setup: %v", err)
+ }
+
+ return &EventPublisher{
+ nc: nc,
+ js: js,
+ sandboxDBs: sandboxDBs,
+ region: region,
+ workerID: workerID,
+ stop: make(chan struct{}),
+ }, nil
+}
+
+// Start begins the event sync loop (every 2 seconds).
+func (p *EventPublisher) Start() {
+ p.wg.Add(1)
+ go func() {
+ defer p.wg.Done()
+ ticker := time.NewTicker(2 * time.Second)
+ defer ticker.Stop()
+
+ for {
+ select {
+ case <-ticker.C:
+ p.syncEvents()
+ case <-p.stop:
+ // Final flush
+ p.syncEvents()
+ return
+ }
+ }
+ }()
+}
+
+// Stop stops the event sync loop and closes the NATS connection.
+func (p *EventPublisher) Stop() {
+ close(p.stop)
+ p.wg.Wait()
+ p.nc.Close()
+}
+
+// PublishHeartbeat sends a worker heartbeat to NATS.
+func (p *EventPublisher) PublishHeartbeat(capacity, current int, cpuPct, memPct float64) {
+ subject := fmt.Sprintf("workers.heartbeat.%s.%s", p.region, p.workerID)
+ payload := map[string]interface{}{
+ "worker_id": p.workerID,
+ "region": p.region,
+ "capacity": capacity,
+ "current": current,
+ "cpu_pct": cpuPct,
+ "mem_pct": memPct,
+ }
+ data, _ := json.Marshal(payload)
+ if err := p.nc.Publish(subject, data); err != nil {
+ log.Printf("event_publisher: heartbeat publish error: %v", err)
+ }
+}
+
+// StartHeartbeat begins sending heartbeats every 5 seconds.
+func (p *EventPublisher) StartHeartbeat(getStats func() (capacity, current int, cpuPct, memPct float64)) {
+ p.wg.Add(1)
+ go func() {
+ defer p.wg.Done()
+ ticker := time.NewTicker(5 * time.Second)
+ defer ticker.Stop()
+
+ for {
+ select {
+ case <-ticker.C:
+ cap, cur, cpu, mem := getStats()
+ p.PublishHeartbeat(cap, cur, cpu, mem)
+ case <-p.stop:
+ return
+ }
+ }
+ }()
+}
+
+func (p *EventPublisher) syncEvents() {
+ events, err := p.sandboxDBs.GetAllUnsyncedEventsFlat(100)
+ if err != nil || len(events) == 0 {
+ return
+ }
+
+ // Group by sandbox for batch marking
+ synced := make(map[string][]int64)
+
+ for _, se := range events {
+ subject := fmt.Sprintf("sandbox.events.%s.%s", p.region, p.workerID)
+ natsEvent := NATSEvent{
+ Type: se.Event.Type,
+ SandboxID: se.SandboxID,
+ WorkerID: p.workerID,
+ Region: p.region,
+ Payload: json.RawMessage(se.Event.Payload),
+ Timestamp: se.Timestamp,
+ }
+ data, _ := json.Marshal(natsEvent)
+
+ if _, err := p.js.Publish(subject, data); err != nil {
+ log.Printf("event_publisher: publish error for sandbox %s: %v", se.SandboxID, err)
+ continue
+ }
+
+ synced[se.SandboxID] = append(synced[se.SandboxID], se.Event.ID)
+ }
+
+ // Mark synced events
+ for sandboxID, ids := range synced {
+ if err := p.sandboxDBs.MarkSynced(sandboxID, ids); err != nil {
+ log.Printf("event_publisher: mark synced error for sandbox %s: %v", sandboxID, err)
+ }
+ }
+
+ if total := len(events); total > 0 {
+ log.Printf("event_publisher: synced %d events to NATS", total)
+ }
+}
diff --git a/internal/worker/grpc_server.go b/internal/worker/grpc_server.go
new file mode 100644
index 00000000..fa0464de
--- /dev/null
+++ b/internal/worker/grpc_server.go
@@ -0,0 +1,210 @@
+package worker
+
+import (
+ "context"
+ "fmt"
+ "net"
+
+ "google.golang.org/grpc"
+
+ "github.com/opensandbox/opensandbox/internal/sandbox"
+ "github.com/opensandbox/opensandbox/pkg/types"
+ pb "github.com/opensandbox/opensandbox/proto/worker"
+)
+
+// GRPCServer implements the SandboxWorker gRPC service for control plane communication.
+type GRPCServer struct {
+ pb.UnimplementedSandboxWorkerServer
+ manager *sandbox.Manager
+ ptyManager *sandbox.PTYManager
+ sandboxDBs *sandbox.SandboxDBManager
+ server *grpc.Server
+}
+
+// NewGRPCServer creates a new gRPC server wrapping the sandbox manager.
+func NewGRPCServer(mgr *sandbox.Manager, ptyMgr *sandbox.PTYManager, sandboxDBs *sandbox.SandboxDBManager) *GRPCServer {
+ s := &GRPCServer{
+ manager: mgr,
+ ptyManager: ptyMgr,
+ sandboxDBs: sandboxDBs,
+ server: grpc.NewServer(),
+ }
+ pb.RegisterSandboxWorkerServer(s.server, s)
+ return s
+}
+
+// Start starts the gRPC server on the given address.
+func (s *GRPCServer) Start(addr string) error {
+ lis, err := net.Listen("tcp", addr)
+ if err != nil {
+ return fmt.Errorf("failed to listen on %s: %w", addr, err)
+ }
+ return s.server.Serve(lis)
+}
+
+// Stop gracefully stops the gRPC server.
+func (s *GRPCServer) Stop() {
+ s.server.GracefulStop()
+}
+
+func (s *GRPCServer) CreateSandbox(ctx context.Context, req *pb.CreateSandboxRequest) (*pb.CreateSandboxResponse, error) {
+ cfg := types.SandboxConfig{
+ Template: req.Template,
+ Timeout: int(req.Timeout),
+ Envs: req.Envs,
+ MemoryMB: int(req.MemoryMb),
+ CpuCount: int(req.CpuCount),
+ NetworkEnabled: req.NetworkEnabled,
+ }
+
+ sb, err := s.manager.Create(ctx, cfg)
+ if err != nil {
+ return nil, fmt.Errorf("failed to create sandbox: %w", err)
+ }
+
+ // Initialize per-sandbox SQLite
+ if s.sandboxDBs != nil {
+ sdb, err := s.sandboxDBs.Get(sb.ID)
+ if err == nil {
+ _ = sdb.LogEvent("created", map[string]string{
+ "sandbox_id": sb.ID,
+ "template": cfg.Template,
+ })
+ }
+ }
+
+ return &pb.CreateSandboxResponse{
+ SandboxId: sb.ID,
+ Status: string(sb.Status),
+ }, nil
+}
+
+func (s *GRPCServer) DestroySandbox(ctx context.Context, req *pb.DestroySandboxRequest) (*pb.DestroySandboxResponse, error) {
+ if err := s.manager.Kill(ctx, req.SandboxId); err != nil {
+ return nil, fmt.Errorf("failed to destroy sandbox: %w", err)
+ }
+
+ // Clean up SQLite
+ if s.sandboxDBs != nil {
+ _ = s.sandboxDBs.Remove(req.SandboxId)
+ }
+
+ return &pb.DestroySandboxResponse{}, nil
+}
+
+func (s *GRPCServer) GetSandbox(ctx context.Context, req *pb.GetSandboxRequest) (*pb.GetSandboxResponse, error) {
+ sb, err := s.manager.Get(ctx, req.SandboxId)
+ if err != nil {
+ return nil, fmt.Errorf("sandbox not found: %w", err)
+ }
+
+ return &pb.GetSandboxResponse{
+ SandboxId: sb.ID,
+ Status: string(sb.Status),
+ Template: sb.Template,
+ StartedAt: sb.StartedAt.Unix(),
+ EndAt: sb.EndAt.Unix(),
+ }, nil
+}
+
+func (s *GRPCServer) ListSandboxes(ctx context.Context, _ *pb.ListSandboxesRequest) (*pb.ListSandboxesResponse, error) {
+ sandboxes, err := s.manager.List(ctx)
+ if err != nil {
+ return nil, fmt.Errorf("failed to list sandboxes: %w", err)
+ }
+
+ var results []*pb.GetSandboxResponse
+ for _, sb := range sandboxes {
+ results = append(results, &pb.GetSandboxResponse{
+ SandboxId: sb.ID,
+ Status: string(sb.Status),
+ Template: sb.Template,
+ StartedAt: sb.StartedAt.Unix(),
+ EndAt: sb.EndAt.Unix(),
+ })
+ }
+
+ return &pb.ListSandboxesResponse{Sandboxes: results}, nil
+}
+
+func (s *GRPCServer) ExecCommand(ctx context.Context, req *pb.ExecCommandRequest) (*pb.ExecCommandResponse, error) {
+ cfg := types.ProcessConfig{
+ Command: req.Command,
+ Args: req.Args,
+ Env: req.Envs,
+ Cwd: req.Cwd,
+ Timeout: int(req.Timeout),
+ }
+
+ result, err := s.manager.Exec(ctx, req.SandboxId, cfg)
+ if err != nil {
+ return nil, fmt.Errorf("exec failed: %w", err)
+ }
+
+ return &pb.ExecCommandResponse{
+ ExitCode: int32(result.ExitCode),
+ Stdout: result.Stdout,
+ Stderr: result.Stderr,
+ }, nil
+}
+
+func (s *GRPCServer) ReadFile(ctx context.Context, req *pb.ReadFileRequest) (*pb.ReadFileResponse, error) {
+ content, err := s.manager.ReadFile(ctx, req.SandboxId, req.Path)
+ if err != nil {
+ return nil, fmt.Errorf("read file failed: %w", err)
+ }
+ return &pb.ReadFileResponse{Content: []byte(content)}, nil
+}
+
+func (s *GRPCServer) WriteFile(ctx context.Context, req *pb.WriteFileRequest) (*pb.WriteFileResponse, error) {
+ if err := s.manager.WriteFile(ctx, req.SandboxId, req.Path, string(req.Content)); err != nil {
+ return nil, fmt.Errorf("write file failed: %w", err)
+ }
+ return &pb.WriteFileResponse{}, nil
+}
+
+func (s *GRPCServer) ListDir(ctx context.Context, req *pb.ListDirRequest) (*pb.ListDirResponse, error) {
+ entries, err := s.manager.ListDir(ctx, req.SandboxId, req.Path)
+ if err != nil {
+ return nil, fmt.Errorf("list dir failed: %w", err)
+ }
+
+ var pbEntries []*pb.DirEntry
+ for _, e := range entries {
+ pbEntries = append(pbEntries, &pb.DirEntry{
+ Name: e.Name,
+ IsDir: e.IsDir,
+ Size: e.Size,
+ Path: e.Path,
+ })
+ }
+
+ return &pb.ListDirResponse{Entries: pbEntries}, nil
+}
+
+// ExecCommandStream and PTY streaming RPCs are not needed since
+// SDKs connect directly to the worker HTTP/WS server.
+// Stubbed out to satisfy the interface.
+
+func (s *GRPCServer) ExecCommandStream(_ *pb.ExecCommandRequest, _ pb.SandboxWorker_ExecCommandStreamServer) error {
+ return fmt.Errorf("streaming exec not implemented, use HTTP API directly")
+}
+
+func (s *GRPCServer) CreatePTY(ctx context.Context, req *pb.CreatePTYRequest) (*pb.CreatePTYResponse, error) {
+ ptyReq := types.PTYCreateRequest{
+ Cols: int(req.Cols),
+ Rows: int(req.Rows),
+ Shell: req.Shell,
+ }
+
+ session, err := s.ptyManager.CreateSession(req.SandboxId, ptyReq)
+ if err != nil {
+ return nil, fmt.Errorf("create PTY failed: %w", err)
+ }
+
+ return &pb.CreatePTYResponse{SessionId: session.ID}, nil
+}
+
+func (s *GRPCServer) PTYStream(_ pb.SandboxWorker_PTYStreamServer) error {
+ return fmt.Errorf("PTY streaming not implemented via gRPC, use WebSocket API directly")
+}
diff --git a/internal/worker/handlers.go b/internal/worker/handlers.go
new file mode 100644
index 00000000..24351637
--- /dev/null
+++ b/internal/worker/handlers.go
@@ -0,0 +1,216 @@
+package worker
+
+import (
+ "io"
+ "net/http"
+ "time"
+
+ "github.com/gorilla/websocket"
+ "github.com/labstack/echo/v4"
+ "github.com/opensandbox/opensandbox/pkg/types"
+)
+
+var upgrader = websocket.Upgrader{
+ CheckOrigin: func(r *http.Request) bool {
+ return true
+ },
+ ReadBufferSize: 1024,
+ WriteBufferSize: 1024,
+}
+
+func (s *HTTPServer) getSandbox(c echo.Context) error {
+ id := c.Param("id")
+ sb, err := s.manager.Get(c.Request().Context(), id)
+ if err != nil {
+ return c.JSON(http.StatusNotFound, map[string]string{"error": err.Error()})
+ }
+ return c.JSON(http.StatusOK, sb)
+}
+
+func (s *HTTPServer) runCommand(c echo.Context) error {
+ id := c.Param("id")
+
+ var cfg types.ProcessConfig
+ if err := c.Bind(&cfg); err != nil {
+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "invalid request body: " + err.Error()})
+ }
+ if cfg.Command == "" {
+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "cmd is required"})
+ }
+
+ start := time.Now()
+ result, err := s.manager.Exec(c.Request().Context(), id, cfg)
+ durationMs := int(time.Since(start).Milliseconds())
+
+ if err != nil {
+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})
+ }
+
+ // Log command to per-sandbox SQLite
+ if s.sandboxDBs != nil {
+ sdb, dbErr := s.sandboxDBs.Get(id)
+ if dbErr == nil {
+ _ = sdb.LogCommand(cfg.Command, cfg.Args, cfg.Cwd, result.ExitCode, durationMs, len(result.Stdout), len(result.Stderr))
+ }
+ }
+
+ return c.JSON(http.StatusOK, result)
+}
+
+func (s *HTTPServer) readFile(c echo.Context) error {
+ id := c.Param("id")
+ path := c.QueryParam("path")
+ if path == "" {
+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "path query parameter is required"})
+ }
+ content, err := s.manager.ReadFile(c.Request().Context(), id, path)
+ if err != nil {
+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})
+ }
+ return c.String(http.StatusOK, content)
+}
+
+func (s *HTTPServer) writeFile(c echo.Context) error {
+ id := c.Param("id")
+ path := c.QueryParam("path")
+ if path == "" {
+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "path query parameter is required"})
+ }
+ body, err := io.ReadAll(c.Request().Body)
+ if err != nil {
+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "failed to read request body: " + err.Error()})
+ }
+ if err := s.manager.WriteFile(c.Request().Context(), id, path, string(body)); err != nil {
+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})
+ }
+ return c.NoContent(http.StatusNoContent)
+}
+
+func (s *HTTPServer) listDir(c echo.Context) error {
+ id := c.Param("id")
+ path := c.QueryParam("path")
+ if path == "" {
+ path = "/"
+ }
+ entries, err := s.manager.ListDir(c.Request().Context(), id, path)
+ if err != nil {
+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})
+ }
+ return c.JSON(http.StatusOK, entries)
+}
+
+func (s *HTTPServer) makeDir(c echo.Context) error {
+ id := c.Param("id")
+ path := c.QueryParam("path")
+ if path == "" {
+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "path query parameter is required"})
+ }
+ if err := s.manager.MakeDir(c.Request().Context(), id, path); err != nil {
+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})
+ }
+ return c.NoContent(http.StatusNoContent)
+}
+
+func (s *HTTPServer) removeFile(c echo.Context) error {
+ id := c.Param("id")
+ path := c.QueryParam("path")
+ if path == "" {
+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "path query parameter is required"})
+ }
+ if err := s.manager.Remove(c.Request().Context(), id, path); err != nil {
+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})
+ }
+ return c.NoContent(http.StatusNoContent)
+}
+
+func (s *HTTPServer) createPTY(c echo.Context) error {
+ id := c.Param("id")
+
+ var req types.PTYCreateRequest
+ if err := c.Bind(&req); err != nil {
+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "invalid request body: " + err.Error()})
+ }
+
+ session, err := s.ptyManager.CreateSession(id, req)
+ if err != nil {
+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})
+ }
+
+ // Log PTY start to SQLite
+ if s.sandboxDBs != nil {
+ sdb, dbErr := s.sandboxDBs.Get(id)
+ if dbErr == nil {
+ _ = sdb.LogPTYStart(session.ID)
+ }
+ }
+
+ return c.JSON(http.StatusCreated, types.PTYSession{
+ SessionID: session.ID,
+ SandboxID: id,
+ })
+}
+
+func (s *HTTPServer) ptyWebSocket(c echo.Context) error {
+ sessionID := c.Param("sessionID")
+
+ session, err := s.ptyManager.GetSession(sessionID)
+ if err != nil {
+ return c.JSON(http.StatusNotFound, map[string]string{"error": err.Error()})
+ }
+
+ ws, err := upgrader.Upgrade(c.Response(), c.Request(), nil)
+ if err != nil {
+ return err
+ }
+ defer ws.Close()
+
+ done := make(chan struct{})
+ go func() {
+ defer close(done)
+ buf := make([]byte, 4096)
+ for {
+ n, err := session.PTY.Read(buf)
+ if n > 0 {
+ if writeErr := ws.WriteMessage(websocket.BinaryMessage, buf[:n]); writeErr != nil {
+ return
+ }
+ }
+ if err != nil {
+ return
+ }
+ }
+ }()
+
+ go func() {
+ for {
+ _, msg, err := ws.ReadMessage()
+ if err != nil {
+ return
+ }
+ if _, err := session.PTY.Write(msg); err != nil {
+ return
+ }
+ }
+ }()
+
+ select {
+ case <-done:
+ case <-session.Done:
+ }
+
+ ws.WriteControl(websocket.CloseMessage,
+ websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""),
+ time.Now().Add(time.Second))
+
+ return nil
+}
+
+func (s *HTTPServer) killPTY(c echo.Context) error {
+ sessionID := c.Param("sessionID")
+
+ if err := s.ptyManager.KillSession(sessionID); err != nil {
+ return c.JSON(http.StatusNotFound, map[string]string{"error": err.Error()})
+ }
+
+ return c.NoContent(http.StatusNoContent)
+}
diff --git a/internal/worker/http_server.go b/internal/worker/http_server.go
new file mode 100644
index 00000000..1aed4fa1
--- /dev/null
+++ b/internal/worker/http_server.go
@@ -0,0 +1,80 @@
+package worker
+
+import (
+ "net/http"
+
+ "github.com/labstack/echo/v4"
+ "github.com/labstack/echo/v4/middleware"
+ "github.com/opensandbox/opensandbox/internal/auth"
+ "github.com/opensandbox/opensandbox/internal/sandbox"
+)
+
+// HTTPServer serves the REST/WebSocket API for direct SDK access on the worker.
+// It exposes the same endpoints as the control plane but authenticates via sandbox-scoped JWTs.
+type HTTPServer struct {
+ echo *echo.Echo
+ manager *sandbox.Manager
+ ptyManager *sandbox.PTYManager
+ jwtIssuer *auth.JWTIssuer
+ sandboxDBs *sandbox.SandboxDBManager
+}
+
+// NewHTTPServer creates a new worker HTTP server for direct SDK access.
+func NewHTTPServer(mgr *sandbox.Manager, ptyMgr *sandbox.PTYManager, jwtIssuer *auth.JWTIssuer, sandboxDBs *sandbox.SandboxDBManager) *HTTPServer {
+ e := echo.New()
+ e.HideBanner = true
+ e.HidePort = true
+
+ s := &HTTPServer{
+ echo: e,
+ manager: mgr,
+ ptyManager: ptyMgr,
+ jwtIssuer: jwtIssuer,
+ sandboxDBs: sandboxDBs,
+ }
+
+ // Global middleware
+ e.Use(middleware.Recover())
+ e.Use(middleware.Logger())
+ e.Use(middleware.CORS())
+ e.Use(middleware.RequestID())
+
+ // Health check (no auth)
+ e.GET("/health", func(c echo.Context) error {
+ return c.JSON(http.StatusOK, map[string]string{"status": "ok", "role": "worker"})
+ })
+
+ // All sandbox routes require JWT auth
+ api := e.Group("")
+ api.Use(auth.SandboxJWTMiddleware(jwtIssuer))
+
+ // Sandbox status
+ api.GET("/sandboxes/:id", s.getSandbox)
+
+ // Commands
+ api.POST("/sandboxes/:id/commands", s.runCommand)
+
+ // Filesystem
+ api.GET("/sandboxes/:id/files", s.readFile)
+ api.PUT("/sandboxes/:id/files", s.writeFile)
+ api.GET("/sandboxes/:id/files/list", s.listDir)
+ api.POST("/sandboxes/:id/files/mkdir", s.makeDir)
+ api.DELETE("/sandboxes/:id/files", s.removeFile)
+
+ // PTY
+ api.POST("/sandboxes/:id/pty", s.createPTY)
+ api.GET("/sandboxes/:id/pty/:sessionID", s.ptyWebSocket)
+ api.DELETE("/sandboxes/:id/pty/:sessionID", s.killPTY)
+
+ return s
+}
+
+// Start starts the HTTP server on the given address.
+func (s *HTTPServer) Start(addr string) error {
+ return s.echo.Start(addr)
+}
+
+// Close gracefully shuts down the server.
+func (s *HTTPServer) Close() error {
+ return s.echo.Close()
+}
diff --git a/pkg/types/sandbox.go b/pkg/types/sandbox.go
index 75779ab9..ea9bd839 100644
--- a/pkg/types/sandbox.go
+++ b/pkg/types/sandbox.go
@@ -24,6 +24,8 @@ type Sandbox struct {
CpuCount int `json:"cpuCount"`
MemoryMB int `json:"memoryMB"`
MachineID string `json:"machineID,omitempty"`
+ ConnectURL string `json:"connectURL,omitempty"` // Direct worker URL for SDK access
+ Token string `json:"token,omitempty"` // Sandbox-scoped JWT for worker auth
}
// SandboxConfig is the request body for creating a sandbox.
diff --git a/proto/worker/worker.pb.go b/proto/worker/worker.pb.go
new file mode 100644
index 00000000..a66605d5
--- /dev/null
+++ b/proto/worker/worker.pb.go
@@ -0,0 +1,1568 @@
+// Code generated by protoc-gen-go. DO NOT EDIT.
+// versions:
+// protoc-gen-go v1.36.11
+// protoc v5.29.3
+// source: proto/worker/worker.proto
+
+package worker
+
+import (
+ protoreflect "google.golang.org/protobuf/reflect/protoreflect"
+ protoimpl "google.golang.org/protobuf/runtime/protoimpl"
+ reflect "reflect"
+ sync "sync"
+ unsafe "unsafe"
+)
+
+const (
+ // Verify that this generated code is sufficiently up-to-date.
+ _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
+ // Verify that runtime/protoimpl is sufficiently up-to-date.
+ _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
+)
+
+type ExecOutputChunk_Stream int32
+
+const (
+ ExecOutputChunk_STDOUT ExecOutputChunk_Stream = 0
+ ExecOutputChunk_STDERR ExecOutputChunk_Stream = 1
+)
+
+// Enum value maps for ExecOutputChunk_Stream.
+var (
+ ExecOutputChunk_Stream_name = map[int32]string{
+ 0: "STDOUT",
+ 1: "STDERR",
+ }
+ ExecOutputChunk_Stream_value = map[string]int32{
+ "STDOUT": 0,
+ "STDERR": 1,
+ }
+)
+
+func (x ExecOutputChunk_Stream) Enum() *ExecOutputChunk_Stream {
+ p := new(ExecOutputChunk_Stream)
+ *p = x
+ return p
+}
+
+func (x ExecOutputChunk_Stream) String() string {
+ return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x))
+}
+
+func (ExecOutputChunk_Stream) Descriptor() protoreflect.EnumDescriptor {
+ return file_proto_worker_worker_proto_enumTypes[0].Descriptor()
+}
+
+func (ExecOutputChunk_Stream) Type() protoreflect.EnumType {
+ return &file_proto_worker_worker_proto_enumTypes[0]
+}
+
+func (x ExecOutputChunk_Stream) Number() protoreflect.EnumNumber {
+ return protoreflect.EnumNumber(x)
+}
+
+// Deprecated: Use ExecOutputChunk_Stream.Descriptor instead.
+func (ExecOutputChunk_Stream) EnumDescriptor() ([]byte, []int) {
+ return file_proto_worker_worker_proto_rawDescGZIP(), []int{10, 0}
+}
+
+type CreateSandboxRequest struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ Template string `protobuf:"bytes,1,opt,name=template,proto3" json:"template,omitempty"`
+ Timeout int32 `protobuf:"varint,2,opt,name=timeout,proto3" json:"timeout,omitempty"`
+ Envs map[string]string `protobuf:"bytes,3,rep,name=envs,proto3" json:"envs,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"`
+ MemoryMb int32 `protobuf:"varint,4,opt,name=memory_mb,json=memoryMb,proto3" json:"memory_mb,omitempty"`
+ CpuCount int32 `protobuf:"varint,5,opt,name=cpu_count,json=cpuCount,proto3" json:"cpu_count,omitempty"`
+ NetworkEnabled bool `protobuf:"varint,6,opt,name=network_enabled,json=networkEnabled,proto3" json:"network_enabled,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *CreateSandboxRequest) Reset() {
+ *x = CreateSandboxRequest{}
+ mi := &file_proto_worker_worker_proto_msgTypes[0]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *CreateSandboxRequest) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*CreateSandboxRequest) ProtoMessage() {}
+
+func (x *CreateSandboxRequest) ProtoReflect() protoreflect.Message {
+ mi := &file_proto_worker_worker_proto_msgTypes[0]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use CreateSandboxRequest.ProtoReflect.Descriptor instead.
+func (*CreateSandboxRequest) Descriptor() ([]byte, []int) {
+ return file_proto_worker_worker_proto_rawDescGZIP(), []int{0}
+}
+
+func (x *CreateSandboxRequest) GetTemplate() string {
+ if x != nil {
+ return x.Template
+ }
+ return ""
+}
+
+func (x *CreateSandboxRequest) GetTimeout() int32 {
+ if x != nil {
+ return x.Timeout
+ }
+ return 0
+}
+
+func (x *CreateSandboxRequest) GetEnvs() map[string]string {
+ if x != nil {
+ return x.Envs
+ }
+ return nil
+}
+
+func (x *CreateSandboxRequest) GetMemoryMb() int32 {
+ if x != nil {
+ return x.MemoryMb
+ }
+ return 0
+}
+
+func (x *CreateSandboxRequest) GetCpuCount() int32 {
+ if x != nil {
+ return x.CpuCount
+ }
+ return 0
+}
+
+func (x *CreateSandboxRequest) GetNetworkEnabled() bool {
+ if x != nil {
+ return x.NetworkEnabled
+ }
+ return false
+}
+
+type CreateSandboxResponse struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ SandboxId string `protobuf:"bytes,1,opt,name=sandbox_id,json=sandboxId,proto3" json:"sandbox_id,omitempty"`
+ Status string `protobuf:"bytes,2,opt,name=status,proto3" json:"status,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *CreateSandboxResponse) Reset() {
+ *x = CreateSandboxResponse{}
+ mi := &file_proto_worker_worker_proto_msgTypes[1]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *CreateSandboxResponse) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*CreateSandboxResponse) ProtoMessage() {}
+
+func (x *CreateSandboxResponse) ProtoReflect() protoreflect.Message {
+ mi := &file_proto_worker_worker_proto_msgTypes[1]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use CreateSandboxResponse.ProtoReflect.Descriptor instead.
+func (*CreateSandboxResponse) Descriptor() ([]byte, []int) {
+ return file_proto_worker_worker_proto_rawDescGZIP(), []int{1}
+}
+
+func (x *CreateSandboxResponse) GetSandboxId() string {
+ if x != nil {
+ return x.SandboxId
+ }
+ return ""
+}
+
+func (x *CreateSandboxResponse) GetStatus() string {
+ if x != nil {
+ return x.Status
+ }
+ return ""
+}
+
+type DestroySandboxRequest struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ SandboxId string `protobuf:"bytes,1,opt,name=sandbox_id,json=sandboxId,proto3" json:"sandbox_id,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *DestroySandboxRequest) Reset() {
+ *x = DestroySandboxRequest{}
+ mi := &file_proto_worker_worker_proto_msgTypes[2]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *DestroySandboxRequest) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*DestroySandboxRequest) ProtoMessage() {}
+
+func (x *DestroySandboxRequest) ProtoReflect() protoreflect.Message {
+ mi := &file_proto_worker_worker_proto_msgTypes[2]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use DestroySandboxRequest.ProtoReflect.Descriptor instead.
+func (*DestroySandboxRequest) Descriptor() ([]byte, []int) {
+ return file_proto_worker_worker_proto_rawDescGZIP(), []int{2}
+}
+
+func (x *DestroySandboxRequest) GetSandboxId() string {
+ if x != nil {
+ return x.SandboxId
+ }
+ return ""
+}
+
+type DestroySandboxResponse struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *DestroySandboxResponse) Reset() {
+ *x = DestroySandboxResponse{}
+ mi := &file_proto_worker_worker_proto_msgTypes[3]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *DestroySandboxResponse) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*DestroySandboxResponse) ProtoMessage() {}
+
+func (x *DestroySandboxResponse) ProtoReflect() protoreflect.Message {
+ mi := &file_proto_worker_worker_proto_msgTypes[3]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use DestroySandboxResponse.ProtoReflect.Descriptor instead.
+func (*DestroySandboxResponse) Descriptor() ([]byte, []int) {
+ return file_proto_worker_worker_proto_rawDescGZIP(), []int{3}
+}
+
+type GetSandboxRequest struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ SandboxId string `protobuf:"bytes,1,opt,name=sandbox_id,json=sandboxId,proto3" json:"sandbox_id,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *GetSandboxRequest) Reset() {
+ *x = GetSandboxRequest{}
+ mi := &file_proto_worker_worker_proto_msgTypes[4]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *GetSandboxRequest) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*GetSandboxRequest) ProtoMessage() {}
+
+func (x *GetSandboxRequest) ProtoReflect() protoreflect.Message {
+ mi := &file_proto_worker_worker_proto_msgTypes[4]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use GetSandboxRequest.ProtoReflect.Descriptor instead.
+func (*GetSandboxRequest) Descriptor() ([]byte, []int) {
+ return file_proto_worker_worker_proto_rawDescGZIP(), []int{4}
+}
+
+func (x *GetSandboxRequest) GetSandboxId() string {
+ if x != nil {
+ return x.SandboxId
+ }
+ return ""
+}
+
+type GetSandboxResponse struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ SandboxId string `protobuf:"bytes,1,opt,name=sandbox_id,json=sandboxId,proto3" json:"sandbox_id,omitempty"`
+ Status string `protobuf:"bytes,2,opt,name=status,proto3" json:"status,omitempty"`
+ Template string `protobuf:"bytes,3,opt,name=template,proto3" json:"template,omitempty"`
+ StartedAt int64 `protobuf:"varint,4,opt,name=started_at,json=startedAt,proto3" json:"started_at,omitempty"`
+ EndAt int64 `protobuf:"varint,5,opt,name=end_at,json=endAt,proto3" json:"end_at,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *GetSandboxResponse) Reset() {
+ *x = GetSandboxResponse{}
+ mi := &file_proto_worker_worker_proto_msgTypes[5]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *GetSandboxResponse) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*GetSandboxResponse) ProtoMessage() {}
+
+func (x *GetSandboxResponse) ProtoReflect() protoreflect.Message {
+ mi := &file_proto_worker_worker_proto_msgTypes[5]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use GetSandboxResponse.ProtoReflect.Descriptor instead.
+func (*GetSandboxResponse) Descriptor() ([]byte, []int) {
+ return file_proto_worker_worker_proto_rawDescGZIP(), []int{5}
+}
+
+func (x *GetSandboxResponse) GetSandboxId() string {
+ if x != nil {
+ return x.SandboxId
+ }
+ return ""
+}
+
+func (x *GetSandboxResponse) GetStatus() string {
+ if x != nil {
+ return x.Status
+ }
+ return ""
+}
+
+func (x *GetSandboxResponse) GetTemplate() string {
+ if x != nil {
+ return x.Template
+ }
+ return ""
+}
+
+func (x *GetSandboxResponse) GetStartedAt() int64 {
+ if x != nil {
+ return x.StartedAt
+ }
+ return 0
+}
+
+func (x *GetSandboxResponse) GetEndAt() int64 {
+ if x != nil {
+ return x.EndAt
+ }
+ return 0
+}
+
+type ListSandboxesRequest struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *ListSandboxesRequest) Reset() {
+ *x = ListSandboxesRequest{}
+ mi := &file_proto_worker_worker_proto_msgTypes[6]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *ListSandboxesRequest) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*ListSandboxesRequest) ProtoMessage() {}
+
+func (x *ListSandboxesRequest) ProtoReflect() protoreflect.Message {
+ mi := &file_proto_worker_worker_proto_msgTypes[6]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use ListSandboxesRequest.ProtoReflect.Descriptor instead.
+func (*ListSandboxesRequest) Descriptor() ([]byte, []int) {
+ return file_proto_worker_worker_proto_rawDescGZIP(), []int{6}
+}
+
+type ListSandboxesResponse struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ Sandboxes []*GetSandboxResponse `protobuf:"bytes,1,rep,name=sandboxes,proto3" json:"sandboxes,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *ListSandboxesResponse) Reset() {
+ *x = ListSandboxesResponse{}
+ mi := &file_proto_worker_worker_proto_msgTypes[7]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *ListSandboxesResponse) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*ListSandboxesResponse) ProtoMessage() {}
+
+func (x *ListSandboxesResponse) ProtoReflect() protoreflect.Message {
+ mi := &file_proto_worker_worker_proto_msgTypes[7]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use ListSandboxesResponse.ProtoReflect.Descriptor instead.
+func (*ListSandboxesResponse) Descriptor() ([]byte, []int) {
+ return file_proto_worker_worker_proto_rawDescGZIP(), []int{7}
+}
+
+func (x *ListSandboxesResponse) GetSandboxes() []*GetSandboxResponse {
+ if x != nil {
+ return x.Sandboxes
+ }
+ return nil
+}
+
+type ExecCommandRequest struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ SandboxId string `protobuf:"bytes,1,opt,name=sandbox_id,json=sandboxId,proto3" json:"sandbox_id,omitempty"`
+ Command string `protobuf:"bytes,2,opt,name=command,proto3" json:"command,omitempty"`
+ Args []string `protobuf:"bytes,3,rep,name=args,proto3" json:"args,omitempty"`
+ Envs map[string]string `protobuf:"bytes,4,rep,name=envs,proto3" json:"envs,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"`
+ Cwd string `protobuf:"bytes,5,opt,name=cwd,proto3" json:"cwd,omitempty"`
+ Timeout int32 `protobuf:"varint,6,opt,name=timeout,proto3" json:"timeout,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *ExecCommandRequest) Reset() {
+ *x = ExecCommandRequest{}
+ mi := &file_proto_worker_worker_proto_msgTypes[8]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *ExecCommandRequest) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*ExecCommandRequest) ProtoMessage() {}
+
+func (x *ExecCommandRequest) ProtoReflect() protoreflect.Message {
+ mi := &file_proto_worker_worker_proto_msgTypes[8]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use ExecCommandRequest.ProtoReflect.Descriptor instead.
+func (*ExecCommandRequest) Descriptor() ([]byte, []int) {
+ return file_proto_worker_worker_proto_rawDescGZIP(), []int{8}
+}
+
+func (x *ExecCommandRequest) GetSandboxId() string {
+ if x != nil {
+ return x.SandboxId
+ }
+ return ""
+}
+
+func (x *ExecCommandRequest) GetCommand() string {
+ if x != nil {
+ return x.Command
+ }
+ return ""
+}
+
+func (x *ExecCommandRequest) GetArgs() []string {
+ if x != nil {
+ return x.Args
+ }
+ return nil
+}
+
+func (x *ExecCommandRequest) GetEnvs() map[string]string {
+ if x != nil {
+ return x.Envs
+ }
+ return nil
+}
+
+func (x *ExecCommandRequest) GetCwd() string {
+ if x != nil {
+ return x.Cwd
+ }
+ return ""
+}
+
+func (x *ExecCommandRequest) GetTimeout() int32 {
+ if x != nil {
+ return x.Timeout
+ }
+ return 0
+}
+
+type ExecCommandResponse struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ ExitCode int32 `protobuf:"varint,1,opt,name=exit_code,json=exitCode,proto3" json:"exit_code,omitempty"`
+ Stdout string `protobuf:"bytes,2,opt,name=stdout,proto3" json:"stdout,omitempty"`
+ Stderr string `protobuf:"bytes,3,opt,name=stderr,proto3" json:"stderr,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *ExecCommandResponse) Reset() {
+ *x = ExecCommandResponse{}
+ mi := &file_proto_worker_worker_proto_msgTypes[9]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *ExecCommandResponse) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*ExecCommandResponse) ProtoMessage() {}
+
+func (x *ExecCommandResponse) ProtoReflect() protoreflect.Message {
+ mi := &file_proto_worker_worker_proto_msgTypes[9]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use ExecCommandResponse.ProtoReflect.Descriptor instead.
+func (*ExecCommandResponse) Descriptor() ([]byte, []int) {
+ return file_proto_worker_worker_proto_rawDescGZIP(), []int{9}
+}
+
+func (x *ExecCommandResponse) GetExitCode() int32 {
+ if x != nil {
+ return x.ExitCode
+ }
+ return 0
+}
+
+func (x *ExecCommandResponse) GetStdout() string {
+ if x != nil {
+ return x.Stdout
+ }
+ return ""
+}
+
+func (x *ExecCommandResponse) GetStderr() string {
+ if x != nil {
+ return x.Stderr
+ }
+ return ""
+}
+
+type ExecOutputChunk struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ Stream ExecOutputChunk_Stream `protobuf:"varint,1,opt,name=stream,proto3,enum=worker.ExecOutputChunk_Stream" json:"stream,omitempty"`
+ Data []byte `protobuf:"bytes,2,opt,name=data,proto3" json:"data,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *ExecOutputChunk) Reset() {
+ *x = ExecOutputChunk{}
+ mi := &file_proto_worker_worker_proto_msgTypes[10]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *ExecOutputChunk) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*ExecOutputChunk) ProtoMessage() {}
+
+func (x *ExecOutputChunk) ProtoReflect() protoreflect.Message {
+ mi := &file_proto_worker_worker_proto_msgTypes[10]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use ExecOutputChunk.ProtoReflect.Descriptor instead.
+func (*ExecOutputChunk) Descriptor() ([]byte, []int) {
+ return file_proto_worker_worker_proto_rawDescGZIP(), []int{10}
+}
+
+func (x *ExecOutputChunk) GetStream() ExecOutputChunk_Stream {
+ if x != nil {
+ return x.Stream
+ }
+ return ExecOutputChunk_STDOUT
+}
+
+func (x *ExecOutputChunk) GetData() []byte {
+ if x != nil {
+ return x.Data
+ }
+ return nil
+}
+
+type ReadFileRequest struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ SandboxId string `protobuf:"bytes,1,opt,name=sandbox_id,json=sandboxId,proto3" json:"sandbox_id,omitempty"`
+ Path string `protobuf:"bytes,2,opt,name=path,proto3" json:"path,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *ReadFileRequest) Reset() {
+ *x = ReadFileRequest{}
+ mi := &file_proto_worker_worker_proto_msgTypes[11]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *ReadFileRequest) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*ReadFileRequest) ProtoMessage() {}
+
+func (x *ReadFileRequest) ProtoReflect() protoreflect.Message {
+ mi := &file_proto_worker_worker_proto_msgTypes[11]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use ReadFileRequest.ProtoReflect.Descriptor instead.
+func (*ReadFileRequest) Descriptor() ([]byte, []int) {
+ return file_proto_worker_worker_proto_rawDescGZIP(), []int{11}
+}
+
+func (x *ReadFileRequest) GetSandboxId() string {
+ if x != nil {
+ return x.SandboxId
+ }
+ return ""
+}
+
+func (x *ReadFileRequest) GetPath() string {
+ if x != nil {
+ return x.Path
+ }
+ return ""
+}
+
+type ReadFileResponse struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ Content []byte `protobuf:"bytes,1,opt,name=content,proto3" json:"content,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *ReadFileResponse) Reset() {
+ *x = ReadFileResponse{}
+ mi := &file_proto_worker_worker_proto_msgTypes[12]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *ReadFileResponse) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*ReadFileResponse) ProtoMessage() {}
+
+func (x *ReadFileResponse) ProtoReflect() protoreflect.Message {
+ mi := &file_proto_worker_worker_proto_msgTypes[12]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use ReadFileResponse.ProtoReflect.Descriptor instead.
+func (*ReadFileResponse) Descriptor() ([]byte, []int) {
+ return file_proto_worker_worker_proto_rawDescGZIP(), []int{12}
+}
+
+func (x *ReadFileResponse) GetContent() []byte {
+ if x != nil {
+ return x.Content
+ }
+ return nil
+}
+
+type WriteFileRequest struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ SandboxId string `protobuf:"bytes,1,opt,name=sandbox_id,json=sandboxId,proto3" json:"sandbox_id,omitempty"`
+ Path string `protobuf:"bytes,2,opt,name=path,proto3" json:"path,omitempty"`
+ Content []byte `protobuf:"bytes,3,opt,name=content,proto3" json:"content,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *WriteFileRequest) Reset() {
+ *x = WriteFileRequest{}
+ mi := &file_proto_worker_worker_proto_msgTypes[13]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *WriteFileRequest) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*WriteFileRequest) ProtoMessage() {}
+
+func (x *WriteFileRequest) ProtoReflect() protoreflect.Message {
+ mi := &file_proto_worker_worker_proto_msgTypes[13]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use WriteFileRequest.ProtoReflect.Descriptor instead.
+func (*WriteFileRequest) Descriptor() ([]byte, []int) {
+ return file_proto_worker_worker_proto_rawDescGZIP(), []int{13}
+}
+
+func (x *WriteFileRequest) GetSandboxId() string {
+ if x != nil {
+ return x.SandboxId
+ }
+ return ""
+}
+
+func (x *WriteFileRequest) GetPath() string {
+ if x != nil {
+ return x.Path
+ }
+ return ""
+}
+
+func (x *WriteFileRequest) GetContent() []byte {
+ if x != nil {
+ return x.Content
+ }
+ return nil
+}
+
+type WriteFileResponse struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *WriteFileResponse) Reset() {
+ *x = WriteFileResponse{}
+ mi := &file_proto_worker_worker_proto_msgTypes[14]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *WriteFileResponse) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*WriteFileResponse) ProtoMessage() {}
+
+func (x *WriteFileResponse) ProtoReflect() protoreflect.Message {
+ mi := &file_proto_worker_worker_proto_msgTypes[14]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use WriteFileResponse.ProtoReflect.Descriptor instead.
+func (*WriteFileResponse) Descriptor() ([]byte, []int) {
+ return file_proto_worker_worker_proto_rawDescGZIP(), []int{14}
+}
+
+type ListDirRequest struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ SandboxId string `protobuf:"bytes,1,opt,name=sandbox_id,json=sandboxId,proto3" json:"sandbox_id,omitempty"`
+ Path string `protobuf:"bytes,2,opt,name=path,proto3" json:"path,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *ListDirRequest) Reset() {
+ *x = ListDirRequest{}
+ mi := &file_proto_worker_worker_proto_msgTypes[15]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *ListDirRequest) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*ListDirRequest) ProtoMessage() {}
+
+func (x *ListDirRequest) ProtoReflect() protoreflect.Message {
+ mi := &file_proto_worker_worker_proto_msgTypes[15]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use ListDirRequest.ProtoReflect.Descriptor instead.
+func (*ListDirRequest) Descriptor() ([]byte, []int) {
+ return file_proto_worker_worker_proto_rawDescGZIP(), []int{15}
+}
+
+func (x *ListDirRequest) GetSandboxId() string {
+ if x != nil {
+ return x.SandboxId
+ }
+ return ""
+}
+
+func (x *ListDirRequest) GetPath() string {
+ if x != nil {
+ return x.Path
+ }
+ return ""
+}
+
+type DirEntry struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`
+ IsDir bool `protobuf:"varint,2,opt,name=is_dir,json=isDir,proto3" json:"is_dir,omitempty"`
+ Size int64 `protobuf:"varint,3,opt,name=size,proto3" json:"size,omitempty"`
+ Path string `protobuf:"bytes,4,opt,name=path,proto3" json:"path,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *DirEntry) Reset() {
+ *x = DirEntry{}
+ mi := &file_proto_worker_worker_proto_msgTypes[16]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *DirEntry) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*DirEntry) ProtoMessage() {}
+
+func (x *DirEntry) ProtoReflect() protoreflect.Message {
+ mi := &file_proto_worker_worker_proto_msgTypes[16]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use DirEntry.ProtoReflect.Descriptor instead.
+func (*DirEntry) Descriptor() ([]byte, []int) {
+ return file_proto_worker_worker_proto_rawDescGZIP(), []int{16}
+}
+
+func (x *DirEntry) GetName() string {
+ if x != nil {
+ return x.Name
+ }
+ return ""
+}
+
+func (x *DirEntry) GetIsDir() bool {
+ if x != nil {
+ return x.IsDir
+ }
+ return false
+}
+
+func (x *DirEntry) GetSize() int64 {
+ if x != nil {
+ return x.Size
+ }
+ return 0
+}
+
+func (x *DirEntry) GetPath() string {
+ if x != nil {
+ return x.Path
+ }
+ return ""
+}
+
+type ListDirResponse struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ Entries []*DirEntry `protobuf:"bytes,1,rep,name=entries,proto3" json:"entries,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *ListDirResponse) Reset() {
+ *x = ListDirResponse{}
+ mi := &file_proto_worker_worker_proto_msgTypes[17]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *ListDirResponse) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*ListDirResponse) ProtoMessage() {}
+
+func (x *ListDirResponse) ProtoReflect() protoreflect.Message {
+ mi := &file_proto_worker_worker_proto_msgTypes[17]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use ListDirResponse.ProtoReflect.Descriptor instead.
+func (*ListDirResponse) Descriptor() ([]byte, []int) {
+ return file_proto_worker_worker_proto_rawDescGZIP(), []int{17}
+}
+
+func (x *ListDirResponse) GetEntries() []*DirEntry {
+ if x != nil {
+ return x.Entries
+ }
+ return nil
+}
+
+type CreatePTYRequest struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ SandboxId string `protobuf:"bytes,1,opt,name=sandbox_id,json=sandboxId,proto3" json:"sandbox_id,omitempty"`
+ Cols int32 `protobuf:"varint,2,opt,name=cols,proto3" json:"cols,omitempty"`
+ Rows int32 `protobuf:"varint,3,opt,name=rows,proto3" json:"rows,omitempty"`
+ Shell string `protobuf:"bytes,4,opt,name=shell,proto3" json:"shell,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *CreatePTYRequest) Reset() {
+ *x = CreatePTYRequest{}
+ mi := &file_proto_worker_worker_proto_msgTypes[18]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *CreatePTYRequest) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*CreatePTYRequest) ProtoMessage() {}
+
+func (x *CreatePTYRequest) ProtoReflect() protoreflect.Message {
+ mi := &file_proto_worker_worker_proto_msgTypes[18]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use CreatePTYRequest.ProtoReflect.Descriptor instead.
+func (*CreatePTYRequest) Descriptor() ([]byte, []int) {
+ return file_proto_worker_worker_proto_rawDescGZIP(), []int{18}
+}
+
+func (x *CreatePTYRequest) GetSandboxId() string {
+ if x != nil {
+ return x.SandboxId
+ }
+ return ""
+}
+
+func (x *CreatePTYRequest) GetCols() int32 {
+ if x != nil {
+ return x.Cols
+ }
+ return 0
+}
+
+func (x *CreatePTYRequest) GetRows() int32 {
+ if x != nil {
+ return x.Rows
+ }
+ return 0
+}
+
+func (x *CreatePTYRequest) GetShell() string {
+ if x != nil {
+ return x.Shell
+ }
+ return ""
+}
+
+type CreatePTYResponse struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ SessionId string `protobuf:"bytes,1,opt,name=session_id,json=sessionId,proto3" json:"session_id,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *CreatePTYResponse) Reset() {
+ *x = CreatePTYResponse{}
+ mi := &file_proto_worker_worker_proto_msgTypes[19]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *CreatePTYResponse) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*CreatePTYResponse) ProtoMessage() {}
+
+func (x *CreatePTYResponse) ProtoReflect() protoreflect.Message {
+ mi := &file_proto_worker_worker_proto_msgTypes[19]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use CreatePTYResponse.ProtoReflect.Descriptor instead.
+func (*CreatePTYResponse) Descriptor() ([]byte, []int) {
+ return file_proto_worker_worker_proto_rawDescGZIP(), []int{19}
+}
+
+func (x *CreatePTYResponse) GetSessionId() string {
+ if x != nil {
+ return x.SessionId
+ }
+ return ""
+}
+
+type PTYInput struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ SessionId string `protobuf:"bytes,1,opt,name=session_id,json=sessionId,proto3" json:"session_id,omitempty"`
+ // Types that are valid to be assigned to Input:
+ //
+ // *PTYInput_Data
+ // *PTYInput_Resize
+ Input isPTYInput_Input `protobuf_oneof:"input"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *PTYInput) Reset() {
+ *x = PTYInput{}
+ mi := &file_proto_worker_worker_proto_msgTypes[20]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *PTYInput) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*PTYInput) ProtoMessage() {}
+
+func (x *PTYInput) ProtoReflect() protoreflect.Message {
+ mi := &file_proto_worker_worker_proto_msgTypes[20]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use PTYInput.ProtoReflect.Descriptor instead.
+func (*PTYInput) Descriptor() ([]byte, []int) {
+ return file_proto_worker_worker_proto_rawDescGZIP(), []int{20}
+}
+
+func (x *PTYInput) GetSessionId() string {
+ if x != nil {
+ return x.SessionId
+ }
+ return ""
+}
+
+func (x *PTYInput) GetInput() isPTYInput_Input {
+ if x != nil {
+ return x.Input
+ }
+ return nil
+}
+
+func (x *PTYInput) GetData() []byte {
+ if x != nil {
+ if x, ok := x.Input.(*PTYInput_Data); ok {
+ return x.Data
+ }
+ }
+ return nil
+}
+
+func (x *PTYInput) GetResize() *PTYResize {
+ if x != nil {
+ if x, ok := x.Input.(*PTYInput_Resize); ok {
+ return x.Resize
+ }
+ }
+ return nil
+}
+
+type isPTYInput_Input interface {
+ isPTYInput_Input()
+}
+
+type PTYInput_Data struct {
+ Data []byte `protobuf:"bytes,2,opt,name=data,proto3,oneof"`
+}
+
+type PTYInput_Resize struct {
+ Resize *PTYResize `protobuf:"bytes,3,opt,name=resize,proto3,oneof"`
+}
+
+func (*PTYInput_Data) isPTYInput_Input() {}
+
+func (*PTYInput_Resize) isPTYInput_Input() {}
+
+type PTYResize struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ Cols int32 `protobuf:"varint,1,opt,name=cols,proto3" json:"cols,omitempty"`
+ Rows int32 `protobuf:"varint,2,opt,name=rows,proto3" json:"rows,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *PTYResize) Reset() {
+ *x = PTYResize{}
+ mi := &file_proto_worker_worker_proto_msgTypes[21]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *PTYResize) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*PTYResize) ProtoMessage() {}
+
+func (x *PTYResize) ProtoReflect() protoreflect.Message {
+ mi := &file_proto_worker_worker_proto_msgTypes[21]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use PTYResize.ProtoReflect.Descriptor instead.
+func (*PTYResize) Descriptor() ([]byte, []int) {
+ return file_proto_worker_worker_proto_rawDescGZIP(), []int{21}
+}
+
+func (x *PTYResize) GetCols() int32 {
+ if x != nil {
+ return x.Cols
+ }
+ return 0
+}
+
+func (x *PTYResize) GetRows() int32 {
+ if x != nil {
+ return x.Rows
+ }
+ return 0
+}
+
+type PTYOutput struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ SessionId string `protobuf:"bytes,1,opt,name=session_id,json=sessionId,proto3" json:"session_id,omitempty"`
+ Data []byte `protobuf:"bytes,2,opt,name=data,proto3" json:"data,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *PTYOutput) Reset() {
+ *x = PTYOutput{}
+ mi := &file_proto_worker_worker_proto_msgTypes[22]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *PTYOutput) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*PTYOutput) ProtoMessage() {}
+
+func (x *PTYOutput) ProtoReflect() protoreflect.Message {
+ mi := &file_proto_worker_worker_proto_msgTypes[22]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use PTYOutput.ProtoReflect.Descriptor instead.
+func (*PTYOutput) Descriptor() ([]byte, []int) {
+ return file_proto_worker_worker_proto_rawDescGZIP(), []int{22}
+}
+
+func (x *PTYOutput) GetSessionId() string {
+ if x != nil {
+ return x.SessionId
+ }
+ return ""
+}
+
+func (x *PTYOutput) GetData() []byte {
+ if x != nil {
+ return x.Data
+ }
+ return nil
+}
+
+var File_proto_worker_worker_proto protoreflect.FileDescriptor
+
+const file_proto_worker_worker_proto_rawDesc = "" +
+ "\n" +
+ "\x19proto/worker/worker.proto\x12\x06worker\"\xa4\x02\n" +
+ "\x14CreateSandboxRequest\x12\x1a\n" +
+ "\btemplate\x18\x01 \x01(\tR\btemplate\x12\x18\n" +
+ "\atimeout\x18\x02 \x01(\x05R\atimeout\x12:\n" +
+ "\x04envs\x18\x03 \x03(\v2&.worker.CreateSandboxRequest.EnvsEntryR\x04envs\x12\x1b\n" +
+ "\tmemory_mb\x18\x04 \x01(\x05R\bmemoryMb\x12\x1b\n" +
+ "\tcpu_count\x18\x05 \x01(\x05R\bcpuCount\x12'\n" +
+ "\x0fnetwork_enabled\x18\x06 \x01(\bR\x0enetworkEnabled\x1a7\n" +
+ "\tEnvsEntry\x12\x10\n" +
+ "\x03key\x18\x01 \x01(\tR\x03key\x12\x14\n" +
+ "\x05value\x18\x02 \x01(\tR\x05value:\x028\x01\"N\n" +
+ "\x15CreateSandboxResponse\x12\x1d\n" +
+ "\n" +
+ "sandbox_id\x18\x01 \x01(\tR\tsandboxId\x12\x16\n" +
+ "\x06status\x18\x02 \x01(\tR\x06status\"6\n" +
+ "\x15DestroySandboxRequest\x12\x1d\n" +
+ "\n" +
+ "sandbox_id\x18\x01 \x01(\tR\tsandboxId\"\x18\n" +
+ "\x16DestroySandboxResponse\"2\n" +
+ "\x11GetSandboxRequest\x12\x1d\n" +
+ "\n" +
+ "sandbox_id\x18\x01 \x01(\tR\tsandboxId\"\x9d\x01\n" +
+ "\x12GetSandboxResponse\x12\x1d\n" +
+ "\n" +
+ "sandbox_id\x18\x01 \x01(\tR\tsandboxId\x12\x16\n" +
+ "\x06status\x18\x02 \x01(\tR\x06status\x12\x1a\n" +
+ "\btemplate\x18\x03 \x01(\tR\btemplate\x12\x1d\n" +
+ "\n" +
+ "started_at\x18\x04 \x01(\x03R\tstartedAt\x12\x15\n" +
+ "\x06end_at\x18\x05 \x01(\x03R\x05endAt\"\x16\n" +
+ "\x14ListSandboxesRequest\"Q\n" +
+ "\x15ListSandboxesResponse\x128\n" +
+ "\tsandboxes\x18\x01 \x03(\v2\x1a.worker.GetSandboxResponseR\tsandboxes\"\x80\x02\n" +
+ "\x12ExecCommandRequest\x12\x1d\n" +
+ "\n" +
+ "sandbox_id\x18\x01 \x01(\tR\tsandboxId\x12\x18\n" +
+ "\acommand\x18\x02 \x01(\tR\acommand\x12\x12\n" +
+ "\x04args\x18\x03 \x03(\tR\x04args\x128\n" +
+ "\x04envs\x18\x04 \x03(\v2$.worker.ExecCommandRequest.EnvsEntryR\x04envs\x12\x10\n" +
+ "\x03cwd\x18\x05 \x01(\tR\x03cwd\x12\x18\n" +
+ "\atimeout\x18\x06 \x01(\x05R\atimeout\x1a7\n" +
+ "\tEnvsEntry\x12\x10\n" +
+ "\x03key\x18\x01 \x01(\tR\x03key\x12\x14\n" +
+ "\x05value\x18\x02 \x01(\tR\x05value:\x028\x01\"b\n" +
+ "\x13ExecCommandResponse\x12\x1b\n" +
+ "\texit_code\x18\x01 \x01(\x05R\bexitCode\x12\x16\n" +
+ "\x06stdout\x18\x02 \x01(\tR\x06stdout\x12\x16\n" +
+ "\x06stderr\x18\x03 \x01(\tR\x06stderr\"\x7f\n" +
+ "\x0fExecOutputChunk\x126\n" +
+ "\x06stream\x18\x01 \x01(\x0e2\x1e.worker.ExecOutputChunk.StreamR\x06stream\x12\x12\n" +
+ "\x04data\x18\x02 \x01(\fR\x04data\" \n" +
+ "\x06Stream\x12\n" +
+ "\n" +
+ "\x06STDOUT\x10\x00\x12\n" +
+ "\n" +
+ "\x06STDERR\x10\x01\"D\n" +
+ "\x0fReadFileRequest\x12\x1d\n" +
+ "\n" +
+ "sandbox_id\x18\x01 \x01(\tR\tsandboxId\x12\x12\n" +
+ "\x04path\x18\x02 \x01(\tR\x04path\",\n" +
+ "\x10ReadFileResponse\x12\x18\n" +
+ "\acontent\x18\x01 \x01(\fR\acontent\"_\n" +
+ "\x10WriteFileRequest\x12\x1d\n" +
+ "\n" +
+ "sandbox_id\x18\x01 \x01(\tR\tsandboxId\x12\x12\n" +
+ "\x04path\x18\x02 \x01(\tR\x04path\x12\x18\n" +
+ "\acontent\x18\x03 \x01(\fR\acontent\"\x13\n" +
+ "\x11WriteFileResponse\"C\n" +
+ "\x0eListDirRequest\x12\x1d\n" +
+ "\n" +
+ "sandbox_id\x18\x01 \x01(\tR\tsandboxId\x12\x12\n" +
+ "\x04path\x18\x02 \x01(\tR\x04path\"]\n" +
+ "\bDirEntry\x12\x12\n" +
+ "\x04name\x18\x01 \x01(\tR\x04name\x12\x15\n" +
+ "\x06is_dir\x18\x02 \x01(\bR\x05isDir\x12\x12\n" +
+ "\x04size\x18\x03 \x01(\x03R\x04size\x12\x12\n" +
+ "\x04path\x18\x04 \x01(\tR\x04path\"=\n" +
+ "\x0fListDirResponse\x12*\n" +
+ "\aentries\x18\x01 \x03(\v2\x10.worker.DirEntryR\aentries\"o\n" +
+ "\x10CreatePTYRequest\x12\x1d\n" +
+ "\n" +
+ "sandbox_id\x18\x01 \x01(\tR\tsandboxId\x12\x12\n" +
+ "\x04cols\x18\x02 \x01(\x05R\x04cols\x12\x12\n" +
+ "\x04rows\x18\x03 \x01(\x05R\x04rows\x12\x14\n" +
+ "\x05shell\x18\x04 \x01(\tR\x05shell\"2\n" +
+ "\x11CreatePTYResponse\x12\x1d\n" +
+ "\n" +
+ "session_id\x18\x01 \x01(\tR\tsessionId\"u\n" +
+ "\bPTYInput\x12\x1d\n" +
+ "\n" +
+ "session_id\x18\x01 \x01(\tR\tsessionId\x12\x14\n" +
+ "\x04data\x18\x02 \x01(\fH\x00R\x04data\x12+\n" +
+ "\x06resize\x18\x03 \x01(\v2\x11.worker.PTYResizeH\x00R\x06resizeB\a\n" +
+ "\x05input\"3\n" +
+ "\tPTYResize\x12\x12\n" +
+ "\x04cols\x18\x01 \x01(\x05R\x04cols\x12\x12\n" +
+ "\x04rows\x18\x02 \x01(\x05R\x04rows\">\n" +
+ "\tPTYOutput\x12\x1d\n" +
+ "\n" +
+ "session_id\x18\x01 \x01(\tR\tsessionId\x12\x12\n" +
+ "\x04data\x18\x02 \x01(\fR\x04data2\x8a\x06\n" +
+ "\rSandboxWorker\x12L\n" +
+ "\rCreateSandbox\x12\x1c.worker.CreateSandboxRequest\x1a\x1d.worker.CreateSandboxResponse\x12O\n" +
+ "\x0eDestroySandbox\x12\x1d.worker.DestroySandboxRequest\x1a\x1e.worker.DestroySandboxResponse\x12C\n" +
+ "\n" +
+ "GetSandbox\x12\x19.worker.GetSandboxRequest\x1a\x1a.worker.GetSandboxResponse\x12L\n" +
+ "\rListSandboxes\x12\x1c.worker.ListSandboxesRequest\x1a\x1d.worker.ListSandboxesResponse\x12F\n" +
+ "\vExecCommand\x12\x1a.worker.ExecCommandRequest\x1a\x1b.worker.ExecCommandResponse\x12J\n" +
+ "\x11ExecCommandStream\x12\x1a.worker.ExecCommandRequest\x1a\x17.worker.ExecOutputChunk0\x01\x12=\n" +
+ "\bReadFile\x12\x17.worker.ReadFileRequest\x1a\x18.worker.ReadFileResponse\x12@\n" +
+ "\tWriteFile\x12\x18.worker.WriteFileRequest\x1a\x19.worker.WriteFileResponse\x12:\n" +
+ "\aListDir\x12\x16.worker.ListDirRequest\x1a\x17.worker.ListDirResponse\x12@\n" +
+ "\tCreatePTY\x12\x18.worker.CreatePTYRequest\x1a\x19.worker.CreatePTYResponse\x124\n" +
+ "\tPTYStream\x12\x10.worker.PTYInput\x1a\x11.worker.PTYOutput(\x010\x01B1Z/github.com/opensandbox/opensandbox/proto/workerb\x06proto3"
+
+var (
+ file_proto_worker_worker_proto_rawDescOnce sync.Once
+ file_proto_worker_worker_proto_rawDescData []byte
+)
+
+func file_proto_worker_worker_proto_rawDescGZIP() []byte {
+ file_proto_worker_worker_proto_rawDescOnce.Do(func() {
+ file_proto_worker_worker_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_proto_worker_worker_proto_rawDesc), len(file_proto_worker_worker_proto_rawDesc)))
+ })
+ return file_proto_worker_worker_proto_rawDescData
+}
+
+var file_proto_worker_worker_proto_enumTypes = make([]protoimpl.EnumInfo, 1)
+var file_proto_worker_worker_proto_msgTypes = make([]protoimpl.MessageInfo, 25)
+var file_proto_worker_worker_proto_goTypes = []any{
+ (ExecOutputChunk_Stream)(0), // 0: worker.ExecOutputChunk.Stream
+ (*CreateSandboxRequest)(nil), // 1: worker.CreateSandboxRequest
+ (*CreateSandboxResponse)(nil), // 2: worker.CreateSandboxResponse
+ (*DestroySandboxRequest)(nil), // 3: worker.DestroySandboxRequest
+ (*DestroySandboxResponse)(nil), // 4: worker.DestroySandboxResponse
+ (*GetSandboxRequest)(nil), // 5: worker.GetSandboxRequest
+ (*GetSandboxResponse)(nil), // 6: worker.GetSandboxResponse
+ (*ListSandboxesRequest)(nil), // 7: worker.ListSandboxesRequest
+ (*ListSandboxesResponse)(nil), // 8: worker.ListSandboxesResponse
+ (*ExecCommandRequest)(nil), // 9: worker.ExecCommandRequest
+ (*ExecCommandResponse)(nil), // 10: worker.ExecCommandResponse
+ (*ExecOutputChunk)(nil), // 11: worker.ExecOutputChunk
+ (*ReadFileRequest)(nil), // 12: worker.ReadFileRequest
+ (*ReadFileResponse)(nil), // 13: worker.ReadFileResponse
+ (*WriteFileRequest)(nil), // 14: worker.WriteFileRequest
+ (*WriteFileResponse)(nil), // 15: worker.WriteFileResponse
+ (*ListDirRequest)(nil), // 16: worker.ListDirRequest
+ (*DirEntry)(nil), // 17: worker.DirEntry
+ (*ListDirResponse)(nil), // 18: worker.ListDirResponse
+ (*CreatePTYRequest)(nil), // 19: worker.CreatePTYRequest
+ (*CreatePTYResponse)(nil), // 20: worker.CreatePTYResponse
+ (*PTYInput)(nil), // 21: worker.PTYInput
+ (*PTYResize)(nil), // 22: worker.PTYResize
+ (*PTYOutput)(nil), // 23: worker.PTYOutput
+ nil, // 24: worker.CreateSandboxRequest.EnvsEntry
+ nil, // 25: worker.ExecCommandRequest.EnvsEntry
+}
+var file_proto_worker_worker_proto_depIdxs = []int32{
+ 24, // 0: worker.CreateSandboxRequest.envs:type_name -> worker.CreateSandboxRequest.EnvsEntry
+ 6, // 1: worker.ListSandboxesResponse.sandboxes:type_name -> worker.GetSandboxResponse
+ 25, // 2: worker.ExecCommandRequest.envs:type_name -> worker.ExecCommandRequest.EnvsEntry
+ 0, // 3: worker.ExecOutputChunk.stream:type_name -> worker.ExecOutputChunk.Stream
+ 17, // 4: worker.ListDirResponse.entries:type_name -> worker.DirEntry
+ 22, // 5: worker.PTYInput.resize:type_name -> worker.PTYResize
+ 1, // 6: worker.SandboxWorker.CreateSandbox:input_type -> worker.CreateSandboxRequest
+ 3, // 7: worker.SandboxWorker.DestroySandbox:input_type -> worker.DestroySandboxRequest
+ 5, // 8: worker.SandboxWorker.GetSandbox:input_type -> worker.GetSandboxRequest
+ 7, // 9: worker.SandboxWorker.ListSandboxes:input_type -> worker.ListSandboxesRequest
+ 9, // 10: worker.SandboxWorker.ExecCommand:input_type -> worker.ExecCommandRequest
+ 9, // 11: worker.SandboxWorker.ExecCommandStream:input_type -> worker.ExecCommandRequest
+ 12, // 12: worker.SandboxWorker.ReadFile:input_type -> worker.ReadFileRequest
+ 14, // 13: worker.SandboxWorker.WriteFile:input_type -> worker.WriteFileRequest
+ 16, // 14: worker.SandboxWorker.ListDir:input_type -> worker.ListDirRequest
+ 19, // 15: worker.SandboxWorker.CreatePTY:input_type -> worker.CreatePTYRequest
+ 21, // 16: worker.SandboxWorker.PTYStream:input_type -> worker.PTYInput
+ 2, // 17: worker.SandboxWorker.CreateSandbox:output_type -> worker.CreateSandboxResponse
+ 4, // 18: worker.SandboxWorker.DestroySandbox:output_type -> worker.DestroySandboxResponse
+ 6, // 19: worker.SandboxWorker.GetSandbox:output_type -> worker.GetSandboxResponse
+ 8, // 20: worker.SandboxWorker.ListSandboxes:output_type -> worker.ListSandboxesResponse
+ 10, // 21: worker.SandboxWorker.ExecCommand:output_type -> worker.ExecCommandResponse
+ 11, // 22: worker.SandboxWorker.ExecCommandStream:output_type -> worker.ExecOutputChunk
+ 13, // 23: worker.SandboxWorker.ReadFile:output_type -> worker.ReadFileResponse
+ 15, // 24: worker.SandboxWorker.WriteFile:output_type -> worker.WriteFileResponse
+ 18, // 25: worker.SandboxWorker.ListDir:output_type -> worker.ListDirResponse
+ 20, // 26: worker.SandboxWorker.CreatePTY:output_type -> worker.CreatePTYResponse
+ 23, // 27: worker.SandboxWorker.PTYStream:output_type -> worker.PTYOutput
+ 17, // [17:28] is the sub-list for method output_type
+ 6, // [6:17] is the sub-list for method input_type
+ 6, // [6:6] is the sub-list for extension type_name
+ 6, // [6:6] is the sub-list for extension extendee
+ 0, // [0:6] is the sub-list for field type_name
+}
+
+func init() { file_proto_worker_worker_proto_init() }
+func file_proto_worker_worker_proto_init() {
+ if File_proto_worker_worker_proto != nil {
+ return
+ }
+ file_proto_worker_worker_proto_msgTypes[20].OneofWrappers = []any{
+ (*PTYInput_Data)(nil),
+ (*PTYInput_Resize)(nil),
+ }
+ type x struct{}
+ out := protoimpl.TypeBuilder{
+ File: protoimpl.DescBuilder{
+ GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
+ RawDescriptor: unsafe.Slice(unsafe.StringData(file_proto_worker_worker_proto_rawDesc), len(file_proto_worker_worker_proto_rawDesc)),
+ NumEnums: 1,
+ NumMessages: 25,
+ NumExtensions: 0,
+ NumServices: 1,
+ },
+ GoTypes: file_proto_worker_worker_proto_goTypes,
+ DependencyIndexes: file_proto_worker_worker_proto_depIdxs,
+ EnumInfos: file_proto_worker_worker_proto_enumTypes,
+ MessageInfos: file_proto_worker_worker_proto_msgTypes,
+ }.Build()
+ File_proto_worker_worker_proto = out.File
+ file_proto_worker_worker_proto_goTypes = nil
+ file_proto_worker_worker_proto_depIdxs = nil
+}
diff --git a/proto/worker/worker_grpc.pb.go b/proto/worker/worker_grpc.pb.go
new file mode 100644
index 00000000..df5a73b7
--- /dev/null
+++ b/proto/worker/worker_grpc.pb.go
@@ -0,0 +1,499 @@
+// Code generated by protoc-gen-go-grpc. DO NOT EDIT.
+// versions:
+// - protoc-gen-go-grpc v1.6.1
+// - protoc v5.29.3
+// source: proto/worker/worker.proto
+
+package worker
+
+import (
+ context "context"
+ grpc "google.golang.org/grpc"
+ codes "google.golang.org/grpc/codes"
+ status "google.golang.org/grpc/status"
+)
+
+// This is a compile-time assertion to ensure that this generated file
+// is compatible with the grpc package it is being compiled against.
+// Requires gRPC-Go v1.64.0 or later.
+const _ = grpc.SupportPackageIsVersion9
+
+const (
+ SandboxWorker_CreateSandbox_FullMethodName = "/worker.SandboxWorker/CreateSandbox"
+ SandboxWorker_DestroySandbox_FullMethodName = "/worker.SandboxWorker/DestroySandbox"
+ SandboxWorker_GetSandbox_FullMethodName = "/worker.SandboxWorker/GetSandbox"
+ SandboxWorker_ListSandboxes_FullMethodName = "/worker.SandboxWorker/ListSandboxes"
+ SandboxWorker_ExecCommand_FullMethodName = "/worker.SandboxWorker/ExecCommand"
+ SandboxWorker_ExecCommandStream_FullMethodName = "/worker.SandboxWorker/ExecCommandStream"
+ SandboxWorker_ReadFile_FullMethodName = "/worker.SandboxWorker/ReadFile"
+ SandboxWorker_WriteFile_FullMethodName = "/worker.SandboxWorker/WriteFile"
+ SandboxWorker_ListDir_FullMethodName = "/worker.SandboxWorker/ListDir"
+ SandboxWorker_CreatePTY_FullMethodName = "/worker.SandboxWorker/CreatePTY"
+ SandboxWorker_PTYStream_FullMethodName = "/worker.SandboxWorker/PTYStream"
+)
+
+// SandboxWorkerClient is the client API for SandboxWorker service.
+//
+// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream.
+type SandboxWorkerClient interface {
+ CreateSandbox(ctx context.Context, in *CreateSandboxRequest, opts ...grpc.CallOption) (*CreateSandboxResponse, error)
+ DestroySandbox(ctx context.Context, in *DestroySandboxRequest, opts ...grpc.CallOption) (*DestroySandboxResponse, error)
+ GetSandbox(ctx context.Context, in *GetSandboxRequest, opts ...grpc.CallOption) (*GetSandboxResponse, error)
+ ListSandboxes(ctx context.Context, in *ListSandboxesRequest, opts ...grpc.CallOption) (*ListSandboxesResponse, error)
+ ExecCommand(ctx context.Context, in *ExecCommandRequest, opts ...grpc.CallOption) (*ExecCommandResponse, error)
+ ExecCommandStream(ctx context.Context, in *ExecCommandRequest, opts ...grpc.CallOption) (grpc.ServerStreamingClient[ExecOutputChunk], error)
+ ReadFile(ctx context.Context, in *ReadFileRequest, opts ...grpc.CallOption) (*ReadFileResponse, error)
+ WriteFile(ctx context.Context, in *WriteFileRequest, opts ...grpc.CallOption) (*WriteFileResponse, error)
+ ListDir(ctx context.Context, in *ListDirRequest, opts ...grpc.CallOption) (*ListDirResponse, error)
+ CreatePTY(ctx context.Context, in *CreatePTYRequest, opts ...grpc.CallOption) (*CreatePTYResponse, error)
+ PTYStream(ctx context.Context, opts ...grpc.CallOption) (grpc.BidiStreamingClient[PTYInput, PTYOutput], error)
+}
+
+type sandboxWorkerClient struct {
+ cc grpc.ClientConnInterface
+}
+
+func NewSandboxWorkerClient(cc grpc.ClientConnInterface) SandboxWorkerClient {
+ return &sandboxWorkerClient{cc}
+}
+
+func (c *sandboxWorkerClient) CreateSandbox(ctx context.Context, in *CreateSandboxRequest, opts ...grpc.CallOption) (*CreateSandboxResponse, error) {
+ cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
+ out := new(CreateSandboxResponse)
+ err := c.cc.Invoke(ctx, SandboxWorker_CreateSandbox_FullMethodName, in, out, cOpts...)
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
+func (c *sandboxWorkerClient) DestroySandbox(ctx context.Context, in *DestroySandboxRequest, opts ...grpc.CallOption) (*DestroySandboxResponse, error) {
+ cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
+ out := new(DestroySandboxResponse)
+ err := c.cc.Invoke(ctx, SandboxWorker_DestroySandbox_FullMethodName, in, out, cOpts...)
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
+func (c *sandboxWorkerClient) GetSandbox(ctx context.Context, in *GetSandboxRequest, opts ...grpc.CallOption) (*GetSandboxResponse, error) {
+ cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
+ out := new(GetSandboxResponse)
+ err := c.cc.Invoke(ctx, SandboxWorker_GetSandbox_FullMethodName, in, out, cOpts...)
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
+func (c *sandboxWorkerClient) ListSandboxes(ctx context.Context, in *ListSandboxesRequest, opts ...grpc.CallOption) (*ListSandboxesResponse, error) {
+ cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
+ out := new(ListSandboxesResponse)
+ err := c.cc.Invoke(ctx, SandboxWorker_ListSandboxes_FullMethodName, in, out, cOpts...)
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
+func (c *sandboxWorkerClient) ExecCommand(ctx context.Context, in *ExecCommandRequest, opts ...grpc.CallOption) (*ExecCommandResponse, error) {
+ cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
+ out := new(ExecCommandResponse)
+ err := c.cc.Invoke(ctx, SandboxWorker_ExecCommand_FullMethodName, in, out, cOpts...)
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
+func (c *sandboxWorkerClient) ExecCommandStream(ctx context.Context, in *ExecCommandRequest, opts ...grpc.CallOption) (grpc.ServerStreamingClient[ExecOutputChunk], error) {
+ cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
+ stream, err := c.cc.NewStream(ctx, &SandboxWorker_ServiceDesc.Streams[0], SandboxWorker_ExecCommandStream_FullMethodName, cOpts...)
+ if err != nil {
+ return nil, err
+ }
+ x := &grpc.GenericClientStream[ExecCommandRequest, ExecOutputChunk]{ClientStream: stream}
+ if err := x.ClientStream.SendMsg(in); err != nil {
+ return nil, err
+ }
+ if err := x.ClientStream.CloseSend(); err != nil {
+ return nil, err
+ }
+ return x, nil
+}
+
+// This type alias is provided for backwards compatibility with existing code that references the prior non-generic stream type by name.
+type SandboxWorker_ExecCommandStreamClient = grpc.ServerStreamingClient[ExecOutputChunk]
+
+func (c *sandboxWorkerClient) ReadFile(ctx context.Context, in *ReadFileRequest, opts ...grpc.CallOption) (*ReadFileResponse, error) {
+ cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
+ out := new(ReadFileResponse)
+ err := c.cc.Invoke(ctx, SandboxWorker_ReadFile_FullMethodName, in, out, cOpts...)
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
+func (c *sandboxWorkerClient) WriteFile(ctx context.Context, in *WriteFileRequest, opts ...grpc.CallOption) (*WriteFileResponse, error) {
+ cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
+ out := new(WriteFileResponse)
+ err := c.cc.Invoke(ctx, SandboxWorker_WriteFile_FullMethodName, in, out, cOpts...)
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
+func (c *sandboxWorkerClient) ListDir(ctx context.Context, in *ListDirRequest, opts ...grpc.CallOption) (*ListDirResponse, error) {
+ cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
+ out := new(ListDirResponse)
+ err := c.cc.Invoke(ctx, SandboxWorker_ListDir_FullMethodName, in, out, cOpts...)
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
+func (c *sandboxWorkerClient) CreatePTY(ctx context.Context, in *CreatePTYRequest, opts ...grpc.CallOption) (*CreatePTYResponse, error) {
+ cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
+ out := new(CreatePTYResponse)
+ err := c.cc.Invoke(ctx, SandboxWorker_CreatePTY_FullMethodName, in, out, cOpts...)
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
+func (c *sandboxWorkerClient) PTYStream(ctx context.Context, opts ...grpc.CallOption) (grpc.BidiStreamingClient[PTYInput, PTYOutput], error) {
+ cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
+ stream, err := c.cc.NewStream(ctx, &SandboxWorker_ServiceDesc.Streams[1], SandboxWorker_PTYStream_FullMethodName, cOpts...)
+ if err != nil {
+ return nil, err
+ }
+ x := &grpc.GenericClientStream[PTYInput, PTYOutput]{ClientStream: stream}
+ return x, nil
+}
+
+// This type alias is provided for backwards compatibility with existing code that references the prior non-generic stream type by name.
+type SandboxWorker_PTYStreamClient = grpc.BidiStreamingClient[PTYInput, PTYOutput]
+
+// SandboxWorkerServer is the server API for SandboxWorker service.
+// All implementations must embed UnimplementedSandboxWorkerServer
+// for forward compatibility.
+type SandboxWorkerServer interface {
+ CreateSandbox(context.Context, *CreateSandboxRequest) (*CreateSandboxResponse, error)
+ DestroySandbox(context.Context, *DestroySandboxRequest) (*DestroySandboxResponse, error)
+ GetSandbox(context.Context, *GetSandboxRequest) (*GetSandboxResponse, error)
+ ListSandboxes(context.Context, *ListSandboxesRequest) (*ListSandboxesResponse, error)
+ ExecCommand(context.Context, *ExecCommandRequest) (*ExecCommandResponse, error)
+ ExecCommandStream(*ExecCommandRequest, grpc.ServerStreamingServer[ExecOutputChunk]) error
+ ReadFile(context.Context, *ReadFileRequest) (*ReadFileResponse, error)
+ WriteFile(context.Context, *WriteFileRequest) (*WriteFileResponse, error)
+ ListDir(context.Context, *ListDirRequest) (*ListDirResponse, error)
+ CreatePTY(context.Context, *CreatePTYRequest) (*CreatePTYResponse, error)
+ PTYStream(grpc.BidiStreamingServer[PTYInput, PTYOutput]) error
+ mustEmbedUnimplementedSandboxWorkerServer()
+}
+
+// UnimplementedSandboxWorkerServer must be embedded to have
+// forward compatible implementations.
+//
+// NOTE: this should be embedded by value instead of pointer to avoid a nil
+// pointer dereference when methods are called.
+type UnimplementedSandboxWorkerServer struct{}
+
+func (UnimplementedSandboxWorkerServer) CreateSandbox(context.Context, *CreateSandboxRequest) (*CreateSandboxResponse, error) {
+ return nil, status.Error(codes.Unimplemented, "method CreateSandbox not implemented")
+}
+func (UnimplementedSandboxWorkerServer) DestroySandbox(context.Context, *DestroySandboxRequest) (*DestroySandboxResponse, error) {
+ return nil, status.Error(codes.Unimplemented, "method DestroySandbox not implemented")
+}
+func (UnimplementedSandboxWorkerServer) GetSandbox(context.Context, *GetSandboxRequest) (*GetSandboxResponse, error) {
+ return nil, status.Error(codes.Unimplemented, "method GetSandbox not implemented")
+}
+func (UnimplementedSandboxWorkerServer) ListSandboxes(context.Context, *ListSandboxesRequest) (*ListSandboxesResponse, error) {
+ return nil, status.Error(codes.Unimplemented, "method ListSandboxes not implemented")
+}
+func (UnimplementedSandboxWorkerServer) ExecCommand(context.Context, *ExecCommandRequest) (*ExecCommandResponse, error) {
+ return nil, status.Error(codes.Unimplemented, "method ExecCommand not implemented")
+}
+func (UnimplementedSandboxWorkerServer) ExecCommandStream(*ExecCommandRequest, grpc.ServerStreamingServer[ExecOutputChunk]) error {
+ return status.Error(codes.Unimplemented, "method ExecCommandStream not implemented")
+}
+func (UnimplementedSandboxWorkerServer) ReadFile(context.Context, *ReadFileRequest) (*ReadFileResponse, error) {
+ return nil, status.Error(codes.Unimplemented, "method ReadFile not implemented")
+}
+func (UnimplementedSandboxWorkerServer) WriteFile(context.Context, *WriteFileRequest) (*WriteFileResponse, error) {
+ return nil, status.Error(codes.Unimplemented, "method WriteFile not implemented")
+}
+func (UnimplementedSandboxWorkerServer) ListDir(context.Context, *ListDirRequest) (*ListDirResponse, error) {
+ return nil, status.Error(codes.Unimplemented, "method ListDir not implemented")
+}
+func (UnimplementedSandboxWorkerServer) CreatePTY(context.Context, *CreatePTYRequest) (*CreatePTYResponse, error) {
+ return nil, status.Error(codes.Unimplemented, "method CreatePTY not implemented")
+}
+func (UnimplementedSandboxWorkerServer) PTYStream(grpc.BidiStreamingServer[PTYInput, PTYOutput]) error {
+ return status.Error(codes.Unimplemented, "method PTYStream not implemented")
+}
+func (UnimplementedSandboxWorkerServer) mustEmbedUnimplementedSandboxWorkerServer() {}
+func (UnimplementedSandboxWorkerServer) testEmbeddedByValue() {}
+
+// UnsafeSandboxWorkerServer may be embedded to opt out of forward compatibility for this service.
+// Use of this interface is not recommended, as added methods to SandboxWorkerServer will
+// result in compilation errors.
+type UnsafeSandboxWorkerServer interface {
+ mustEmbedUnimplementedSandboxWorkerServer()
+}
+
+func RegisterSandboxWorkerServer(s grpc.ServiceRegistrar, srv SandboxWorkerServer) {
+ // If the following call panics, it indicates UnimplementedSandboxWorkerServer was
+ // embedded by pointer and is nil. This will cause panics if an
+ // unimplemented method is ever invoked, so we test this at initialization
+ // time to prevent it from happening at runtime later due to I/O.
+ if t, ok := srv.(interface{ testEmbeddedByValue() }); ok {
+ t.testEmbeddedByValue()
+ }
+ s.RegisterService(&SandboxWorker_ServiceDesc, srv)
+}
+
+func _SandboxWorker_CreateSandbox_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
+ in := new(CreateSandboxRequest)
+ if err := dec(in); err != nil {
+ return nil, err
+ }
+ if interceptor == nil {
+ return srv.(SandboxWorkerServer).CreateSandbox(ctx, in)
+ }
+ info := &grpc.UnaryServerInfo{
+ Server: srv,
+ FullMethod: SandboxWorker_CreateSandbox_FullMethodName,
+ }
+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+ return srv.(SandboxWorkerServer).CreateSandbox(ctx, req.(*CreateSandboxRequest))
+ }
+ return interceptor(ctx, in, info, handler)
+}
+
+func _SandboxWorker_DestroySandbox_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
+ in := new(DestroySandboxRequest)
+ if err := dec(in); err != nil {
+ return nil, err
+ }
+ if interceptor == nil {
+ return srv.(SandboxWorkerServer).DestroySandbox(ctx, in)
+ }
+ info := &grpc.UnaryServerInfo{
+ Server: srv,
+ FullMethod: SandboxWorker_DestroySandbox_FullMethodName,
+ }
+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+ return srv.(SandboxWorkerServer).DestroySandbox(ctx, req.(*DestroySandboxRequest))
+ }
+ return interceptor(ctx, in, info, handler)
+}
+
+func _SandboxWorker_GetSandbox_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
+ in := new(GetSandboxRequest)
+ if err := dec(in); err != nil {
+ return nil, err
+ }
+ if interceptor == nil {
+ return srv.(SandboxWorkerServer).GetSandbox(ctx, in)
+ }
+ info := &grpc.UnaryServerInfo{
+ Server: srv,
+ FullMethod: SandboxWorker_GetSandbox_FullMethodName,
+ }
+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+ return srv.(SandboxWorkerServer).GetSandbox(ctx, req.(*GetSandboxRequest))
+ }
+ return interceptor(ctx, in, info, handler)
+}
+
+func _SandboxWorker_ListSandboxes_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
+ in := new(ListSandboxesRequest)
+ if err := dec(in); err != nil {
+ return nil, err
+ }
+ if interceptor == nil {
+ return srv.(SandboxWorkerServer).ListSandboxes(ctx, in)
+ }
+ info := &grpc.UnaryServerInfo{
+ Server: srv,
+ FullMethod: SandboxWorker_ListSandboxes_FullMethodName,
+ }
+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+ return srv.(SandboxWorkerServer).ListSandboxes(ctx, req.(*ListSandboxesRequest))
+ }
+ return interceptor(ctx, in, info, handler)
+}
+
+func _SandboxWorker_ExecCommand_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
+ in := new(ExecCommandRequest)
+ if err := dec(in); err != nil {
+ return nil, err
+ }
+ if interceptor == nil {
+ return srv.(SandboxWorkerServer).ExecCommand(ctx, in)
+ }
+ info := &grpc.UnaryServerInfo{
+ Server: srv,
+ FullMethod: SandboxWorker_ExecCommand_FullMethodName,
+ }
+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+ return srv.(SandboxWorkerServer).ExecCommand(ctx, req.(*ExecCommandRequest))
+ }
+ return interceptor(ctx, in, info, handler)
+}
+
+func _SandboxWorker_ExecCommandStream_Handler(srv interface{}, stream grpc.ServerStream) error {
+ m := new(ExecCommandRequest)
+ if err := stream.RecvMsg(m); err != nil {
+ return err
+ }
+ return srv.(SandboxWorkerServer).ExecCommandStream(m, &grpc.GenericServerStream[ExecCommandRequest, ExecOutputChunk]{ServerStream: stream})
+}
+
+// This type alias is provided for backwards compatibility with existing code that references the prior non-generic stream type by name.
+type SandboxWorker_ExecCommandStreamServer = grpc.ServerStreamingServer[ExecOutputChunk]
+
+func _SandboxWorker_ReadFile_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
+ in := new(ReadFileRequest)
+ if err := dec(in); err != nil {
+ return nil, err
+ }
+ if interceptor == nil {
+ return srv.(SandboxWorkerServer).ReadFile(ctx, in)
+ }
+ info := &grpc.UnaryServerInfo{
+ Server: srv,
+ FullMethod: SandboxWorker_ReadFile_FullMethodName,
+ }
+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+ return srv.(SandboxWorkerServer).ReadFile(ctx, req.(*ReadFileRequest))
+ }
+ return interceptor(ctx, in, info, handler)
+}
+
+func _SandboxWorker_WriteFile_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
+ in := new(WriteFileRequest)
+ if err := dec(in); err != nil {
+ return nil, err
+ }
+ if interceptor == nil {
+ return srv.(SandboxWorkerServer).WriteFile(ctx, in)
+ }
+ info := &grpc.UnaryServerInfo{
+ Server: srv,
+ FullMethod: SandboxWorker_WriteFile_FullMethodName,
+ }
+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+ return srv.(SandboxWorkerServer).WriteFile(ctx, req.(*WriteFileRequest))
+ }
+ return interceptor(ctx, in, info, handler)
+}
+
+func _SandboxWorker_ListDir_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
+ in := new(ListDirRequest)
+ if err := dec(in); err != nil {
+ return nil, err
+ }
+ if interceptor == nil {
+ return srv.(SandboxWorkerServer).ListDir(ctx, in)
+ }
+ info := &grpc.UnaryServerInfo{
+ Server: srv,
+ FullMethod: SandboxWorker_ListDir_FullMethodName,
+ }
+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+ return srv.(SandboxWorkerServer).ListDir(ctx, req.(*ListDirRequest))
+ }
+ return interceptor(ctx, in, info, handler)
+}
+
+func _SandboxWorker_CreatePTY_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
+ in := new(CreatePTYRequest)
+ if err := dec(in); err != nil {
+ return nil, err
+ }
+ if interceptor == nil {
+ return srv.(SandboxWorkerServer).CreatePTY(ctx, in)
+ }
+ info := &grpc.UnaryServerInfo{
+ Server: srv,
+ FullMethod: SandboxWorker_CreatePTY_FullMethodName,
+ }
+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+ return srv.(SandboxWorkerServer).CreatePTY(ctx, req.(*CreatePTYRequest))
+ }
+ return interceptor(ctx, in, info, handler)
+}
+
+func _SandboxWorker_PTYStream_Handler(srv interface{}, stream grpc.ServerStream) error {
+ return srv.(SandboxWorkerServer).PTYStream(&grpc.GenericServerStream[PTYInput, PTYOutput]{ServerStream: stream})
+}
+
+// This type alias is provided for backwards compatibility with existing code that references the prior non-generic stream type by name.
+type SandboxWorker_PTYStreamServer = grpc.BidiStreamingServer[PTYInput, PTYOutput]
+
+// SandboxWorker_ServiceDesc is the grpc.ServiceDesc for SandboxWorker service.
+// It's only intended for direct use with grpc.RegisterService,
+// and not to be introspected or modified (even as a copy)
+var SandboxWorker_ServiceDesc = grpc.ServiceDesc{
+ ServiceName: "worker.SandboxWorker",
+ HandlerType: (*SandboxWorkerServer)(nil),
+ Methods: []grpc.MethodDesc{
+ {
+ MethodName: "CreateSandbox",
+ Handler: _SandboxWorker_CreateSandbox_Handler,
+ },
+ {
+ MethodName: "DestroySandbox",
+ Handler: _SandboxWorker_DestroySandbox_Handler,
+ },
+ {
+ MethodName: "GetSandbox",
+ Handler: _SandboxWorker_GetSandbox_Handler,
+ },
+ {
+ MethodName: "ListSandboxes",
+ Handler: _SandboxWorker_ListSandboxes_Handler,
+ },
+ {
+ MethodName: "ExecCommand",
+ Handler: _SandboxWorker_ExecCommand_Handler,
+ },
+ {
+ MethodName: "ReadFile",
+ Handler: _SandboxWorker_ReadFile_Handler,
+ },
+ {
+ MethodName: "WriteFile",
+ Handler: _SandboxWorker_WriteFile_Handler,
+ },
+ {
+ MethodName: "ListDir",
+ Handler: _SandboxWorker_ListDir_Handler,
+ },
+ {
+ MethodName: "CreatePTY",
+ Handler: _SandboxWorker_CreatePTY_Handler,
+ },
+ },
+ Streams: []grpc.StreamDesc{
+ {
+ StreamName: "ExecCommandStream",
+ Handler: _SandboxWorker_ExecCommandStream_Handler,
+ ServerStreams: true,
+ },
+ {
+ StreamName: "PTYStream",
+ Handler: _SandboxWorker_PTYStream_Handler,
+ ServerStreams: true,
+ ClientStreams: true,
+ },
+ },
+ Metadata: "proto/worker/worker.proto",
+}
diff --git a/sdks/python/opensandbox/sandbox.py b/sdks/python/opensandbox/sandbox.py
index 31b3c61b..13d8c1a2 100644
--- a/sdks/python/opensandbox/sandbox.py
+++ b/sdks/python/opensandbox/sandbox.py
@@ -22,7 +22,10 @@ class Sandbox:
template: str = ""
_api_url: str = ""
_api_key: str = ""
+ _connect_url: str = ""
+ _token: str = ""
_client: httpx.AsyncClient = field(default=None, repr=False)
+ _data_client: httpx.AsyncClient = field(default=None, repr=False)
@classmethod
async def create(
@@ -57,13 +60,28 @@ class Sandbox:
resp.raise_for_status()
data = resp.json()
+ connect_url = data.get("connectURL", "")
+ token = data.get("token", "")
+
+ # If worker returned a direct connectURL, create a separate client for data ops
+ data_client = None
+ if connect_url and token:
+ data_client = httpx.AsyncClient(
+ base_url=connect_url,
+ headers={"Authorization": f"Bearer {token}"},
+ timeout=30.0,
+ )
+
return cls(
sandbox_id=data["sandboxID"],
status=data.get("status", "running"),
template=template,
_api_url=url,
_api_key=key,
+ _connect_url=connect_url,
+ _token=token,
_client=client,
+ _data_client=data_client,
)
@classmethod
@@ -87,15 +105,36 @@ class Sandbox:
resp.raise_for_status()
data = resp.json()
+ connect_url = data.get("connectURL", "")
+ token = data.get("token", "")
+
+ data_client = None
+ if connect_url and token:
+ data_client = httpx.AsyncClient(
+ base_url=connect_url,
+ headers={"Authorization": f"Bearer {token}"},
+ timeout=30.0,
+ )
+
return cls(
sandbox_id=sandbox_id,
status=data.get("status", "running"),
template=data.get("templateID", ""),
_api_url=url,
_api_key=key,
+ _connect_url=connect_url,
+ _token=token,
_client=client,
+ _data_client=data_client,
)
+ @property
+ def _ops_client(self) -> httpx.AsyncClient:
+ """Return the client for data operations (direct worker if available, else CP)."""
+ if self._data_client is not None:
+ return self._data_client
+ return self._client
+
async def kill(self) -> None:
"""Kill and remove the sandbox."""
resp = await self._client.delete(f"/sandboxes/{self.sandbox_id}")
@@ -124,21 +163,25 @@ class Sandbox:
@property
def files(self) -> Filesystem:
"""Access filesystem operations."""
- return Filesystem(self._client, self.sandbox_id)
+ return Filesystem(self._ops_client, self.sandbox_id)
@property
def commands(self) -> Commands:
"""Access command execution."""
- return Commands(self._client, self.sandbox_id)
+ return Commands(self._ops_client, self.sandbox_id)
@property
def pty(self) -> Pty:
"""Access PTY terminal sessions."""
- return Pty(self._client, self.sandbox_id, self._api_url, self._api_key)
+ pty_url = self._connect_url or self._api_url
+ pty_key = self._token or self._api_key
+ return Pty(self._ops_client, self.sandbox_id, pty_url, pty_key)
async def close(self) -> None:
"""Close the HTTP client (does not kill the sandbox)."""
await self._client.aclose()
+ if self._data_client is not None:
+ await self._data_client.aclose()
async def __aenter__(self) -> Sandbox:
return self
diff --git a/sdks/typescript/src/commands.ts b/sdks/typescript/src/commands.ts
index d1567af6..c905fd45 100644
--- a/sdks/typescript/src/commands.ts
+++ b/sdks/typescript/src/commands.ts
@@ -15,11 +15,16 @@ export class Commands {
private apiUrl: string,
private apiKey: string,
private sandboxId: string,
+ private token: string = "",
) {}
private get headers(): Record<string, string> {
const h: Record<string, string> = { "Content-Type": "application/json" };
- if (this.apiKey) h["X-API-Key"] = this.apiKey;
+ if (this.token) {
+ h["Authorization"] = `Bearer ${this.token}`;
+ } else if (this.apiKey) {
+ h["X-API-Key"] = this.apiKey;
+ }
return h;
}
diff --git a/sdks/typescript/src/filesystem.ts b/sdks/typescript/src/filesystem.ts
index e24ee40b..ca0bb8ca 100644
--- a/sdks/typescript/src/filesystem.ts
+++ b/sdks/typescript/src/filesystem.ts
@@ -10,9 +10,11 @@ export class Filesystem {
private apiUrl: string,
private apiKey: string,
private sandboxId: string,
+ private token: string = "",
) {}
private get headers(): Record<string, string> {
+ if (this.token) return { "Authorization": `Bearer ${this.token}` };
return this.apiKey ? { "X-API-Key": this.apiKey } : {};
}
diff --git a/sdks/typescript/src/pty.ts b/sdks/typescript/src/pty.ts
index b18e92a6..8dddd212 100644
--- a/sdks/typescript/src/pty.ts
+++ b/sdks/typescript/src/pty.ts
@@ -15,11 +15,16 @@ export class Pty {
private apiUrl: string,
private apiKey: string,
private sandboxId: string,
+ private token: string = "",
) {}
private get headers(): Record<string, string> {
const h: Record<string, string> = { "Content-Type": "application/json" };
- if (this.apiKey) h["X-API-Key"] = this.apiKey;
+ if (this.token) {
+ h["Authorization"] = `Bearer ${this.token}`;
+ } else if (this.apiKey) {
+ h["X-API-Key"] = this.apiKey;
+ }
return h;
}
diff --git a/sdks/typescript/src/sandbox.ts b/sdks/typescript/src/sandbox.ts
index 81c3e386..b7e3bc9a 100644
--- a/sdks/typescript/src/sandbox.ts
+++ b/sdks/typescript/src/sandbox.ts
@@ -15,6 +15,8 @@ interface SandboxData {
sandboxID: string;
status: string;
templateID?: string;
+ connectURL?: string;
+ token?: string;
}
export class Sandbox {
@@ -25,6 +27,8 @@ export class Sandbox {
private apiUrl: string;
private apiKey: string;
+ private connectUrl: string;
+ private token: string;
private _status: string;
private constructor(data: SandboxData, apiUrl: string, apiKey: string) {
@@ -32,9 +36,17 @@ export class Sandbox {
this._status = data.status;
this.apiUrl = apiUrl;
this.apiKey = apiKey;
- this.files = new Filesystem(apiUrl, apiKey, this.sandboxId);
- this.commands = new Commands(apiUrl, apiKey, this.sandboxId);
- this.pty = new Pty(apiUrl, apiKey, this.sandboxId);
+ this.connectUrl = data.connectURL || "";
+ this.token = data.token || "";
+
+ // Use direct worker URL for data operations if available
+ const opsUrl = this.connectUrl || apiUrl;
+ const opsKey = this.connectUrl ? "" : apiKey;
+ const opsToken = this.connectUrl ? this.token : "";
+
+ this.files = new Filesystem(opsUrl, opsKey, this.sandboxId, opsToken);
+ this.commands = new Commands(opsUrl, opsKey, this.sandboxId, opsToken);
+ this.pty = new Pty(opsUrl, opsKey, this.sandboxId, opsToken);
}
get status(): string {