carlos / platform Public

feat: enforce durable local demo traffic caps

Persist assigned-box lifetime request and byte allowances before dispatch and output. Wire resident policy, banner, compression, cancellation and purge while leaving production serving closed for Task 4.

Cover concurrency, crash recovery, disk and sync failures, forwarding, streaming and retirement. Refuse unsupported document types and retain the demo box label for local binding checks.
codex agent, operated by paul@keymail.dev pushed by claude agent, operated by paul@keymail.dev 9281928378341046e206652a4ca2197a1b6c8b27 parent 7e43747
21 files changed, +2,043 −34
  • internal/demo/config.go +19 −2
  • internal/demo/config_test.go +39 −0
  • internal/demo/traffic.go +28 −0
  • internal/edge/demo.go +10 −3
  • internal/edge/demo_banner.go +19 −5
  • internal/edge/demo_banner_test.go +13 −0
  • internal/edge/demo_forward_test.go +169 −0
  • internal/edge/demo_response.go +14 −1
  • internal/edge/demo_traffic.go +568 −0
  • internal/edge/demo_traffic_test.go +475 −0
  • internal/edge/edge.go +13 −13
  • internal/host/agent.go +28 −1
  • internal/host/demo_cleanup.go +11 −1
  • internal/host/demo_cleanup_test.go +18 −2
  • internal/host/demo_jobs.go +4 −2
  • internal/host/demo_retirement_stream_test.go +21 −3
  • internal/host/demo_traffic.go +191 −0
  • internal/host/demo_traffic_linux_test.go +70 −0
  • internal/host/demo_traffic_test.go +329 −0
  • internal/provision/demo_policy.go +3 −0
  • internal/provision/demo_routing_test.go +1 −1

CI failed — run details

Intent

Human

<task-notification> <task-id>bdwcc51s9</task-id> <tool-use-id>toolu_01MG16vfAwp9tTZpt3qXo3SU</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/6e566fe9-9aca-47cb-9753-64e881b0d285/tasks/bdwcc51s9.output</output-file> <status>completed</status> <summary>Background command "Wait for Task 2 Codex run" completed (exit code 0)</summary> </task-notification>

Human

<task-notification> <task-id>ac14b015ced7de9b6</task-id> <tool-use-id>toolu_01J1fihWLrd8mUnwZqwz27Ep</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/6e566fe9-9aca-47cb-9753-64e881b0d285/tasks/ac14b015ced7de9b6.output</output-file> <status>completed</status> <summary>Agent "Review Task 2 (Opus)" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>Spec verdict: compliant except P2-1. `edge.go` is not modified, which differs from the brief, but production serving is still closed and Task 3's brief owns that wiring. Recorded as P3-1, not a blocker. Quality verdict: READY AFTER FIXES. Counts: P1 0, P2 1, P3 9. - **P2-1:** the "refuse other active document types" rule is a short denylist (`internal/edge/demo_banner.go:238-241`). It covers XHTML, XML and SVG but not `application/*+xml` or `multipart/x-mixed-replace`. Chromium renders `+xml` types and applies same-origin XSLT, and Firefox renders `multipart/x-mixed-replace` HTML parts as pages. Either way a page shows with no warning and no script needed. CSP still holds. Fix: refuse any `+xml` subtype, `multipart/x-mixed-replace` and `text/xsl`, or switch to an allowlist. Invariant: the warning appears on every document the browser renders as a page; it is a notice, not an authority boundary. Two things for the controller to check later: - **Task 3:** put the `/.carlos/demo/` reservation ahead of the local-asset shortcut at `edge.go:2532`. Otherwise a locally served HTML file could skip the banner. - **Task 6:** rerun the browser test against the production wiring. Today it drives a test-only pipeline, which is fine while serving is closed. The targeted tests pass, and the readiness probe and `edge.go` are unchanged. Full review: `/home/paulca/amadan.net/carlos/platform/.claude/worktrees/agent-start-demo-2/.superpowers/sdd/2026-11-04-agent-start-demo-2-edge-protections/task-2-review-r1.md`</result> <usage><subagent_tokens>141308</subagent_tokens><tool_uses>16</tool_uses><duration_ms>353785</duration_ms></usage> </task-notification>

Attributed to this commit: 18.5 g CO₂e (2,157,744 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on agent-start-demo-2, never backward from it. A turn that produced more than one commit books all of its tokens to the last one, and a concurrent session on this branch can add to the same figure. Some of it was priced using the shared default rate, because no model-specific factor row exists yet for at least one model involved. The Carbon view has the repo total, which is never derived from this attribution.

diff --git a/internal/demo/config.go b/internal/demo/config.go
index f827d2fff..18d0c87ae 100644
--- a/internal/demo/config.go
+++ b/internal/demo/config.go
@@ -21,6 +21,8 @@ var ErrConfig = errors.New("DEMO-CONFIG")
type Config struct {
Enabled bool
+ EdgeProtections bool
+ RequestCap, BandwidthCapBytes int64
Account, Fleet, Domain string
CreatePerIPDay, CreateGlobalDay, MaxLive int
BuildWorker bool
@@ -29,8 +31,8 @@ type Config struct {
}
func LoadConfig(getenv func(string) string) (Config, error) {
- c := Config{CreatePerIPDay: 30, CreateGlobalDay: 100, MaxLive: 20, BuildConcurrency: 1}
- for key, dst := range map[string]*bool{"CARLOS_DEMO_APPS": &c.Enabled, "CARLOS_DEMO_BUILD_WORKER": &c.BuildWorker} {
+ c := Config{CreatePerIPDay: 30, CreateGlobalDay: 100, MaxLive: 20, BuildConcurrency: 1, RequestCap: DefaultRequestCap, BandwidthCapBytes: DefaultBandwidthCapBytes}
+ for key, dst := range map[string]*bool{"CARLOS_DEMO_EDGE_PROTECTIONS": &c.EdgeProtections, "CARLOS_DEMO_APPS": &c.Enabled, "CARLOS_DEMO_BUILD_WORKER": &c.BuildWorker} {
switch getenv(key) {
case "":
case "1":
@@ -52,6 +54,21 @@ func LoadConfig(getenv func(string) string) (Config, error) {
*dst = n
}
}
+ for key, setting := range map[string]struct {
+ dst *int64
+ max int64
+ }{
+ "CARLOS_DEMO_REQUEST_CAP": {&c.RequestCap, MaxRequestCap},
+ "CARLOS_DEMO_BANDWIDTH_CAP_BYTES": {&c.BandwidthCapBytes, MaxBandwidthCapBytes},
+ } {
+ if raw := getenv(key); raw != "" {
+ n, err := strconv.ParseInt(raw, 10, 64)
+ if err != nil || n < 1 || n > setting.max {
+ return Config{}, fmt.Errorf("%w: %s", ErrConfig, key)
+ }
+ *setting.dst = n
+ }
+ }
if err := c.Validate(); err != nil {
return Config{}, err
}
diff --git a/internal/demo/config_test.go b/internal/demo/config_test.go
index 43d14a321..d9ef22dea 100644
--- a/internal/demo/config_test.go
+++ b/internal/demo/config_test.go
@@ -130,3 +130,42 @@ func TestDemoConfigValidateOrder(t *testing.T) {
t.Fatal(err)
}
}
+
+func TestDemoTrafficConfig(t *testing.T) {
+ cfg, err := LoadConfig(func(string) string { return "" })
+ if err != nil || cfg.RequestCap != 2000 || cfg.BandwidthCapBytes != 200000000 || cfg.EdgeProtections {
+ t.Fatalf("defaults %+v %v", cfg, err)
+ }
+ for key, max := range map[string]string{"CARLOS_DEMO_REQUEST_CAP": "1000000", "CARLOS_DEMO_BANDWIDTH_CAP_BYTES": "10000000000"} {
+ for _, raw := range []string{"0", "-1", "9223372036854775808", "1.5", "10000000001"} {
+ if _, err := LoadConfig(func(k string) string {
+ if k == key {
+ return raw
+ }
+ return ""
+ }); err == nil {
+ t.Fatalf("accepted %s=%s", key, raw)
+ }
+ }
+ for _, raw := range []string{"1", max} {
+ if _, err := LoadConfig(func(k string) string {
+ if k == key {
+ return raw
+ }
+ return ""
+ }); err != nil {
+ t.Fatal(err)
+ }
+ }
+ }
+ for _, raw := range []string{"0", "true", "false", "2"} {
+ if _, err := LoadConfig(func(k string) string {
+ if k == "CARLOS_DEMO_EDGE_PROTECTIONS" {
+ return raw
+ }
+ return ""
+ }); err == nil {
+ t.Fatalf("accepted switch %s", raw)
+ }
+ }
+}
diff --git a/internal/demo/traffic.go b/internal/demo/traffic.go
new file mode 100644
index 000000000..823e88cbe
--- /dev/null
+++ b/internal/demo/traffic.go
@@ -0,0 +1,28 @@
+package demo
+
+import (
+ "context"
+ "errors"
+)
+
+const (
+ DefaultRequestCap int64 = 2000
+ DefaultBandwidthCapBytes int64 = 200000000
+ MaxRequestCap int64 = 1000000
+ MaxBandwidthCapBytes int64 = 10000000000
+)
+
+var ErrTrafficLimit = errors.New("DEMO-LIMIT")
+var ErrTrafficUnavailable = errors.New("DEMO-UNAVAILABLE")
+
+type TrafficIdentity struct{ ID, Lifetime, Host string }
+type TrafficCaps struct{ Requests, BodyBytes int64 }
+
+func (c TrafficCaps) Valid() bool {
+ return c.Requests > 0 && c.Requests <= MaxRequestCap && c.BodyBytes > 0 && c.BodyBytes <= MaxBandwidthCapBytes
+}
+
+type TrafficCounter interface {
+ Admit(context.Context, TrafficIdentity) error
+ DebitBytes(context.Context, TrafficIdentity, int64) (int64, error)
+}
diff --git a/internal/edge/demo.go b/internal/edge/demo.go
index 97dbef23f..ba59cb37e 100644
--- a/internal/edge/demo.go
+++ b/internal/edge/demo.go
@@ -79,9 +79,12 @@ func demoRefusalNames(m map[string]upstream, routes []registry.Route, aliases []
}
// refuseDemoRequest runs before any response exit, including HTTP fallback.
-// Task 3 adds durable traffic admission and Task 4 the serving gate. Until
-// both are wired, even a valid live demo must stop here without dispatch.
+// HTTP fallback remains closed until Task 4 adds its HTTPS redirect gate.
func (e *Edge) refuseDemoRequest(w http.ResponseWriter, r *http.Request) bool {
+ return e.handleDemoRequest(w, r, false)
+}
+
+func (e *Edge) handleDemoRequest(w http.ResponseWriter, r *http.Request, serve bool) bool {
host, valid := demoAuthority(r.Host)
marked := false
if names := e.demoNames.Load(); names != nil {
@@ -91,6 +94,10 @@ func (e *Edge) refuseDemoRequest(w http.ResponseWriter, r *http.Request) bool {
if !e.demoReserved(host) && !marked && !(ok && up.route.IsDemo()) {
return false
}
+ if serve && valid && ok && up.route.IsDemo() && e.demoRouteOK(host, up.route) && !up.alias && !up.platformAlias {
+ e.serveDemoTraffic(w, r, up)
+ return true
+ }
w = e.beginDemoResponse(w, r)
if !valid {
serveDemoPlain(w, r, http.StatusBadRequest, "DEMO-GONE")
@@ -103,7 +110,7 @@ func (e *Edge) refuseDemoRequest(w http.ResponseWriter, r *http.Request) bool {
}
func demoEdgeConfig() demo.Config {
- return demo.Config{Account: os.Getenv("CARLOS_DEMO_ACCOUNT"), Fleet: os.Getenv("CARLOS_DEMO_FLEET"), Domain: os.Getenv("CARLOS_DEMO_DOMAIN")}
+ return demo.Config{EdgeProtections: os.Getenv("CARLOS_DEMO_EDGE_PROTECTIONS") == "1", Account: os.Getenv("CARLOS_DEMO_ACCOUNT"), Fleet: os.Getenv("CARLOS_DEMO_FLEET"), Domain: os.Getenv("CARLOS_DEMO_DOMAIN")}
}
// demoHost recognizes one direct label independently of the route table.
diff --git a/internal/edge/demo_banner.go b/internal/edge/demo_banner.go
index 6687ef427..2d5bc62ea 100644
--- a/internal/edge/demo_banner.go
+++ b/internal/edge/demo_banner.go
@@ -188,6 +188,9 @@ func (t demoBannerTransport) RoundTrip(r *http.Request) (*http.Response, error)
}
func demoBannerRefusal(resp *http.Response) *http.Response {
+ if resp.Request != nil {
+ demoPlatformResponse(resp.Request)
+ }
_ = resp.Body.Close()
resp.StatusCode = http.StatusBadGateway
resp.Status = "502 Bad Gateway"
@@ -235,12 +238,11 @@ func transformDemoHTMLResponse(resp *http.Response, host, reportOrigin string) e
if err != nil && ct != "" {
return errors.New("DEMO-RESPONSE")
}
- switch mt {
- case "application/xhtml+xml", "application/xml", "text/xml", "image/svg+xml":
- return errors.New("DEMO-RESPONSE")
- }
if mt != "text/html" {
- return nil
+ if demoPassiveMediaType(mt) {
+ return nil
+ }
+ return errors.New("DEMO-RESPONSE")
}
if charset := params["charset"]; charset != "" && !strings.EqualFold(charset, "utf-8") {
return errors.New("DEMO-RESPONSE")
@@ -284,3 +286,15 @@ type demoHTMLBody struct {
io.Reader
io.Closer
}
+
+// Unknown types fail closed: only these non-document representations pass.
+func demoPassiveMediaType(mt string) bool {
+ if strings.HasSuffix(mt, "+xml") {
+ return false
+ }
+ switch mt {
+ case "text/plain", "text/css", "text/javascript", "application/javascript", "application/x-javascript", "text/event-stream", "application/json", "text/json", "application/octet-stream", "application/wasm", "multipart/byteranges", "application/font-woff", "application/vnd.ms-fontobject", "application/x-font-ttf", "application/x-font-opentype":
+ return true
+ }
+ return strings.HasSuffix(mt, "+json") || strings.HasPrefix(mt, "image/") || strings.HasPrefix(mt, "font/") || strings.HasPrefix(mt, "audio/") || strings.HasPrefix(mt, "video/")
+}
diff --git a/internal/edge/demo_banner_test.go b/internal/edge/demo_banner_test.go
index c60cf83ff..51d92ab4f 100644
--- a/internal/edge/demo_banner_test.go
+++ b/internal/edge/demo_banner_test.go
@@ -121,6 +121,19 @@ func TestDemoBannerRepresentations(t *testing.T) {
{name: "charset", ct: "text/html; charset=iso-8859-1", status: 200, refuse: true},
{name: "xhtml", ct: "application/xhtml+xml", status: 200, refuse: true},
{name: "svg", ct: "image/svg+xml", status: 200, refuse: true},
+ {name: "xml", ct: "application/xml", status: 200, refuse: true},
+ {name: "text-xml", ct: "text/xml", status: 200, refuse: true},
+ {name: "custom-xml", ct: "application/shop+xml", status: 200, refuse: true},
+ {name: "text-custom-xml", ct: "text/shop+xml", status: 200, refuse: true},
+ {name: "xsl", ct: "text/xsl", status: 200, refuse: true},
+ {name: "mixed-replace", ct: "multipart/x-mixed-replace; boundary=shop", status: 200, refuse: true},
+ {name: "pdf", ct: "application/pdf", status: 200, refuse: true},
+ {name: "unknown", ct: "application/shop", status: 200, refuse: true},
+ {name: "css", ct: "text/css", status: 200},
+ {name: "js", ct: "application/javascript", status: 200},
+ {name: "font", ct: "font/woff2", status: 200},
+ {name: "media", ct: "video/mp4", status: 200},
+ {name: "binary", ct: "application/octet-stream", status: 200},
{name: "head", method: "HEAD", ct: "text/html", status: 200, bodyless: true},
{name: "204", ct: "text/html", status: 204, bodyless: true},
{name: "304-image", ct: "image/png", status: 304, bodyless: true},
diff --git a/internal/edge/demo_forward_test.go b/internal/edge/demo_forward_test.go
new file mode 100644
index 000000000..cb4a7417a
--- /dev/null
+++ b/internal/edge/demo_forward_test.go
@@ -0,0 +1,169 @@
+package edge
+
+import (
+ "bytes"
+ "compress/gzip"
+ "context"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "net/http/httputil"
+ "net/url"
+ "strings"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/demo"
+ "github.com/carlosframework/platform/internal/registry"
+)
+
+func demoTestProxy(t *testing.T, target string) *httputil.ReverseProxy {
+ t.Helper()
+ u, err := url.Parse(target)
+ if err != nil {
+ t.Fatal(err)
+ }
+ tr := http.DefaultTransport.(*http.Transport).Clone()
+ tr.DisableCompression = true
+ t.Cleanup(tr.CloseIdleConnections)
+ return &httputil.ReverseProxy{Transport: tr, Rewrite: func(p *httputil.ProxyRequest) { p.SetURL(u); p.Out.Host = p.In.Host }}
+}
+func demoSetProxy(e *Edge, rt registry.Route, handler http.Handler) {
+ m := map[string]upstream{rt.Host: {route: rt, proxy: handler}}
+ e.upstreams.Store(&m)
+}
+func demoDo(t *testing.T, base, host, method, path, encoding string) (*http.Response, []byte) {
+ t.Helper()
+ r, err := http.NewRequest(method, base+path, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ r.Host = host
+ r.Header.Set("Accept-Encoding", encoding)
+ r.Header.Set("X-Carlos-Demo-Counted", "1")
+ r.Header.Set("X-Carlos-Demo-Skip", "1")
+ tr := http.DefaultTransport.(*http.Transport).Clone()
+ tr.DisableCompression = true
+ defer tr.CloseIdleConnections()
+ client := &http.Client{Transport: tr, Timeout: 5 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}
+ res, err := client.Do(r)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer res.Body.Close()
+ b, err := io.ReadAll(res.Body)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return res, b
+}
+func TestDemoTrafficAcrossIngresses(t *testing.T) {
+ var appCalls atomic.Int64
+ app := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ appCalls.Add(1)
+ w.Header().Set("Content-Type", "text/html")
+ w.Header().Set("X-Carlos-Version", "v1")
+ if r.URL.Path == "/error" {
+ w.WriteHeader(500)
+ }
+ if r.Method != "HEAD" {
+ io.WriteString(w, "<body>"+strings.Repeat("shop", 1000)+"</body>")
+ }
+ }))
+ defer app.Close()
+ resident, rt, counter := demoTrafficFixture(t, demoTestProxy(t, app.URL))
+ resident.gzipOn = true
+ box := httptest.NewServer(resident)
+ defer box.Close()
+ var ingresses []*httptest.Server
+ for range 2 {
+ e, _, unused := demoTrafficFixture(t, nil)
+ e.gzipOn = true
+ forward := rt
+ forward.Kind = "forward"
+ forward.Socket = ""
+ forward.FleetLabel = "box"
+ forward.FleetBox = "box"
+ forward.Hibernate = false
+ demoSetProxy(e, forward, demoTestProxy(t, box.URL))
+ e.SetDemoTraffic(unused, func(registry.Route, time.Time) bool { return false })
+ server := httptest.NewServer(e)
+ defer server.Close()
+ ingresses = append(ingresses, server)
+ t.Cleanup(func() {
+ if unused.requests != 0 || unused.bytes != 0 {
+ t.Error("ingress debited")
+ }
+ })
+ }
+ var expectedBytes int64
+ for i, method := range []string{"GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS"} {
+ path := "/shop"
+ if method == "DELETE" {
+ path = "/error"
+ }
+ res, b := demoDo(t, ingresses[i%2].URL, rt.Host, method, path, "gzip")
+ want := 200
+ if path == "/error" {
+ want = 500
+ }
+ if res.StatusCode != want || res.Header.Get("X-Carlos-Version") != "v1" {
+ t.Fatalf("response %d %v", res.StatusCode, res.Header)
+ }
+ assertDemoPolicy(t, res.Header)
+ expectedBytes += int64(len(b))
+ if method != "HEAD" {
+ gz, err := gzip.NewReader(bytes.NewReader(b))
+ if err != nil {
+ t.Fatal(err)
+ }
+ decoded, err := io.ReadAll(gz)
+ gz.Close()
+ if err != nil || strings.Count(string(decoded), `id="carlos-demo-warning"`) != 1 {
+ t.Fatalf("not exactly once: %v", err)
+ }
+ }
+ }
+ res, _ := demoDo(t, ingresses[0].URL, rt.Host, "GET", demoAssetPrefix+"banner.css", "gzip")
+ if res.StatusCode != 200 || res.Header.Get("X-Carlos-Version") != "" {
+ t.Fatal("platform asset")
+ }
+ if counter.requests != 6 || counter.bytes != expectedBytes || appCalls.Load() != 6 {
+ t.Fatalf("resident accounting %d %d want 6 %d; app %d", counter.requests, counter.bytes, expectedBytes, appCalls.Load())
+ }
+ // Copied descriptors never make a replacement box the owner.
+ resident.box = "other"
+ res, _ = demoDo(t, ingresses[1].URL, rt.Host, "GET", "/shop", "gzip")
+ if res.StatusCode != 503 || counter.requests != 6 {
+ t.Fatal("replacement served")
+ }
+ resident.box = "box"
+ for _, mutate := range []func(*registry.Route){func(r *registry.Route) { r.Account = "other" }, func(r *registry.Route) { r.Region = "fleet/other" }, func(r *registry.Route) { r.DemoLifetime = "other"; r.FleetBox = "other" }, func(r *registry.Route) { r.DemoHost = "other.example.com" }} {
+ bad := rt
+ mutate(&bad)
+ demoSetProxy(resident, bad, demoTestProxy(t, app.URL))
+ res, _ = demoDo(t, ingresses[0].URL, rt.Host, "GET", "/shop", "identity")
+ if res.StatusCode < 400 || counter.requests != 6 {
+ t.Fatal("bad assignment served")
+ }
+ }
+}
+
+func TestDemoTrafficForwardFailure(t *testing.T) {
+ e, rt, _ := demoTrafficFixture(t, nil)
+ rt.Kind = "forward"
+ rt.FleetLabel = "box"
+ rt.Socket = ""
+ rt.Hibernate = false
+ p := &httputil.ReverseProxy{Director: func(r *http.Request) { r.URL.Scheme = "http"; r.URL.Host = "example.com" }, Transport: roundTripperFunc(func(*http.Request) (*http.Response, error) { return nil, context.DeadlineExceeded })}
+ demoSetProxy(e, rt, p)
+ rec := httptest.NewRecorder()
+ e.ServeHTTP(rec, httptest.NewRequest("GET", "https://"+rt.Host+"/", nil))
+ if rec.Code != 503 || rec.Body.String() != demoCopy["DEMO-UNAVAILABLE"]+"\n" {
+ t.Fatalf("failure %d %s", rec.Code, rec.Body.String())
+ }
+ assertDemoPolicy(t, rec.Header())
+}
+
+var _ demo.TrafficCounter = (*demoTestCounter)(nil)
diff --git a/internal/edge/demo_response.go b/internal/edge/demo_response.go
index a27d61573..96c748294 100644
--- a/internal/edge/demo_response.go
+++ b/internal/edge/demo_response.go
@@ -7,6 +7,7 @@ import (
"net/url"
"strconv"
"strings"
+ "time"
"golang.org/x/net/http/httpguts"
)
@@ -187,6 +188,9 @@ func (w *demoResponseWriter) WriteHeader(status int) {
return
}
h := w.header.Clone()
+ if output, ok := w.request.Context().Value(demoOutputKey{}).(*demoTrafficWriter); ok && output.overhead {
+ h.Del("X-Carlos-Version")
+ }
err := sanitizeDemoHeaders(h, w.request.Host)
missingLocation := (status == 301 || status == 302 || status == 303 || status == 307 || status == 308) && h.Get("Location") == ""
worker := false
@@ -198,6 +202,7 @@ func (w *demoResponseWriter) WriteHeader(status int) {
}
worker = worker && status < 400
if status == http.StatusSwitchingProtocols || err != nil || missingLocation || worker {
+ demoPlatformResponse(w.request)
w.refused = true
status = http.StatusBadGateway
if worker {
@@ -213,6 +218,7 @@ func (w *demoResponseWriter) WriteHeader(status int) {
for key, values := range h {
dst[key] = append([]string(nil), values...)
}
+ _ = w.SetWriteDeadline(time.Now().Add(demoWriteTimeout))
w.dst.WriteHeader(status)
if w.refused && w.request.Method != http.MethodHead {
_, _ = io.WriteString(w.dst, demoCopy["DEMO-RESPONSE"]+"\n")
@@ -223,9 +229,10 @@ func (w *demoResponseWriter) Write(p []byte) (int, error) {
if w.status == 0 {
w.WriteHeader(http.StatusOK)
}
- if w.refused || w.request.Method == http.MethodHead || w.status == http.StatusNoContent || w.status == http.StatusNotModified {
+ if w.refused || w.request.Method == http.MethodHead || w.status == http.StatusNoContent || w.status == http.StatusResetContent || w.status == http.StatusNotModified {
return len(p), nil
}
+ _ = w.SetWriteDeadline(time.Now().Add(demoWriteTimeout))
return w.dst.Write(p)
}
@@ -233,9 +240,14 @@ func (w *demoResponseWriter) FlushError() error {
if w.status == 0 {
w.WriteHeader(http.StatusOK)
}
+ _ = w.SetWriteDeadline(time.Now().Add(demoWriteTimeout))
return http.NewResponseController(w.dst).Flush()
}
+func (w *demoResponseWriter) SetWriteDeadline(t time.Time) error {
+ return http.NewResponseController(w.dst).SetWriteDeadline(t)
+}
+
func (w *demoResponseWriter) Flush() { _ = w.FlushError() }
func demoPlainHeaders(h http.Header, copyID string) {
@@ -245,6 +257,7 @@ func demoPlainHeaders(h http.Header, copyID string) {
}
func serveDemoPlain(w http.ResponseWriter, r *http.Request, status int, copyID string) {
+ demoPlatformResponse(r)
if _, ok := demoCopy[copyID]; !ok {
copyID = "DEMO-UNAVAILABLE"
status = http.StatusServiceUnavailable
diff --git a/internal/edge/demo_traffic.go b/internal/edge/demo_traffic.go
new file mode 100644
index 000000000..8797d858a
--- /dev/null
+++ b/internal/edge/demo_traffic.go
@@ -0,0 +1,568 @@
+package edge
+
+import (
+ "context"
+ "errors"
+ "io"
+ "net/http"
+ "net/http/httputil"
+ "strings"
+ "sync"
+ "time"
+
+ "github.com/carlosframework/platform/internal/demo"
+ "github.com/carlosframework/platform/internal/edgeguard"
+ "github.com/carlosframework/platform/internal/geoip"
+ "github.com/carlosframework/platform/internal/registry"
+ "github.com/carlosframework/platform/internal/release"
+ "github.com/carlosframework/platform/internal/tunnelclient"
+)
+
+const demoWriteTimeout = 5 * time.Second
+const demoDebitChunk = 32 << 10
+
+type demoTrafficState struct {
+ counter demo.TrafficCounter
+ serving func(registry.Route, time.Time) bool
+ mu sync.Mutex
+ retired map[demo.TrafficIdentity]bool
+ active map[*demoActive]demo.TrafficIdentity
+}
+type demoActive struct {
+ cancel context.CancelFunc
+ done chan struct{}
+}
+
+// SetDemoTraffic is a startup hook. Serving is always checked separately from
+// counter availability; forwarding edges need no local counter.
+func (e *Edge) SetDemoTraffic(counter demo.TrafficCounter, serving func(registry.Route, time.Time) bool) {
+ e.demoTraffic = &demoTrafficState{counter: counter, serving: serving, retired: make(map[demo.TrafficIdentity]bool), active: make(map[*demoActive]demo.TrafficIdentity)}
+}
+
+// StopDemoTraffic closes this lifetime permanently and waits for all writers.
+// The retirement worker calls it before local purge. Task 4 can also call it
+// when applying an authenticated retirement; a later on cannot undo it.
+func (e *Edge) StopDemoTraffic(ctx context.Context, id demo.TrafficIdentity) error {
+ s := e.demoTraffic
+ if s == nil {
+ return demo.ErrTrafficUnavailable
+ }
+ s.mu.Lock()
+ s.retired[id] = true
+ var active []*demoActive
+ for a, key := range s.active {
+ if key == id {
+ a.cancel()
+ active = append(active, a)
+ }
+ }
+ s.mu.Unlock()
+ for _, a := range active {
+ select {
+ case <-a.done:
+ case <-ctx.Done():
+ return ctx.Err()
+ }
+ }
+ return nil
+}
+
+func demoTrafficID(rt registry.Route) demo.TrafficIdentity {
+ return demo.TrafficIdentity{ID: rt.DemoID, Lifetime: rt.DemoLifetime, Host: rt.Host}
+}
+
+func (e *Edge) demoTrafficAllowed(rt registry.Route) bool {
+ up, ok := e.lookupUpstream(rt.Host)
+ if !ok || !e.demoRouteOK(rt.Host, up.route) || up.alias || up.platformAlias {
+ return false
+ }
+ now := up.route
+ if now.DemoID != rt.DemoID || now.DemoLifetime != rt.DemoLifetime || now.DemoExpiresAt != rt.DemoExpiresAt || now.Account != rt.Account || now.App != rt.App || now.Region != rt.Region || now.Assigned != rt.Assigned || now.FleetBox != rt.FleetBox || now.FleetLabel != rt.FleetLabel || (now.HoldOp != "" || registry.IsHold(now.Status)) {
+ return false
+ }
+ if rt.IsForward() {
+ return now.IsForward()
+ }
+ s := e.demoTraffic
+ if s == nil || s.counter == nil || s.serving == nil || now.IsForward() || up.viaTunnel || e.box == "" || now.FleetBox != e.box {
+ return false
+ }
+ s.mu.Lock()
+ retired := s.retired[demoTrafficID(rt)]
+ s.mu.Unlock()
+ return !retired && s.serving(now, time.Now())
+}
+
+type demoOutputKey struct{}
+
+func demoPlatformResponse(r *http.Request) {
+ if w, ok := r.Context().Value(demoOutputKey{}).(*demoTrafficWriter); ok {
+ w.overhead = true
+ }
+}
+
+// serveDemoTraffic is the demo-only route. It never enters a shared cache,
+// local-asset catch, held-stream reconnect, or raw-socket upgrade path.
+func (e *Edge) serveDemoTraffic(dst http.ResponseWriter, r *http.Request, up upstream) {
+ host, valid := demoAuthority(r.Host)
+ if !valid {
+ serveDemoPlain(dst, r, 400, "DEMO-GONE")
+ return
+ }
+ if !e.demoRouteOK(host, up.route) || up.alias || up.platformAlias {
+ serveDemoPlain(dst, r, 404, "DEMO-GONE")
+ return
+ }
+ if !e.demo.EdgeProtections || !e.demoTrafficAllowed(up.route) {
+ serveDemoPlain(dst, r, 503, "DEMO-UNAVAILABLE")
+ return
+ }
+ r = r.Clone(r.Context())
+ r.Host = host
+ // Reuse transport authentication and header scrubbing. Client-supplied
+ // markers never grant an exemption from the resident counter.
+ geo := geoip.Capture(r.Header)
+ hopPresent := r.Header.Get(hopHeader) != ""
+ r, hopped := e.acceptHop(r, host)
+ for _, key := range []string{assetAckHeader, assetExpiresHeader, assetFillHeader, tunnelclient.UpgradeHeader, tunnelclient.ReplicaProbeHeader} {
+ r.Header.Del(key)
+ }
+ door, isDoor := doorCallerFrom(r.Context())
+ if isDoor && !doorOwnsRoute(door, up.route) {
+ serveDemoPlain(dst, r, 404, "DEMO-GONE")
+ return
+ }
+ ans := e.decideGeo(r, geo, hopPresent, hopped, isDoor)
+ r = r.WithContext(context.WithValue(r.Context(), geoResultKey{}, ans))
+ ans.WriteApp(r.Header)
+ r = e.withForwardKey(r)
+ ctx, cancel := context.WithDeadline(r.Context(), time.Unix(up.route.DemoExpiresAt, 0))
+ defer cancel()
+ r = r.WithContext(ctx)
+ active := &demoActive{cancel: cancel, done: make(chan struct{})}
+ if !up.route.IsForward() {
+ s := e.demoTraffic
+ s.mu.Lock()
+ if s.retired[demoTrafficID(up.route)] {
+ s.mu.Unlock()
+ serveDemoPlain(dst, r, 404, "DEMO-GONE")
+ return
+ }
+ s.active[active] = demoTrafficID(up.route)
+ s.mu.Unlock()
+ defer func() { s.mu.Lock(); delete(s.active, active); close(active.done); s.mu.Unlock() }()
+ }
+ // This only observes local memory. It also cancels a silent upstream when
+ // controls expire, without waiting for another request or another body write.
+ monitorDone := make(chan struct{})
+ go func() {
+ defer close(monitorDone)
+ tick := time.NewTicker(100 * time.Millisecond)
+ defer tick.Stop()
+ for {
+ select {
+ case <-ctx.Done():
+ return
+ case <-tick.C:
+ if !e.demoTrafficAllowed(up.route) {
+ cancel()
+ return
+ }
+ }
+ }
+ }()
+ defer func() { cancel(); <-monitorDone }()
+ var delivered int64
+ ob := &countingWriter{ResponseWriter: dst, n: &delivered}
+ r, out := withOutcome(r)
+ if e.guard != guardOff && !isDoor && !hopDoorFrom(ctx) && !fromTunnel(ctx) {
+ out.guard = e.newGuardState(up.route)
+ out.guard.acct, out.guard.app = release.RouteAccount(up.route), up.route.App
+ }
+ defer func() {
+ if m := e.usageMeter.Load(); m != nil {
+ m.Record(up.route, 1, delivered, hopped)
+ }
+ if ob.status >= 500 && !out.answered {
+ e.emitEdgeError(up.route, up.viaTunnel, r, ob.status, out.cause)
+ }
+ e.observeAnalytics(up.route, r, ob, delivered)
+ e.observeRecords(up.route, up.viaTunnel, r, ob, out)
+ e.observeGuardCount(up.route, out)
+ e.noteBurst(up.route, r, ob.status, out)
+ }()
+ wire := &demoTrafficWriter{dst: ob, request: r, header: make(http.Header), cancel: cancel, allowed: func() bool { return ctx.Err() == nil && e.demoTrafficAllowed(up.route) }, id: demoTrafficID(up.route), overhead: true}
+ if !up.route.IsForward() {
+ wire.counter = e.demoTraffic.counter
+ }
+ r = r.WithContext(context.WithValue(r.Context(), demoOutputKey{}, wire))
+ wire.request = r
+ // The outer policy controls all early exits. The byte writer is below the
+ // compressor, so only the final representation spends the byte allowance.
+ var output http.ResponseWriter = wire
+ var gz *gzipWriter
+ if !up.route.IsForward() && e.gzipOn {
+ gz = newGzipWriter(output, r)
+ if gz != nil {
+ output = gz
+ }
+ }
+ policy := e.beginDemoResponse(output, r).(*demoResponseWriter)
+ defer func() {
+ if p := recover(); p != nil {
+ if gz != nil && gz.gz != nil {
+ gz.gz.Reset(io.Discard)
+ gzipPool.Put(gz.gz)
+ gz.gz = nil
+ }
+ if p == http.ErrAbortHandler && wire.fallback {
+ return
+ }
+ panic(p)
+ }
+ if policy.status == 0 {
+ serveDemoPlain(policy, r, 502, "DEMO-RESPONSE")
+ }
+ if gz != nil {
+ gz.finish()
+ }
+ wire.finish()
+ }()
+ refusal := &demoRefusalWriter{dst: policy, request: r, header: make(http.Header)}
+ if e.admissionRefuses(refusal, r, up.route) || !e.importGateAdmit(refusal, r, host, up.route) || !e.planDisabledAdmit(refusal, r, host, up.route) {
+ return
+ }
+ if out.guard != nil {
+ if hit, matched := edgeguard.Check(r.URL.Path, r.URL.RawQuery); matched {
+ if until, from, cooling := out.guard.cooling(r); cooling && burstDecide(refusal, r, until, from, up.viaTunnel || up.route.IsForward()) {
+ return
+ }
+ if guardDecide(refusal, r, hit) {
+ return
+ }
+ }
+ }
+ if !e.planThrottleAdmit(refusal, r, up) {
+ return
+ }
+ releaseSlot, ok := e.rateAdmit(refusal, r, up)
+ if !ok {
+ return
+ }
+ if releaseSlot != nil {
+ defer releaseSlot()
+ }
+ var appWriter http.ResponseWriter = policy
+ if releaseSlot != nil {
+ appWriter = &slotWriter{ResponseWriter: policy, release: releaseSlot}
+ }
+ if isUpgradeRequest(r) {
+ serveDemoPlain(policy, r, 400, "DEMO-RESPONSE")
+ return
+ }
+ for _, dest := range r.Header.Values("Sec-Fetch-Dest") {
+ dest = strings.ToLower(strings.TrimSpace(dest))
+ if dest == "worker" || dest == "serviceworker" || dest == "sharedworker" {
+ serveDemoPlain(policy, r, 400, "DEMO-RESPONSE")
+ return
+ }
+ }
+ if !up.route.IsForward() {
+ if e.serveDemoAsset(policy, r) {
+ return
+ }
+ if err := wire.counter.Admit(ctx, wire.id); err != nil {
+ status, copyID := demoTrafficError(err)
+ serveDemoPlain(policy, r, status, copyID)
+ return
+ }
+ }
+ if !wire.allowed() {
+ serveDemoPlain(policy, r, 503, "DEMO-UNAVAILABLE")
+ return
+ }
+ wire.overhead = false
+ proxy := up.proxy
+ if p, ok := proxy.(*httputil.ReverseProxy); ok {
+ proxy = e.demoProxy(p, up.route)
+ }
+
+ if proxy == nil {
+ serveDemoPlain(policy, r, 503, "DEMO-UNAVAILABLE")
+ return
+ }
+ if up.hibernating && e.act != nil {
+ // The activator's own answers are platform refusals. A successful wake
+ // invokes the app proxy with the normal counted writer instead.
+ appProxy := http.HandlerFunc(func(_ http.ResponseWriter, req *http.Request) { proxy.ServeHTTP(appWriter, req) })
+ if e.act.ServeHTTP(refusal, r, up.route, appProxy) {
+ return
+ }
+ }
+ proxy.ServeHTTP(appWriter, r)
+}
+
+func demoTrafficError(err error) (int, string) {
+ if errors.Is(err, demo.ErrTrafficLimit) {
+ return 429, "DEMO-LIMIT-PRECLAIM"
+ }
+ return 503, "DEMO-UNAVAILABLE"
+}
+
+// No embedding, Unwrap, Hijack or ReaderFrom: all output passes Write.
+// Headers are delayed until a successful debit, so failure before output can
+// still produce the bounded platform page instead of an empty app response.
+type demoTrafficWriter struct {
+ dst http.ResponseWriter
+ request *http.Request
+ header http.Header
+ counter demo.TrafficCounter
+ id demo.TrafficIdentity
+ cancel context.CancelFunc
+ allowed func() bool
+ status int
+ committed, overhead, failed, fallback bool
+}
+
+func (w *demoTrafficWriter) Header() http.Header { return w.header }
+func (w *demoTrafficWriter) WriteHeader(status int) {
+ if w.status == 0 && status >= 200 {
+ w.status = status
+ }
+}
+func (w *demoTrafficWriter) deadline() error {
+ err := http.NewResponseController(w.dst).SetWriteDeadline(time.Now().Add(demoWriteTimeout))
+ if errors.Is(err, http.ErrNotSupported) {
+ return nil
+ }
+ return err
+}
+func (w *demoTrafficWriter) commit() error {
+ if w.committed {
+ return nil
+ }
+ if w.status == 0 {
+ w.status = 200
+ }
+ if err := w.deadline(); err != nil {
+ return err
+ }
+ clear(w.dst.Header())
+ for k, v := range w.header {
+ w.dst.Header()[k] = append([]string(nil), v...)
+ }
+ w.dst.WriteHeader(w.status)
+ w.committed = true
+ return nil
+}
+func (w *demoTrafficWriter) check() error {
+ if w.failed || !w.allowed() {
+ return demo.ErrTrafficUnavailable
+ }
+ return nil
+}
+func (w *demoTrafficWriter) fail(err error) error {
+ if w.failed {
+ return err
+ }
+ w.failed = true
+ w.cancel()
+ if !w.committed {
+ w.fallback = true
+ status, copyID := demoTrafficError(err)
+ // The fallback goes straight to the policy writer, outside this debit.
+ _ = w.deadline()
+ serveDemoPlain(w.dst, w.request, status, copyID)
+ }
+ return err
+}
+func (w *demoTrafficWriter) Write(p []byte) (int, error) {
+ if err := w.check(); err != nil {
+ return 0, w.fail(err)
+ }
+ if w.status == 0 {
+ w.status = 200
+ }
+ if w.request.Method == "HEAD" || w.status == 204 || w.status == 205 || w.status == 304 {
+ return len(p), nil
+ }
+ written := 0
+ for len(p) > 0 {
+ if err := w.check(); err != nil {
+ return written, w.fail(err)
+ }
+ n := min(len(p), demoDebitChunk)
+ allowed := int64(n)
+ if w.counter != nil && !w.overhead {
+ var err error
+ allowed, err = w.counter.DebitBytes(w.request.Context(), w.id, int64(n))
+ if err != nil {
+ return written, w.fail(err)
+ }
+ if allowed < 0 || allowed > int64(n) {
+ return written, w.fail(demo.ErrTrafficUnavailable)
+ }
+ }
+ if allowed == 0 {
+ return written, w.fail(demo.ErrTrafficLimit)
+ }
+ if err := w.check(); err != nil {
+ return written, w.fail(err)
+ }
+ if err := w.commit(); err != nil {
+ return written, w.fail(err)
+ }
+ if err := w.deadline(); err != nil {
+ return written, w.fail(err)
+ }
+ got, err := w.dst.Write(p[:int(allowed)])
+ written += got
+ if err != nil {
+ return written, w.fail(err)
+ }
+ if got != int(allowed) {
+ return written, w.fail(io.ErrShortWrite)
+ }
+ if allowed < int64(n) {
+ return written, w.fail(demo.ErrTrafficLimit)
+ }
+ p = p[n:]
+ }
+ return written, nil
+}
+func (w *demoTrafficWriter) FlushError() error {
+ if err := w.check(); err != nil {
+ return w.fail(err)
+ }
+ if w.counter != nil && !w.overhead && !w.committed {
+ if _, err := w.counter.DebitBytes(w.request.Context(), w.id, 0); err != nil {
+ return w.fail(err)
+ }
+ }
+ if err := w.commit(); err != nil {
+ return w.fail(err)
+ }
+ if err := w.deadline(); err != nil {
+ return w.fail(err)
+ }
+ if err := http.NewResponseController(w.dst).Flush(); err != nil {
+ return w.fail(err)
+ }
+ return nil
+}
+func (w *demoTrafficWriter) Flush() { _ = w.FlushError() }
+func (w *demoTrafficWriter) finish() {
+ if !w.failed && !w.allowed() {
+ w.fail(demo.ErrTrafficUnavailable)
+ }
+ if !w.failed && !w.committed {
+ if err := w.check(); err != nil {
+ w.fail(err)
+ } else if w.counter != nil && !w.overhead {
+ if _, err := w.counter.DebitBytes(w.request.Context(), w.id, 0); err != nil {
+ w.fail(err)
+ }
+ }
+ if !w.failed {
+ if err := w.commit(); err != nil {
+ w.fail(err)
+ }
+ }
+ }
+ if w.failed && !w.fallback {
+ panic(http.ErrAbortHandler)
+ }
+}
+
+// Installed before the asset scrubber and version wrapper hide the proxy.
+func (e *Edge) demoProxy(p *httputil.ReverseProxy, rt registry.Route) *httputil.ReverseProxy {
+ cp := *p
+ cp.ErrorHandler = func(w http.ResponseWriter, r *http.Request, _ error) { serveDemoPlain(w, r, 503, "DEMO-UNAVAILABLE") }
+ if rt.IsForward() {
+ base := cp.Transport
+ if base == nil {
+ base = http.DefaultTransport
+ }
+ if _, wrapped := base.(demoForwardTransport); !wrapped {
+ cp.Transport = demoForwardTransport{base: base}
+ }
+ }
+ if !rt.IsForward() {
+ base := cp.Transport
+ if base == nil {
+ base = http.DefaultTransport
+ }
+ if _, wrapped := base.(demoBannerTransport); !wrapped {
+ cp.Transport = demoBannerTransport{base: base, host: rt.Host, reportOrigin: e.demoReportOrigin}
+ }
+ }
+ return &cp
+}
+
+// Existing admission/abuse/activation helpers keep their decision logic but
+// demos use only bounded, approved plain refusals, outside lifetime bytes.
+type demoRefusalWriter struct {
+ dst http.ResponseWriter
+ request *http.Request
+ header http.Header
+ wrote bool
+}
+
+func (w *demoRefusalWriter) Header() http.Header { return w.header }
+func (w *demoRefusalWriter) WriteHeader(status int) {
+ if w.wrote || status < 200 {
+ return
+ }
+ w.wrote = true
+ copyID := "DEMO-UNAVAILABLE"
+ switch status {
+ case 404:
+ copyID = "DEMO-GONE"
+ case 429:
+ copyID = "DEMO-LIMIT-PRECLAIM"
+ default:
+ if status < 400 {
+ status = 503
+ }
+ }
+ serveDemoPlain(w.dst, w.request, status, copyID)
+}
+func (w *demoRefusalWriter) Write(p []byte) (int, error) {
+ if !w.wrote {
+ w.WriteHeader(503)
+ }
+ return len(p), nil
+}
+func (w *demoRefusalWriter) Flush() {
+ if !w.wrote {
+ w.WriteHeader(503)
+ }
+ http.NewResponseController(w.dst).Flush()
+}
+
+// CancelDemoResponses ends current resident streams without retiring their
+// lifetimes. Task 4 calls it immediately on off/disconnect after closing its
+// serving snapshot; the per-write check also observes that closed snapshot.
+func (e *Edge) CancelDemoResponses() {
+ s := e.demoTraffic
+ if s == nil {
+ return
+ }
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ for a := range s.active {
+ a.cancel()
+ }
+}
+
+// An absent Accept-Encoding must not let net/http negotiate and transparently
+// decompress on a forwarding hop. The resident owns the wire representation.
+type demoForwardTransport struct{ base http.RoundTripper }
+
+func (t demoForwardTransport) RoundTrip(r *http.Request) (*http.Response, error) {
+ req := r.Clone(r.Context())
+ if req.Header.Get("Accept-Encoding") == "" {
+ req.Header.Set("Accept-Encoding", "identity")
+ }
+ return t.base.RoundTrip(req)
+}
diff --git a/internal/edge/demo_traffic_test.go b/internal/edge/demo_traffic_test.go
new file mode 100644
index 000000000..1a5cac678
--- /dev/null
+++ b/internal/edge/demo_traffic_test.go
@@ -0,0 +1,475 @@
+package edge
+
+import (
+ "bytes"
+ "compress/gzip"
+ "context"
+ "errors"
+ "fmt"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "sync"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/demo"
+ "github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/registry"
+)
+
+type demoTestCounter struct {
+ mu sync.Mutex
+ requests, bytes int64
+ caps demo.TrafficCaps
+ err error
+}
+
+func (c *demoTestCounter) Admit(ctx context.Context, id demo.TrafficIdentity) error {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ if c.err != nil {
+ return c.err
+ }
+ if c.requests >= c.caps.Requests || c.bytes >= c.caps.BodyBytes {
+ return demo.ErrTrafficLimit
+ }
+ c.requests++
+ return nil
+}
+func (c *demoTestCounter) DebitBytes(ctx context.Context, id demo.TrafficIdentity, n int64) (int64, error) {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ if c.err != nil {
+ return 0, c.err
+ }
+ if c.bytes >= c.caps.BodyBytes {
+ return 0, demo.ErrTrafficLimit
+ }
+ n = min(n, c.caps.BodyBytes-c.bytes)
+ c.bytes += n
+ return n, nil
+}
+
+func demoTrafficFixture(t *testing.T, handler http.Handler) (*Edge, registry.Route, *demoTestCounter) {
+ t.Helper()
+ id, err := demo.NewIdentity(strings.NewReader(strings.Repeat("\x00", 64)))
+ if err != nil {
+ t.Fatal(err)
+ }
+ host := id.Name + ".example.com"
+ rt := provision.RouteFor(provision.Record{Host: host, App: id.App, Account: "shop", Region: "fleet/demo", Channel: "edge", FleetBox: "box", FleetBoxAt: time.Now().UTC().Format(time.RFC3339Nano), Demo: &demo.Descriptor{ID: id.ID, Host: host, Lifetime: "life", ExpiresAt: time.Now().Add(time.Hour).Unix()}}, t.TempDir(), "", true, nil)
+ reg := openReg(t)
+ t.Cleanup(func() { reg.Close() })
+ e, err := New(reg, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(e.probers.Stop)
+ e.demo = demo.Config{Account: "shop", Fleet: "demo", Domain: "example.com", EdgeProtections: true}
+ e.box = "box"
+ e.demoReportOrigin = "https://console.example.com"
+ e.gzipOn = false
+
+ m := map[string]upstream{host: {route: rt, proxy: handler}}
+ e.upstreams.Store(&m)
+ c := &demoTestCounter{caps: demo.TrafficCaps{Requests: 2000, BodyBytes: 200000000}}
+ e.SetDemoTraffic(c, func(registry.Route, time.Time) bool { return true })
+ return e, rt, c
+}
+func TestDemoTrafficNoConsole(t *testing.T) {
+ e, rt, c := demoTrafficFixture(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+ w.Write([]byte("{}"))
+ }))
+ for _, method := range []string{"GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS"} {
+ r := httptest.NewRequest(method, "https://"+rt.Host+"/shop", nil)
+ rec := httptest.NewRecorder()
+ e.ServeHTTP(rec, r)
+ if rec.Code != 200 {
+ t.Fatalf("%s: %d %s", method, rec.Code, rec.Body.String())
+ }
+ assertDemoPolicy(t, rec.Header())
+ }
+ if c.requests != 6 || c.bytes != 10 {
+ t.Fatalf("counts %d %d", c.requests, c.bytes)
+ }
+ rec := httptest.NewRecorder()
+ e.ServeHTTP(rec, httptest.NewRequest("GET", "https://"+rt.Host+demoAssetPrefix+"banner.css", nil))
+ if rec.Code != 200 || c.requests != 6 || c.bytes != 10 {
+ t.Fatal("platform asset counted")
+ }
+}
+
+// This witness runs at the actual resident output boundary, after policy and
+// compression. Every body chunk must already appear in the counter.
+type demoOutputWitness struct {
+ *httptest.ResponseRecorder
+ counter *demoTestCounter
+ t *testing.T
+ delivered int64
+ short bool
+ deadlines int
+}
+
+func (w *demoOutputWitness) Write(p []byte) (int, error) {
+ w.counter.mu.Lock()
+ debit := w.counter.bytes
+ w.counter.mu.Unlock()
+ if len(p) > demoDebitChunk || w.delivered+int64(len(p)) > debit {
+ w.t.Fatalf("output outran debit: chunk %d delivered %d debit %d", len(p), w.delivered, debit)
+ }
+ if w.short {
+ return 0, io.ErrShortWrite
+ }
+ n, err := w.ResponseRecorder.Write(p)
+ w.delivered += int64(n)
+ return n, err
+}
+func (w *demoOutputWitness) SetWriteDeadline(time.Time) error { w.deadlines++; return nil }
+func demoRunAbort(f func()) (aborted bool) {
+ defer func() {
+ if p := recover(); p != nil {
+ if p != http.ErrAbortHandler {
+ panic(p)
+ }
+ aborted = true
+ }
+ }()
+ f()
+ return false
+}
+
+func TestDemoTrafficStreaming(t *testing.T) {
+ for _, kind := range []string{"large", "gzip-html", "gzip-json", "gzip-nonhtml", "range", "sse", "empty", "head", "partial", "endless", "short", "trailers", "no-write", "read-failure"} {
+ t.Run(kind, func(t *testing.T) {
+ body := strings.Repeat("shop", (3<<20)/4)
+ app := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "application/octet-stream")
+ switch kind {
+ case "gzip-html":
+ w.Header().Set("Content-Type", "text/html")
+ w.Header().Set("Content-Encoding", "gzip")
+ gz := gzip.NewWriter(w)
+ io.WriteString(gz, "<body>"+body)
+ gz.Close()
+ return
+ case "gzip-nonhtml":
+ w.Header().Set("Content-Type", "application/json")
+ w.Header().Set("Content-Encoding", "gzip")
+ gz := gzip.NewWriter(w)
+ io.WriteString(gz, body)
+ gz.Close()
+ return
+ case "gzip-json":
+ w.Header().Set("Content-Type", "application/json")
+ case "range":
+ w.Header().Set("Content-Range", "bytes 0-3/100")
+ w.WriteHeader(206)
+ io.WriteString(w, "shop")
+ return
+ case "endless":
+ w.Header().Set("Content-Type", "text/event-stream")
+ for {
+ select {
+ case <-r.Context().Done():
+ return
+ default:
+ }
+ if _, err := io.WriteString(w, strings.Repeat("data: shop\n\n", 1024)); err != nil {
+ return
+ }
+ w.(http.Flusher).Flush()
+ }
+ case "sse":
+ w.Header().Set("Content-Type", "text/event-stream")
+ for range 10 {
+ io.WriteString(w, "data: shop\n\n")
+ w.(http.Flusher).Flush()
+ }
+ return
+ case "empty":
+ w.WriteHeader(204)
+ return
+ case "head":
+ w.Header().Set("Content-Length", "100")
+ return
+ case "trailers":
+ w.Header().Set("Trailer", "Set-Cookie, Content-Security-Policy")
+ io.WriteString(w, "shop")
+ w.Header().Set("Set-Cookie", "bad=1; Domain=example.com")
+ w.Header().Set("Content-Security-Policy", "bad")
+ return
+ case "read-failure":
+ w.Header().Set("Content-Length", "100")
+ io.WriteString(w, "shop")
+ return
+ }
+ io.Copy(w, strings.NewReader(body))
+ }))
+ defer app.Close()
+ e, rt, c := demoTrafficFixture(t, demoTestProxy(t, app.URL))
+ e.gzipOn = true
+ if kind == "no-write" {
+ demoSetProxy(e, rt, http.HandlerFunc(func(http.ResponseWriter, *http.Request) {}))
+ }
+ if kind == "partial" || kind == "endless" {
+ c.caps.BodyBytes = 33000
+ }
+ rec := httptest.NewRecorder()
+ w := &demoOutputWitness{ResponseRecorder: rec, counter: c, t: t, short: kind == "short"}
+ method := "GET"
+ if kind == "head" {
+ method = "HEAD"
+ }
+ r := httptest.NewRequest(method, "https://"+rt.Host+"/shop", nil)
+ r = r.WithContext(context.WithValue(r.Context(), http.ServerContextKey, &http.Server{}))
+ if strings.HasPrefix(kind, "gzip") {
+ r.Header.Set("Accept-Encoding", "gzip")
+ }
+ // A no-write response is platform overhead; use its ordinary recorder.
+ var dst http.ResponseWriter = w
+ if kind == "no-write" {
+ dst = rec
+ }
+ aborted := demoRunAbort(func() { e.ServeHTTP(dst, r) })
+ if (kind == "partial" || kind == "endless" || kind == "short" || kind == "read-failure") != aborted {
+ t.Fatalf("aborted %v", aborted)
+ }
+ if c.requests != 1 {
+ t.Fatalf("requests %d", c.requests)
+ }
+ if kind == "no-write" {
+ if rec.Code != 502 || c.bytes != 0 {
+ t.Fatalf("empty handler %d %d", rec.Code, c.bytes)
+ }
+ return
+ }
+ if w.delivered > c.bytes || w.deadlines == 0 {
+ t.Fatalf("wire %d debit %d deadlines %d", w.delivered, c.bytes, w.deadlines)
+ }
+ if kind == "head" || kind == "empty" {
+ if c.bytes != 0 {
+ t.Fatal("bodyless debit")
+ }
+ }
+ if kind == "partial" || kind == "endless" {
+ if c.bytes != 33000 || w.delivered != 33000 {
+ t.Fatalf("partial %d/%d", c.bytes, w.delivered)
+ }
+ next := httptest.NewRecorder()
+ e.ServeHTTP(next, r)
+ if next.Code != 429 {
+ t.Fatalf("later %d", next.Code)
+ }
+ }
+ if kind == "large" && w.delivered != int64(len(body)) {
+ t.Fatal("large body capped")
+ }
+ if strings.HasPrefix(kind, "gzip") {
+ gz, err := gzip.NewReader(bytes.NewReader(rec.Body.Bytes()))
+ if err != nil {
+ t.Fatal(err)
+ }
+ b, err := io.ReadAll(gz)
+ gz.Close()
+ if err != nil {
+ t.Fatal(err)
+ }
+ if kind == "gzip-html" && strings.Count(string(b), `id="carlos-demo-warning"`) != 1 {
+ t.Fatal("HTML warning")
+ }
+ }
+ if rec.Header().Get("Trailer") != "" || rec.Result().Trailer.Get("Set-Cookie") != "" {
+ t.Fatal("trailer escaped")
+ }
+ assertDemoPolicy(t, rec.Result().Header)
+ })
+ }
+}
+
+func TestDemoTrafficStorageErrorPage(t *testing.T) {
+ for _, after := range []bool{false, true} {
+ t.Run(fmt.Sprint(after), func(t *testing.T) {
+ var c *demoTestCounter
+ e, rt, counter := demoTrafficFixture(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if after {
+ w.Write([]byte("shop"))
+ }
+ c.mu.Lock()
+ c.err = errors.New("disk failure")
+ c.mu.Unlock()
+ w.Header().Set("Content-Type", "application/json")
+ w.Write([]byte("{}"))
+ }))
+ c = counter
+ rec := httptest.NewRecorder()
+ aborted := demoRunAbort(func() { e.ServeHTTP(rec, httptest.NewRequest("GET", "https://"+rt.Host+"/", nil)) })
+ if aborted != after {
+ t.Fatalf("abort %v", aborted)
+ }
+ if !after && (rec.Code != 503 || rec.Body.String() != demoCopy["DEMO-UNAVAILABLE"]+"\n") {
+ t.Fatalf("fallback %d %s", rec.Code, rec.Body.String())
+ }
+ })
+ }
+}
+
+func TestDemoTrafficStopActive(t *testing.T) {
+ for _, mode := range []string{"stop", "control", "expiry"} {
+ t.Run(mode, func(t *testing.T) {
+ started := make(chan struct{})
+ ended := make(chan struct{})
+ e, rt, c := demoTrafficFixture(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "text/event-stream")
+ w.Write([]byte("data: shop\n\n"))
+ w.(http.Flusher).Flush()
+ close(started)
+ <-r.Context().Done()
+ close(ended)
+ }))
+ var open atomic.Bool
+ open.Store(true)
+ e.SetDemoTraffic(c, func(registry.Route, time.Time) bool { return open.Load() })
+ if mode == "expiry" {
+ rt.DemoExpiresAt = time.Now().Add(time.Second).Unix()
+ demoSetProxy(e, rt, e.current()[rt.Host].proxy)
+ }
+ done := make(chan struct{})
+ go func() {
+ defer close(done)
+ demoRunAbort(func() { e.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest("GET", "https://"+rt.Host+"/", nil)) })
+ }()
+ select {
+ case <-started:
+ case <-time.After(2 * time.Second):
+ t.Fatal("did not start")
+ }
+ if mode == "stop" {
+ if err := e.StopDemoTraffic(t.Context(), demoTrafficID(rt)); err != nil {
+ t.Fatal(err)
+ }
+ } else if mode == "control" {
+ open.Store(false)
+ }
+ select {
+ case <-ended:
+ case <-time.After(2 * time.Second):
+ t.Fatal("upstream still active")
+ }
+ <-done
+ rec := httptest.NewRecorder()
+ e.ServeHTTP(rec, httptest.NewRequest("GET", "https://"+rt.Host+"/", nil))
+ if rec.Code < 400 || c.requests != 1 {
+ t.Fatal("reopened after stop")
+ }
+ })
+ }
+}
+
+func TestDemoTrafficReloadAndCacheBypass(t *testing.T) {
+ e, rt, c := demoTrafficFixture(t, nil)
+ rt.AssetsOff = false
+ if err := e.reg.Upsert(rt); err != nil {
+ t.Fatal(err)
+ }
+ if err := e.Reload(); err != nil {
+ t.Fatal(err)
+ }
+ up := e.current()[rt.Host]
+ wrapped, ok := up.proxy.(assetScrubbedProxy)
+ if !ok {
+ t.Fatalf("proxy %T", up.proxy)
+ }
+ transport, ok := wrapped.proxy.Transport.(demoBannerTransport)
+ if !ok {
+ t.Fatalf("transport %T", wrapped.proxy.Transport)
+ }
+ calls := 0
+ transport.base = roundTripperFunc(func(r *http.Request) (*http.Response, error) {
+ calls++
+ return &http.Response{StatusCode: 200, Header: http.Header{"Content-Type": {"text/html"}, "X-Carlos-Version": {"v1"}}, Body: io.NopCloser(strings.NewReader("<body>shop</body>")), Request: r, ContentLength: -1}, nil
+ })
+ wrapped.proxy.Transport = transport
+ e.EnableCache(NewCache(8, 4096))
+ // Seed a response the ordinary cache would reuse for the same request.
+ key := CacheKey{Host: rt.Host, Method: "GET", Path: "/index.html"}
+ e.cache.Put(key, "", &CachedResponse{StatusCode: 200, Header: http.Header{"Content-Type": {"text/html"}}, Body: []byte("stale"), StoredAt: time.Now(), TTL: time.Hour})
+ r := httptest.NewRequest("GET", "https://"+rt.Host+"/index.html", nil)
+ for range 2 {
+ rec := httptest.NewRecorder()
+ e.ServeHTTP(rec, r)
+ if rec.Code != 200 || !strings.Contains(rec.Body.String(), `id="carlos-demo-warning"`) || strings.Contains(rec.Body.String(), "stale") {
+ t.Fatalf("reload output %d %s", rec.Code, rec.Body.String())
+ }
+ }
+ if calls != 2 || c.requests != 2 {
+ t.Fatalf("cache shortcut %d %d", calls, c.requests)
+ }
+ rec := httptest.NewRecorder()
+ e.ServeHTTP(rec, httptest.NewRequest("GET", "https://"+rt.Host+demoAssetPrefix+"banner.css", nil))
+ if calls != 2 || c.requests != 2 || rec.Header().Get("X-Carlos-Version") != "" {
+ t.Fatal("reserved path escaped")
+ }
+ // A new build generation reuses the original lifetime counter.
+ rt.Version = "v2"
+ if err := e.reg.Upsert(rt); err != nil {
+ t.Fatal(err)
+ }
+ if err := e.Reload(); err != nil {
+ t.Fatal(err)
+ }
+ // A failed dispatch still costs a request, but its platform page has no version.
+ rec = httptest.NewRecorder()
+ e.ServeHTTP(rec, r)
+ if rec.Code != 503 || rec.Header().Get("X-Carlos-Version") != "" || c.requests != 3 {
+ t.Fatalf("failed update dispatch %d %v count %d", rec.Code, rec.Header(), c.requests)
+ }
+}
+
+func TestDemoTrafficPurgeDrainsWriter(t *testing.T) {
+ entered := make(chan struct{})
+ release := make(chan struct{})
+ e, rt, c := demoTrafficFixture(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Write([]byte("shop")) }))
+ dst := &demoBlockedWriter{ResponseRecorder: httptest.NewRecorder(), entered: entered, release: release}
+ done := make(chan struct{})
+ go func() {
+ defer close(done)
+ demoRunAbort(func() { e.ServeHTTP(dst, httptest.NewRequest("GET", "https://"+rt.Host+"/", nil)) })
+ }()
+ <-entered
+ stopped := make(chan error, 1)
+ go func() { stopped <- e.StopDemoTraffic(t.Context(), demoTrafficID(rt)) }()
+ select {
+ case <-stopped:
+ t.Fatal("purge passed an active writer")
+ case <-time.After(20 * time.Millisecond):
+ }
+ close(release)
+ if err := <-stopped; err != nil {
+ t.Fatal(err)
+ }
+ <-done
+ if c.bytes != 4 {
+ t.Fatal("in-flight bytes were not charged")
+ }
+ rec := httptest.NewRecorder()
+ e.ServeHTTP(rec, httptest.NewRequest("GET", "https://"+rt.Host+"/", nil))
+ if rec.Code < 400 || c.requests != 1 {
+ t.Fatal("stale route recreated")
+ }
+}
+
+type demoBlockedWriter struct {
+ *httptest.ResponseRecorder
+ entered, release chan struct{}
+}
+
+func (w *demoBlockedWriter) Write(p []byte) (int, error) {
+ close(w.entered)
+ <-w.release
+ return w.ResponseRecorder.Write(p)
+}
+func (w *demoBlockedWriter) SetWriteDeadline(time.Time) error { return nil }
diff --git a/internal/edge/edge.go b/internal/edge/edge.go
index 69bc13f9f..a4feaefd4 100644
--- a/internal/edge/edge.go
+++ b/internal/edge/edge.go
@@ -121,10 +121,12 @@ type Edge struct {
replicaMu sync.Mutex
replicaProbes *replicaProber
- demo demo.Config
- demoNames atomic.Pointer[map[string]bool] // includes marked routes refused by reload
- devbox bool // installs front-door proxy hooks on every reload
- reg *registry.Registry
+ demoTraffic *demoTrafficState
+ demoReportOrigin string
+ demo demo.Config
+ demoNames atomic.Pointer[map[string]bool] // includes marked routes refused by reload
+ devbox bool // installs front-door proxy hooks on every reload
+ reg *registry.Registry
// hold is this Edge's local-upstream hold settings (localhold.go), set
// before the startup Reload and read by it.
hold localHold
@@ -569,7 +571,7 @@ func New(reg *registry.Registry, act Activator) (*Edge, error) {
// newEdge is New with the local-upstream hold settings given, so a test can
// shorten or turn off a hold on its own Edge without touching a global.
func newEdge(reg *registry.Registry, act Activator, hold localHold) (*Edge, error) {
- e := &Edge{demo: demoEdgeConfig(), reg: reg, act: act, hold: hold, gate: gate.New(), probers: newProberSet(hold), gzipOn: gzipEnabled(), guard: guardModeFromEnv(os.Getenv), steeringHost: steeringProbeHostFromEnv(), appsDomain: appsDomainFromEnv(),
+ e := &Edge{demoReportOrigin: os.Getenv("CARLOS_DEMO_CONSOLE_URL"), demo: demoEdgeConfig(), reg: reg, act: act, hold: hold, gate: gate.New(), probers: newProberSet(hold), gzipOn: gzipEnabled(), guard: guardModeFromEnv(os.Getenv), steeringHost: steeringProbeHostFromEnv(), appsDomain: appsDomainFromEnv(),
lbHealth: lbHealthFromEnv(os.Getenv, act), rateMode: rateModeFromEnv(), rateLimiter: ratelimit.NewLimiter(time.Now, 100_000),
planLimiter: ratelimit.NewLimiter(time.Now, 100_000), burst: newBurstLimiter(time.Now), notices: newBurstNotices(),
held: newHeldSet(DefaultHeldConfig)}
@@ -1168,6 +1170,9 @@ func (e *Edge) Reload() error {
// Wrapping the handler covers each way the proxy is reached: the
// ordinary path, the upgrade branch, the activator and a fill.
if p, ok := proxy.(*httputil.ReverseProxy); ok {
+ if t.IsDemo() {
+ p = e.demoProxy(p, t)
+ }
if e.devbox {
socketPath := ""
if arm == ArmSocket {
@@ -1891,7 +1896,7 @@ func firstSegmentClean(p string) string {
}
func (e *Edge) ServeHTTP(w http.ResponseWriter, r *http.Request) {
- if e.refuseDemoRequest(w, r) {
+ if e.handleDemoRequest(w, r, true) {
return
}
host := r.Host
@@ -2003,15 +2008,10 @@ func (e *Edge) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// Recheck the selected row: reload may have published since entry, and
// no marked route may enter ordinary dispatch even outside the demo zone.
if ok && up.route.IsDemo() {
- status, copyID := http.StatusNotFound, "DEMO-GONE"
- if _, valid := demoAuthority(r.Host); !valid {
- status = http.StatusBadRequest
- } else if e.demoRouteOK(host, up.route) && !up.alias && !up.platformAlias {
- status, copyID = http.StatusServiceUnavailable, "DEMO-UNAVAILABLE"
- }
- serveDemoPlain(w, r, status, copyID)
+ e.serveDemoTraffic(w, r, up)
return
}
+
if ok && e.admissionRefuses(w, r, up.route) {
return
}
diff --git a/internal/host/agent.go b/internal/host/agent.go
index 90e3ab431..63356b004 100644
--- a/internal/host/agent.go
+++ b/internal/host/agent.go
@@ -186,6 +186,7 @@ import (
"github.com/carlosframework/platform/internal/caps"
"github.com/carlosframework/platform/internal/cgroup"
"github.com/carlosframework/platform/internal/controlsock"
+ "github.com/carlosframework/platform/internal/demo"
"github.com/carlosframework/platform/internal/domains"
"github.com/carlosframework/platform/internal/edge"
"github.com/carlosframework/platform/internal/edgesfile"
@@ -305,6 +306,25 @@ func runAgent(args []string, buildClaims ClaimFactory) {
log.Fatalf("agent: open registry %s: %v", regPath, err)
}
+ var traffic *demoTrafficStore
+ var demoEdge atomic.Pointer[edge.Edge]
+ if os.Getenv("CARLOS_DEMO_DOMAIN") != "" {
+ traffic, err = openDemoTraffic(filepath.Join(filepath.Dir(regPath), "demo-traffic.db"))
+ if err != nil {
+ log.Printf("agent: DEMO-UNAVAILABLE: %v", err)
+ }
+ if traffic != nil {
+ defer traffic.Close()
+ }
+ }
+ stopDemoTraffic := func(ctx context.Context, id demo.TrafficIdentity) error {
+ e := demoEdge.Load()
+ if e == nil {
+ return demo.ErrTrafficUnavailable
+ }
+ return e.StopDemoTraffic(ctx, id)
+ }
+
// Constructed once here so the activator's ExecBackend (purges) and the
// edge (reads + serves cached hits) share the very same store — see the
// package doc comment above about caching applying before the
@@ -985,7 +1005,7 @@ func runAgent(args []string, buildClaims ClaimFactory) {
// box), before any loop that reconciles.
admission.armRoles(agentCtx, os.Getenv, metricsBoxLabel(os.Getenv, readMachineID()))
armPolicyCache()
- startDemoWorker(agentCtx, reg, demoData, cfg.Prefix)
+ startDemoWorker(agentCtx, reg, demoData, cfg.Prefix, traffic, stopDemoTraffic)
go adoptLoop(reg, svc, sd, claims.Writes)
go fastConvergeLoop(reg, svc, sd, claims.Writes, serialClaims, bs, boxJudge, claims.Providers.Provision)
if logSink != nil {
@@ -1131,6 +1151,13 @@ func runAgent(args []string, buildClaims ClaimFactory) {
var healthWG sync.WaitGroup
defer func() { healthCancel(); healthWG.Wait() }()
edge.RunWithActivatorReady(args, act, cache, func(e *edge.Edge) {
+ var counter demo.TrafficCounter
+ if traffic != nil {
+ counter = traffic
+ }
+ // Task 4 supplies demoServingAllowed and authenticated initialization.
+ e.SetDemoTraffic(counter, func(registry.Route, time.Time) bool { return false })
+ demoEdge.Store(e)
armedGroupReaders.Store(&groupReaderSource{snapshot: e.GroupReaderSnapshot})
// Read the current hub view on each private socket request.
readReplicaHealth := e.ReplicaSnapshots
diff --git a/internal/host/demo_cleanup.go b/internal/host/demo_cleanup.go
index 8b28fb4a7..c2701307b 100644
--- a/internal/host/demo_cleanup.go
+++ b/internal/host/demo_cleanup.go
@@ -48,7 +48,7 @@ func (w *demoWorker) retireDemo(ctx context.Context, wire []byte) error {
}
op := "demo-retire/" + r.Demo.ID
if rt != nil {
- if rt.DemoID != r.Demo.ID || rt.DemoLifetime != r.Demo.Lifetime || rt.DemoHost != r.Demo.Host || rt.Account != r.Account || rt.App != r.App || rt.Assigned != w.box || rt.Region != "fleet/"+r.Fleet {
+ if rt.DemoID != r.Demo.ID || rt.DemoLifetime != r.Demo.Lifetime || rt.DemoHost != r.Demo.Host || rt.Account != r.Account || rt.App != r.App || rt.FleetBox != w.box || rt.Region != "fleet/"+r.Fleet {
return demo.ErrPolicy
}
ok, err := w.reg.SetHoldIf(rt.Host, "releasing", op, rt.HoldOp)
@@ -62,6 +62,13 @@ func (w *demoWorker) retireDemo(ctx context.Context, wire []byte) error {
w.notify()
}
}
+ id := demo.TrafficIdentity{ID: r.Demo.ID, Lifetime: r.Demo.Lifetime, Host: r.Demo.Host}
+ if w.traffic == nil || w.stopTraffic == nil {
+ return demo.ErrTrafficUnavailable
+ }
+ if err = w.stopTraffic(ctx, id); err != nil {
+ return err
+ }
if err = w.purge(ctx, instancectl.DemoPurgeRequest{Demo: r.Demo, Jobs: r.Jobs}); err != nil {
return err
}
@@ -75,6 +82,9 @@ func (w *demoWorker) retireDemo(ctx context.Context, wire []byte) error {
if w.notify != nil {
w.notify()
}
+ if err = w.traffic.Purge(ctx, id); err != nil {
+ return err
+ }
if err = w.acknowledge(ctx, wire); err != nil {
return err
}
diff --git a/internal/host/demo_cleanup_test.go b/internal/host/demo_cleanup_test.go
index 4bf0ba1a6..380dff30d 100644
--- a/internal/host/demo_cleanup_test.go
+++ b/internal/host/demo_cleanup_test.go
@@ -32,7 +32,7 @@ func TestDemoOfflineRetirement(t *testing.T) {
t.Fatal(err)
}
defer reg.Close()
- rt := registry.Route{Host: d.Host, Kind: "instance", Account: "shop", App: id.App, Region: "fleet/demo", Assigned: "box", DemoID: d.ID, DemoHost: d.Host, DemoLifetime: d.Lifetime, DemoExpiresAt: d.ExpiresAt}
+ rt := registry.Route{Host: d.Host, Kind: "instance", Account: "shop", App: id.App, Region: "fleet/demo", Assigned: time.Now().UTC().Format(time.RFC3339Nano), FleetBox: "box", DemoID: d.ID, DemoHost: d.Host, DemoLifetime: d.Lifetime, DemoExpiresAt: d.ExpiresAt}
if err = reg.Upsert(rt); err != nil {
t.Fatal(err)
}
@@ -48,9 +48,19 @@ func TestDemoOfflineRetirement(t *testing.T) {
if _, err = data.Put(t.Context(), marker, []byte("proof"), ""); err != nil {
t.Fatal(err)
}
+ traffic, err := openDemoTraffic(filepath.Join(t.TempDir(), "demo-traffic.db"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer traffic.Close()
+ trafficID := demo.TrafficIdentity{ID: d.ID, Lifetime: d.Lifetime, Host: d.Host}
+ if err = traffic.Initialize(t.Context(), trafficID, demo.TrafficCaps{Requests: 2000, BodyBytes: 200000000}); err != nil {
+ t.Fatal(err)
+ }
+ fenced := false
rootCalls, acks := 0, 0
fail := true
- w := &demoWorker{store: store, cfg: cfg, pub: pub, box: "box", reg: reg, data: data, dataPrefix: "instances", complete: func(ctx context.Context, _ []byte) error {
+ w := &demoWorker{traffic: traffic, stopTraffic: func(context.Context, demo.TrafficIdentity) error { fenced = true; return nil }, store: store, cfg: cfg, pub: pub, box: "box", reg: reg, data: data, dataPrefix: "instances", complete: func(ctx context.Context, _ []byte) error {
if _, _, err := data.Get(ctx, marker); !errors.Is(err, os.ErrNotExist) {
t.Fatal("remote marker retained after final ack")
}
@@ -58,6 +68,9 @@ func TestDemoOfflineRetirement(t *testing.T) {
},
purge: func(ctx context.Context, in instancectl.DemoPurgeRequest) error {
rootCalls++
+ if !fenced {
+ t.Fatal("root purge before writer fence")
+ }
row, _ := reg.Get(d.Host)
if rootCalls <= 2 && (row == nil || row.HoldOp != "demo-retire/"+d.ID) {
t.Fatal("purge before route held")
@@ -69,6 +82,9 @@ func TestDemoOfflineRetirement(t *testing.T) {
},
acknowledge: func(ctx context.Context, b []byte) error {
acks++
+ if err := traffic.Admit(ctx, trafficID); err == nil {
+ t.Fatal("ack before counter purge")
+ }
if acks == 1 {
if _, _, err := data.Get(ctx, marker); err != nil {
t.Fatal("remote marker removed before local acknowledgment")
diff --git a/internal/host/demo_jobs.go b/internal/host/demo_jobs.go
index 84cf6af9e..4ef54e986 100644
--- a/internal/host/demo_jobs.go
+++ b/internal/host/demo_jobs.go
@@ -39,6 +39,8 @@ type demoRootBuilder interface {
}
type demoWorker struct {
+ traffic *demoTrafficStore
+ stopTraffic func(context.Context, demo.TrafficIdentity) error
reg *registry.Registry
data release.Store
dataPrefix string
@@ -60,7 +62,7 @@ type demoWorker struct {
notify func()
}
-func startDemoWorker(ctx context.Context, reg *registry.Registry, data release.Store, dataPrefix string) {
+func startDemoWorker(ctx context.Context, reg *registry.Registry, data release.Store, dataPrefix string, traffic *demoTrafficStore, stopTraffic func(context.Context, demo.TrafficIdentity) error) {
if os.Getenv("CARLOS_DEMO_BUILD_WORKER") != "1" {
return
}
@@ -96,7 +98,7 @@ func startDemoWorker(ctx context.Context, reg *registry.Registry, data release.S
log.Printf("agent: demo worker: console origin unavailable")
return
}
- w := &demoWorker{reg: reg, data: data, dataPrefix: dataPrefix, purge: instancectl.NewClient(controlsock.Path).PurgeDemo, cfg: cfg, pub: pub, box: identity.Label, base: base, store: store, credentials: fleetCredential(os.Getenv), build: root.BuildDemo, notify: func() { backstopFullDue.Store(true) }}
+ w := &demoWorker{traffic: traffic, stopTraffic: stopTraffic, reg: reg, data: data, dataPrefix: dataPrefix, purge: instancectl.NewClient(controlsock.Path).PurgeDemo, cfg: cfg, pub: pub, box: identity.Label, base: base, store: store, credentials: fleetCredential(os.Getenv), build: root.BuildDemo, notify: func() { backstopFullDue.Store(true) }}
w.http = &http.Client{Timeout: demobuild.ResultGrace, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}
w.readiness = root.DemoBuildReadiness
w.pickup = w.pickupHTTP
diff --git a/internal/host/demo_retirement_stream_test.go b/internal/host/demo_retirement_stream_test.go
index 1556159bf..321b7aef1 100644
--- a/internal/host/demo_retirement_stream_test.go
+++ b/internal/host/demo_retirement_stream_test.go
@@ -78,7 +78,7 @@ func testDemoRetirementStream(t *testing.T, builderReady, slow bool) {
if err := release.TrashApp(t.Context(), store, "shop", id.App, "expiry", time.Unix(d.ExpiresAt, 0)); err != nil {
t.Fatal(err)
}
- if err := reg.Upsert(registry.Route{Host: d.Host, Kind: "instance", Hibernate: true, Provisioned: true, Socket: provision.NestedSocket(d.Host), Account: "shop", App: id.App, Region: "fleet/demo", Assigned: "box", DemoID: d.ID, DemoHost: d.Host, DemoLifetime: d.Lifetime, DemoExpiresAt: d.ExpiresAt}); err != nil {
+ if err := reg.Upsert(registry.Route{Host: d.Host, Kind: "instance", Hibernate: true, Provisioned: true, Socket: provision.NestedSocket(d.Host), Account: "shop", App: id.App, Region: "fleet/demo", Assigned: time.Now().UTC().Format(time.RFC3339Nano), FleetBox: "box", DemoID: d.ID, DemoHost: d.Host, DemoLifetime: d.Lifetime, DemoExpiresAt: d.ExpiresAt}); err != nil {
t.Fatal(err)
}
}
@@ -92,8 +92,15 @@ func testDemoRetirementStream(t *testing.T, builderReady, slow bool) {
var releaseOnce sync.Once
defer releaseOnce.Do(func() { close(releasePurge) })
var failed, completed atomic.Int32
+ completedRetirement := make(chan struct{}, retirementCount)
reached := make(chan struct{}, retirementCount*2)
- w := &demoWorker{reg: reg, store: store, data: release.NewDirStore(t.TempDir()), cfg: cfg, pub: pub, box: "box", credentials: func() (string, string, bool) { return "demo/box", "token", true },
+ traffic, err := openDemoTraffic(filepath.Join(t.TempDir(), "demo-traffic.db"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer traffic.Close()
+ front.SetDemoTraffic(traffic, func(registry.Route, time.Time) bool { return false })
+ w := &demoWorker{traffic: traffic, stopTraffic: front.StopDemoTraffic, reg: reg, store: store, data: release.NewDirStore(t.TempDir()), cfg: cfg, pub: pub, box: "box", credentials: func() (string, string, bool) { return "demo/box", "token", true },
purge: func(ctx context.Context, in instancectl.DemoPurgeRequest) error {
row, err := reg.Get(in.Demo.Host)
if err != nil || row == nil || !registry.IsHold(row.Status) {
@@ -129,7 +136,7 @@ func testDemoRetirementStream(t *testing.T, builderReady, slow bool) {
}
return nil
},
- acknowledge: func(context.Context, []byte) error { return nil }, complete: func(context.Context, []byte) error { completed.Add(1); return nil }, notify: func() { reached <- struct{}{} }}
+ acknowledge: func(context.Context, []byte) error { return nil }, complete: func(context.Context, []byte) error { completed.Add(1); completedRetirement <- struct{}{}; return nil }, notify: func() { reached <- struct{}{} }}
w.readiness = func(ctx context.Context) (demobuild.WorkerReady, error) {
if !builderReady {
<-ctx.Done()
@@ -215,6 +222,17 @@ func testDemoRetirementStream(t *testing.T, builderReady, slow bool) {
t.Error("failed retirement blocked build pickup")
}
}
+ if attempt == 0 {
+ for range retirementCount - 1 {
+ select {
+ case <-completedRetirement:
+ case <-time.After(5 * time.Second):
+ cancel()
+ <-done
+ t.Fatal("counter purge did not complete")
+ }
+ }
+ }
cancel()
<-done
if w.buildReady().Valid() {
diff --git a/internal/host/demo_traffic.go b/internal/host/demo_traffic.go
new file mode 100644
index 000000000..7920700ec
--- /dev/null
+++ b/internal/host/demo_traffic.go
@@ -0,0 +1,191 @@
+package host
+
+import (
+ "context"
+ "database/sql"
+ "errors"
+ "net/url"
+ "os"
+ "path/filepath"
+
+ "github.com/carlosframework/platform/internal/demo"
+ _ "modernc.org/sqlite"
+)
+
+// Only the authenticated assignment stream may initialize an identity. Traffic
+// never inserts rows. The small assignment tombstone survives counter purge so
+// retries cannot reset an allowance or resurrect a retired lifetime.
+type demoTrafficStore struct{ db *sql.DB }
+
+func openDemoTraffic(path string) (*demoTrafficStore, error) {
+ if !filepath.IsAbs(path) {
+ return nil, demo.ErrTrafficUnavailable
+ }
+ f, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE, 0600)
+ if err != nil {
+ return nil, err
+ }
+ if err = f.Chmod(0600); err != nil {
+ f.Close()
+ return nil, err
+ }
+ if err = f.Close(); err != nil {
+ return nil, err
+ }
+ u := url.URL{Scheme: "file", Path: filepath.ToSlash(path)}
+ q := u.Query()
+ q.Add("_pragma", "busy_timeout(5000)")
+ q.Add("_pragma", "synchronous(FULL)")
+ q.Add("_pragma", "foreign_keys(ON)")
+ u.RawQuery = q.Encode()
+ db, err := sql.Open("sqlite", u.String())
+ if err != nil {
+ return nil, err
+ }
+ db.SetMaxOpenConns(1)
+ s := &demoTrafficStore{db: db}
+ _, err = db.Exec(`
+ CREATE TABLE IF NOT EXISTS demo_assignments (
+ demo_id TEXT NOT NULL, lifetime TEXT NOT NULL, host TEXT NOT NULL UNIQUE,
+ request_cap INTEGER NOT NULL CHECK(request_cap BETWEEN 1 AND 1000000),
+ byte_cap INTEGER NOT NULL CHECK(byte_cap BETWEEN 1 AND 10000000000),
+ terminal INTEGER NOT NULL DEFAULT 0 CHECK(terminal IN (0,1)),
+ PRIMARY KEY(demo_id,lifetime), UNIQUE(demo_id));
+ CREATE TABLE IF NOT EXISTS demo_traffic (
+ demo_id TEXT NOT NULL,lifetime TEXT NOT NULL,
+ requests INTEGER NOT NULL DEFAULT 0 CHECK(typeof(requests)='integer' AND requests>=0),
+ body_bytes INTEGER NOT NULL DEFAULT 0 CHECK(typeof(body_bytes)='integer' AND body_bytes>=0),
+ PRIMARY KEY(demo_id,lifetime),
+ FOREIGN KEY(demo_id,lifetime) REFERENCES demo_assignments(demo_id,lifetime));`)
+ if err != nil {
+ db.Close()
+ return nil, err
+ }
+ return s, nil
+}
+func (s *demoTrafficStore) Close() error { return s.db.Close() }
+
+// BEGIN IMMEDIATE serializes read/check/update across all database handles.
+// Returning success requires COMMIT, including SQLite's FULL sync, to succeed.
+func (s *demoTrafficStore) transaction(ctx context.Context, f func(*sql.Conn) error) error {
+ if s == nil || s.db == nil {
+ return demo.ErrTrafficUnavailable
+ }
+ c, err := s.db.Conn(ctx)
+ if err != nil {
+ return err
+ }
+ defer c.Close()
+ if _, err = c.ExecContext(ctx, "BEGIN IMMEDIATE"); err != nil {
+ return err
+ }
+ defer c.ExecContext(context.Background(), "ROLLBACK")
+ if err = f(c); err != nil {
+ return err
+ }
+ _, err = c.ExecContext(ctx, "COMMIT")
+ return err
+}
+func validTrafficIdentity(id demo.TrafficIdentity) bool {
+ return id.ID != "" && id.Lifetime != "" && demo.ValidDomain(id.Host)
+}
+
+func (s *demoTrafficStore) Initialize(ctx context.Context, id demo.TrafficIdentity, caps demo.TrafficCaps) error {
+ if !validTrafficIdentity(id) || !caps.Valid() {
+ return demo.ErrTrafficUnavailable
+ }
+ return s.transaction(ctx, func(c *sql.Conn) error {
+ var host string
+ var requests, bytes int64
+ var terminal int
+ err := c.QueryRowContext(ctx, `SELECT host,request_cap,byte_cap,terminal FROM demo_assignments WHERE demo_id=? AND lifetime=?`, id.ID, id.Lifetime).Scan(&host, &requests, &bytes, &terminal)
+ if err == nil {
+ if host != id.Host || requests != caps.Requests || bytes != caps.BodyBytes || terminal != 0 {
+ return demo.ErrTrafficUnavailable
+ }
+ var exists int
+ if err = c.QueryRowContext(ctx, `SELECT 1 FROM demo_traffic WHERE demo_id=? AND lifetime=?`, id.ID, id.Lifetime).Scan(&exists); err != nil {
+ return err
+ }
+ return nil
+ }
+ if !errors.Is(err, sql.ErrNoRows) {
+ return err
+ }
+ if _, err = c.ExecContext(ctx, `INSERT INTO demo_assignments(demo_id,lifetime,host,request_cap,byte_cap) VALUES(?,?,?,?,?)`, id.ID, id.Lifetime, id.Host, caps.Requests, caps.BodyBytes); err != nil {
+ return err
+ }
+ _, err = c.ExecContext(ctx, `INSERT INTO demo_traffic(demo_id,lifetime) VALUES(?,?)`, id.ID, id.Lifetime)
+ return err
+ })
+}
+
+func (s *demoTrafficStore) debit(ctx context.Context, id demo.TrafficIdentity, n int64, admit bool) (int64, error) {
+ if !validTrafficIdentity(id) || n < 0 {
+ return 0, demo.ErrTrafficUnavailable
+ }
+ var spent int64
+ err := s.transaction(ctx, func(c *sql.Conn) error {
+ var host string
+ var requests, bytes, rc, bc int64
+ var terminal int
+ err := c.QueryRowContext(ctx, `SELECT a.host,t.requests,t.body_bytes,a.request_cap,a.byte_cap,a.terminal FROM demo_assignments a JOIN demo_traffic t USING(demo_id,lifetime) WHERE a.demo_id=? AND a.lifetime=?`, id.ID, id.Lifetime).Scan(&host, &requests, &bytes, &rc, &bc, &terminal)
+ if err != nil {
+ return err
+ }
+ if host != id.Host || terminal != 0 || !(demo.TrafficCaps{Requests: rc, BodyBytes: bc}).Valid() || requests < 0 || requests > rc || bytes < 0 || bytes > bc {
+ return demo.ErrTrafficUnavailable
+ }
+ if bytes == bc || admit && requests == rc {
+ return demo.ErrTrafficLimit
+ }
+ if admit {
+ requests++
+ } else {
+ spent = min(n, bc-bytes)
+ bytes += spent
+ }
+ _, err = c.ExecContext(ctx, `UPDATE demo_traffic SET requests=?,body_bytes=? WHERE demo_id=? AND lifetime=?`, requests, bytes, id.ID, id.Lifetime)
+ return err
+ })
+ if err != nil {
+ return 0, err
+ }
+ return spent, nil
+}
+func (s *demoTrafficStore) Admit(ctx context.Context, id demo.TrafficIdentity) error {
+ _, err := s.debit(ctx, id, 0, true)
+ return err
+}
+func (s *demoTrafficStore) DebitBytes(ctx context.Context, id demo.TrafficIdentity, n int64) (int64, error) {
+ return s.debit(ctx, id, n, false)
+}
+
+// The caller first fences and drains the edge's responses and retires the
+// local app. Deletion and the permanent refusal commit in one transaction.
+func (s *demoTrafficStore) Purge(ctx context.Context, id demo.TrafficIdentity) error {
+ if !validTrafficIdentity(id) {
+ return demo.ErrTrafficUnavailable
+ }
+ return s.transaction(ctx, func(c *sql.Conn) error {
+ var host string
+ err := c.QueryRowContext(ctx, `SELECT host FROM demo_assignments WHERE demo_id=? AND lifetime=?`, id.ID, id.Lifetime).Scan(&host)
+ if errors.Is(err, sql.ErrNoRows) {
+ // A demo created before traffic protection has no counters to remove.
+ // Still remember retirement, so assignment replay cannot create them.
+ _, err = c.ExecContext(ctx, `INSERT INTO demo_assignments(demo_id,lifetime,host,request_cap,byte_cap,terminal) VALUES(?,?,?,?,?,1)`, id.ID, id.Lifetime, id.Host, demo.DefaultRequestCap, demo.DefaultBandwidthCapBytes)
+ return err
+ }
+ if err != nil {
+ return err
+ }
+ if host != id.Host {
+ return demo.ErrTrafficUnavailable
+ }
+ if _, err = c.ExecContext(ctx, `UPDATE demo_assignments SET terminal=1 WHERE demo_id=? AND lifetime=?`, id.ID, id.Lifetime); err != nil {
+ return err
+ }
+ _, err = c.ExecContext(ctx, `DELETE FROM demo_traffic WHERE demo_id=? AND lifetime=?`, id.ID, id.Lifetime)
+ return err
+ })
+}
diff --git a/internal/host/demo_traffic_linux_test.go b/internal/host/demo_traffic_linux_test.go
new file mode 100644
index 000000000..4c34ac29c
--- /dev/null
+++ b/internal/host/demo_traffic_linux_test.go
@@ -0,0 +1,70 @@
+//go:build linux
+
+package host
+
+import (
+ "errors"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "testing"
+ "unsafe"
+
+ "github.com/carlosframework/platform/internal/demo"
+ "golang.org/x/sys/unix"
+)
+
+// Inject EIO at the kernel sync boundary in an isolated test subprocess.
+// The filter only removes permission, needs no root, and dies with the child.
+func TestDemoTrafficFsyncFailure(t *testing.T) {
+ path := os.Getenv("CARLOS_TEST_TRAFFIC_SYNC_DB")
+ if path == "" {
+ path = filepath.Join(t.TempDir(), "demo-traffic.db")
+ cmd := exec.Command(os.Args[0], "-test.run=^TestDemoTrafficFsyncFailure$")
+ cmd.Dir = t.TempDir()
+ cmd.Env = append(os.Environ(), "CARLOS_TEST_TRAFFIC_SYNC_DB="+path)
+ if out, err := cmd.CombinedOutput(); err != nil {
+ t.Fatalf("sync failure child: %v\n%s", err, out)
+ }
+ s, err := openDemoTraffic(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer s.Close()
+ var requests, bytes int64
+ if err = s.db.QueryRow(`SELECT requests,body_bytes FROM demo_traffic`).Scan(&requests, &bytes); err != nil || requests != 0 || bytes != 0 {
+ t.Fatalf("failed sync committed: %d %d %v", requests, bytes, err)
+ }
+ return
+ }
+ s, err := openDemoTraffic(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer s.Close()
+ id := demo.TrafficIdentity{ID: "shop", Lifetime: "life", Host: "shop.example.com"}
+ if err = s.Initialize(t.Context(), id, demo.TrafficCaps{Requests: 2000, BodyBytes: 200000000}); err != nil {
+ t.Fatal(err)
+ }
+ filter := []unix.SockFilter{
+ {Code: unix.BPF_LD | unix.BPF_W | unix.BPF_ABS, K: 0},
+ {Code: unix.BPF_JMP | unix.BPF_JEQ | unix.BPF_K, K: uint32(unix.SYS_FSYNC), Jt: 1},
+ {Code: unix.BPF_JMP | unix.BPF_JEQ | unix.BPF_K, K: uint32(unix.SYS_FDATASYNC), Jf: 1},
+ {Code: unix.BPF_RET | unix.BPF_K, K: unix.SECCOMP_RET_ERRNO | uint32(unix.EIO)},
+ {Code: unix.BPF_RET | unix.BPF_K, K: unix.SECCOMP_RET_ALLOW},
+ }
+ if err = unix.Prctl(unix.PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0); err != nil {
+ t.Fatal(err)
+ }
+ program := unix.SockFprog{Len: uint16(len(filter)), Filter: &filter[0]}
+ unsynced, _, errno := unix.Syscall(unix.SYS_SECCOMP, unix.SECCOMP_SET_MODE_FILTER, unix.SECCOMP_FILTER_FLAG_TSYNC, uintptr(unsafe.Pointer(&program)))
+ if errno != 0 || unsynced != 0 {
+ t.Fatalf("install sync fault: %d %v", unsynced, errno)
+ }
+ if err = s.Admit(t.Context(), id); err == nil || errors.Is(err, demo.ErrTrafficLimit) {
+ t.Fatalf("request escaped sync failure: %v", err)
+ }
+ if n, err := s.DebitBytes(t.Context(), id, 17); n != 0 || err == nil || errors.Is(err, demo.ErrTrafficLimit) {
+ t.Fatalf("bytes escaped sync failure: %d %v", n, err)
+ }
+}
diff --git a/internal/host/demo_traffic_test.go b/internal/host/demo_traffic_test.go
new file mode 100644
index 000000000..31b4227d9
--- /dev/null
+++ b/internal/host/demo_traffic_test.go
@@ -0,0 +1,329 @@
+package host
+
+import (
+ "bufio"
+ "context"
+ "errors"
+ "fmt"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "strings"
+ "sync"
+ "testing"
+
+ "github.com/carlosframework/platform/internal/demo"
+)
+
+func TestDemoTrafficDurability(t *testing.T) {
+ path := filepath.Join(t.TempDir(), "demo-traffic.db")
+ a, err := openDemoTraffic(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer a.Close()
+ b, err := openDemoTraffic(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer b.Close()
+ for _, handle := range []*demoTrafficStore{a, b} {
+ var sync int
+ if err := handle.db.QueryRow("PRAGMA synchronous").Scan(&sync); err != nil || sync != 2 {
+ t.Fatalf("FULL sync: %d %v", sync, err)
+ }
+ }
+ if info, err := os.Stat(path); err != nil || info.Mode().Perm() != 0600 {
+ t.Fatalf("private database: %v %v", info, err)
+ }
+ ctx := t.Context()
+ id := demo.TrafficIdentity{ID: "shop", Lifetime: "life", Host: "shop.example.com"}
+ caps := demo.TrafficCaps{Requests: 2000, BodyBytes: 200000000}
+ if err := a.Initialize(ctx, id, caps); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := a.db.Exec(`UPDATE demo_traffic SET requests=1999`); err != nil {
+ t.Fatal(err)
+ }
+
+ var wg sync.WaitGroup
+ results := make(chan error, 2)
+ for _, s := range []*demoTrafficStore{a, b} {
+ wg.Add(1)
+ go func() { defer wg.Done(); results <- s.Admit(ctx, id) }()
+ }
+ wg.Wait()
+ close(results)
+ admitted := 0
+ for err := range results {
+ if err == nil {
+ admitted++
+ } else if !errors.Is(err, demo.ErrTrafficLimit) {
+ t.Fatal(err)
+ }
+ }
+ if admitted != 1 {
+ t.Fatalf("admitted %d", admitted)
+ }
+ if n, err := a.DebitBytes(ctx, id, 199999999); n != 199999999 || err != nil {
+ t.Fatalf("debit %d %v", n, err)
+ }
+ bytes := make(chan int64, 2)
+ for _, s := range []*demoTrafficStore{a, b} {
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ n, err := s.DebitBytes(ctx, id, 1)
+ if err != nil && !errors.Is(err, demo.ErrTrafficLimit) {
+ t.Error(err)
+ }
+ bytes <- n
+ }()
+ }
+ wg.Wait()
+ close(bytes)
+ var total int64
+ for n := range bytes {
+ total += n
+ }
+ if total != 1 {
+ t.Fatalf("bytes %d", total)
+ }
+ if err := a.Initialize(ctx, id, caps); err != nil {
+ t.Fatal(err)
+ }
+ c, err := openDemoTraffic(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer c.Close()
+ if !errors.Is(c.Admit(ctx, id), demo.ErrTrafficLimit) {
+ t.Fatal("reopen reset requests")
+ }
+ wrong := id
+ wrong.Host = "other.example.com"
+ if err := c.Admit(ctx, wrong); err == nil || errors.Is(err, demo.ErrTrafficLimit) {
+ t.Fatalf("binding %v", err)
+ }
+ if _, err := c.DebitBytes(ctx, id, -1); err == nil {
+ t.Fatal("negative debit")
+ }
+}
+
+func TestDemoTrafficPurge(t *testing.T) {
+ s, err := openDemoTraffic(filepath.Join(t.TempDir(), "demo-traffic.db"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer s.Close()
+ id := demo.TrafficIdentity{ID: "shop", Lifetime: "life", Host: "shop.example.com"}
+ caps := demo.TrafficCaps{Requests: 2000, BodyBytes: 200000000}
+ if err := s.Initialize(t.Context(), id, caps); err != nil {
+ t.Fatal(err)
+ }
+ for range 2 {
+ if err := s.Purge(t.Context(), id); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if err := s.Initialize(t.Context(), id, caps); err == nil {
+ t.Fatal("purge resurrected")
+ }
+ if err := s.Admit(t.Context(), id); err == nil {
+ t.Fatal("stale route admitted")
+ }
+ if n, err := s.DebitBytes(context.Background(), id, 1); err == nil || n != 0 {
+ t.Fatal("stale writer admitted")
+ }
+}
+
+func TestDemoTrafficStorageFailures(t *testing.T) {
+ for _, mode := range []string{"missing", "corrupt-row", "read-only", "disk-full", "commit-failure", "closed", "replacement"} {
+ t.Run(mode, func(t *testing.T) {
+ s, err := openDemoTraffic(filepath.Join(t.TempDir(), "demo-traffic.db"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer s.Close()
+ id := demo.TrafficIdentity{ID: "shop", Lifetime: "life", Host: "shop.example.com"}
+ caps := demo.TrafficCaps{Requests: 2000, BodyBytes: 200000000}
+ if mode != "replacement" {
+ if err = s.Initialize(t.Context(), id, caps); err != nil {
+ t.Fatal(err)
+ }
+ }
+ var setup string
+ switch mode {
+ case "missing":
+ setup = `DELETE FROM demo_traffic`
+ case "corrupt-row":
+ setup = `PRAGMA ignore_check_constraints=ON; UPDATE demo_traffic SET body_bytes=-1`
+ case "read-only":
+ setup = `PRAGMA query_only=ON`
+ case "disk-full":
+ setup = `PRAGMA max_page_count=10; CREATE TABLE fill(data BLOB); CREATE TRIGGER full_debit BEFORE UPDATE ON demo_traffic BEGIN INSERT INTO fill VALUES(zeroblob(1000000)); END`
+ case "commit-failure":
+ setup = `CREATE TABLE parent(id INTEGER PRIMARY KEY); CREATE TABLE child(id INTEGER REFERENCES parent(id) DEFERRABLE INITIALLY DEFERRED); CREATE TRIGGER failed_commit BEFORE UPDATE ON demo_traffic BEGIN INSERT INTO child VALUES(1); END`
+ case "closed":
+ s.Close()
+ }
+ if setup != "" {
+ if _, err = s.db.Exec(setup); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if err = s.Admit(t.Context(), id); err == nil || errors.Is(err, demo.ErrTrafficLimit) {
+ t.Fatalf("request failure = %v", err)
+ }
+ if n, err := s.DebitBytes(t.Context(), id, 10); n != 0 || err == nil || errors.Is(err, demo.ErrTrafficLimit) {
+ t.Fatalf("bytes %d %v", n, err)
+ }
+ if mode == "missing" {
+ if err = s.Initialize(t.Context(), id, caps); err == nil {
+ t.Fatal("missing counter reset")
+ }
+ }
+ if mode == "disk-full" || mode == "commit-failure" {
+ var requests, bytes int64
+ if err = s.db.QueryRow(`SELECT requests,body_bytes FROM demo_traffic`).Scan(&requests, &bytes); err != nil || requests != 0 || bytes != 0 {
+ t.Fatalf("rollback %d %d %v", requests, bytes, err)
+ }
+ }
+ })
+ }
+ t.Run("corrupt-database", func(t *testing.T) {
+ path := filepath.Join(t.TempDir(), "demo-traffic.db")
+ if err := os.WriteFile(path, []byte("not a database"), 0600); err != nil {
+ t.Fatal(err)
+ }
+ if s, err := openDemoTraffic(path); err == nil {
+ s.Close()
+ t.Fatal("corrupt database accepted")
+ }
+ })
+}
+
+func TestDemoTrafficCrashBoundaries(t *testing.T) {
+ for _, boundary := range []string{"before-request-commit", "after-request-commit", "before-byte-commit", "after-byte-commit", "after-output"} {
+ t.Run(boundary, func(t *testing.T) {
+ path := filepath.Join(t.TempDir(), "demo-traffic.db")
+ s, err := openDemoTraffic(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ id := demo.TrafficIdentity{ID: "shop", Lifetime: "life", Host: "shop.example.com"}
+ if err = s.Initialize(t.Context(), id, demo.TrafficCaps{Requests: 2000, BodyBytes: 200000000}); err != nil {
+ t.Fatal(err)
+ }
+ s.Close()
+ cmd := exec.Command(os.Args[0], "-test.run=^TestDemoTrafficCrashChild$")
+ cmd.Env = append(os.Environ(), "CARLOS_TEST_TRAFFIC_DB="+path, "CARLOS_TEST_TRAFFIC_BOUNDARY="+boundary)
+ cmd.Dir = t.TempDir()
+ stdout, err := cmd.StdoutPipe()
+ if err != nil {
+ t.Fatal(err)
+ }
+ stdin, err := cmd.StdinPipe()
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer stdin.Close()
+ cmd.Stderr = os.Stderr
+ if err = cmd.Start(); err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() {
+ if cmd.ProcessState == nil {
+ cmd.Process.Kill()
+ cmd.Wait()
+ }
+ })
+ scanner := bufio.NewScanner(stdout)
+ if !scanner.Scan() || scanner.Text() != "boundary" {
+ t.Fatal("child did not reach boundary")
+ }
+ if err = cmd.Process.Kill(); err != nil {
+ t.Fatal(err)
+ }
+ _ = cmd.Wait()
+ s, err = openDemoTraffic(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer s.Close()
+ var requests, bytes int64
+ if err = s.db.QueryRow(`SELECT requests,body_bytes FROM demo_traffic`).Scan(&requests, &bytes); err != nil {
+ t.Fatal(err)
+ }
+ wantReq, wantBytes := int64(1), int64(0)
+ if boundary == "before-request-commit" {
+ wantReq = 0
+ }
+ if boundary == "after-byte-commit" || boundary == "after-output" {
+ wantBytes = 17
+ }
+ if requests != wantReq || bytes != wantBytes {
+ t.Fatalf("after crash: %d/%d want %d/%d", requests, bytes, wantReq, wantBytes)
+ }
+ delivered, err := os.ReadFile(path + ".output")
+ if err != nil && !errors.Is(err, os.ErrNotExist) {
+ t.Fatal(err)
+ }
+ if int64(len(delivered)) > bytes {
+ t.Fatal("delivered bytes escaped commit")
+ }
+ })
+ }
+}
+
+func TestDemoTrafficCrashChild(t *testing.T) {
+ path := os.Getenv("CARLOS_TEST_TRAFFIC_DB")
+ if path == "" {
+ t.Skip("subprocess helper")
+ }
+ s, err := openDemoTraffic(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ ctx := context.Background()
+ id := demo.TrafficIdentity{ID: "shop", Lifetime: "life", Host: "shop.example.com"}
+ boundary := os.Getenv("CARLOS_TEST_TRAFFIC_BOUNDARY")
+ if boundary == "before-request-commit" || boundary == "before-byte-commit" {
+ if boundary == "before-byte-commit" {
+ if err = s.Admit(ctx, id); err != nil {
+ t.Fatal(err)
+ }
+ }
+ c, err := s.db.Conn(ctx)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err = c.ExecContext(ctx, "BEGIN IMMEDIATE"); err != nil {
+ t.Fatal(err)
+ }
+ update := `UPDATE demo_traffic SET requests=requests+1`
+ if boundary == "before-byte-commit" {
+ update = `UPDATE demo_traffic SET body_bytes=body_bytes+17`
+ }
+ if _, err = c.ExecContext(ctx, update); err != nil {
+ t.Fatal(err)
+ }
+ } else {
+ if err = s.Admit(ctx, id); err != nil {
+ t.Fatal(err)
+ }
+ if boundary != "after-request-commit" {
+ if n, err := s.DebitBytes(ctx, id, 17); err != nil || n != 17 {
+ t.Fatal("debit", n, err)
+ }
+ }
+ if boundary == "after-output" {
+ if err = os.WriteFile(path+".output", []byte(strings.Repeat("x", 17)), 0600); err != nil {
+ t.Fatal(err)
+ }
+ }
+ }
+ fmt.Println("boundary")
+ var ack [1]byte
+ _, _ = os.Stdin.Read(ack[:])
+}
diff --git a/internal/provision/demo_policy.go b/internal/provision/demo_policy.go
index bdddfff7c..c1d435094 100644
--- a/internal/provision/demo_policy.go
+++ b/internal/provision/demo_policy.go
@@ -71,6 +71,9 @@ func stampDemoRoute(rt *registry.Route, rec Record) {
if rec.Demo == nil {
return
}
+ // Assigned is the assignment timestamp, not the box label. Retain the
+ // label as well so serving and retirement can verify the local owner.
+ rt.FleetBox = rec.FleetBox
rt.DemoID, rt.DemoHost, rt.DemoLifetime, rt.DemoExpiresAt = rec.Demo.ID, rec.Demo.Host, rec.Demo.Lifetime, rec.Demo.ExpiresAt
}
diff --git a/internal/provision/demo_routing_test.go b/internal/provision/demo_routing_test.go
index 92a234621..b3c35e17e 100644
--- a/internal/provision/demo_routing_test.go
+++ b/internal/provision/demo_routing_test.go
@@ -45,7 +45,7 @@ func TestDemoDomainRouting(t *testing.T) {
cfg := ReconcileConfig{Region: rec.Region, FleetBox: rec.FleetBox, DataDir: data}
mustPass(t, store, local, cfg)
rt := getRow(t, local, rec.Host)
- if rt == nil || rt.DemoID != id.ID || rt.Socket != NestedSocket(rec.Host) || rt.Assigned == "" {
+ if rt == nil || rt.DemoID != id.ID || rt.Socket != NestedSocket(rec.Host) || rt.Assigned != rec.FleetBoxAt || rt.FleetBox != rec.FleetBox {
t.Fatalf("local route: %+v", rt)
}
rt.Provisioned = false