Skip to content

Modern Docker Management, Designed for Everyone

refactor: use encoding/json/v2 for the backend api (#3303)

Kyle Mendell17b3048b01b7
diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json
index 8a567a46f..d3d6efbbd 100644
--- a/.devcontainer/devcontainer.json
+++ b/.devcontainer/devcontainer.json
@@ -45,9 +45,10 @@
],
"postCreateCommand": "npx -y corepack enable && pnpm install && cd backend && go mod download",
"remoteUser": "root",
- "containerEnv": {
- "TZ": "Pacific/Auckland"
- },
+ "containerEnv": {
+ "TZ": "Pacific/Auckland",
+ "GOEXPERIMENT": "jsonv2"
+ },
"remoteEnv": {
"HOST_PROJECT_ROOT": "${localWorkspaceFolder}"
}
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index d57578372..5a587759a 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -1,5 +1,8 @@
name: CI
+env:
+ GOEXPERIMENT: jsonv2
+
on:
push:
branches: [main]
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index 307934988..887017eee 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -1,5 +1,8 @@
name: Release New Arcane Version
+env:
+ GOEXPERIMENT: jsonv2
+
on:
push:
tags:
diff --git a/.goreleaser.yaml b/.goreleaser.yaml
index 347441bd1..d7efe715d 100644
--- a/.goreleaser.yaml
+++ b/.goreleaser.yaml
@@ -23,6 +23,7 @@ builds:
binary: arcane
env:
- CGO_ENABLED=0
+ - GOEXPERIMENT=jsonv2
goos:
- linux
- darwin
@@ -63,6 +64,7 @@ builds:
- exclude_frontend
env:
- CGO_ENABLED=0
+ - GOEXPERIMENT=jsonv2
goos:
- linux
- darwin
@@ -99,6 +101,7 @@ builds:
binary: arcane-cli
env:
- CGO_ENABLED=0
+ - GOEXPERIMENT=jsonv2
goos:
- linux
- darwin
diff --git a/.vscode/settings.json b/.vscode/settings.json
index 7ede92430..470dd7502 100644
--- a/.vscode/settings.json
+++ b/.vscode/settings.json
@@ -7,6 +7,17 @@
"typescript": true
},
"go.buildTags": "playwright,buildables",
+ "go.toolsEnvVars": {
+ "GOEXPERIMENT": "jsonv2"
+ },
+ "go.testEnvVars": {
+ "GOEXPERIMENT": "jsonv2"
+ },
+ "gopls": {
+ "ui.diagnostic.analyses": {
+ "stdversion": false
+ }
+ },
"prettier.documentSelectors": ["**/*.svelte"],
"tasks.statusbar.default.hide": true,
"tasks.statusbar.limit": 8,
diff --git a/Justfile b/Justfile
index 4e69435e4..f740de6a3 100644
--- a/Justfile
+++ b/Justfile
@@ -4,6 +4,8 @@
set working-directory := './'
+export GOEXPERIMENT := "jsonv2"
+
edge_proto_dir := 'backend/pkg/libarcane/edge/proto'
_default:
diff --git a/backend/.air.toml b/backend/.air.toml
index 90ec24640..ce7cd713a 100644
--- a/backend/.air.toml
+++ b/backend/.air.toml
@@ -5,7 +5,7 @@ env_files = [".env"]
[build]
#cmd = "CGO_ENABLED=1 go build -tags 'exclude_frontend,buildables' -ldflags='-X github.com/getarcaneapp/arcane/backend/buildables.EnabledFeatures=autologin' -o ./.bin/arcane ./cmd"
- cmd = "CGO_ENABLED=1 go build -tags 'exclude_frontend' -o ./.bin/arcane ./cmd"
+ cmd = "GOEXPERIMENT=jsonv2 CGO_ENABLED=1 go build -tags 'exclude_frontend' -o ./.bin/arcane ./cmd"
bin = "./.bin/arcane"
entrypoint = ["./.bin/arcane"]
include_ext = ["go", "tpl", "tmpl", "html"]
diff --git a/backend/api/api.go b/backend/api/api.go
index 5295e63fe..53df6623b 100644
--- a/backend/api/api.go
+++ b/backend/api/api.go
@@ -2,6 +2,9 @@ package api
import (
"context"
+ json "encoding/json/v2"
+ "io"
+ "maps"
"net/http"
"reflect"
"strings"
@@ -36,6 +39,15 @@ var dockerSchemaPrefixes = map[string]string{
"image": "DockerImage",
}
+var jsonV2Format = huma.Format{
+ Marshal: func(writer io.Writer, value any) error {
+ return json.MarshalWrite(writer, value, jsonV2APIOptions)
+ },
+ Unmarshal: func(data []byte, value any) error {
+ return json.Unmarshal(data, value, jsonV2APIOptions)
+ },
+}
+
// customSchemaNamer creates unique schema names using package prefix for types
// from github.com/getarcaneapp/arcane/types/v2 to avoid conflicts between packages that have
// types with the same name (e.g., image.Summary vs env.Summary).
@@ -139,7 +151,12 @@ func capitalizeFirst(s string) string {
// SetupAPI creates and configures the Huma API attached to the Echo router.
func SetupAPI(e *echo.Echo, apiGroup *echo.Group, appCtx handlers.ActivityAppContext, cfg *config.Config, svc *di.Services) huma.API {
+ e.JSONSerializer = jsonV2Serializer{}
+
humaConfig := huma.DefaultConfig("Arcane API", config.Version)
+ humaConfig.Formats = maps.Clone(humaConfig.Formats)
+ humaConfig.Formats["application/json"] = jsonV2Format
+ humaConfig.Formats["json"] = jsonV2Format
humaConfig.Info.Description = "Modern Docker Management, Designed for Everyone"
// Disable default docs path - we'll use Scalar instead
@@ -234,6 +251,9 @@ func SetupAPIForSpec() huma.API {
apiGroup := e.Group("/api")
humaConfig := huma.DefaultConfig("Arcane API", config.Version)
+ humaConfig.Formats = maps.Clone(humaConfig.Formats)
+ humaConfig.Formats["application/json"] = jsonV2Format
+ humaConfig.Formats["json"] = jsonV2Format
humaConfig.Info.Description = "Modern Docker Management, Designed for Everyone"
humaConfig.Servers = []*huma.Server{
{URL: "/api"},
diff --git a/backend/api/api_test.go b/backend/api/api_test.go
index 1694914df..041ddecb7 100644
--- a/backend/api/api_test.go
+++ b/backend/api/api_test.go
@@ -1,9 +1,11 @@
package api
import (
+ "bytes"
"reflect"
"strings"
"testing"
+ "time"
humav2 "github.com/danielgtaylor/huma/v2"
basetypes "github.com/getarcaneapp/arcane/types/v2/base"
@@ -72,6 +74,41 @@ func TestSetupAPIForSpec_DefaultSecurity(t *testing.T) {
}
}
+func TestSetupAPIForSpecUsesV2JSONFormats(t *testing.T) {
+ type response struct {
+ Items []string `json:"items"`
+ Count int `json:"count,omitempty"`
+ }
+
+ api := SetupAPIForSpec()
+ for _, contentType := range []string{"application/json", "application/problem+json"} {
+ t.Run(contentType, func(t *testing.T) {
+ var body bytes.Buffer
+ if err := api.Marshal(&body, contentType, response{}); err != nil {
+ t.Fatalf("marshal %s: %v", contentType, err)
+ }
+ if got, want := body.String(), `{"items":[],"count":0}`; got != want {
+ t.Fatalf("marshal %s = %s, want %s", contentType, got, want)
+ }
+ })
+ }
+}
+
+func TestSetupAPIForSpecPreservesDurationNanoseconds(t *testing.T) {
+ type response struct {
+ HeartbeatPeriod time.Duration `json:"heartbeatPeriod"`
+ }
+
+ api := SetupAPIForSpec()
+ var body bytes.Buffer
+ if err := api.Marshal(&body, "application/json", response{HeartbeatPeriod: 5 * time.Second}); err != nil {
+ t.Fatalf("marshal duration: %v", err)
+ }
+ if got, want := body.String(), `{"heartbeatPeriod":5000000000}`; got != want {
+ t.Fatalf("marshal duration = %s, want %s", got, want)
+ }
+}
+
func TestSetupAPIForSpec_PublicRoutesOverrideSecurity(t *testing.T) {
api := SetupAPIForSpec()
diff --git a/backend/api/handlers/activities.go b/backend/api/handlers/activities.go
index 40744c8b0..fef0d68d4 100644
--- a/backend/api/handlers/activities.go
+++ b/backend/api/handlers/activities.go
@@ -2,9 +2,9 @@ package handlers
import (
"context"
- "encoding/json"
"errors"
"fmt"
+ "io"
"net/http"
"net/url"
"strconv"
@@ -315,7 +315,6 @@ func (h *ActivityHandler) StreamAllActivities(ctx context.Context, input *Stream
httpx.SetJSONStreamHeaders(humaCtx)
writer := humaCtx.BodyWriter()
- encoder := json.NewEncoder(writer)
flush := func() {
if f, ok := writer.(http.Flusher); ok {
f.Flush()
@@ -323,7 +322,7 @@ func (h *ActivityHandler) StreamAllActivities(ctx context.Context, input *Stream
}
ps, _ := humamw.PermissionsFromContext(humaCtx.Context())
- h.streamAllActivitiesInternal(humaCtx.Context(), ps, input.Limit, encoder, flush)
+ h.streamAllActivitiesInternal(humaCtx.Context(), ps, input.Limit, writer, flush)
},
}, nil
}
@@ -331,9 +330,9 @@ func (h *ActivityHandler) StreamAllActivities(ctx context.Context, input *Stream
// streamAllActivitiesInternal multiplexes activity events for the local
// environment and every enabled remote environment over a single response so
// the browser needs one connection regardless of environment count.
-func (h *ActivityHandler) streamAllActivitiesInternal(ctx context.Context, ps *authz.PermissionSet, limit int, encoder *json.Encoder, flush func()) {
+func (h *ActivityHandler) streamAllActivitiesInternal(ctx context.Context, ps *authz.PermissionSet, limit int, writer io.Writer, flush func()) {
_ = httpx.RunAuthorizedAggregateStream(ctx, ps, authz.PermActivitiesRead, agg.Config[activity.StreamEvent]{
- Encoder: encoder,
+ Writer: writer,
Flush: flush,
Buffer: activityStreamEventBuffer,
HeartbeatInterval: activityStreamHeartbeatInterval,
diff --git a/backend/api/handlers/activities_test.go b/backend/api/handlers/activities_test.go
index f0244800c..1ec2cf3b0 100644
--- a/backend/api/handlers/activities_test.go
+++ b/backend/api/handlers/activities_test.go
@@ -133,7 +133,7 @@ func createStreamTestRemoteEnvironmentInternal(t *testing.T, db *database.DB, en
// runStreamAllInternal drives streamAllActivitiesInternal through a pipe and
// returns each decoded event to onEvent until it reports done or the stream
-// ends; remaining output is drained so a blocked encoder can always finish.
+// ends; remaining output is drained so a blocked writer can always finish.
func runStreamAllInternal(t *testing.T, ctx context.Context, cancel context.CancelFunc, handler *ActivityHandler, ps *authz.PermissionSet, onEvent func(activity.StreamEvent) bool) {
t.Helper()
@@ -142,7 +142,7 @@ func runStreamAllInternal(t *testing.T, ctx context.Context, cancel context.Canc
go func() {
defer close(done)
defer func() { _ = pw.Close() }()
- handler.streamAllActivitiesInternal(ctx, ps, 50, json.NewEncoder(pw), func() {})
+ handler.streamAllActivitiesInternal(ctx, ps, 50, pw, func() {})
}()
scanner := bufio.NewScanner(pr)
diff --git a/backend/api/handlers/dashboard.go b/backend/api/handlers/dashboard.go
index 3c903c5f0..d14f165e2 100644
--- a/backend/api/handlers/dashboard.go
+++ b/backend/api/handlers/dashboard.go
@@ -2,8 +2,8 @@ package handlers
import (
"context"
- "encoding/json"
"errors"
+ "io"
"net/http"
"time"
@@ -121,7 +121,6 @@ func (h *DashboardHandler) StreamAllDashboards(ctx context.Context, input *Strea
httpx.SetJSONStreamHeaders(humaCtx)
writer := humaCtx.BodyWriter()
- encoder := json.NewEncoder(writer)
flush := func() {
if f, ok := writer.(http.Flusher); ok {
f.Flush()
@@ -129,7 +128,7 @@ func (h *DashboardHandler) StreamAllDashboards(ctx context.Context, input *Strea
}
ps, _ := humamw.PermissionsFromContext(humaCtx.Context())
- h.streamAllDashboardsInternal(humaCtx.Context(), ps, input.DebugAllGood, encoder, flush)
+ h.streamAllDashboardsInternal(humaCtx.Context(), ps, input.DebugAllGood, writer, flush)
},
}, nil
}
@@ -137,9 +136,9 @@ func (h *DashboardHandler) StreamAllDashboards(ctx context.Context, input *Strea
// streamAllDashboardsInternal multiplexes dashboard snapshots for the local
// environment and every enabled remote environment over a single response so
// the browser needs one connection regardless of environment count.
-func (h *DashboardHandler) streamAllDashboardsInternal(ctx context.Context, ps *authz.PermissionSet, debugAllGood bool, encoder *json.Encoder, flush func()) {
+func (h *DashboardHandler) streamAllDashboardsInternal(ctx context.Context, ps *authz.PermissionSet, debugAllGood bool, writer io.Writer, flush func()) {
_ = httpx.RunAuthorizedAggregateStream(ctx, ps, authz.PermDashboardRead, agg.Config[dashboardtypes.StreamEvent]{
- Encoder: encoder,
+ Writer: writer,
Flush: flush,
Buffer: dashboardStreamEventBuffer,
HeartbeatInterval: dashboardStreamHeartbeatInterval,
diff --git a/backend/api/handlers/dashboard_test.go b/backend/api/handlers/dashboard_test.go
index 395f0858d..e5b63f7ca 100644
--- a/backend/api/handlers/dashboard_test.go
+++ b/backend/api/handlers/dashboard_test.go
@@ -139,7 +139,7 @@ func TestDashboardHandlerGetDashboardReturnsSnapshot(t *testing.T) {
// runDashboardStreamAllInternal drives streamAllDashboardsInternal through a
// pipe and returns each decoded event to onEvent until it reports done or the
-// stream ends; remaining output is drained so a blocked encoder can finish.
+// stream ends; remaining output is drained so a blocked writer can finish.
func runDashboardStreamAllInternal(t *testing.T, ctx context.Context, cancel context.CancelFunc, handler *DashboardHandler, ps *authz.PermissionSet, onEvent func(dashboardtypes.StreamEvent) bool) {
t.Helper()
@@ -148,7 +148,7 @@ func runDashboardStreamAllInternal(t *testing.T, ctx context.Context, cancel con
go func() {
defer close(done)
defer func() { _ = pw.Close() }()
- handler.streamAllDashboardsInternal(ctx, ps, false, json.NewEncoder(pw), func() {})
+ handler.streamAllDashboardsInternal(ctx, ps, false, pw, func() {})
}()
scanner := bufio.NewScanner(pr)
diff --git a/backend/api/handlers/environments.go b/backend/api/handlers/environments.go
index 4684cc6a2..cd0c93c05 100644
--- a/backend/api/handlers/environments.go
+++ b/backend/api/handlers/environments.go
@@ -4,7 +4,7 @@ import (
"archive/zip"
"bytes"
"context"
- "encoding/json"
+ json "encoding/json/v2"
"fmt"
"log/slog"
"net/http"
@@ -1116,7 +1116,7 @@ func (h *EnvironmentHandler) GetEnvironmentVersion(ctx context.Context, input *G
return nil, huma.Error500InternalServerError(fmt.Sprintf("Unexpected status code: %d", resp.StatusCode))
}
- if err := json.NewDecoder(resp.Body).Decode(&versionInfo); err != nil {
+ if err := json.UnmarshalRead(resp.Body, &versionInfo); err != nil {
return nil, huma.Error500InternalServerError("Failed to decode version response")
}
}
diff --git a/backend/api/handlers/events.go b/backend/api/handlers/events.go
index 229ca7f2f..a55fa1ea0 100644
--- a/backend/api/handlers/events.go
+++ b/backend/api/handlers/events.go
@@ -2,7 +2,7 @@ package handlers
import (
"context"
- "encoding/json"
+ json "encoding/json/v2"
"log/slog"
"net/http"
"strings"
@@ -114,8 +114,7 @@ func RegisterAgentEventIngestion(g *echo.Group, eventService *services.EventServ
}
var input services.CreateEventRequest
- decoder := json.NewDecoder(http.MaxBytesReader(c.Response(), c.Request().Body, 1<<20))
- if err := decoder.Decode(&input); err != nil {
+ if err := json.UnmarshalRead(http.MaxBytesReader(c.Response(), c.Request().Body, 1<<20), &input); err != nil {
return c.JSON(http.StatusBadRequest, base.ApiResponse[base.MessageResponse]{
Success: false,
Data: base.MessageResponse{Message: "invalid event payload"},
diff --git a/backend/api/handlers/helpers.go b/backend/api/handlers/helpers.go
index 45bd41153..a45e83052 100644
--- a/backend/api/handlers/helpers.go
+++ b/backend/api/handlers/helpers.go
@@ -2,7 +2,7 @@ package handlers
import (
"context"
- "encoding/json"
+ json "encoding/json/v2"
"errors"
"strings"
diff --git a/backend/api/handlers/templates.go b/backend/api/handlers/templates.go
index de2583947..5b9438240 100644
--- a/backend/api/handlers/templates.go
+++ b/backend/api/handlers/templates.go
@@ -2,7 +2,7 @@ package handlers
import (
"context"
- "encoding/json"
+ json "encoding/json/v2"
"net/http"
"net/url"
diff --git a/backend/api/json_serializer.go b/backend/api/json_serializer.go
new file mode 100644
index 000000000..ba59170c5
--- /dev/null
+++ b/backend/api/json_serializer.go
@@ -0,0 +1,56 @@
+package api
+
+import (
+ jsonv1 "encoding/json"
+ "encoding/json/jsontext"
+ json "encoding/json/v2"
+ "errors"
+ "fmt"
+ "net/http"
+
+ "github.com/labstack/echo/v4"
+)
+
+type jsonV2Serializer struct{}
+
+// Preserve the established numeric wire format for duration fields in third-party API types.
+var jsonV2APIOptions = jsonv1.FormatDurationAsNano(true)
+
+func (jsonV2Serializer) Serialize(c echo.Context, value any, indent string) error {
+ if indent != "" {
+ return json.MarshalWrite(c.Response(), value, jsonV2APIOptions, jsontext.WithIndent(indent))
+ }
+
+ return json.MarshalWrite(c.Response(), value, jsonV2APIOptions)
+}
+
+func (jsonV2Serializer) Deserialize(c echo.Context, value any) error {
+ err := json.UnmarshalRead(c.Request().Body, value, jsonV2APIOptions)
+ if err == nil {
+ return nil
+ }
+
+ var semanticErr *json.SemanticError
+ if errors.As(err, &semanticErr) {
+ return echo.NewHTTPError(
+ http.StatusBadRequest,
+ fmt.Sprintf(
+ "Unmarshal type error: expected=%v, got=%v, field=%v, offset=%v",
+ semanticErr.GoType,
+ semanticErr.JSONKind,
+ semanticErr.JSONPointer,
+ semanticErr.ByteOffset,
+ ),
+ ).SetInternal(err)
+ }
+
+ var syntacticErr *jsontext.SyntacticError
+ if errors.As(err, &syntacticErr) {
+ return echo.NewHTTPError(
+ http.StatusBadRequest,
+ fmt.Sprintf("Syntax error: offset=%v, error=%v", syntacticErr.ByteOffset, syntacticErr.Error()),
+ ).SetInternal(err)
+ }
+
+ return err
+}
diff --git a/backend/api/json_serializer_benchmark_test.go b/backend/api/json_serializer_benchmark_test.go
new file mode 100644
index 000000000..9b6112238
--- /dev/null
+++ b/backend/api/json_serializer_benchmark_test.go
@@ -0,0 +1,88 @@
+package api
+
+import (
+ "bytes"
+ jsonv1 "encoding/json"
+ jsonv2 "encoding/json/v2"
+ "io"
+ "testing"
+)
+
+type jsonBenchmarkItem struct {
+ ID string `json:"id"`
+ Name string `json:"name"`
+ State string `json:"state"`
+ Image string `json:"image"`
+ Ports []int `json:"ports"`
+ Aliases []string `json:"aliases"`
+}
+
+type jsonBenchmarkResponse struct {
+ Items []jsonBenchmarkItem `json:"items"`
+ Total int `json:"total"`
+}
+
+var jsonBenchmarkPayload = func() jsonBenchmarkResponse {
+ items := make([]jsonBenchmarkItem, 64)
+ for index := range items {
+ items[index] = jsonBenchmarkItem{
+ ID: "01JARCANEJSONBENCHMARK",
+ Name: "arcane-backend",
+ State: "running",
+ Image: "ghcr.io/getarcaneapp/arcane:latest",
+ Ports: []int{3552, 3553},
+ Aliases: []string{"arcane", "backend"},
+ }
+ }
+
+ return jsonBenchmarkResponse{Items: items, Total: len(items)}
+}()
+
+func BenchmarkJSONResponseEncoding(b *testing.B) {
+ b.Run("v1 encoder", func(b *testing.B) {
+ b.ReportAllocs()
+ for b.Loop() {
+ if err := jsonv1.NewEncoder(io.Discard).Encode(jsonBenchmarkPayload); err != nil {
+ b.Fatal(err)
+ }
+ }
+ })
+
+ b.Run("v2 MarshalWrite", func(b *testing.B) {
+ b.ReportAllocs()
+ for b.Loop() {
+ if err := jsonv2.MarshalWrite(io.Discard, jsonBenchmarkPayload, jsonV2APIOptions); err != nil {
+ b.Fatal(err)
+ }
+ }
+ })
+}
+
+func BenchmarkJSONRequestDecoding(b *testing.B) {
+ data, err := jsonv2.Marshal(jsonBenchmarkPayload)
+ if err != nil {
+ b.Fatal(err)
+ }
+
+ b.SetBytes(int64(len(data)))
+
+ b.Run("v1 decoder", func(b *testing.B) {
+ b.ReportAllocs()
+ for b.Loop() {
+ var output jsonBenchmarkResponse
+ if err := jsonv1.NewDecoder(bytes.NewReader(data)).Decode(&output); err != nil {
+ b.Fatal(err)
+ }
+ }
+ })
+
+ b.Run("v2 UnmarshalRead", func(b *testing.B) {
+ b.ReportAllocs()
+ for b.Loop() {
+ var output jsonBenchmarkResponse
+ if err := jsonv2.UnmarshalRead(bytes.NewReader(data), &output, jsonV2APIOptions); err != nil {
+ b.Fatal(err)
+ }
+ }
+ })
+}
diff --git a/backend/api/json_serializer_test.go b/backend/api/json_serializer_test.go
new file mode 100644
index 000000000..ebaf1024f
--- /dev/null
+++ b/backend/api/json_serializer_test.go
@@ -0,0 +1,92 @@
+package api
+
+import (
+ "bytes"
+ "errors"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+ "time"
+
+ "github.com/labstack/echo/v4"
+)
+
+func TestJSONV2SerializerUsesV2ResponseSemantics(t *testing.T) {
+ type response struct {
+ Items []string `json:"items"`
+ Count int `json:"count,omitempty"`
+ }
+
+ e := echo.New()
+ recorder := httptest.NewRecorder()
+ context := e.NewContext(httptest.NewRequest("GET", "/", nil), recorder)
+
+ err := (jsonV2Serializer{}).Serialize(context, response{}, "")
+ if err != nil {
+ t.Fatalf("serialize response: %v", err)
+ }
+ if got, want := recorder.Body.String(), `{"items":[],"count":0}`; got != want {
+ t.Fatalf("serialized response = %s, want %s", got, want)
+ }
+}
+
+func TestJSONV2SerializerPreservesDurationNanoseconds(t *testing.T) {
+ type response struct {
+ HeartbeatPeriod time.Duration `json:"heartbeatPeriod"`
+ }
+
+ e := echo.New()
+ recorder := httptest.NewRecorder()
+ context := e.NewContext(httptest.NewRequest("GET", "/", nil), recorder)
+
+ err := (jsonV2Serializer{}).Serialize(context, response{HeartbeatPeriod: 5 * time.Second}, "")
+ if err != nil {
+ t.Fatalf("serialize duration: %v", err)
+ }
+ if got, want := recorder.Body.String(), `{"heartbeatPeriod":5000000000}`; got != want {
+ t.Fatalf("serialized response = %s, want %s", got, want)
+ }
+}
+
+func TestJSONV2SerializerUsesStrictV2Decoding(t *testing.T) {
+ type requestBody struct {
+ Name string `json:"name"`
+ }
+
+ t.Run("field names are case sensitive", func(t *testing.T) {
+ e := echo.New()
+ context := e.NewContext(httptest.NewRequest("POST", "/", bytes.NewBufferString(`{"Name":"arcane"}`)), httptest.NewRecorder())
+
+ var body requestBody
+ err := (jsonV2Serializer{}).Deserialize(context, &body)
+ if err != nil {
+ t.Fatalf("deserialize case-variant field: %v", err)
+ }
+ if body.Name != "" {
+ t.Fatalf("case-variant field populated Name with %q", body.Name)
+ }
+ })
+
+ for _, test := range []struct {
+ name string
+ body []byte
+ }{
+ {name: "duplicate names", body: []byte(`{"name":"first","name":"second"}`)},
+ {name: "invalid UTF-8", body: []byte{'{', '"', 'n', 'a', 'm', 'e', '"', ':', '"', 0xff, '"', '}'}},
+ } {
+ t.Run(test.name, func(t *testing.T) {
+ e := echo.New()
+ context := e.NewContext(httptest.NewRequest("POST", "/", bytes.NewReader(test.body)), httptest.NewRecorder())
+
+ var body requestBody
+ err := (jsonV2Serializer{}).Deserialize(context, &body)
+ var httpErr *echo.HTTPError
+ if !errors.As(err, &httpErr) {
+ t.Fatalf("deserialize error = %T %v, want *echo.HTTPError", err, err)
+ }
+ if httpErr.Code != http.StatusBadRequest {
+ t.Fatalf("HTTP status = %d, want %d", httpErr.Code, http.StatusBadRequest)
+ }
+ })
+ }
+}
diff --git a/backend/api/ws/diagnostics.go b/backend/api/ws/diagnostics.go
index 3af06538c..4d9cef032 100644
--- a/backend/api/ws/diagnostics.go
+++ b/backend/api/ws/diagnostics.go
@@ -1,7 +1,7 @@
package ws
import (
- "encoding/json"
+ json "encoding/json/v2"
"net/http"
"net/http/pprof"
"time"
diff --git a/backend/api/ws/handler.go b/backend/api/ws/handler.go
index b90879483..f8998848a 100644
--- a/backend/api/ws/handler.go
+++ b/backend/api/ws/handler.go
@@ -2,7 +2,7 @@ package ws
import (
"context"
- "encoding/json"
+ json "encoding/json/v2"
"errors"
"io"
"log/slog"
diff --git a/backend/go.mod b/backend/go.mod
index 26110a22e..fe2c077aa 100644
--- a/backend/go.mod
+++ b/backend/go.mod
@@ -53,13 +53,13 @@ require (
github.com/stretchr/testify v1.11.1
github.com/subosito/gotenv v1.6.0
github.com/wneessen/go-mail v0.8.1
- go.getarcane.app/builds v0.1.1
+ go.getarcane.app/builds v0.2.0
go.getarcane.app/docker/convert v0.1.0
- go.getarcane.app/streams v0.2.0
+ go.getarcane.app/streams v0.3.0
go.getarcane.app/sys/atomic v0.1.0
go.getarcane.app/sys/cgroup v0.1.0
go.getarcane.app/sys/crypto v0.1.0
- go.getarcane.app/updater v0.5.3
+ go.getarcane.app/updater v0.6.0
go.yaml.in/yaml/v4 v4.0.0-rc.6
golang.org/x/crypto v0.54.0
golang.org/x/mod v0.38.0
diff --git a/backend/go.sum b/backend/go.sum
index e790d60c6..55ca64bad 100644
--- a/backend/go.sum
+++ b/backend/go.sum
@@ -533,20 +533,20 @@ github.com/youmark/pkcs8 v0.0.0-20240726163527-a2c0da244d78 h1:ilQV1hzziu+LLM3zU
github.com/youmark/pkcs8 v0.0.0-20240726163527-a2c0da244d78/go.mod h1:aL8wCCfTfSfmXjznFBSZNN13rSJjlIOI1fUNAtF7rmI=
github.com/yusufpapurcu/wmi v1.2.4 h1:zFUKzehAFReQwLys1b/iSMl+JQGSCSjtVqQn9bBrPo0=
github.com/yusufpapurcu/wmi v1.2.4/go.mod h1:SBZ9tNy3G9/m5Oi98Zks0QjeHVDvuK0qfxQmPyzfmi0=
-go.getarcane.app/builds v0.1.1 h1:sEwZJtf+wbf+KzQyGimk78ZMqqlcKvDo5SI+FOeoO1Y=
-go.getarcane.app/builds v0.1.1/go.mod h1:3g7+969+qWH33EXnA+nu5MKhs72JYDPf9Q/OtYO6CIA=
+go.getarcane.app/builds v0.2.0 h1:IXl78t2Lpr4FJ+HQhAGbTgENyPr2WLBxAmFebRu5kuU=
+go.getarcane.app/builds v0.2.0/go.mod h1:korkB7gWCiWx00SbKtX0sTwxWYeL1pxeTKOYxohjJUA=
go.getarcane.app/docker/convert v0.1.0 h1:prlIOs6dMx6CdnetsJFZ6ak0vcistM3DcH5lrZiFHBU=
go.getarcane.app/docker/convert v0.1.0/go.mod h1:o9y4z/vah8HiHFtI+jJVFHbs8nLrkARYt88OaUlvGig=
-go.getarcane.app/streams v0.2.0 h1:qQ1pcHaFVeeWxRd81jAhf6SaY3DfNWeKnMtUtyghOWw=
-go.getarcane.app/streams v0.2.0/go.mod h1:LHMKblQvsL1nqKh/Y+KgQbwFSMI2I7bs9u8ZwZqzjnQ=
+go.getarcane.app/streams v0.3.0 h1:UM4Y8E0lpi0GEKSJ5zUyeho9aJoBIi/Pr3dJnnhCkK4=
+go.getarcane.app/streams v0.3.0/go.mod h1:LHMKblQvsL1nqKh/Y+KgQbwFSMI2I7bs9u8ZwZqzjnQ=
go.getarcane.app/sys/atomic v0.1.0 h1:0HhUeGXYdKAmMW24O+OaqcjDZx6twAuYPBu9T91zKsk=
go.getarcane.app/sys/atomic v0.1.0/go.mod h1:QPb5eUXYKYG5acp9jJBAZ/PTbHbByDAQG6eDNAsZZ2w=
go.getarcane.app/sys/cgroup v0.1.0 h1:SCAbuU+rZ/EjMU8kkVxmXZsMchiZp9eFdMQFnbU+asA=
go.getarcane.app/sys/cgroup v0.1.0/go.mod h1:Paj4QOazrTXO/Ivhmvt1E/RjPJFTdKkxRgRDk4qBCUI=
go.getarcane.app/sys/crypto v0.1.0 h1:HDQ2CKHkm+wZe5xb/qR7MzW5fKi0Wq8Jcyr7qDVgRWg=
go.getarcane.app/sys/crypto v0.1.0/go.mod h1:YtoRB0TENwfdNl0ZUTWkeas/8rT7NhCbI8ENsZzCCdU=
-go.getarcane.app/updater v0.5.3 h1:nhdpT2JFVC12EHZEy2HFyt1A5NS0t46Go+Ns3VlWN8Y=
-go.getarcane.app/updater v0.5.3/go.mod h1:8f0/0pi7J0yFqgwFTywiwk/NoUN/g6AfmprOuAUrI20=
+go.getarcane.app/updater v0.6.0 h1:dwnCjQdYMCB7xuCmODs/FhT28BCOUT5Uxmn1XydHv2Q=
+go.getarcane.app/updater v0.6.0/go.mod h1:8f0/0pi7J0yFqgwFTywiwk/NoUN/g6AfmprOuAUrI20=
go.opencensus.io v0.24.0 h1:y73uSU6J157QMP2kn2r30vwW1A2W2WFwSCGnAVxeaD0=
go.opencensus.io v0.24.0/go.mod h1:vNK8G9p7aAivkbmorf4v+7Hgx+Zs0yY+0fOtgBfjQKo=
go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=
diff --git a/backend/internal/bootstrap/edge_bootstrap.go b/backend/internal/bootstrap/edge_bootstrap.go
index 8ec45279b..2efb4d9bc 100644
--- a/backend/internal/bootstrap/edge_bootstrap.go
+++ b/backend/internal/bootstrap/edge_bootstrap.go
@@ -2,7 +2,7 @@ package bootstrap
import (
"context"
- "encoding/json"
+ json "encoding/json/v2"
"errors"
"fmt"
"log/slog"
diff --git a/backend/internal/bootstrap/jobs_bootstrap.go b/backend/internal/bootstrap/jobs_bootstrap.go
index 88b309111..699a098dd 100644
--- a/backend/internal/bootstrap/jobs_bootstrap.go
+++ b/backend/internal/bootstrap/jobs_bootstrap.go
@@ -2,7 +2,7 @@ package bootstrap
import (
"context"
- "encoding/json"
+ json "encoding/json/v2"
"log/slog"
"net/http"
diff --git a/backend/internal/configschema/schema.go b/backend/internal/configschema/schema.go
index 0e35c64bc..4d0317ea2 100644
--- a/backend/internal/configschema/schema.go
+++ b/backend/internal/configschema/schema.go
@@ -2,7 +2,8 @@ package configschema
import (
"bytes"
- "encoding/json"
+ "encoding/json/jsontext"
+ json "encoding/json/v2"
"errors"
"fmt"
"go/ast"
@@ -166,7 +167,7 @@ func GenerateWithSourceRoot(sourceRoot string) (*SchemaDocument, error) {
// MarshalJSON returns a stable, indented JSON encoding of the schema document.
func MarshalJSON(doc *SchemaDocument) ([]byte, error) {
- output, err := json.MarshalIndent(doc, "", " ")
+ output, err := json.Marshal(doc, json.Deterministic(true), jsontext.WithIndent(" "))
if err != nil {
return nil, fmt.Errorf("marshal schema document: %w", err)
}
diff --git a/backend/internal/models/base.go b/backend/internal/models/base.go
index 8978aae24..d9d533977 100644
--- a/backend/internal/models/base.go
+++ b/backend/internal/models/base.go
@@ -2,7 +2,7 @@ package models
import (
"database/sql/driver"
- "encoding/json"
+ json "encoding/json/v2"
"time"
"github.com/google/uuid"
diff --git a/backend/internal/models/environment_update_job.go b/backend/internal/models/environment_update_job.go
index 6d984aaaa..40f092943 100644
--- a/backend/internal/models/environment_update_job.go
+++ b/backend/internal/models/environment_update_job.go
@@ -2,7 +2,7 @@ package models
import (
"database/sql/driver"
- "encoding/json"
+ json "encoding/json/v2"
"fmt"
"time"
)
diff --git a/backend/internal/services/build_service.go b/backend/internal/services/build_service.go
index 3f07b4d3f..36fe78949 100644
--- a/backend/internal/services/build_service.go
+++ b/backend/internal/services/build_service.go
@@ -2,7 +2,7 @@ package services
import (
"context"
- "encoding/json"
+ json "encoding/json/v2"
"errors"
"fmt"
"io"
@@ -374,12 +374,16 @@ func writeBuildProgressStatusInternal(progressWriter io.Writer, serviceName, sta
return
}
- if err := json.NewEncoder(progressWriter).Encode(buildtypes.ProgressEvent{
+ if err := json.MarshalWrite(progressWriter, buildtypes.ProgressEvent{
Type: "build",
Service: serviceName,
Status: status,
}); err != nil {
slog.Debug("failed to write build progress status", "error", err)
+ return
+ }
+ if _, err := io.WriteString(progressWriter, "\n"); err != nil {
+ slog.Debug("failed to terminate build progress status", "error", err)
}
}
diff --git a/backend/internal/services/container_registry_service.go b/backend/internal/services/container_registry_service.go
index 335a960d4..0cdfbeeb7 100644
--- a/backend/internal/services/container_registry_service.go
+++ b/backend/internal/services/container_registry_service.go
@@ -2,7 +2,7 @@ package services
import (
"context"
- "encoding/json"
+ json "encoding/json/v2"
"errors"
"fmt"
"log/slog"
diff --git a/backend/internal/services/container_service.go b/backend/internal/services/container_service.go
index 1cff99d07..0c5ec4582 100644
--- a/backend/internal/services/container_service.go
+++ b/backend/internal/services/container_service.go
@@ -2,7 +2,8 @@ package services
import (
"context"
- "encoding/json"
+ "encoding/json/jsontext"
+ json "encoding/json/v2"
"errors"
"fmt"
"io"
@@ -895,7 +896,7 @@ func (s *ContainerService) StreamStats(ctx context.Context, containerID string,
}
defer func() { _ = stats.Body.Close() }()
- decoder := json.NewDecoder(stats.Body)
+ decoder := jsontext.NewDecoder(stats.Body)
historySent := false
for {
@@ -904,11 +905,11 @@ func (s *ContainerService) StreamStats(ctx context.Context, containerID string,
}
var statsData container.StatsResponse
- if err := decoder.Decode(&statsData); err != nil {
+ if err := json.UnmarshalDecode(decoder, &statsData); err != nil {
if ctx.Err() != nil {
return ctx.Err()
}
- if err == io.EOF {
+ if errors.Is(err, io.EOF) {
return nil
}
return fmt.Errorf("failed to decode stats: %w", err)
diff --git a/backend/internal/services/environment_service.go b/backend/internal/services/environment_service.go
index 41bd84426..c96df1cdf 100644
--- a/backend/internal/services/environment_service.go
+++ b/backend/internal/services/environment_service.go
@@ -2,7 +2,7 @@ package services
import (
"context"
- "encoding/json"
+ json "encoding/json/v2"
"errors"
"fmt"
"log/slog"
diff --git a/backend/internal/services/event_service.go b/backend/internal/services/event_service.go
index 160faf6c9..013ca6f55 100644
--- a/backend/internal/services/event_service.go
+++ b/backend/internal/services/event_service.go
@@ -3,7 +3,7 @@ package services
import (
"bytes"
"context"
- "encoding/json"
+ json "encoding/json/v2"
"errors"
"fmt"
"io"
diff --git a/backend/internal/services/gitops_sync_service.go b/backend/internal/services/gitops_sync_service.go
index c74a3ac4f..115dedcca 100644
--- a/backend/internal/services/gitops_sync_service.go
+++ b/backend/internal/services/gitops_sync_service.go
@@ -2,7 +2,7 @@ package services
import (
"context"
- "encoding/json"
+ json "encoding/json/v2"
"errors"
"fmt"
"log/slog"
diff --git a/backend/internal/services/image_attestations_service.go b/backend/internal/services/image_attestations_service.go
index 6ef878325..c984e08db 100644
--- a/backend/internal/services/image_attestations_service.go
+++ b/backend/internal/services/image_attestations_service.go
@@ -4,7 +4,7 @@ import (
"bytes"
"compress/gzip"
"context"
- "encoding/json"
+ json "encoding/json/v2"
"errors"
"fmt"
"io"
diff --git a/backend/internal/services/notification_service.go b/backend/internal/services/notification_service.go
index b5864e1ae..69ea2c31e 100644
--- a/backend/internal/services/notification_service.go
+++ b/backend/internal/services/notification_service.go
@@ -3,7 +3,7 @@ package services
import (
"bytes"
"context"
- "encoding/json"
+ json "encoding/json/v2"
"errors"
"fmt"
"html"
@@ -165,7 +165,7 @@ func (s *NotificationService) dispatchNotificationToManagerInternal(ctx context.
var apiResponse struct {
Data notificationdto.DispatchResponse `json:"data"`
}
- if err := json.NewDecoder(resp.Body).Decode(&apiResponse); err != nil {
+ if err := json.UnmarshalRead(resp.Body, &apiResponse); err != nil {
return notificationdto.DispatchResponse{}, fmt.Errorf("failed to decode manager notification dispatch response: %w", err)
}
return apiResponse.Data, nil
diff --git a/backend/internal/services/oidc_service.go b/backend/internal/services/oidc_service.go
index 3e6ef3f8c..7ae081ea7 100644
--- a/backend/internal/services/oidc_service.go
+++ b/backend/internal/services/oidc_service.go
@@ -4,7 +4,7 @@ import (
"context"
"crypto/tls"
"encoding/base64"
- "encoding/json"
+ json "encoding/json/v2"
"errors"
"fmt"
"log/slog"
@@ -464,8 +464,7 @@ func (s *OidcService) fetchUserInfoClaimsInternal(ctx context.Context, cfg *mode
}
var claims map[string]any
- decoder := json.NewDecoder(resp.Body)
- if err := decoder.Decode(&claims); err != nil {
+ if err := json.UnmarshalRead(resp.Body, &claims); err != nil {
return nil, err
}
@@ -761,7 +760,7 @@ func (s *OidcService) makeDeviceAuthRequestInternal(ctx context.Context, endpoin
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
var errorResp map[string]any
- if err := json.NewDecoder(resp.Body).Decode(&errorResp); err == nil {
+ if err := json.UnmarshalRead(resp.Body, &errorResp); err == nil {
if errMsg, ok := errorResp["error"].(string); ok {
return nil, fmt.Errorf("device authorization failed: %s", errMsg)
}
@@ -770,7 +769,7 @@ func (s *OidcService) makeDeviceAuthRequestInternal(ctx context.Context, endpoin
}
var respData map[string]any
- if err := json.NewDecoder(resp.Body).Decode(&respData); err != nil {
+ if err := json.UnmarshalRead(resp.Body, &respData); err != nil {
return nil, fmt.Errorf("failed to decode device authorization response: %w", err)
}
@@ -869,7 +868,7 @@ func (s *OidcService) makeTokenRequestInternal(ctx context.Context, endpoint str
defer func() { _ = resp.Body.Close() }()
var tokenResp map[string]any
- if err := json.NewDecoder(resp.Body).Decode(&tokenResp); err != nil {
+ if err := json.UnmarshalRead(resp.Body, &tokenResp); err != nil {
return nil, fmt.Errorf("failed to decode token response: %w", err)
}
diff --git a/backend/internal/services/project_service.go b/backend/internal/services/project_service.go
index 0af239692..4ab0bf0c1 100644
--- a/backend/internal/services/project_service.go
+++ b/backend/internal/services/project_service.go
@@ -3,7 +3,7 @@ package services
import (
"bufio"
"context"
- "encoding/json"
+ json "encoding/json/v2"
"errors"
"fmt"
"io"
diff --git a/backend/internal/services/role_service.go b/backend/internal/services/role_service.go
index 1683c96b0..144d7162c 100644
--- a/backend/internal/services/role_service.go
+++ b/backend/internal/services/role_service.go
@@ -2,7 +2,7 @@ package services
import (
"context"
- "encoding/json"
+ json "encoding/json/v2"
"errors"
"fmt"
"log/slog"
diff --git a/backend/internal/services/swarm_service.go b/backend/internal/services/swarm_service.go
index b38d42743..27d78fb51 100644
--- a/backend/internal/services/swarm_service.go
+++ b/backend/internal/services/swarm_service.go
@@ -3,7 +3,8 @@ package services
import (
"bytes"
"context"
- "encoding/json"
+ stdjson "encoding/json"
+ json "encoding/json/v2"
"errors"
"fmt"
"io/fs"
@@ -2478,7 +2479,7 @@ func isTaskTerminalInternal(state swarm.TaskState) bool {
return false
}
-func decodeConfigSpecInternal(raw json.RawMessage) (swarm.ConfigSpec, error) {
+func decodeConfigSpecInternal(raw stdjson.RawMessage) (swarm.ConfigSpec, error) {
if len(raw) == 0 || strings.TrimSpace(string(raw)) == "" || strings.TrimSpace(string(raw)) == "null" {
return swarm.ConfigSpec{}, errors.New("config spec is required")
}
@@ -2495,7 +2496,7 @@ func decodeConfigSpecInternal(raw json.RawMessage) (swarm.ConfigSpec, error) {
return spec, nil
}
-func decodeSwarmSpecInternal(raw json.RawMessage) (swarm.Spec, error) {
+func decodeSwarmSpecInternal(raw stdjson.RawMessage) (swarm.Spec, error) {
trimmed := bytes.TrimSpace(raw)
if len(trimmed) == 0 || bytes.Equal(trimmed, []byte("null")) {
return swarm.Spec{}, errors.New("swarm spec is required")
@@ -2522,7 +2523,7 @@ func defaultSwarmListenAddrInternal(listenAddr string) string {
return trimmed
}
-func decodeSecretSpecInternal(raw json.RawMessage) (swarm.SecretSpec, error) {
+func decodeSecretSpecInternal(raw stdjson.RawMessage) (swarm.SecretSpec, error) {
if len(raw) == 0 || strings.TrimSpace(string(raw)) == "" || strings.TrimSpace(string(raw)) == "null" {
return swarm.SecretSpec{}, errors.New("secret spec is required")
}
diff --git a/backend/internal/services/template_service.go b/backend/internal/services/template_service.go
index d70d8cccf..70e146ca0 100644
--- a/backend/internal/services/template_service.go
+++ b/backend/internal/services/template_service.go
@@ -3,7 +3,7 @@ package services
import (
"bufio"
"context"
- "encoding/json"
+ json "encoding/json/v2"
"errors"
"fmt"
"io"
diff --git a/backend/internal/services/version_service.go b/backend/internal/services/version_service.go
index f2bf1975e..159773153 100644
--- a/backend/internal/services/version_service.go
+++ b/backend/internal/services/version_service.go
@@ -2,7 +2,7 @@ package services
import (
"context"
- "encoding/json"
+ json "encoding/json/v2"
"errors"
"fmt"
"log/slog"
@@ -88,7 +88,7 @@ func (s *VersionService) getLatestReleaseInternal(ctx context.Context) (latestRe
Body string `json:"body"`
PublishedAt string `json:"published_at"`
}
- if err := json.NewDecoder(resp.Body).Decode(&payload); err != nil {
+ if err := json.UnmarshalRead(resp.Body, &payload); err != nil {
return latestRelease{}, fmt.Errorf("decode payload: %w", err)
}
if payload.TagName == "" {
diff --git a/backend/internal/services/vulnerability_service.go b/backend/internal/services/vulnerability_service.go
index a780517d4..e7bb59fa0 100644
--- a/backend/internal/services/vulnerability_service.go
+++ b/backend/internal/services/vulnerability_service.go
@@ -4,7 +4,8 @@ import (
"archive/tar"
"bytes"
"context"
- "encoding/json"
+ "encoding/json/jsontext"
+ json "encoding/json/v2"
"errors"
"fmt"
"io"
@@ -2959,10 +2960,10 @@ func decodeTrivyReportFromBytesInternal(rawOutput []byte) (*vulnerability.TrivyR
}
func decodeSingleTrivyReportInternal(rawOutput []byte) (*vulnerability.TrivyReport, error) {
- decoder := json.NewDecoder(bytes.NewReader(rawOutput))
+ decoder := jsontext.NewDecoder(bytes.NewReader(rawOutput))
var report vulnerability.TrivyReport
- if err := decoder.Decode(&report); err != nil {
+ if err := json.UnmarshalDecode(decoder, &report); err != nil {
return nil, err
}
diff --git a/backend/pkg/dockerutil/jsonstream.go b/backend/pkg/dockerutil/jsonstream.go
index 482850870..3c23f6ae6 100644
--- a/backend/pkg/dockerutil/jsonstream.go
+++ b/backend/pkg/dockerutil/jsonstream.go
@@ -2,7 +2,7 @@ package docker
import (
"bufio"
- "encoding/json"
+ json "encoding/json/v2"
"io"
"github.com/moby/moby/api/types/jsonstream"
diff --git a/backend/pkg/libarcane/activity/handler.go b/backend/pkg/libarcane/activity/handler.go
index 815d4be51..88aa9dafe 100644
--- a/backend/pkg/libarcane/activity/handler.go
+++ b/backend/pkg/libarcane/activity/handler.go
@@ -2,7 +2,7 @@ package activity
import (
"context"
- "encoding/json"
+ json "encoding/json/v2"
"errors"
"fmt"
"io"
@@ -149,9 +149,11 @@ func WriteStartedLine(writer io.Writer, activityID string) {
"type": "activity",
"activityId": activityID,
}
- if err := json.NewEncoder(writer).Encode(payload); err != nil {
+ if err := json.MarshalWrite(writer, payload); err != nil {
_, _ = fmt.Fprintf(writer, `{"activityId":%q}`+"\n", activityID)
+ return
}
+ _, _ = io.WriteString(writer, "\n")
}
func FlushWriter(writer io.Writer) {
diff --git a/backend/pkg/libarcane/activity/writer.go b/backend/pkg/libarcane/activity/writer.go
index 06309d28c..f652522ff 100644
--- a/backend/pkg/libarcane/activity/writer.go
+++ b/backend/pkg/libarcane/activity/writer.go
@@ -3,7 +3,8 @@ package activity
import (
"bytes"
"context"
- "encoding/json"
+ stdjson "encoding/json"
+ json "encoding/json/v2"
"fmt"
"io"
"net/http"
@@ -299,7 +300,7 @@ func numberToInt64Internal(value any) int64 {
return typed
case int:
return int64(typed)
- case json.Number:
+ case stdjson.Number:
out, _ := typed.Int64()
return out
default:
diff --git a/backend/pkg/libarcane/edge/client_transport_poll.go b/backend/pkg/libarcane/edge/client_transport_poll.go
index f07885aac..730d909da 100644
--- a/backend/pkg/libarcane/edge/client_transport_poll.go
+++ b/backend/pkg/libarcane/edge/client_transport_poll.go
@@ -3,7 +3,7 @@ package edge
import (
"bytes"
"context"
- "encoding/json"
+ json "encoding/json/v2"
"errors"
"fmt"
"io"
@@ -195,7 +195,7 @@ func (c *TunnelClient) pollTunnelControlInternal(ctx context.Context, pollURL st
}
var pollResp TunnelPollResponse
- if err := json.NewDecoder(resp.Body).Decode(&pollResp); err != nil {
+ if err := json.UnmarshalRead(resp.Body, &pollResp); err != nil {
return nil, fmt.Errorf("failed to decode poll response: %w", err)
}
return &pollResp, nil
diff --git a/backend/pkg/libarcane/edge/poll_control.go b/backend/pkg/libarcane/edge/poll_control.go
index bd8db3a0a..03b52e238 100644
--- a/backend/pkg/libarcane/edge/poll_control.go
+++ b/backend/pkg/libarcane/edge/poll_control.go
@@ -1,7 +1,7 @@
package edge
import (
- "encoding/json"
+ json "encoding/json/v2"
"errors"
"io"
"log/slog"
@@ -228,7 +228,7 @@ func decodeTunnelPollRequestInternal(c echo.Context) (*TunnelPollRequest, error)
defer func() { _ = req.Body.Close() }()
var pollReq TunnelPollRequest
- if err := json.NewDecoder(req.Body).Decode(&pollReq); err != nil {
+ if err := json.UnmarshalRead(req.Body, &pollReq); err != nil {
if errors.Is(err, http.ErrBodyReadAfterClose) {
return &TunnelPollRequest{}, nil
}
diff --git a/backend/pkg/libarcane/edge/tls.go b/backend/pkg/libarcane/edge/tls.go
index 4f01fbd59..8f842992f 100644
--- a/backend/pkg/libarcane/edge/tls.go
+++ b/backend/pkg/libarcane/edge/tls.go
@@ -8,7 +8,7 @@ import (
"crypto/rand"
"crypto/tls"
"crypto/x509"
- "encoding/json"
+ json "encoding/json/v2"
"encoding/pem"
"errors"
"fmt"
@@ -358,7 +358,7 @@ func enrollAgentMTLSAssetsInternal(ctx context.Context, cfg *Config, assetsDir,
}
var enrollResp enrollMTLSResponse
- if err := json.NewDecoder(io.LimitReader(resp.Body, maxEnrollResponseBytes)).Decode(&enrollResp); err != nil {
+ if err := json.UnmarshalRead(io.LimitReader(resp.Body, maxEnrollResponseBytes), &enrollResp); err != nil {
return fmt.Errorf("failed to decode edge mTLS enrollment response: %w", err)
}
if len(enrollResp.Files) == 0 {
diff --git a/backend/pkg/libarcane/edge/tunnel.go b/backend/pkg/libarcane/edge/tunnel.go
index 6d602f661..ff60b891d 100644
--- a/backend/pkg/libarcane/edge/tunnel.go
+++ b/backend/pkg/libarcane/edge/tunnel.go
@@ -2,7 +2,7 @@ package edge
import (
"context"
- "encoding/json"
+ json "encoding/json/v2"
"errors"
"io"
"sync"
@@ -105,16 +105,6 @@ type TunnelEvent struct {
MetadataJSON []byte `json:"metadata_json,omitempty"`
}
-// MarshalJSON custom marshaler to handle nil body as empty.
-func (m *TunnelMessage) MarshalJSON() ([]byte, error) {
- type Alias TunnelMessage
- return json.Marshal(&struct {
- *Alias
- }{
- Alias: (*Alias)(m),
- })
-}
-
// PendingRequest tracks an in-flight request waiting for response.
type PendingRequest struct {
ResponseCh chan *TunnelMessage
diff --git a/backend/pkg/libarcane/inspect_compat.go b/backend/pkg/libarcane/inspect_compat.go
index 70a06172a..0272533b2 100644
--- a/backend/pkg/libarcane/inspect_compat.go
+++ b/backend/pkg/libarcane/inspect_compat.go
@@ -3,7 +3,7 @@ package libarcane
import (
"bufio"
"context"
- "encoding/json"
+ json "encoding/json/v2"
"errors"
"fmt"
"io"
diff --git a/backend/pkg/libarcane/vuln/trivy.go b/backend/pkg/libarcane/vuln/trivy.go
index 2be709bfc..5434dd670 100644
--- a/backend/pkg/libarcane/vuln/trivy.go
+++ b/backend/pkg/libarcane/vuln/trivy.go
@@ -5,7 +5,7 @@ package vuln
import (
"encoding/base64"
- "encoding/json"
+ json "encoding/json/v2"
"fmt"
"net/url"
"runtime"
diff --git a/backend/pkg/libarcane/ws/bridge.go b/backend/pkg/libarcane/ws/bridge.go
index 9fadd591f..a7d1761fe 100644
--- a/backend/pkg/libarcane/ws/bridge.go
+++ b/backend/pkg/libarcane/ws/bridge.go
@@ -2,7 +2,7 @@ package ws
import (
"context"
- "encoding/json"
+ json "encoding/json/v2"
"time"
)
diff --git a/backend/pkg/projects/cmds.go b/backend/pkg/projects/cmds.go
index 07f534dfe..71cd3ded5 100644
--- a/backend/pkg/projects/cmds.go
+++ b/backend/pkg/projects/cmds.go
@@ -2,7 +2,7 @@ package projects
import (
"context"
- "encoding/json"
+ json "encoding/json/v2"
"io"
"strings"
"time"
diff --git a/backend/pkg/projects/image_refs.go b/backend/pkg/projects/image_refs.go
index f5212070f..eccd6c202 100644
--- a/backend/pkg/projects/image_refs.go
+++ b/backend/pkg/projects/image_refs.go
@@ -1,7 +1,7 @@
package projects
import (
- "encoding/json"
+ json "encoding/json/v2"
"sort"
"strings"
diff --git a/backend/pkg/remenv/client.go b/backend/pkg/remenv/client.go
index 6e658c59f..cff55901d 100644
--- a/backend/pkg/remenv/client.go
+++ b/backend/pkg/remenv/client.go
@@ -3,7 +3,7 @@ package remenv
import (
"bytes"
"context"
- "encoding/json"
+ json "encoding/json/v2"
"errors"
"fmt"
"io"
diff --git a/backend/pkg/scheduler/analytics_job.go b/backend/pkg/scheduler/analytics_job.go
index 0fd1d52bf..86359b9c3 100644
--- a/backend/pkg/scheduler/analytics_job.go
+++ b/backend/pkg/scheduler/analytics_job.go
@@ -3,7 +3,7 @@ package scheduler
import (
"bytes"
"context"
- "encoding/json"
+ json "encoding/json/v2"
"errors"
"fmt"
"io"
diff --git a/backend/pkg/utils/jwtclaims/jwt.go b/backend/pkg/utils/jwtclaims/jwt.go
index ca25f2aa0..ca6ab0ba6 100644
--- a/backend/pkg/utils/jwtclaims/jwt.go
+++ b/backend/pkg/utils/jwtclaims/jwt.go
@@ -3,7 +3,7 @@ package jwtclaims
import (
"crypto/rand"
"encoding/base64"
- "encoding/json"
+ json "encoding/json/v2"
"fmt"
"strings"
)
@@ -84,12 +84,12 @@ func GetStringSliceClaim(m map[string]any, key string) []string {
}
const (
- // KnownInsecureJWTSecret is the placeholder shipped in config.go's struct
+ // knownInsecureJWTSecret is the placeholder shipped in config.go's struct
// tag; it must never sign real tokens. Keep in sync with the `default:` tag
// on Config.JWTSecret.
- KnownInsecureJWTSecret = "default-jwt-secret-change-me" // #nosec G101: public placeholder config default, intentionally rejected for production signing
- // MinJWTSecretLength matches the 32-byte floor enforced for ENCRYPTION_KEY.
- MinJWTSecretLength = 32
+ knownInsecureJWTSecret = "default-jwt-secret-change-me" // #nosec G101: public placeholder config default, intentionally rejected for production signing
+ // minJWTSecretLength matches the 32-byte floor enforced for ENCRYPTION_KEY.
+ minJWTSecretLength = 32
)
// CheckOrGenerateJwtSecret returns the HMAC signing key for JWTs.
@@ -100,16 +100,16 @@ const (
// a random per-boot key is generated when none (or only the public default) is
// configured, so the public default never becomes a live signing key.
func CheckOrGenerateJwtSecret(jwtSecret string, requireExplicit bool) []byte {
- isDefault := jwtSecret == "" || jwtSecret == KnownInsecureJWTSecret
+ isDefault := jwtSecret == "" || jwtSecret == knownInsecureJWTSecret
if requireExplicit {
if isDefault {
panic("JWT_SECRET is required in production. Set JWT_SECRET to a unique " +
"random value of at least 32 characters (e.g. `openssl rand -base64 32`).")
}
- if len(jwtSecret) < MinJWTSecretLength {
+ if len(jwtSecret) < minJWTSecretLength {
panic(fmt.Sprintf("JWT_SECRET must be at least %d characters (got %d).",
- MinJWTSecretLength, len(jwtSecret)))
+ minJWTSecretLength, len(jwtSecret)))
}
return []byte(jwtSecret)
}
diff --git a/backend/pkg/utils/jwtclaims/jwt_test.go b/backend/pkg/utils/jwtclaims/jwt_test.go
index eb6a3ed5a..7d75a76a1 100644
--- a/backend/pkg/utils/jwtclaims/jwt_test.go
+++ b/backend/pkg/utils/jwtclaims/jwt_test.go
@@ -9,7 +9,7 @@ import (
func TestCheckOrGenerateJwtSecret(t *testing.T) {
// Production (requireExplicit) must reject empty, the public default, and short secrets.
assert.Panics(t, func() { CheckOrGenerateJwtSecret("", true) })
- assert.Panics(t, func() { CheckOrGenerateJwtSecret(KnownInsecureJWTSecret, true) })
+ assert.Panics(t, func() { CheckOrGenerateJwtSecret(knownInsecureJWTSecret, true) })
assert.Panics(t, func() { CheckOrGenerateJwtSecret("too-short", true) })
// Production accepts a real secret verbatim.
@@ -17,7 +17,7 @@ func TestCheckOrGenerateJwtSecret(t *testing.T) {
assert.Equal(t, []byte(good), CheckOrGenerateJwtSecret(good, true))
// Development / agent mode replaces the public default with a random key.
- got := CheckOrGenerateJwtSecret(KnownInsecureJWTSecret, false)
+ got := CheckOrGenerateJwtSecret(knownInsecureJWTSecret, false)
assert.Len(t, got, 32)
- assert.NotEqual(t, []byte(KnownInsecureJWTSecret), got)
+ assert.NotEqual(t, []byte(knownInsecureJWTSecret), got)
}
diff --git a/backend/pkg/utils/notifications/config_credentials.go b/backend/pkg/utils/notifications/config_credentials.go
index 9194ba699..4cc68d3cc 100644
--- a/backend/pkg/utils/notifications/config_credentials.go
+++ b/backend/pkg/utils/notifications/config_credentials.go
@@ -2,7 +2,7 @@ package notifications
import (
"encoding/base64"
- "encoding/json"
+ json "encoding/json/v2"
"errors"
"fmt"
"log/slog"
diff --git a/backend/pkg/utils/notifications/generic_sender.go b/backend/pkg/utils/notifications/generic_sender.go
index d254d77b9..a957a77c0 100644
--- a/backend/pkg/utils/notifications/generic_sender.go
+++ b/backend/pkg/utils/notifications/generic_sender.go
@@ -3,7 +3,7 @@ package notifications
import (
"bytes"
"context"
- "encoding/json"
+ json "encoding/json/v2"
"errors"
"fmt"
"io"
diff --git a/docker/Dockerfile b/docker/Dockerfile
index 88af5761f..5245e2088 100644
--- a/docker/Dockerfile
+++ b/docker/Dockerfile
@@ -30,6 +30,7 @@ RUN pnpm -C frontend build
# Stage 2: Build Backend
FROM --platform=$BUILDPLATFORM golang:1.26.5-trixie AS backend-builder
+ENV GOEXPERIMENT=jsonv2
ARG TARGETARCH
ARG TARGETVARIANT
ARG BUILD_TAGS
diff --git a/docker/Dockerfile-agent b/docker/Dockerfile-agent
index 80387f168..4913dcd60 100644
--- a/docker/Dockerfile-agent
+++ b/docker/Dockerfile-agent
@@ -4,6 +4,7 @@ ARG REVISION="unknown"
ARG ARCANE_RUNTIME_BASE_IMAGE=ghcr.io/getarcaneapp/base:distroless
FROM --platform=$BUILDPLATFORM golang:1.26.5-trixie AS agent-builder
+ENV GOEXPERIMENT=jsonv2
ARG TARGETARCH
ARG TARGETVARIANT
ARG BUILD_TAGS="exclude_frontend"
diff --git a/docker/Dockerfile.dev b/docker/Dockerfile.dev
index 1330f7fc2..ba924a9f8 100644
--- a/docker/Dockerfile.dev
+++ b/docker/Dockerfile.dev
@@ -32,6 +32,7 @@ CMD ["pnpm", "-C", "frontend", "dev", "--host", "0.0.0.0"]
# Stage 2: Backend Development with optimized caching
FROM --platform=$BUILDPLATFORM golang:1.26.5-trixie AS backend-dev
+ENV GOEXPERIMENT=jsonv2
# Install development tools in a single layer
RUN apt-get update && apt-get install -y --no-install-recommends \
diff --git a/frontend/src/service-worker.ts b/frontend/src/service-worker.ts
index 0a868e539..50e34f9a7 100644
--- a/frontend/src/service-worker.ts
+++ b/frontend/src/service-worker.ts
@@ -3,20 +3,22 @@
/// <reference lib="webworker" />
/// <reference types="@sveltejs/kit" />
-import { files, version } from '$service-worker';
+import { base, files, version } from '$service-worker';
const self = globalThis.self as unknown as ServiceWorkerGlobalScope;
const CACHE = `cache-${version}`;
+const API_PREFIX = `${base}/api/`;
const ASSETS = files;
+const ASSET_PATHS = new Set(ASSETS.map((asset) => new URL(asset, self.location.origin).pathname));
self.addEventListener('install', (event) => {
console.log('[ServiceWorker] Install');
async function addFilesToCache() {
const cache = await caches.open(CACHE);
- console.log('[ServiceWorker] Caching app shell');
+ console.log('[ServiceWorker] Caching static assets');
await cache.addAll(ASSETS);
}
@@ -55,12 +57,18 @@ self.addEventListener('fetch', (event) => {
if (event.request.method !== 'GET') return;
const url = new URL(event.request.url);
+ if (url.origin !== self.location.origin) return;
// Never intercept API requests. Caching the never-ending `/api/.../stream`
// responses leaked memory and collapsed every tab onto a single cached
// connection, so only the first tab received live events. Let API requests
// — including streams — go straight to the network, one per tab.
- if (url.pathname.startsWith('/api/')) return;
+ if (url.pathname.startsWith(API_PREFIX)) return;
+
+ // Generated application chunks and navigations already carry content-hashed
+ // URLs or need the current backend response. Intercept only the static assets
+ // installed above so an uncached network failure cannot reject respondWith().
+ if (!ASSET_PATHS.has(url.pathname)) return;
async function respond() {
const cache = await caches.open(CACHE);
@@ -70,7 +78,11 @@ self.addEventListener('fetch', (event) => {
return cachedResponse;
}
- return fetch(event.request);
+ try {
+ return await fetch(event.request);
+ } catch {
+ return new Response(null, { status: 503 });
+ }
}
event.respondWith(respond());
diff --git a/go.work.sum b/go.work.sum
index ed555a66c..06b3f41ea 100644
--- a/go.work.sum
+++ b/go.work.sum
@@ -420,7 +420,6 @@ github.com/Microsoft/cosesign1go v1.4.0/go.mod h1:1La/HcGw19rRLhPW0S6u55K6LKfti+
github.com/Microsoft/didx509go v0.0.3 h1:n/owuFOXVzCEzSyzivMEolKEouBm9G0NrEDgoTekM8A=
github.com/Microsoft/didx509go v0.0.3/go.mod h1:wWt+iQsLzn3011+VfESzznLIp/Owhuj7rLF7yLglYbk=
github.com/Microsoft/go-winio v0.4.21/go.mod h1:JPGBdM1cNvN/6ISo+n8V5iA4v8pBzdOpzfwIujj1a84=
-github.com/Microsoft/go-winio v0.6.2/go.mod h1:yd8OoFMLzJbo9gZq8j5qaps8bJ9aShtEA8Ipt1oGCvU=
github.com/Microsoft/hcsshim v0.14.1/go.mod h1:VnzvPLyWUhxiPVsJ31P6XadxCcTogTguBFDy/1GR/OM=
github.com/NYTimes/gziphandler v1.1.1 h1:ZUDjpQae29j0ryrS0u/B8HZfJBtBQHjqw2rQ2cqUQ3I=
github.com/NYTimes/gziphandler v1.1.1/go.mod h1:n/CVRwUEOgIxrgPvAQhUUr9oeUtvrhMomdKFjzJNB0c=
@@ -2082,12 +2081,16 @@ go.etcd.io/gofail v0.2.0 h1:p19drv16FKK345a09a1iubchlw/vmRuksmRzgBIGjcA=
go.etcd.io/gofail v0.2.0/go.mod h1:nL3ILMGfkXTekKI3clMBNazKnjUZjYLKmBHzsVAnC1o=
go.etcd.io/raft/v3 v3.6.0 h1:5NtvbDVYpnfZWcIHgGRk9DyzkBIXOi8j+DDp1IcnUWQ=
go.etcd.io/raft/v3 v3.6.0/go.mod h1:nLvLevg6+xrVtHUmVaTcTz603gQPHfh7kUAwV6YpfGo=
-go.getarcane.app/streams v0.2.0 h1:qQ1pcHaFVeeWxRd81jAhf6SaY3DfNWeKnMtUtyghOWw=
-go.getarcane.app/streams v0.2.0/go.mod h1:LHMKblQvsL1nqKh/Y+KgQbwFSMI2I7bs9u8ZwZqzjnQ=
+go.getarcane.app/builds v0.2.0 h1:IXl78t2Lpr4FJ+HQhAGbTgENyPr2WLBxAmFebRu5kuU=
+go.getarcane.app/builds v0.2.0/go.mod h1:korkB7gWCiWx00SbKtX0sTwxWYeL1pxeTKOYxohjJUA=
+go.getarcane.app/streams v0.3.0 h1:UM4Y8E0lpi0GEKSJ5zUyeho9aJoBIi/Pr3dJnnhCkK4=
+go.getarcane.app/streams v0.3.0/go.mod h1:LHMKblQvsL1nqKh/Y+KgQbwFSMI2I7bs9u8ZwZqzjnQ=
go.getarcane.app/updater v0.3.6 h1:+BqoycaRsHj+cLVSzcYQuqbHxUKbtmaozMNblz5bVSw=
go.getarcane.app/updater v0.3.6/go.mod h1:2ENitZR/lA5MuBn60OZYR5wvU3ZCE+pAgfrebfOlRDA=
go.getarcane.app/updater v0.3.7 h1:WqHsxudvt8gvCR7iSHdxdzwH0+hM0FAh64bSypBX9Mo=
go.getarcane.app/updater v0.3.7/go.mod h1:9RZOKaBbpUJfVA4Q9/jvqtjvWBwCnVw0OkPeQCnqAAo=
+go.getarcane.app/updater v0.6.0 h1:dwnCjQdYMCB7xuCmODs/FhT28BCOUT5Uxmn1XydHv2Q=
+go.getarcane.app/updater v0.6.0/go.mod h1:8f0/0pi7J0yFqgwFTywiwk/NoUN/g6AfmprOuAUrI20=
go.mongodb.org/mongo-driver v1.7.5 h1:ny3p0reEpgsR2cfA5cjgwFZg3Cv/ofFh/8jbhGtz9VI=
go.mongodb.org/mongo-driver v1.7.5/go.mod h1:VXEWRZ6URJIkUq2SCAyapmhH0ZLRBP+FT4xhp5Zvxng=
go.mongodb.org/mongo-driver v1.17.6 h1:87JUG1wZfWsr6rIz3ZmpH90rL5tea7O3IHuSwHUpsss=
@@ -2262,7 +2265,6 @@ golang.org/x/mod v0.32.0/go.mod h1:SgipZ/3h2Ci89DlEtEXWUk/HteuRin+HHhN+WbNhguU=
golang.org/x/mod v0.33.0/go.mod h1:swjeQEj+6r7fODbD2cqrnje9PnziFuw4bmLbBZFrQ5w=
golang.org/x/mod v0.35.0/go.mod h1:+GwiRhIInF8wPm+4AoT6L0FA1QWAad3OMdTRx4tFYlU=
golang.org/x/mod v0.36.0/go.mod h1:moc6ELqsWcOw5Ef3xVprK5ul/MvtVvkIXLziUOICjUQ=
-golang.org/x/mod v0.37.0/go.mod h1:m8S8VeM9r4dzDwjrKO0a1sZP3YjeMamRRlD+fmR2Q/0=
golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
@@ -2307,6 +2309,7 @@ golang.org/x/net v0.49.0/go.mod h1:/ysNB2EvaqvesRkuLAyjI1ycPZlQHM3q01F02UY/MV8=
golang.org/x/net v0.50.0/go.mod h1:UgoSli3F/pBgdJBHCTc+tp3gmrU4XswgGRgtnwWTfyM=
golang.org/x/net v0.51.0/go.mod h1:aamm+2QF5ogm02fjy5Bb7CQ0WMt1/WVM7FtyaTLlA9Y=
golang.org/x/net v0.52.0/go.mod h1:R1MAz7uMZxVMualyPXb+VaqGSa3LIaUqk0eEt3w36Sw=
+golang.org/x/net v0.53.0/go.mod h1:JvMuJH7rrdiCfbeHoo3fCQU24Lf5JJwT9W3sJFulfgs=
golang.org/x/net v0.54.0/go.mod h1:Sj4oj8jK6XmHpBZU/zWHw3BV3abl4Kvi+Ut7cQcY+cQ=
golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww=
golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
@@ -2394,7 +2397,6 @@ golang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
golang.org/x/sys v0.42.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
golang.org/x/sys v0.43.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
golang.org/x/sys v0.44.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
-golang.org/x/sys v0.45.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
golang.org/x/telemetry v0.0.0-20240228155512-f48c80bd79b2/go.mod h1:TeRTkGYfJXctD9OcfyVLyj2J3IxLnKwHJR8f4D8a3YE=
golang.org/x/telemetry v0.0.0-20251008203120-078029d740a8 h1:LvzTn0GQhWuvKH/kVRS3R3bVAsdQWI7hvfLHGgh9+lU=
golang.org/x/telemetry v0.0.0-20251008203120-078029d740a8/go.mod h1:Pi4ztBfryZoJEkyFTI5/Ocsu2jXyDr6iSdgJiYE/uwE=
diff --git a/types/base/json.go b/types/base/json.go
index 0ad561910..b0359f336 100644
--- a/types/base/json.go
+++ b/types/base/json.go
@@ -2,7 +2,7 @@ package base
import (
"database/sql/driver"
- "encoding/json"
+ json "encoding/json/v2"
)
// JsonObject is a map-based representation of a JSON object that can be stored
diff --git a/types/dockerinfo/docker_info_test.go b/types/dockerinfo/docker_info_test.go
new file mode 100644
index 000000000..7fc0f2fd6
--- /dev/null
+++ b/types/dockerinfo/docker_info_test.go
@@ -0,0 +1,43 @@
+package dockerinfo
+
+import (
+ json "encoding/json/v2"
+ "testing"
+
+ "github.com/moby/moby/api/types/system"
+)
+
+func TestInfoMarshalsEmbeddedDockerFieldsAtTopLevel(t *testing.T) {
+ data, err := json.Marshal(Info{
+ Info: system.Info{
+ Name: "arcane-host",
+ NCPU: 8,
+ MemTotal: 16 * 1024 * 1024 * 1024,
+ ContainersRunning: 3,
+ },
+ Success: true,
+ APIVersion: "1.55",
+ })
+ if err != nil {
+ t.Fatalf("marshal Docker info: %v", err)
+ }
+
+ var payload map[string]any
+ if err := json.Unmarshal(data, &payload); err != nil {
+ t.Fatalf("unmarshal Docker info payload: %v", err)
+ }
+
+ for name, want := range map[string]any{
+ "Name": "arcane-host",
+ "NCPU": float64(8),
+ "ContainersRunning": float64(3),
+ "apiVersion": "1.55",
+ } {
+ if got := payload[name]; got != want {
+ t.Fatalf("payload[%q] = %#v, want %#v; payload: %s", name, got, want, data)
+ }
+ }
+ if _, nested := payload["Info"]; nested {
+ t.Fatalf("Docker fields were nested under Info: %s", data)
+ }
+}
diff --git a/types/project/marshal_utils.go b/types/project/marshal_utils.go
index eff2fc212..de92864bb 100644
--- a/types/project/marshal_utils.go
+++ b/types/project/marshal_utils.go
@@ -1,11 +1,9 @@
package project
import (
- "bytes"
- "encoding/json"
+ "encoding/json/jsontext"
+ json "encoding/json/v2"
"fmt"
- "maps"
- "reflect"
"strconv"
"strings"
@@ -13,318 +11,54 @@ import (
"github.com/docker/go-units"
)
-// unitBytesType is used to detect compose-go fields that need string-or-number
-// normalization before they can be decoded by encoding/json.
-var unitBytesType = reflect.TypeFor[composetypes.UnitBytes]()
-
-// runtimeServiceJSON is an internal decode shape that lets RuntimeService
-// handle serviceConfig separately from the rest of the payload.
-type runtimeServiceJSON struct {
- runtimeServiceAlias
-
- ServiceConfig json.RawMessage `json:"serviceConfig,omitempty"`
-}
-
-// runtimeServiceAlias prevents recursive calls back into RuntimeService's
-// custom UnmarshalJSON implementation.
-type runtimeServiceAlias RuntimeService
-
-// detailsJSON is an internal decode shape that lets Details intercept the
-// services array while still decoding the rest of the struct normally.
-type detailsJSON struct {
- detailsAlias
-
- Services []json.RawMessage `json:"services,omitempty"`
- RuntimeServices []RuntimeService `json:"runtimeServices,omitempty"`
-}
-
-// detailsAlias prevents recursive calls back into Details.UnmarshalJSON.
-type detailsAlias Details
-
-// UnmarshalJSON makes RuntimeService tolerant of compose-go UnitBytes fields
-// encoded as either JSON strings or JSON numbers inside serviceConfig.
-//
-// This only affects JSON decoding of RuntimeService values. It does not change
-// API response shapes, backend serialization, YAML loading, or any non-JSON
-// code paths.
-func (r *RuntimeService) UnmarshalJSON(data []byte) error {
- var aux runtimeServiceJSON
- if err := decodeJSONWithNumbersInternal(data, &aux); err != nil {
- return err
- }
-
- *r = RuntimeService(aux.runtimeServiceAlias)
-
- serviceConfig, err := unmarshalComposeServiceConfigJSONInternal(aux.ServiceConfig)
+var unitBytesUnmarshalers = json.UnmarshalFromFunc(func(decoder *jsontext.Decoder, value *composetypes.UnitBytes) error {
+ token, err := decoder.ReadToken()
if err != nil {
- return fmt.Errorf("serviceConfig: %w", err)
- }
- r.ServiceConfig = serviceConfig
-
- return nil
-}
-
-// UnmarshalJSON makes Details tolerant of compose-go UnitBytes fields encoded
-// as either JSON strings or JSON numbers inside services and runtime service
-// configs.
-//
-// The rest of the Details payload is decoded normally. Only compose service
-// payloads are normalized before they are unmarshaled into
-// composetypes.ServiceConfig values.
-func (d *Details) UnmarshalJSON(data []byte) error {
- var aux detailsJSON
- if err := decodeJSONWithNumbersInternal(data, &aux); err != nil {
return err
}
- *d = Details(aux.detailsAlias)
- d.RuntimeServices = aux.RuntimeServices
-
- if len(aux.Services) == 0 {
- d.Services = nil
+ switch token.Kind() {
+ case jsontext.KindNull:
return nil
- }
-
- services := make([]composetypes.ServiceConfig, 0, len(aux.Services))
- for i, rawService := range aux.Services {
- service, err := unmarshalComposeServiceConfigJSONInternal(rawService)
+ case jsontext.KindString:
+ parsed, err := units.RAMInBytes(strings.TrimSpace(token.String()))
if err != nil {
- return fmt.Errorf("services[%d]: %w", i, err)
+ return err
}
- if service == nil {
- continue
- }
- services = append(services, *service)
- }
- d.Services = services
-
- return nil
-}
-
-// unmarshalComposeServiceConfigJSON decodes a raw service JSON object into a
-// compose-go ServiceConfig after recursively normalizing any UnitBytes-backed
-// fields so compose-go can accept string and numeric JSON representations.
-func unmarshalComposeServiceConfigJSONInternal(data []byte) (*composetypes.ServiceConfig, error) {
- trimmed := bytes.TrimSpace(data)
- if len(trimmed) == 0 || bytes.Equal(trimmed, []byte("null")) {
- return nil, nil
- }
-
- var raw any
- if err := decodeJSONWithNumbersInternal(trimmed, &raw); err != nil {
- return nil, err
- }
-
- normalized, err := normalizeJSONValueForTypeInternal(raw, reflect.TypeFor[composetypes.ServiceConfig]())
- if err != nil {
- return nil, err
- }
-
- normalizedBytes, err := json.Marshal(normalized)
- if err != nil {
- return nil, err
- }
-
- var service composetypes.ServiceConfig
- if err := json.Unmarshal(normalizedBytes, &service); err != nil {
- return nil, err
- }
-
- return &service, nil
-}
-
-// decodeJSONWithNumbers preserves JSON numbers as json.Number so the
-// normalizer can distinguish integer-like values from quoted strings.
-func decodeJSONWithNumbersInternal(data []byte, dest any) error {
- decoder := json.NewDecoder(bytes.NewReader(data))
- decoder.UseNumber()
- return decoder.Decode(dest)
-}
-
-// normalizeJSONValueForType walks decoded JSON using the destination Go type
-// as the source of truth.
-//
-// That keeps the fix generic: any field reachable from ServiceConfig that uses
-// composetypes.UnitBytes gets normalized without maintaining a hardcoded field
-// name list.
-func normalizeJSONValueForTypeInternal(value any, destType reflect.Type) (any, error) {
- if destType == nil || value == nil {
- return value, nil
- }
-
- for destType.Kind() == reflect.Pointer {
- destType = destType.Elem()
- }
-
- if destType == unitBytesType {
- return normalizeUnitBytesValueInternal(value)
- }
-
- switch destType.Kind() {
- case reflect.Struct:
- return normalizeJSONObjectForTypeInternal(value, destType)
- case reflect.Slice, reflect.Array:
- return normalizeJSONArrayForTypeInternal(value, destType)
- case reflect.Map:
- return normalizeJSONMapForTypeInternal(value, destType)
- case reflect.Pointer:
- // Pointer kinds are fully dereferenced above. This branch only exists to
- // keep the reflect.Kind switch exhaustive for linting.
- return value, nil
- case reflect.Invalid, reflect.Bool, reflect.Int, reflect.Int8, reflect.Int16,
- reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16,
- reflect.Uint32, reflect.Uint64, reflect.Uintptr, reflect.Float32, reflect.Float64,
- reflect.Complex64, reflect.Complex128, reflect.Chan, reflect.Func, reflect.Interface,
- reflect.String, reflect.UnsafePointer:
- return value, nil
- }
-
- return value, nil
-}
-
-// normalizeJSONObjectForType normalizes a decoded JSON object according to the
-// exported JSON fields of the destination struct type.
-func normalizeJSONObjectForTypeInternal(value any, destType reflect.Type) (any, error) {
- object, ok := value.(map[string]any)
- if !ok {
- return value, nil
- }
-
- normalized := make(map[string]any, len(object))
- maps.Copy(normalized, object)
-
- for field := range destType.Fields() {
- if field.PkgPath != "" {
- continue
- }
-
- if field.Anonymous {
- embedded, err := normalizeJSONValueForTypeInternal(normalized, field.Type)
- if err != nil {
- return nil, err
+ *value = composetypes.UnitBytes(parsed)
+ return nil
+ case jsontext.KindNumber:
+ raw := token.String()
+ parsed, err := strconv.ParseInt(raw, 10, 64)
+ if err != nil {
+ floatValue, parseErr := strconv.ParseFloat(raw, 64)
+ if parseErr != nil {
+ return parseErr
}
- embeddedMap, ok := embedded.(map[string]any)
- if ok {
- normalized = embeddedMap
+ parsed = int64(floatValue)
+ if floatValue != float64(parsed) {
+ return fmt.Errorf("invalid UnitBytes value %q", raw)
}
- continue
- }
-
- fieldName, ok := jsonFieldNameInternal(field)
- if !ok {
- continue
}
-
- fieldValue, exists := normalized[fieldName]
- if !exists {
- continue
- }
-
- normalizedValue, err := normalizeJSONValueForTypeInternal(fieldValue, field.Type)
- if err != nil {
- return nil, fmt.Errorf("%s: %w", fieldName, err)
- }
- normalized[fieldName] = normalizedValue
- }
-
- return normalized, nil
-}
-
-// normalizeJSONArrayForType normalizes each decoded array element according to
-// the destination element type.
-func normalizeJSONArrayForTypeInternal(value any, destType reflect.Type) (any, error) {
- items, ok := value.([]any)
- if !ok {
- return value, nil
- }
-
- normalized := make([]any, len(items))
- for i, item := range items {
- normalizedItem, err := normalizeJSONValueForTypeInternal(item, destType.Elem())
- if err != nil {
- return nil, fmt.Errorf("[%d]: %w", i, err)
- }
- normalized[i] = normalizedItem
- }
-
- return normalized, nil
-}
-
-// normalizeJSONMapForType normalizes map values for string-keyed JSON objects
-// whose destination type is a Go map.
-func normalizeJSONMapForTypeInternal(value any, destType reflect.Type) (any, error) {
- if destType.Key().Kind() != reflect.String {
- return value, nil
- }
-
- items, ok := value.(map[string]any)
- if !ok {
- return value, nil
- }
-
- normalized := make(map[string]any, len(items))
- for key, item := range items {
- normalizedItem, err := normalizeJSONValueForTypeInternal(item, destType.Elem())
- if err != nil {
- return nil, fmt.Errorf("%s: %w", key, err)
- }
- normalized[key] = normalizedItem
+ *value = composetypes.UnitBytes(parsed)
+ return nil
+ case jsontext.KindInvalid, jsontext.KindFalse, jsontext.KindTrue,
+ jsontext.KindBeginObject, jsontext.KindEndObject,
+ jsontext.KindBeginArray, jsontext.KindEndArray:
+ return fmt.Errorf("unsupported JSON kind %s for UnitBytes", token.Kind())
}
- return normalized, nil
-}
-
-// normalizeUnitBytesValue converts supported JSON representations for
-// compose-go UnitBytes fields into integer byte counts.
-//
-// Supported inputs:
-// - json numbers
-// - quoted byte strings such as "268435456"
-// - human-readable Docker memory strings such as "256m" or "1g"
-func normalizeUnitBytesValueInternal(value any) (any, error) {
- switch v := value.(type) {
- case json.Number:
- if parsed, err := v.Int64(); err == nil {
- return parsed, nil
- }
-
- floatValue, err := strconv.ParseFloat(v.String(), 64)
- if err != nil {
- return nil, err
- }
- if floatValue != float64(int64(floatValue)) {
- return nil, fmt.Errorf("invalid UnitBytes value %q", v.String())
- }
- return int64(floatValue), nil
+ return fmt.Errorf("unsupported JSON kind %s for UnitBytes", token.Kind())
+})
- case string:
- parsed, err := units.RAMInBytes(strings.TrimSpace(v))
- if err != nil {
- return nil, err
- }
- return parsed, nil
+type runtimeServiceAlias RuntimeService
- default:
- return nil, fmt.Errorf("unsupported type %T for UnitBytes field", value)
- }
+func (r *RuntimeService) UnmarshalJSON(data []byte) error {
+ return json.Unmarshal(data, (*runtimeServiceAlias)(r), json.WithUnmarshalers(unitBytesUnmarshalers))
}
-// jsonFieldName returns the JSON field name that should be used for a struct
-// field during normalization.
-func jsonFieldNameInternal(field reflect.StructField) (string, bool) {
- tag := field.Tag.Get("json")
- if tag == "-" {
- return "", false
- }
-
- if tag == "" {
- return field.Name, true
- }
-
- name := strings.Split(tag, ",")[0]
- if name == "" {
- return field.Name, true
- }
+type detailsAlias Details
- return name, true
+func (d *Details) UnmarshalJSON(data []byte) error {
+ return json.Unmarshal(data, (*detailsAlias)(d), json.WithUnmarshalers(unitBytesUnmarshalers))
}
diff --git a/types/project/marshal_utils_test.go b/types/project/marshal_utils_test.go
new file mode 100644
index 000000000..a904d4797
--- /dev/null
+++ b/types/project/marshal_utils_test.go
@@ -0,0 +1,40 @@
+package project
+
+import (
+ json "encoding/json/v2"
+ "testing"
+
+ composetypes "github.com/compose-spec/compose-go/v2/types"
+)
+
+func TestDetailsUnmarshalJSONAcceptsUnitBytesStringsAndNumbers(t *testing.T) {
+ tests := []struct {
+ name string
+ payload string
+ }{
+ {
+ name: "human readable string",
+ payload: `{"services":[{"name":"app","mem_limit":"256m"}]}`,
+ },
+ {
+ name: "number",
+ payload: `{"services":[{"name":"app","mem_limit":268435456}]}`,
+ },
+ }
+
+ for _, test := range tests {
+ t.Run(test.name, func(t *testing.T) {
+ var details Details
+ err := json.Unmarshal([]byte(test.payload), &details)
+ if err != nil {
+ t.Fatalf("unmarshal Details: %v", err)
+ }
+ if len(details.Services) != 1 {
+ t.Fatalf("decoded %d services, want 1", len(details.Services))
+ }
+ if got, want := details.Services[0].MemLimit, composetypes.UnitBytes(256*1024*1024); got != want {
+ t.Fatalf("mem_limit = %d, want %d", got, want)
+ }
+ })
+ }
+}
diff --git a/types/system/prune.go b/types/system/prune.go
index b86858f39..ad89c921e 100644
--- a/types/system/prune.go
+++ b/types/system/prune.go
@@ -1,6 +1,9 @@
package system
-import "encoding/json"
+import (
+ stdjson "encoding/json"
+ json "encoding/json/v2"
+)
type PruneContainerMode string
@@ -78,12 +81,12 @@ type PruneAllRequest struct {
}
type pruneAllRequestWireInternal struct {
- Containers json.RawMessage `json:"containers,omitempty"`
- Images json.RawMessage `json:"images,omitempty"`
- Volumes json.RawMessage `json:"volumes,omitempty"`
- Networks json.RawMessage `json:"networks,omitempty"`
- BuildCache json.RawMessage `json:"buildCache,omitempty"`
- Dangling *bool `json:"dangling,omitempty"`
+ Containers stdjson.RawMessage `json:"containers,omitempty"`
+ Images stdjson.RawMessage `json:"images,omitempty"`
+ Volumes stdjson.RawMessage `json:"volumes,omitempty"`
+ Networks stdjson.RawMessage `json:"networks,omitempty"`
+ BuildCache stdjson.RawMessage `json:"buildCache,omitempty"`
+ Dangling *bool `json:"dangling,omitempty"`
}
func (r *PruneAllRequest) UnmarshalJSON(data []byte) error {
@@ -127,7 +130,7 @@ func (r *PruneAllRequest) UnmarshalJSON(data []byte) error {
return nil
}
-func decodePruneContainersOptionsInternal(raw json.RawMessage) (*PruneContainersOptions, error) {
+func decodePruneContainersOptionsInternal(raw stdjson.RawMessage) (*PruneContainersOptions, error) {
if len(raw) == 0 || string(raw) == "null" {
return nil, nil
}
@@ -147,7 +150,7 @@ func decodePruneContainersOptionsInternal(raw json.RawMessage) (*PruneContainers
return &options, nil
}
-func decodePruneImagesOptionsInternal(raw json.RawMessage, dangling *bool) (*PruneImagesOptions, error) {
+func decodePruneImagesOptionsInternal(raw stdjson.RawMessage, dangling *bool) (*PruneImagesOptions, error) {
if len(raw) == 0 || string(raw) == "null" {
return nil, nil
}
@@ -171,7 +174,7 @@ func decodePruneImagesOptionsInternal(raw json.RawMessage, dangling *bool) (*Pru
return &options, nil
}
-func decodePruneVolumesOptionsInternal(raw json.RawMessage, dangling *bool) (*PruneVolumesOptions, error) {
+func decodePruneVolumesOptionsInternal(raw stdjson.RawMessage, dangling *bool) (*PruneVolumesOptions, error) {
if len(raw) == 0 || string(raw) == "null" {
return nil, nil
}
@@ -195,7 +198,7 @@ func decodePruneVolumesOptionsInternal(raw json.RawMessage, dangling *bool) (*Pr
return &options, nil
}
-func decodePruneNetworksOptionsInternal(raw json.RawMessage) (*PruneNetworksOptions, error) {
+func decodePruneNetworksOptionsInternal(raw stdjson.RawMessage) (*PruneNetworksOptions, error) {
if len(raw) == 0 || string(raw) == "null" {
return nil, nil
}
@@ -215,7 +218,7 @@ func decodePruneNetworksOptionsInternal(raw json.RawMessage) (*PruneNetworksOpti
return &options, nil
}
-func decodePruneBuildCacheOptionsInternal(raw json.RawMessage, dangling *bool) (*PruneBuildCacheOptions, error) {
+func decodePruneBuildCacheOptionsInternal(raw stdjson.RawMessage, dangling *bool) (*PruneBuildCacheOptions, error) {
if len(raw) == 0 || string(raw) == "null" {
return nil, nil
}