Skip to content

Modern Docker Management, Designed for Everyone

refactor: use generics to eliminate rudundant logic (#3683)

Kyle Mendell671ebef57234
diff --git a/.github/.golangci.yml b/.github/.golangci.yml
index fa7c1c7f4..e85b65e63 100644
--- a/.github/.golangci.yml
+++ b/.github/.golangci.yml
@@ -1,4 +1,4 @@
-version: "2"
+version: '2'
run:
tests: false
timeout: 5m
@@ -11,7 +11,6 @@ linters:
- asciicheck
- bidichk
- bodyclose
- - canonicalheader
- clickhouselint
- contextcheck
- copyloopvar
@@ -118,13 +117,13 @@ linters:
rules:
- linters:
- revive
- text: "var-naming:"
+ text: 'var-naming:'
- linters:
- revive
- text: "unused-parameter:"
+ text: 'unused-parameter:'
- linters:
- revive
- text: "exported:"
+ text: 'exported:'
- linters:
- forbidigo
path: cli/
diff --git a/.vscode/settings.json b/.vscode/settings.json
index 61847b62a..1de29dbdd 100644
--- a/.vscode/settings.json
+++ b/.vscode/settings.json
@@ -22,5 +22,16 @@
},
"tasks.statusbar.default.hide": true,
"tasks.statusbar.limit": 8,
- "js/ts.tsdk.path": "node_modules/@typescript/native-preview"
+ "js/ts.tsdk.path": "node_modules/@typescript/native-preview",
+ "yaml.disableSchemaDetection": [
+ "**/.github/workflows/*.yml",
+ "**/.github/workflows/*.yaml",
+ "**/.gitea/workflows/*.yml",
+ "**/.gitea/workflows/*.yaml",
+ "**/.forgejo/workflows/*.yml",
+ "**/.forgejo/workflows/*.yaml"
+ ],
+ "yaml.schemas": {
+ "https://json.schemastore.org/github-workflow.json": ".github/workflows/*"
+ }
}
diff --git a/backend/cli/recovery/recovery.go b/backend/cli/recovery/recovery.go
index 06d3d9a14..7c98b3081 100644
--- a/backend/cli/recovery/recovery.go
+++ b/backend/cli/recovery/recovery.go
@@ -2,7 +2,7 @@ package recovery
import (
"context"
- "encoding/json"
+ "encoding/json/v2"
"fmt"
"log/slog"
"os"
diff --git a/backend/internal/activity/handler.go b/backend/internal/activity/handler.go
index 1e71b3463..a0d842b1b 100644
--- a/backend/internal/activity/handler.go
+++ b/backend/internal/activity/handler.go
@@ -56,28 +56,16 @@ type ListActivitiesInput struct {
ResourceType string `query:"resourceType" doc:"Filter by resource type"`
}
-type ListActivitiesOutput struct {
- Body base.Paginated[activitytypes.Activity]
-}
-
type GetActivityInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
ActivityID string `path:"activityId" doc:"Activity ID"`
Limit int `query:"limit" default:"500" doc:"Maximum messages to return"`
}
-type GetActivityOutput struct {
- Body base.ApiResponse[activitytypes.Detail]
-}
-
type ClearActivityHistoryInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
}
-type ClearActivityHistoryOutput struct {
- Body base.ApiResponse[activitytypes.ClearHistoryResult]
-}
-
type StreamAllActivitiesInput struct {
Limit int `query:"limit" default:"50" doc:"Snapshot limit per environment"`
}
@@ -95,10 +83,6 @@ type CancelActivityInput struct {
RequestedBy string `query:"requestedBy" doc:"Display name to attribute the cancellation to (used when proxying to a remote environment)"`
}
-type CancelActivityOutput struct {
- Body base.ApiResponse[activitytypes.Activity]
-}
-
func NewHandler(activityService *ActivityService, environment EnvironmentDependencies) *ActivityHandler {
return &ActivityHandler{
activityService: activityService,
@@ -149,7 +133,7 @@ func RegisterActivities(api huma.API, h *ActivityHandler) {
}, authz.PermActivitiesDelete, h.ClearHistory)
}
-func (h *ActivityHandler) ListActivities(ctx context.Context, input *ListActivitiesInput) (*ListActivitiesOutput, error) {
+func (h *ActivityHandler) ListActivities(ctx context.Context, input *ListActivitiesInput) (*handlerutil.Page[activitytypes.Activity], error) {
if input.EnvironmentID != "0" {
return h.proxyListActivitiesInternal(ctx, input)
}
@@ -171,7 +155,7 @@ func (h *ActivityHandler) ListActivities(ctx context.Context, input *ListActivit
}
h.applyActivitySourceLabelsInternal(ctx, input.EnvironmentID, activities)
- return &ListActivitiesOutput{
+ return &handlerutil.Page[activitytypes.Activity]{
Body: base.Paginated[activitytypes.Activity]{
Success: true,
Data: activities,
@@ -180,7 +164,7 @@ func (h *ActivityHandler) ListActivities(ctx context.Context, input *ListActivit
}, nil
}
-func (h *ActivityHandler) GetActivity(ctx context.Context, input *GetActivityInput) (*GetActivityOutput, error) {
+func (h *ActivityHandler) GetActivity(ctx context.Context, input *GetActivityInput) (*handlerutil.Out[activitytypes.Detail], error) {
if input.EnvironmentID != "0" {
return h.proxyGetActivityInternal(ctx, input)
}
@@ -197,7 +181,7 @@ func (h *ActivityHandler) GetActivity(ctx context.Context, input *GetActivityInp
}
h.applyActivitySourceLabelInternal(ctx, input.EnvironmentID, &detail.Activity)
- return &GetActivityOutput{
+ return &handlerutil.Out[activitytypes.Detail]{
Body: base.ApiResponse[activitytypes.Detail]{
Success: true,
Data: *detail,
@@ -205,7 +189,7 @@ func (h *ActivityHandler) GetActivity(ctx context.Context, input *GetActivityInp
}, nil
}
-func (h *ActivityHandler) ClearHistory(ctx context.Context, input *ClearActivityHistoryInput) (*ClearActivityHistoryOutput, error) {
+func (h *ActivityHandler) ClearHistory(ctx context.Context, input *ClearActivityHistoryInput) (*handlerutil.Out[activitytypes.ClearHistoryResult], error) {
if input.EnvironmentID != "0" {
return h.proxyClearHistoryInternal(ctx, input)
}
@@ -215,7 +199,7 @@ func (h *ActivityHandler) ClearHistory(ctx context.Context, input *ClearActivity
return nil, huma.Error500InternalServerError(err.Error())
}
- return &ClearActivityHistoryOutput{
+ return &handlerutil.Out[activitytypes.ClearHistoryResult]{
Body: base.ApiResponse[activitytypes.ClearHistoryResult]{
Success: true,
Data: activitytypes.ClearHistoryResult{Deleted: deleted},
@@ -223,7 +207,7 @@ func (h *ActivityHandler) ClearHistory(ctx context.Context, input *ClearActivity
}, nil
}
-func (h *ActivityHandler) CancelActivity(ctx context.Context, input *CancelActivityInput) (*CancelActivityOutput, error) {
+func (h *ActivityHandler) CancelActivity(ctx context.Context, input *CancelActivityInput) (*handlerutil.Out[activitytypes.Activity], error) {
if input.EnvironmentID != "0" {
return h.proxyCancelActivityInternal(ctx, input)
}
@@ -245,7 +229,7 @@ func (h *ActivityHandler) CancelActivity(ctx context.Context, input *CancelActiv
}
h.applyActivitySourceLabelInternal(ctx, input.EnvironmentID, cancelled)
- return &CancelActivityOutput{
+ return &handlerutil.Out[activitytypes.Activity]{
Body: base.ApiResponse[activitytypes.Activity]{
Success: true,
Data: *cancelled,
@@ -253,17 +237,17 @@ func (h *ActivityHandler) CancelActivity(ctx context.Context, input *CancelActiv
}, nil
}
-func (h *ActivityHandler) proxyCancelActivityInternal(ctx context.Context, input *CancelActivityInput) (*CancelActivityOutput, error) {
+func (h *ActivityHandler) proxyCancelActivityInternal(ctx context.Context, input *CancelActivityInput) (*handlerutil.Out[activitytypes.Activity], error) {
path := fmt.Sprintf("/api/environments/0/activities/%s/cancel", url.PathEscape(input.ActivityID))
if requestedBy := h.cancelRequestedByInternal(ctx, input.RequestedBy); requestedBy != "" {
path += "?requestedBy=" + url.QueryEscape(requestedBy)
}
- out, err := handlerutil.ProxyRemoteJSON[base.ApiResponse[activitytypes.Activity]](ctx, h.environment.ProxyJSONRequest, input.EnvironmentID, http.MethodPost, path, nil)
+ out, err := h.environment.ProxyJSONRequest.JSON[base.ApiResponse[activitytypes.Activity]](ctx, input.EnvironmentID, http.MethodPost, path, nil)
if err != nil {
return nil, err
}
h.applyActivitySourceLabelInternal(ctx, input.EnvironmentID, &out.Data)
- return &CancelActivityOutput{Body: *out}, nil
+ return &handlerutil.Out[activitytypes.Activity]{Body: *out}, nil
}
// cancelRequestedByInternal resolves a human-readable name for the cancellation
@@ -480,42 +464,42 @@ func (h *ActivityHandler) runRemoteActivityStreamPollerInternal(ctx context.Cont
}
}
-func (h *ActivityHandler) proxyListActivitiesInternal(ctx context.Context, input *ListActivitiesInput) (*ListActivitiesOutput, error) {
+func (h *ActivityHandler) proxyListActivitiesInternal(ctx context.Context, input *ListActivitiesInput) (*handlerutil.Page[activitytypes.Activity], error) {
path := "/api/environments/0/activities?" + activityListQueryInternal(input).Encode()
- out, err := handlerutil.ProxyRemoteJSON[base.Paginated[activitytypes.Activity]](ctx, h.environment.ProxyJSONRequest, input.EnvironmentID, http.MethodGet, path, nil)
+ out, err := h.environment.ProxyJSONRequest.JSON[base.Paginated[activitytypes.Activity]](ctx, input.EnvironmentID, http.MethodGet, path, nil)
if err != nil {
return nil, err
}
h.applyActivitySourceLabelsInternal(ctx, input.EnvironmentID, out.Data)
- return &ListActivitiesOutput{Body: *out}, nil
+ return &handlerutil.Page[activitytypes.Activity]{Body: *out}, nil
}
-func (h *ActivityHandler) proxyListActivitiesForEnvironmentInternal(ctx context.Context, environment environment.Environment, input *ListActivitiesInput) (*ListActivitiesOutput, error) {
+func (h *ActivityHandler) proxyListActivitiesForEnvironmentInternal(ctx context.Context, environment environment.Environment, input *ListActivitiesInput) (*handlerutil.Page[activitytypes.Activity], error) {
path := "/api/environments/0/activities?" + activityListQueryInternal(input).Encode()
var out base.Paginated[activitytypes.Activity]
if err := h.environment.ProxyJSONRequestForEnvironment(ctx, environment, http.MethodGet, path, nil, &out); err != nil {
return nil, handlerutil.TranslateRemoteProxyError(err)
}
applyActivitySourceLabelsForEnvironmentInternal(environment, out.Data)
- return &ListActivitiesOutput{Body: out}, nil
+ return &handlerutil.Page[activitytypes.Activity]{Body: out}, nil
}
-func (h *ActivityHandler) proxyGetActivityInternal(ctx context.Context, input *GetActivityInput) (*GetActivityOutput, error) {
+func (h *ActivityHandler) proxyGetActivityInternal(ctx context.Context, input *GetActivityInput) (*handlerutil.Out[activitytypes.Detail], error) {
path := fmt.Sprintf("/api/environments/0/activities/%s?limit=%d", url.PathEscape(input.ActivityID), input.Limit)
- out, err := handlerutil.ProxyRemoteJSON[base.ApiResponse[activitytypes.Detail]](ctx, h.environment.ProxyJSONRequest, input.EnvironmentID, http.MethodGet, path, nil)
+ out, err := h.environment.ProxyJSONRequest.JSON[base.ApiResponse[activitytypes.Detail]](ctx, input.EnvironmentID, http.MethodGet, path, nil)
if err != nil {
return nil, err
}
h.applyActivitySourceLabelInternal(ctx, input.EnvironmentID, &out.Data.Activity)
- return &GetActivityOutput{Body: *out}, nil
+ return &handlerutil.Out[activitytypes.Detail]{Body: *out}, nil
}
-func (h *ActivityHandler) proxyClearHistoryInternal(ctx context.Context, input *ClearActivityHistoryInput) (*ClearActivityHistoryOutput, error) {
- out, err := handlerutil.ProxyRemoteJSON[base.ApiResponse[activitytypes.ClearHistoryResult]](ctx, h.environment.ProxyJSONRequest, input.EnvironmentID, http.MethodDelete, "/api/environments/0/activities/history", nil)
+func (h *ActivityHandler) proxyClearHistoryInternal(ctx context.Context, input *ClearActivityHistoryInput) (*handlerutil.Out[activitytypes.ClearHistoryResult], error) {
+ out, err := h.environment.ProxyJSONRequest.JSON[base.ApiResponse[activitytypes.ClearHistoryResult]](ctx, input.EnvironmentID, http.MethodDelete, "/api/environments/0/activities/history", nil)
if err != nil {
return nil, err
}
- return &ClearActivityHistoryOutput{Body: *out}, nil
+ return &handlerutil.Out[activitytypes.ClearHistoryResult]{Body: *out}, nil
}
func (h *ActivityHandler) applyActivitySourceLabelsInternal(ctx context.Context, environmentID string, activities []activitytypes.Activity) {
diff --git a/backend/internal/actors/actor.go b/backend/internal/actors/actor.go
index 22cc40ef8..e84e03bf5 100644
--- a/backend/internal/actors/actor.go
+++ b/backend/internal/actors/actor.go
@@ -113,12 +113,12 @@ func (a *Actor) Stop(ctx context.Context) error {
}
// Request sends one typed request and consumes its response.
-func Request[K comparable, Q, R any](ctx context.Context, a *Actor, request Message[K, Q]) (Message[K, R], error) {
+func (a *Actor) Request[K comparable, Q, R any](ctx context.Context, request Message[K, Q]) (Message[K, R], error) {
if a == nil {
var zero Message[K, R]
return zero, errors.New("actor unavailable")
}
- return requestHandleInternal[K, Q, R](ctx, a.handle, request)
+ return a.handle.request[K, Q, R](ctx, request)
}
func (a *behaviorActorInternal) Receive(ctx *actor.Context) {
diff --git a/backend/internal/actors/executor.go b/backend/internal/actors/executor.go
index 6f1c7e443..718e7775e 100644
--- a/backend/internal/actors/executor.go
+++ b/backend/internal/actors/executor.go
@@ -65,9 +65,9 @@ func NewExecutor(ctx context.Context, runtime *Runtime, kind, id string, maxRest
// Execute queues work, waits for its typed result, and runs after only once the
// result is available to the caller. Work and after are both panic-contained.
-func Execute[T any](ctx context.Context, executor *Executor, label string, work func(context.Context) (T, error), after func(T, error)) (T, error) {
+func (e *Executor) Execute[T any](ctx context.Context, label string, work func(context.Context) (T, error), after func(T, error)) (T, error) {
var zero T
- task, err := Submit(ctx, executor, label, work, after)
+ task, err := e.Submit(ctx, label, work, after)
if err != nil {
return zero, err
}
@@ -77,8 +77,8 @@ func Execute[T any](ctx context.Context, executor *Executor, label string, work
// Submit queues work synchronously and returns a handle that can be awaited
// separately. This is useful for terminal cleanup that must stay queued even
// when the shutdown wait context expires.
-func Submit[T any](ctx context.Context, executor *Executor, label string, work func(context.Context) (T, error), after func(T, error)) (*Task[T], error) {
- if executor == nil || executor.actor == nil {
+func (e *Executor) Submit[T any](ctx context.Context, label string, work func(context.Context) (T, error), after func(T, error)) (*Task[T], error) {
+ if e == nil || e.actor == nil {
return nil, errors.New("actor executor unavailable")
}
if ctx == nil {
@@ -92,7 +92,7 @@ func Submit[T any](ctx context.Context, executor *Executor, label string, work f
}
result := NewPromise[executorResultInternal[T]]()
- if err := executor.actor.Send(executorTaskValueInternal[T]{
+ if err := e.actor.Send(executorTaskValueInternal[T]{
ctx: ctx,
label: label,
work: work,
@@ -102,7 +102,7 @@ func Submit[T any](ctx context.Context, executor *Executor, label string, work f
}); err != nil {
return nil, err
}
- return &Task[T]{result: result, actor: executor.actor}, nil
+ return &Task[T]{result: result, actor: e.actor}, nil
}
// Wait waits for the submitted task result without changing the task lifetime.
@@ -114,7 +114,7 @@ func (t *Task[T]) Wait(ctx context.Context) (T, error) {
if ctx == nil {
return zero, errors.New("task wait context unavailable")
}
- completed, err := awaitInternal(ctx, t.actor.handle, t.result, errors.New("actor executor stopped"))
+ completed, err := t.actor.handle.await(ctx, t.result, errors.New("actor executor stopped"))
if err != nil {
return zero, err
}
diff --git a/backend/internal/actors/executor_test.go b/backend/internal/actors/executor_test.go
index 10cd1a2e9..a34c72167 100644
--- a/backend/internal/actors/executor_test.go
+++ b/backend/internal/actors/executor_test.go
@@ -20,7 +20,7 @@ func TestExecutorSerializesHeterogeneousTasksInternal(t *testing.T) {
releaseFirst := make(chan struct{})
firstResult := make(chan error, 1)
go func() {
- _, executeErr := Execute(t.Context(), executor, "first", func(context.Context) (int, error) {
+ _, executeErr := executor.Execute(t.Context(), "first", func(context.Context) (int, error) {
close(firstStarted)
<-releaseFirst
return 1, nil
@@ -32,7 +32,7 @@ func TestExecutorSerializesHeterogeneousTasksInternal(t *testing.T) {
secondStarted := make(chan struct{})
secondResult := make(chan string, 1)
go func() {
- value, executeErr := Execute(t.Context(), executor, "second", func(context.Context) (string, error) {
+ value, executeErr := executor.Execute(t.Context(), "second", func(context.Context) (string, error) {
close(secondStarted)
return "two", nil
}, nil)
@@ -65,7 +65,7 @@ func TestExecutorPublishesResultBeforeCompletionCallbackInternal(t *testing.T) {
releaseAfter := make(chan struct{})
result := make(chan int, 1)
go func() {
- value, _ := Execute(t.Context(), executor, "ordered", func(context.Context) (int, error) {
+ value, _ := executor.Execute(t.Context(), "ordered", func(context.Context) (int, error) {
return 42, nil
}, func(int, error) {
close(afterStarted)
@@ -91,12 +91,12 @@ func TestExecutorContainsTaskPanicAndContinuesInternal(t *testing.T) {
executor, err := NewExecutor(t.Context(), runtime, "executor-test", "panic", 1)
require.NoError(t, err)
- _, err = Execute(t.Context(), executor, "panic task", func(context.Context) (NoPayload, error) {
+ _, err = executor.Execute(t.Context(), "panic task", func(context.Context) (NoPayload, error) {
panic("deliberate executor panic")
}, nil)
require.ErrorContains(t, err, "panic task panicked")
- value, err := Execute(t.Context(), executor, "following task", func(context.Context) (int, error) {
+ value, err := executor.Execute(t.Context(), "following task", func(context.Context) (int, error) {
return 7, nil
}, nil)
require.NoError(t, err)
diff --git a/backend/internal/actors/gate.go b/backend/internal/actors/gate.go
index 50015a7cc..a67c59f4f 100644
--- a/backend/internal/actors/gate.go
+++ b/backend/internal/actors/gate.go
@@ -99,7 +99,7 @@ func (g *Gate[K]) TryAcquire(ctx context.Context, key K) (*Lease[K], bool, error
// Admission must resolve after it is queued; abandoning an admitted reply on
// caller cancellation would leak the key without a lease to release it.
- admitted, err := awaitInternal(context.WithoutCancel(ctx), g.actor.handle, reply, errors.New("actor gate stopped"))
+ admitted, err := g.actor.handle.await(context.WithoutCancel(ctx), reply, errors.New("actor gate stopped"))
if err != nil {
return nil, false, err
}
@@ -125,7 +125,7 @@ func (l *Lease[K]) Release() {
}); err != nil {
return
}
- _, _ = awaitInternal(context.Background(), l.gate.actor.handle, reply, errors.New("actor gate stopped"))
+ _, _ = l.gate.actor.handle.await(context.Background(), reply, errors.New("actor gate stopped"))
})
}
diff --git a/backend/internal/actors/message.go b/backend/internal/actors/message.go
index 3429b9948..eca454db0 100644
--- a/backend/internal/actors/message.go
+++ b/backend/internal/actors/message.go
@@ -61,11 +61,11 @@ func (p *Promise[T]) Done() <-chan T {
return p.done
}
-// awaitInternal waits for a promise while preserving a result that races with caller
+// await waits for a promise while preserving a result that races with caller
// cancellation or actor termination.
-func awaitInternal[T any](ctx context.Context, handle *handleInternal, promise *Promise[T], stoppedErr error) (T, error) {
+func (h *handleInternal) await[T any](ctx context.Context, promise *Promise[T], stoppedErr error) (T, error) {
var zero T
- if ctx == nil || handle == nil || promise == nil {
+ if ctx == nil || h == nil || promise == nil {
return zero, errors.New("actor wait unavailable")
}
select {
@@ -78,7 +78,7 @@ func awaitInternal[T any](ctx context.Context, handle *handleInternal, promise *
default:
return zero, ctx.Err()
}
- case <-handle.Done():
+ case <-h.Done():
select {
case result := <-promise.Done():
return result, nil
@@ -279,7 +279,7 @@ func (t *Timer[K]) Stop() {
}
}
-// requestHandleInternal sends a typed request through Arcane's promise envelope.
+// requestInternal sends a typed request through Arcane's promise envelope.
type requestInternal struct {
message any
reply *Promise[requestResultInternal]
@@ -290,16 +290,16 @@ type requestResultInternal struct {
err error
}
-func requestHandleInternal[K comparable, Q, R any](ctx context.Context, handle *handleInternal, request Message[K, Q]) (Message[K, R], error) {
+func (h *handleInternal) request[K comparable, Q, R any](ctx context.Context, request Message[K, Q]) (Message[K, R], error) {
var zero Message[K, R]
- if ctx == nil || handle == nil {
+ if ctx == nil || h == nil {
return zero, errors.New("actor request target unavailable")
}
reply := NewPromise[requestResultInternal]()
- if err := handle.Send(requestInternal{message: request, reply: reply}); err != nil {
+ if err := h.Send(requestInternal{message: request, reply: reply}); err != nil {
return zero, err
}
- result, err := awaitInternal(ctx, handle, reply, errors.New("actor stopped"))
+ result, err := h.await(ctx, reply, errors.New("actor stopped"))
if err != nil {
return zero, err
}
diff --git a/backend/internal/actors/message_test.go b/backend/internal/actors/message_test.go
index d930b1050..3b667bdb0 100644
--- a/backend/internal/actors/message_test.go
+++ b/backend/internal/actors/message_test.go
@@ -123,7 +123,7 @@ func TestRequestReturnsTypedResponseInternal(t *testing.T) {
)
require.NoError(t, err)
for range 10 {
- response, requestErr := Request[messageKindInternal, int, string](t.Context(), applicationActor, Message[messageKindInternal, int]{Kind: requestMessageInternal, Value: 1})
+ response, requestErr := applicationActor.Request[messageKindInternal, int, string](t.Context(), Message[messageKindInternal, int]{Kind: requestMessageInternal, Value: 1})
require.NoError(t, requestErr)
require.Equal(t, responseMessageInternal, response.Kind)
require.Equal(t, "ok", response.Value)
@@ -150,7 +150,7 @@ func TestRequestFailsWhenHandlerReturnsWithoutResponseInternal(t *testing.T) {
)
require.NoError(t, err)
- _, err = Request[messageKindInternal, int, string](context.Background(), applicationActor, Message[messageKindInternal, int]{Kind: requestMessageInternal})
+ _, err = applicationActor.Request[messageKindInternal, int, string](context.Background(), Message[messageKindInternal, int]{Kind: requestMessageInternal})
require.ErrorContains(t, err, "without response")
stopCtx, cancel := context.WithTimeout(context.Background(), time.Second)
diff --git a/backend/internal/actors/resource.go b/backend/internal/actors/resource.go
index 08f526751..62d39280f 100644
--- a/backend/internal/actors/resource.go
+++ b/backend/internal/actors/resource.go
@@ -42,7 +42,7 @@ func (r *Resource[T]) Restart(ctx context.Context, label string, build func(cont
if r.terminal.Load() {
return ErrResourceStopped
}
- _, err := Execute(ctx, r.executor, label, func(workCtx context.Context) (NoPayload, error) {
+ _, err := r.executor.Execute(ctx, label, func(workCtx context.Context) (NoPayload, error) {
if r.terminal.Load() {
return NoPayload{}, ErrResourceStopped
}
@@ -72,7 +72,7 @@ func (r *Resource[T]) Do(ctx context.Context, label string, work func(context.Co
if r.terminal.Load() {
return ErrResourceStopped
}
- _, err := Execute(ctx, r.executor, label, func(workCtx context.Context) (NoPayload, error) {
+ _, err := r.executor.Execute(ctx, label, func(workCtx context.Context) (NoPayload, error) {
if r.terminal.Load() {
return NoPayload{}, ErrResourceStopped
}
@@ -86,7 +86,7 @@ func (r *Resource[T]) Clear(ctx context.Context, label string) error {
if r.terminal.Load() {
return ErrResourceStopped
}
- _, err := Execute(ctx, r.executor, label, func(context.Context) (NoPayload, error) {
+ _, err := r.executor.Execute(ctx, label, func(context.Context) (NoPayload, error) {
if r.terminal.Load() {
return NoPayload{}, ErrResourceStopped
}
@@ -101,7 +101,7 @@ func (r *Resource[T]) Stop(ctx context.Context) error {
return errors.New("resource stop context unavailable")
}
r.terminal.Store(true)
- task, submitErr := Submit(context.WithoutCancel(ctx), r.executor, "stop actor resource", func(context.Context) (NoPayload, error) {
+ task, submitErr := r.executor.Submit(context.WithoutCancel(ctx), "stop actor resource", func(context.Context) (NoPayload, error) {
return NoPayload{}, r.clearInternal()
}, nil)
var clearErr error
diff --git a/backend/internal/actors/state.go b/backend/internal/actors/state.go
index 74e969715..cb1abdaaa 100644
--- a/backend/internal/actors/state.go
+++ b/backend/internal/actors/state.go
@@ -40,7 +40,7 @@ func (s *State[T]) Apply(ctx context.Context, label string, mutate func(context.
if mutate == nil {
return errors.New("actor state mutation unavailable")
}
- _, err := Execute(ctx, s.executor, label, func(actorCtx context.Context) (NoPayload, error) {
+ _, err := s.executor.Execute(ctx, label, func(actorCtx context.Context) (NoPayload, error) {
defer func() {
s.snapshot.Store(s.clone(s.value))
}()
diff --git a/backend/internal/actors/state_map.go b/backend/internal/actors/state_map.go
index e9863be7a..d4619c43d 100644
--- a/backend/internal/actors/state_map.go
+++ b/backend/internal/actors/state_map.go
@@ -75,17 +75,16 @@ func (s *StateMap[K, V]) Apply(ctx context.Context, label string, mutate func(ma
if mutate == nil {
return errors.New("state map mutation unavailable")
}
- _, err := ApplyStateMap(ctx, s, label, func(values map[K]V) (NoPayload, bool, error) {
+ _, err := s.ApplyTyped(ctx, label, func(values map[K]V) (NoPayload, bool, error) {
changed, err := mutate(values)
return NoPayload{}, changed, err
})
return err
}
-// ApplyStateMap serializes a typed mutation and publishes its resulting state.
-func ApplyStateMap[K comparable, V, R any](
+// ApplyTyped serializes a typed mutation and publishes its resulting state.
+func (s *StateMap[K, V]) ApplyTyped[R any](
ctx context.Context,
- s *StateMap[K, V],
label string,
mutate func(map[K]V) (result R, changed bool, err error),
) (R, error) {
@@ -111,7 +110,7 @@ func ApplyStateMap[K comparable, V, R any](
return result, err
}
if s.executor != nil {
- return Execute(ctx, s.executor, label, work, nil)
+ return s.executor.Execute(ctx, label, work, nil)
}
s.mu.Lock()
@@ -121,7 +120,7 @@ func ApplyStateMap[K comparable, V, R any](
// Store publishes a value and returns the value it replaced, if any.
func (s *StateMap[K, V]) Store(ctx context.Context, label string, key K, value V) (V, bool, error) {
- result, err := ApplyStateMap(ctx, s, label, func(values map[K]V) (stateMapValueInternal[V], bool, error) {
+ result, err := s.ApplyTyped(ctx, label, func(values map[K]V) (stateMapValueInternal[V], bool, error) {
previous, replaced := values[key]
values[key] = value
return stateMapValueInternal[V]{value: previous, found: replaced}, true, nil
@@ -131,7 +130,7 @@ func (s *StateMap[K, V]) Store(ctx context.Context, label string, key K, value V
// Remove deletes and returns one value.
func (s *StateMap[K, V]) Remove(ctx context.Context, label string, key K) (V, bool, error) {
- result, err := ApplyStateMap(ctx, s, label, func(values map[K]V) (stateMapValueInternal[V], bool, error) {
+ result, err := s.ApplyTyped(ctx, label, func(values map[K]V) (stateMapValueInternal[V], bool, error) {
value, removed := values[key]
if removed {
delete(values, key)
@@ -146,7 +145,7 @@ func (s *StateMap[K, V]) RemoveWhere(ctx context.Context, label string, predicat
if predicate == nil {
return nil, errors.New("state map predicate unavailable")
}
- return ApplyStateMap(ctx, s, label, func(values map[K]V) ([]V, bool, error) {
+ return s.ApplyTyped(ctx, label, func(values map[K]V) ([]V, bool, error) {
removed := make([]V, 0)
for key, value := range values {
if predicate(key, value) {
diff --git a/backend/internal/apikey/handler.go b/backend/internal/apikey/handler.go
index e9c9f6214..76cf668c4 100644
--- a/backend/internal/apikey/handler.go
+++ b/backend/internal/apikey/handler.go
@@ -29,10 +29,6 @@ type ListApiKeysInput struct {
Limit int `query:"limit" default:"20" doc:"Number of items per page"`
}
-type ListApiKeysOutput struct {
- Body base.Paginated[apikeytypes.ApiKey]
-}
-
type CreateApiKeyInput struct {
Body apikeytypes.CreateApiKey
}
@@ -41,39 +37,19 @@ type CreateMyApiKeyInput struct {
Body apikeytypes.CreateUserApiKey
}
-type CreateApiKeyOutput struct {
- Body base.ApiResponse[apikeytypes.ApiKeyCreatedDto]
-}
-
type GetApiKeyInput struct {
ID string `path:"id" doc:"API key ID"`
}
-type GetApiKeyOutput struct {
- Body base.ApiResponse[apikeytypes.ApiKey]
-}
-
type UpdateApiKeyInput struct {
ID string `path:"id" doc:"API key ID"`
Body apikeytypes.UpdateApiKey
}
-type UpdateApiKeyOutput struct {
- Body base.ApiResponse[apikeytypes.ApiKey]
-}
-
type DeleteApiKeyInput struct {
ID string `path:"id" doc:"API key ID"`
}
-type DeleteApiKeyOutput struct {
- Body base.ApiResponse[base.MessageResponse]
-}
-
-type ListMyApiKeysOutput struct {
- Body base.ApiResponse[[]apikeytypes.ApiKey]
-}
-
// RegisterApiKeys registers API key management routes using Huma.
func RegisterApiKeys(api huma.API, apiKeyService *ApiKeyService) {
h := &ApiKeyHandler{
@@ -176,7 +152,7 @@ func RegisterApiKeys(api huma.API, apiKeyService *ApiKeyService) {
}
// ListApiKeys returns a paginated list of API keys.
-func (h *ApiKeyHandler) ListApiKeys(ctx context.Context, input *ListApiKeysInput) (*ListApiKeysOutput, error) {
+func (h *ApiKeyHandler) ListApiKeys(ctx context.Context, input *ListApiKeysInput) (*handlerutil.Page[apikeytypes.ApiKey], error) {
params := handlerutil.PaginationParams(input.Start, input.Limit, input.Sort, input.Order, input.Search)
apiKeys, paginationResp, err := h.apiKeyService.ListApiKeys(ctx, params)
@@ -184,7 +160,7 @@ func (h *ApiKeyHandler) ListApiKeys(ctx context.Context, input *ListApiKeysInput
return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to list API keys").Error())
}
- return &ListApiKeysOutput{
+ return &handlerutil.Page[apikeytypes.ApiKey]{
Body: base.Paginated[apikeytypes.ApiKey]{
Success: true,
Data: apiKeys,
@@ -195,7 +171,7 @@ func (h *ApiKeyHandler) ListApiKeys(ctx context.Context, input *ListApiKeysInput
// CreateApiKey creates a new scoped API key. Requested grants are capped by
// the calling credential's effective permissions.
-func (h *ApiKeyHandler) CreateApiKey(ctx context.Context, input *CreateApiKeyInput) (*CreateApiKeyOutput, error) {
+func (h *ApiKeyHandler) CreateApiKey(ctx context.Context, input *CreateApiKeyInput) (*handlerutil.Out[apikeytypes.ApiKeyCreatedDto], error) {
user, err := handlerutil.RequireUser(ctx)
if err != nil {
return nil, err
@@ -210,7 +186,7 @@ func (h *ApiKeyHandler) CreateApiKey(ctx context.Context, input *CreateApiKeyInp
return nil, huma.Error500InternalServerError("Failed to create API key")
}
- return &CreateApiKeyOutput{
+ return &handlerutil.Out[apikeytypes.ApiKeyCreatedDto]{
Body: base.ApiResponse[apikeytypes.ApiKeyCreatedDto]{
Success: true,
Data: *apiKey,
@@ -219,13 +195,13 @@ func (h *ApiKeyHandler) CreateApiKey(ctx context.Context, input *CreateApiKeyInp
}
// GetApiKey returns details of a specific API key.
-func (h *ApiKeyHandler) GetApiKey(ctx context.Context, input *GetApiKeyInput) (*GetApiKeyOutput, error) {
+func (h *ApiKeyHandler) GetApiKey(ctx context.Context, input *GetApiKeyInput) (*handlerutil.Out[apikeytypes.ApiKey], error) {
apiKey, err := h.apiKeyService.GetApiKey(ctx, input.ID)
if err != nil {
return nil, huma.Error404NotFound("API key not found")
}
- return &GetApiKeyOutput{
+ return &handlerutil.Out[apikeytypes.ApiKey]{
Body: base.ApiResponse[apikeytypes.ApiKey]{
Success: true,
Data: *apiKey,
@@ -234,7 +210,7 @@ func (h *ApiKeyHandler) GetApiKey(ctx context.Context, input *GetApiKeyInput) (*
}
// UpdateApiKey updates an existing API key.
-func (h *ApiKeyHandler) UpdateApiKey(ctx context.Context, input *UpdateApiKeyInput) (*UpdateApiKeyOutput, error) {
+func (h *ApiKeyHandler) UpdateApiKey(ctx context.Context, input *UpdateApiKeyInput) (*handlerutil.Out[apikeytypes.ApiKey], error) {
if _, err := handlerutil.RequireUser(ctx); err != nil {
return nil, err
}
@@ -257,7 +233,7 @@ func (h *ApiKeyHandler) UpdateApiKey(ctx context.Context, input *UpdateApiKeyInp
return nil, huma.Error500InternalServerError("Failed to update API key")
}
- return &UpdateApiKeyOutput{
+ return &handlerutil.Out[apikeytypes.ApiKey]{
Body: base.ApiResponse[apikeytypes.ApiKey]{
Success: true,
Data: *apiKey,
@@ -266,7 +242,7 @@ func (h *ApiKeyHandler) UpdateApiKey(ctx context.Context, input *UpdateApiKeyInp
}
// DeleteApiKey deletes an API key.
-func (h *ApiKeyHandler) DeleteApiKey(ctx context.Context, input *DeleteApiKeyInput) (*DeleteApiKeyOutput, error) {
+func (h *ApiKeyHandler) DeleteApiKey(ctx context.Context, input *DeleteApiKeyInput) (*handlerutil.Out[base.MessageResponse], error) {
if err := h.apiKeyService.DeleteApiKey(ctx, input.ID); err != nil {
if errors.Is(err, ErrApiKeyNotFound) {
return nil, huma.Error404NotFound("API key not found")
@@ -277,7 +253,7 @@ func (h *ApiKeyHandler) DeleteApiKey(ctx context.Context, input *DeleteApiKeyInp
return nil, huma.Error500InternalServerError("Failed to delete API key")
}
- return &DeleteApiKeyOutput{
+ return &handlerutil.Out[base.MessageResponse]{
Body: base.ApiResponse[base.MessageResponse]{
Success: true,
Data: base.MessageResponse{
@@ -288,7 +264,7 @@ func (h *ApiKeyHandler) DeleteApiKey(ctx context.Context, input *DeleteApiKeyInp
}
// ListMyApiKeys lists API keys owned by the current user (self-service).
-func (h *ApiKeyHandler) ListMyApiKeys(ctx context.Context, input *struct{}) (*ListMyApiKeysOutput, error) {
+func (h *ApiKeyHandler) ListMyApiKeys(ctx context.Context, input *struct{}) (*handlerutil.Out[[]apikeytypes.ApiKey], error) {
user, err := handlerutil.RequireUser(ctx)
if err != nil {
return nil, err
@@ -299,7 +275,7 @@ func (h *ApiKeyHandler) ListMyApiKeys(ctx context.Context, input *struct{}) (*Li
return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to list API keys").Error())
}
- return &ListMyApiKeysOutput{
+ return &handlerutil.Out[[]apikeytypes.ApiKey]{
Body: base.ApiResponse[[]apikeytypes.ApiKey]{
Success: true,
Data: keys,
@@ -310,7 +286,7 @@ func (h *ApiKeyHandler) ListMyApiKeys(ctx context.Context, input *struct{}) (*Li
// CreateMyApiKey creates a new personal API key owned by the current user
// (self-service). Personal keys inherit the owner's role permissions, and may
// only be minted from an interactive session — never by another API key.
-func (h *ApiKeyHandler) CreateMyApiKey(ctx context.Context, input *CreateMyApiKeyInput) (*CreateApiKeyOutput, error) {
+func (h *ApiKeyHandler) CreateMyApiKey(ctx context.Context, input *CreateMyApiKeyInput) (*handlerutil.Out[apikeytypes.ApiKeyCreatedDto], error) {
// Defense in depth alongside the BearerAuth-only Security requirement:
// only session auth sets a session ID, so API-key and sudo callers stop here.
if _, ok := middleware.GetCurrentSessionIDFromContext(ctx); !ok {
@@ -327,7 +303,7 @@ func (h *ApiKeyHandler) CreateMyApiKey(ctx context.Context, input *CreateMyApiKe
return nil, huma.Error500InternalServerError("Failed to create API key")
}
- return &CreateApiKeyOutput{
+ return &handlerutil.Out[apikeytypes.ApiKeyCreatedDto]{
Body: base.ApiResponse[apikeytypes.ApiKeyCreatedDto]{
Success: true,
Data: *apiKey,
@@ -338,7 +314,7 @@ func (h *ApiKeyHandler) CreateMyApiKey(ctx context.Context, input *CreateMyApiKe
// DeleteMyApiKey deletes one of the current user's API keys, validating
// ownership before removal so the endpoint can't be used to delete other
// users' keys.
-func (h *ApiKeyHandler) DeleteMyApiKey(ctx context.Context, input *DeleteApiKeyInput) (*DeleteApiKeyOutput, error) {
+func (h *ApiKeyHandler) DeleteMyApiKey(ctx context.Context, input *DeleteApiKeyInput) (*handlerutil.Out[base.MessageResponse], error) {
// Defense in depth alongside the BearerAuth-only Security requirement:
// only session auth sets a session ID, so API-key and sudo callers stop here.
if _, ok := middleware.GetCurrentSessionIDFromContext(ctx); !ok {
@@ -368,7 +344,7 @@ func (h *ApiKeyHandler) DeleteMyApiKey(ctx context.Context, input *DeleteApiKeyI
return nil, huma.Error500InternalServerError("Failed to delete API key")
}
- return &DeleteApiKeyOutput{
+ return &handlerutil.Out[base.MessageResponse]{
Body: base.ApiResponse[base.MessageResponse]{
Success: true,
Data: base.MessageResponse{
diff --git a/backend/internal/apns/handler.go b/backend/internal/apns/handler.go
index 3fcb61127..c5c131afb 100644
--- a/backend/internal/apns/handler.go
+++ b/backend/internal/apns/handler.go
@@ -17,22 +17,10 @@ type ApnsHandler struct {
service *ApnsService
}
-type StatusOutput struct {
- Body base.ApiResponse[apnstypes.Status]
-}
-
-type PairingTokenOutput struct {
- Body base.ApiResponse[apnstypes.PairingToken]
-}
-
type RegisterDeviceInput struct {
Body apnstypes.RegisterDeviceRequest
}
-type DeviceOutput struct {
- Body base.ApiResponse[apnstypes.Device]
-}
-
type UpdateDeviceInput struct {
ID string `path:"id" doc:"Device ID"`
Body apnstypes.UpdateDeviceRequest
@@ -42,69 +30,21 @@ type DeviceIDInput struct {
ID string `path:"id" doc:"Device ID"`
}
-type MessageOutput struct {
- Body base.ApiResponse[base.MessageResponse]
-}
-
func RegisterApns(api huma.API, service *ApnsService) {
h := &ApnsHandler{service: service}
- tags := []string{"Mobile Push"}
-
- huma.Register(api, huma.Operation{
- OperationID: "get-apns-status",
- Method: http.MethodGet,
- Path: "/apns/status",
- Summary: "Get mobile push status",
- Description: "Whether mobile push is enabled and the caller's registered devices",
- Tags: tags,
- Security: handlerutil.DefaultOperationSecurity(),
- }, h.Status)
-
- huma.Register(api, huma.Operation{
- OperationID: "create-apns-pairing-token",
- Method: http.MethodPost,
- Path: "/apns/pairing-token",
- Summary: "Issue a pairing token",
- Description: "Issue a short-lived signed token the mobile app presents to the push relay",
- Tags: tags,
- Security: handlerutil.DefaultOperationSecurity(),
- }, h.PairingToken)
-
- huma.Register(api, huma.Operation{
- OperationID: "register-apns-device",
- Method: http.MethodPost,
- Path: "/apns/devices",
- Summary: "Register a mobile device",
- Tags: tags,
- Security: handlerutil.DefaultOperationSecurity(),
- }, h.RegisterDevice)
-
- huma.Register(api, huma.Operation{
- OperationID: "update-apns-device",
- Method: http.MethodPatch,
- Path: "/apns/devices/{id}",
- Summary: "Update a mobile device",
- Tags: tags,
- Security: handlerutil.DefaultOperationSecurity(),
- }, h.UpdateDevice)
-
- huma.Register(api, huma.Operation{
- OperationID: "delete-apns-device",
- Method: http.MethodDelete,
- Path: "/apns/devices/{id}",
- Summary: "Remove a mobile device",
- Tags: tags,
- Security: handlerutil.DefaultOperationSecurity(),
- }, h.DeleteDevice)
-
- huma.Register(api, huma.Operation{
- OperationID: "test-apns-device",
- Method: http.MethodPost,
- Path: "/apns/devices/{id}/test",
- Summary: "Send a test push",
- Tags: tags,
- Security: handlerutil.DefaultOperationSecurity(),
- }, h.TestDevice)
+
+ huma.Register(api, securedApnsOperationInternal("get-apns-status", http.MethodGet, "/apns/status", "Get mobile push status", "Whether mobile push is enabled and the caller's registered devices"), h.Status)
+ huma.Register(api, securedApnsOperationInternal("create-apns-pairing-token", http.MethodPost, "/apns/pairing-token", "Issue a pairing token", "Issue a short-lived signed token the mobile app presents to the push relay"), h.PairingToken)
+ huma.Register(api, securedApnsOperationInternal("register-apns-device", http.MethodPost, "/apns/devices", "Register a mobile device", ""), h.RegisterDevice)
+ huma.Register(api, securedApnsOperationInternal("update-apns-device", http.MethodPatch, "/apns/devices/{id}", "Update a mobile device", ""), h.UpdateDevice)
+ huma.Register(api, securedApnsOperationInternal("delete-apns-device", http.MethodDelete, "/apns/devices/{id}", "Remove a mobile device", ""), h.DeleteDevice)
+ huma.Register(api, securedApnsOperationInternal("test-apns-device", http.MethodPost, "/apns/devices/{id}/test", "Send a test push", ""), h.TestDevice)
+}
+
+func securedApnsOperationInternal(operationID, method, path, summary, description string) huma.Operation {
+ op := handlerutil.Operation(operationID, method, path, summary, description, "Mobile Push")
+ op.Security = handlerutil.DefaultOperationSecurity()
+ return op
}
func apnsHTTPErrorInternal(err error) error {
@@ -122,7 +62,7 @@ func apnsHTTPErrorInternal(err error) error {
}
}
-func (h *ApnsHandler) Status(ctx context.Context, _ *struct{}) (*StatusOutput, error) {
+func (h *ApnsHandler) Status(ctx context.Context, _ *struct{}) (*handlerutil.Out[apnstypes.Status], error) {
user, err := handlerutil.RequireUser(ctx)
if err != nil {
return nil, err
@@ -131,10 +71,10 @@ func (h *ApnsHandler) Status(ctx context.Context, _ *struct{}) (*StatusOutput, e
if err != nil {
return nil, apnsHTTPErrorInternal(err)
}
- return &StatusOutput{Body: base.ApiResponse[apnstypes.Status]{Success: true, Data: status}}, nil
+ return &handlerutil.Out[apnstypes.Status]{Body: base.ApiResponse[apnstypes.Status]{Success: true, Data: status}}, nil
}
-func (h *ApnsHandler) PairingToken(ctx context.Context, _ *struct{}) (*PairingTokenOutput, error) {
+func (h *ApnsHandler) PairingToken(ctx context.Context, _ *struct{}) (*handlerutil.Out[apnstypes.PairingToken], error) {
if _, err := handlerutil.RequireUser(ctx); err != nil {
return nil, err
}
@@ -142,10 +82,10 @@ func (h *ApnsHandler) PairingToken(ctx context.Context, _ *struct{}) (*PairingTo
if err != nil {
return nil, apnsHTTPErrorInternal(err)
}
- return &PairingTokenOutput{Body: base.ApiResponse[apnstypes.PairingToken]{Success: true, Data: token}}, nil
+ return &handlerutil.Out[apnstypes.PairingToken]{Body: base.ApiResponse[apnstypes.PairingToken]{Success: true, Data: token}}, nil
}
-func (h *ApnsHandler) RegisterDevice(ctx context.Context, input *RegisterDeviceInput) (*DeviceOutput, error) {
+func (h *ApnsHandler) RegisterDevice(ctx context.Context, input *RegisterDeviceInput) (*handlerutil.Out[apnstypes.Device], error) {
user, err := handlerutil.RequireUser(ctx)
if err != nil {
return nil, err
@@ -154,10 +94,10 @@ func (h *ApnsHandler) RegisterDevice(ctx context.Context, input *RegisterDeviceI
if err != nil {
return nil, apnsHTTPErrorInternal(err)
}
- return &DeviceOutput{Body: base.ApiResponse[apnstypes.Device]{Success: true, Data: device}}, nil
+ return &handlerutil.Out[apnstypes.Device]{Body: base.ApiResponse[apnstypes.Device]{Success: true, Data: device}}, nil
}
-func (h *ApnsHandler) UpdateDevice(ctx context.Context, input *UpdateDeviceInput) (*DeviceOutput, error) {
+func (h *ApnsHandler) UpdateDevice(ctx context.Context, input *UpdateDeviceInput) (*handlerutil.Out[apnstypes.Device], error) {
user, err := handlerutil.RequireUser(ctx)
if err != nil {
return nil, err
@@ -166,10 +106,10 @@ func (h *ApnsHandler) UpdateDevice(ctx context.Context, input *UpdateDeviceInput
if err != nil {
return nil, apnsHTTPErrorInternal(err)
}
- return &DeviceOutput{Body: base.ApiResponse[apnstypes.Device]{Success: true, Data: device}}, nil
+ return &handlerutil.Out[apnstypes.Device]{Body: base.ApiResponse[apnstypes.Device]{Success: true, Data: device}}, nil
}
-func (h *ApnsHandler) DeleteDevice(ctx context.Context, input *DeviceIDInput) (*MessageOutput, error) {
+func (h *ApnsHandler) DeleteDevice(ctx context.Context, input *DeviceIDInput) (*handlerutil.Out[base.MessageResponse], error) {
user, err := handlerutil.RequireUser(ctx)
if err != nil {
return nil, err
@@ -177,10 +117,10 @@ func (h *ApnsHandler) DeleteDevice(ctx context.Context, input *DeviceIDInput) (*
if err := h.service.DeleteDevice(ctx, user.ID, input.ID); err != nil {
return nil, apnsHTTPErrorInternal(err)
}
- return &MessageOutput{Body: base.ApiResponse[base.MessageResponse]{Success: true, Data: base.MessageResponse{Message: "Device removed"}}}, nil
+ return &handlerutil.Out[base.MessageResponse]{Body: base.ApiResponse[base.MessageResponse]{Success: true, Data: base.MessageResponse{Message: "Device removed"}}}, nil
}
-func (h *ApnsHandler) TestDevice(ctx context.Context, input *DeviceIDInput) (*MessageOutput, error) {
+func (h *ApnsHandler) TestDevice(ctx context.Context, input *DeviceIDInput) (*handlerutil.Out[base.MessageResponse], error) {
user, err := handlerutil.RequireUser(ctx)
if err != nil {
return nil, err
@@ -188,5 +128,5 @@ func (h *ApnsHandler) TestDevice(ctx context.Context, input *DeviceIDInput) (*Me
if err := h.service.TestDevice(ctx, user.ID, input.ID); err != nil {
return nil, apnsHTTPErrorInternal(err)
}
- return &MessageOutput{Body: base.ApiResponse[base.MessageResponse]{Success: true, Data: base.MessageResponse{Message: "Test notification queued"}}}, nil
+ return &handlerutil.Out[base.MessageResponse]{Body: base.ApiResponse[base.MessageResponse]{Success: true, Data: base.MessageResponse{Message: "Test notification queued"}}}, nil
}
diff --git a/backend/internal/auth/handler.go b/backend/internal/auth/handler.go
index fe04a84a9..33e2fb35d 100644
--- a/backend/internal/auth/handler.go
+++ b/backend/internal/auth/handler.go
@@ -71,14 +71,6 @@ type ChangePasswordInput struct {
Body authtypes.PasswordChange
}
-type ChangePasswordOutput struct {
- Body base.ApiResponse[base.MessageResponse]
-}
-
-type LogoutAllOtherSessionsOutput struct {
- Body base.ApiResponse[base.MessageResponse]
-}
-
type UpdateMyProfileBody struct {
DisplayName *string `json:"displayName,omitempty"`
Email *string `json:"email,omitempty"`
@@ -92,26 +84,10 @@ type UpdateMyProfileInput struct {
Body UpdateMyProfileBody
}
-type UpdateMyProfileOutput struct {
- Body base.ApiResponse[usertypes.User]
-}
-
-type GetCurrentUserOutput struct {
- Body base.ApiResponse[usertypes.User]
-}
-
type UploadMyAvatarInput struct {
RawBody multipart.Form `contentType:"multipart/form-data"`
}
-type UploadMyAvatarOutput struct {
- Body base.ApiResponse[usertypes.User]
-}
-
-type DeleteMyAvatarOutput struct {
- Body base.ApiResponse[usertypes.User]
-}
-
// RegisterAuth registers authentication routes using Huma.
func RegisterAuth(api huma.API, userService *user.UserService, authService *AuthService, settingsService *settings.SettingsService, beginMFAAuthentication func(context.Context, string, authtypes.SessionMeta, string) (*authtypes.MFAChallenge, error)) {
h := &AuthHandler{
@@ -322,7 +298,7 @@ func (h *AuthHandler) Logout(ctx context.Context, input *struct{}) (*LogoutOutpu
// GetCurrentUser returns the currently authenticated user's information.
// Uses ToUserResponseDto (not the generic struct mapper) so the RBAC fields
// (RoleAssignments, PermissionsByEnv) are resolved via RoleService.
-func (h *AuthHandler) GetCurrentUser(ctx context.Context, input *struct{}) (*GetCurrentUserOutput, error) {
+func (h *AuthHandler) GetCurrentUser(ctx context.Context, input *struct{}) (*handlerutil.Out[usertypes.User], error) {
userID, exists := middleware.GetUserIDFromContext(ctx)
if !exists {
return nil, huma.Error401Unauthorized("Not authenticated")
@@ -338,7 +314,7 @@ func (h *AuthHandler) GetCurrentUser(ctx context.Context, input *struct{}) (*Get
return nil, huma.Error500InternalServerError("Failed to map user")
}
- return &GetCurrentUserOutput{
+ return &handlerutil.Out[usertypes.User]{
Body: base.ApiResponse[usertypes.User]{
Success: true,
Data: out,
@@ -375,7 +351,7 @@ func (h *AuthHandler) RefreshToken(ctx context.Context, input *RefreshTokenInput
}
// ChangePassword changes the current user's password.
-func (h *AuthHandler) ChangePassword(ctx context.Context, input *ChangePasswordInput) (*ChangePasswordOutput, error) {
+func (h *AuthHandler) ChangePassword(ctx context.Context, input *ChangePasswordInput) (*handlerutil.Out[base.MessageResponse], error) {
userModel, err := handlerutil.RequireUser(ctx)
if err != nil {
return nil, err
@@ -398,7 +374,7 @@ func (h *AuthHandler) ChangePassword(ctx context.Context, input *ChangePasswordI
}
}
- return &ChangePasswordOutput{
+ return &handlerutil.Out[base.MessageResponse]{
Body: base.ApiResponse[base.MessageResponse]{
Success: true,
Data: base.MessageResponse{
@@ -410,7 +386,7 @@ func (h *AuthHandler) ChangePassword(ctx context.Context, input *ChangePasswordI
// LogoutAllOtherSessions revokes every active session for the current user
// except the session making this request.
-func (h *AuthHandler) LogoutAllOtherSessions(ctx context.Context, input *struct{}) (*LogoutAllOtherSessionsOutput, error) {
+func (h *AuthHandler) LogoutAllOtherSessions(ctx context.Context, input *struct{}) (*handlerutil.Out[base.MessageResponse], error) {
userModel, err := handlerutil.RequireUser(ctx)
if err != nil {
return nil, err
@@ -421,7 +397,7 @@ func (h *AuthHandler) LogoutAllOtherSessions(ctx context.Context, input *struct{
return nil, huma.Error500InternalServerError("failed to revoke sessions: " + err.Error())
}
- return &LogoutAllOtherSessionsOutput{
+ return &handlerutil.Out[base.MessageResponse]{
Body: base.ApiResponse[base.MessageResponse]{
Success: true,
Data: base.MessageResponse{
@@ -466,7 +442,7 @@ func mergePreferencesInternal(dst, src *usertypes.Preferences) {
// UpdateMyProfile lets the current user update their own displayName and email.
// OIDC-managed accounts are read-only here.
-func (h *AuthHandler) UpdateMyProfile(ctx context.Context, input *UpdateMyProfileInput) (*UpdateMyProfileOutput, error) {
+func (h *AuthHandler) UpdateMyProfile(ctx context.Context, input *UpdateMyProfileInput) (*handlerutil.Out[usertypes.User], error) {
currentUser, err := handlerutil.RequireUser(ctx)
if err != nil {
return nil, err
@@ -519,7 +495,7 @@ func (h *AuthHandler) UpdateMyProfile(ctx context.Context, input *UpdateMyProfil
return nil, huma.Error500InternalServerError("Failed to map user")
}
- return &UpdateMyProfileOutput{
+ return &handlerutil.Out[usertypes.User]{
Body: base.ApiResponse[usertypes.User]{
Success: true,
Data: out,
@@ -529,7 +505,7 @@ func (h *AuthHandler) UpdateMyProfile(ctx context.Context, input *UpdateMyProfil
// UploadMyAvatar lets the current user upload a custom profile picture.
// Accepts PNG, JPEG, or WebP images up to the configured avatar upload limit.
-func (h *AuthHandler) UploadMyAvatar(ctx context.Context, input *UploadMyAvatarInput) (*UploadMyAvatarOutput, error) {
+func (h *AuthHandler) UploadMyAvatar(ctx context.Context, input *UploadMyAvatarInput) (*handlerutil.Out[usertypes.User], error) {
currentUser, err := handlerutil.RequireUser(ctx)
if err != nil {
return nil, err
@@ -587,7 +563,7 @@ func (h *AuthHandler) UploadMyAvatar(ctx context.Context, input *UploadMyAvatarI
return nil, huma.Error500InternalServerError("Failed to map user")
}
- return &UploadMyAvatarOutput{
+ return &handlerutil.Out[usertypes.User]{
Body: base.ApiResponse[usertypes.User]{
Success: true,
Data: out,
@@ -608,7 +584,7 @@ func (h *AuthHandler) avatarMaxUploadSizeMbInternal(ctx context.Context) int {
}
// DeleteMyAvatar removes the current user's custom profile picture.
-func (h *AuthHandler) DeleteMyAvatar(ctx context.Context, input *struct{}) (*DeleteMyAvatarOutput, error) {
+func (h *AuthHandler) DeleteMyAvatar(ctx context.Context, input *struct{}) (*handlerutil.Out[usertypes.User], error) {
currentUser, err := handlerutil.RequireUser(ctx)
if err != nil {
return nil, err
@@ -629,7 +605,7 @@ func (h *AuthHandler) DeleteMyAvatar(ctx context.Context, input *struct{}) (*Del
return nil, huma.Error500InternalServerError("Failed to map user")
}
- return &DeleteMyAvatarOutput{
+ return &handlerutil.Out[usertypes.User]{
Body: base.ApiResponse[usertypes.User]{
Success: true,
Data: out,
diff --git a/backend/internal/auth/service.go b/backend/internal/auth/service.go
index b27317540..9f588fb61 100644
--- a/backend/internal/auth/service.go
+++ b/backend/internal/auth/service.go
@@ -657,14 +657,14 @@ func (s *AuthService) extractOidcGroups(ctx context.Context, userInfo auth.OidcU
if claim != "" {
if v, ok := jwtclaims.GetByPath(userInfo.Extra, claim).Get(); ok {
- if groups := jwtclaims.StringSliceFromClaimValue(v); len(groups) > 0 {
+ if groups := jwtclaims.GetStringSliceClaim(map[string]any{"groups": v}, "groups"); len(groups) > 0 {
return groups
}
}
if tokenResp != nil && tokenResp.IDToken != "" {
if parsed := jwtclaims.ParseJWTClaims(tokenResp.IDToken); parsed != nil {
if v, ok := jwtclaims.GetByPath(parsed, claim).Get(); ok {
- if groups := jwtclaims.StringSliceFromClaimValue(v); len(groups) > 0 {
+ if groups := jwtclaims.GetStringSliceClaim(map[string]any{"groups": v}, "groups"); len(groups) > 0 {
return groups
}
}
diff --git a/backend/internal/backup/engine.go b/backend/internal/backup/engine.go
index ed2a9cd06..d6df12468 100644
--- a/backend/internal/backup/engine.go
+++ b/backend/internal/backup/engine.go
@@ -317,7 +317,7 @@ func (e *Engine) executorForInternal(repositoryID string) (*actors.Executor, err
if executor, ok := e.executors.Get(repositoryID); ok {
return executor, nil
}
- return actors.ApplyStateMap(e.lifecycleCtx, e.executors, "backup repository executor", func(values map[string]*actors.Executor) (*actors.Executor, bool, error) {
+ return e.executors.ApplyTyped(e.lifecycleCtx, "backup repository executor", func(values map[string]*actors.Executor) (*actors.Executor, bool, error) {
if executor, ok := values[repositoryID]; ok {
return executor, false, nil
}
@@ -341,7 +341,7 @@ func (e *Engine) runInternal(ctx context.Context, dockerClient *client.Client, r
if err != nil {
return "", err
}
- return actors.Execute(ctx, executor, "rustic "+command[0], func(workCtx context.Context) (string, error) {
+ return executor.Execute(ctx, "rustic "+command[0], func(workCtx context.Context) (string, error) {
return e.runContainerInternal(workCtx, dockerClient, repository, password, command, extraMounts...)
}, nil)
}
diff --git a/backend/internal/bootstrap/jobs_bootstrap.go b/backend/internal/bootstrap/jobs_bootstrap.go
index 739f1f66c..8572d2c17 100644
--- a/backend/internal/bootstrap/jobs_bootstrap.go
+++ b/backend/internal/bootstrap/jobs_bootstrap.go
@@ -388,7 +388,7 @@ func setupTimeoutSettingsSubscriptionInternal(params settingsSubscriptionsParams
}
timeoutSyncContext, cancelTimeoutSync := context.WithCancel(params.LifecycleCtx)
subscribe(libarcane.TimeoutSettingKeys(), func(updates []libarcane.SettingUpdate) {
- _, err := actors.Submit(timeoutSyncContext, timeoutSyncExecutor, "sync timeout settings to remote environments", func(ctx context.Context) (actors.NoPayload, error) {
+ _, err := timeoutSyncExecutor.Submit(timeoutSyncContext, "sync timeout settings to remote environments", func(ctx context.Context) (actors.NoPayload, error) {
syncTimeoutSettingsToAgentsInternal(ctx, params.Environment, updates)
return actors.NoPayload{}, nil
}, nil)
diff --git a/backend/internal/build/workspace_handler.go b/backend/internal/build/workspace_handler.go
index af8b4e373..3c4768c42 100644
--- a/backend/internal/build/workspace_handler.go
+++ b/backend/internal/build/workspace_handler.go
@@ -92,10 +92,6 @@ type BrowseBuildsInput struct {
Path string `query:"path" default:"/" doc:"Directory path to browse"`
}
-type BrowseBuildsOutput struct {
- Body base.ApiResponse[[]workspacetypes.FileEntry]
-}
-
type GetBuildFileContentInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
Path string `query:"path" doc:"File path"`
@@ -107,10 +103,6 @@ type BuildFileContentResponse struct {
MimeType string `json:"mimeType"`
}
-type GetBuildFileContentOutput struct {
- Body base.ApiResponse[BuildFileContentResponse]
-}
-
type DownloadBuildFileInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
Path string `query:"path" doc:"File path"`
@@ -139,20 +131,20 @@ type DeleteBuildFileInput struct {
Path string `query:"path" doc:"File or directory path to delete"`
}
-func (h *BuildWorkspaceHandler) BrowseDirectory(ctx context.Context, input *BrowseBuildsInput) (*BrowseBuildsOutput, error) {
+func (h *BuildWorkspaceHandler) BrowseDirectory(ctx context.Context, input *BrowseBuildsInput) (*handlerutil.Out[[]workspacetypes.FileEntry], error) {
entries, err := h.service.ListDirectory(ctx, input.Path)
if err != nil {
return nil, huma.Error500InternalServerError(err.Error())
}
- return &BrowseBuildsOutput{Body: base.ApiResponse[[]workspacetypes.FileEntry]{Success: true, Data: entries}}, nil
+ return &handlerutil.Out[[]workspacetypes.FileEntry]{Body: base.ApiResponse[[]workspacetypes.FileEntry]{Success: true, Data: entries}}, nil
}
-func (h *BuildWorkspaceHandler) GetFileContent(ctx context.Context, input *GetBuildFileContentInput) (*GetBuildFileContentOutput, error) {
+func (h *BuildWorkspaceHandler) GetFileContent(ctx context.Context, input *GetBuildFileContentInput) (*handlerutil.Out[BuildFileContentResponse], error) {
content, mimeType, err := h.service.GetFileContent(ctx, input.Path, input.MaxBytes)
if err != nil {
return nil, huma.Error500InternalServerError(err.Error())
}
- return &GetBuildFileContentOutput{Body: base.ApiResponse[BuildFileContentResponse]{
+ return &handlerutil.Out[BuildFileContentResponse]{Body: base.ApiResponse[BuildFileContentResponse]{
Success: true,
Data: BuildFileContentResponse{Content: content, MimeType: mimeType},
}}, nil
diff --git a/backend/internal/container/handler.go b/backend/internal/container/handler.go
index 59e698e15..62b130882 100644
--- a/backend/internal/container/handler.go
+++ b/backend/internal/container/handler.go
@@ -73,37 +73,21 @@ type GetContainerStatusCountsInput struct {
IncludeInternal bool `query:"includeInternal" default:"false" doc:"Include internal containers"`
}
-type GetContainerStatusCountsOutput struct {
- Body base.ApiResponse[containertypes.StatusCounts]
-}
-
type CreateContainerInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
Body containertypes.Create
}
-type CreateContainerOutput struct {
- Body base.ApiResponse[containertypes.Created]
-}
-
type GetContainerInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
ContainerID string `path:"containerId" doc:"Container ID"`
}
-type GetContainerOutput struct {
- Body base.ApiResponse[containertypes.Details]
-}
-
type ContainerActionInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
ContainerID string `path:"containerId" doc:"Container ID"`
}
-type ContainerActionOutput struct {
- Body base.ApiResponse[base.MessageResponse]
-}
-
type DeleteContainerInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
ContainerID string `path:"containerId" doc:"Container ID"`
@@ -111,10 +95,6 @@ type DeleteContainerInput struct {
RemoveVolumes bool `query:"volumes" default:"false" doc:"Remove associated volumes"`
}
-type DeleteContainerOutput struct {
- Body base.ApiResponse[base.MessageResponse]
-}
-
// SetAutoUpdateInput is the request input for toggling container auto-update.
type SetAutoUpdateInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
@@ -124,10 +104,6 @@ type SetAutoUpdateInput struct {
}
}
-type SetAutoUpdateOutput struct {
- Body base.ApiResponse[base.MessageResponse]
-}
-
// KillContainerInput carries the optional signal for a container kill.
type KillContainerInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
@@ -146,29 +122,17 @@ type GetContainerEditConfigInput struct {
ContainerID string `path:"containerId" doc:"Container ID"`
}
-type GetContainerEditConfigOutput struct {
- Body base.ApiResponse[containertypes.EditConfig]
-}
-
type EditContainerInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
ContainerID string `path:"containerId" doc:"Container ID"`
Body containertypes.Edit
}
-type CommitContainerOutput struct {
- Body base.ApiResponse[containertypes.CommitResult]
-}
-
type GenerateComposeInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
Body containertypes.GenerateComposeRequest
}
-type GenerateComposeOutput struct {
- Body base.ApiResponse[containertypes.GenerateComposeResponse]
-}
-
func RegisterContainers(api huma.API, containerSvc *ContainerService, dockerSvc *docker.DockerClientService, settingsSvc *settings.SettingsService, activitySvc *activity.ActivityService, appCtx handlerutil.ActivityAppContext) {
h := &ContainerHandler{
containerService: containerSvc,
@@ -365,7 +329,7 @@ func (h *ContainerHandler) ListContainers(ctx context.Context, input *ListContai
}, nil
}
-func (h *ContainerHandler) GetContainerStatusCounts(ctx context.Context, input *GetContainerStatusCountsInput) (*GetContainerStatusCountsOutput, error) {
+func (h *ContainerHandler) GetContainerStatusCounts(ctx context.Context, input *GetContainerStatusCountsInput) (*handlerutil.Out[containertypes.StatusCounts], error) {
containers, _, _, _, err := h.dockerService.GetAllContainers(ctx)
if err != nil {
return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to get container counts").Error())
@@ -392,7 +356,7 @@ func (h *ContainerHandler) GetContainerStatusCounts(ctx context.Context, input *
}
total := len(containers)
- return &GetContainerStatusCountsOutput{
+ return &handlerutil.Out[containertypes.StatusCounts]{
Body: base.ApiResponse[containertypes.StatusCounts]{
Success: true,
Data: containertypes.StatusCounts{
@@ -619,7 +583,7 @@ func buildNetworkingConfig(body containertypes.Create) (*network.NetworkingConfi
return nil, nil
}
-func (h *ContainerHandler) CreateContainer(ctx context.Context, input *CreateContainerInput) (*CreateContainerOutput, error) {
+func (h *ContainerHandler) CreateContainer(ctx context.Context, input *CreateContainerInput) (*handlerutil.Out[containertypes.Created], error) {
user, err := handlerutil.RequireUser(ctx)
if err != nil {
return nil, err
@@ -658,7 +622,7 @@ func (h *ContainerHandler) CreateContainer(ctx context.Context, input *CreateCon
Created: containerJSON.Created,
}
- return &CreateContainerOutput{
+ return &handlerutil.Out[containertypes.Created]{
Body: base.ApiResponse[containertypes.Created]{
Success: true,
Data: out,
@@ -666,13 +630,13 @@ func (h *ContainerHandler) CreateContainer(ctx context.Context, input *CreateCon
}, nil
}
-func (h *ContainerHandler) GetContainer(ctx context.Context, input *GetContainerInput) (*GetContainerOutput, error) {
+func (h *ContainerHandler) GetContainer(ctx context.Context, input *GetContainerInput) (*handlerutil.Out[containertypes.Details], error) {
details, err := h.containerService.GetContainerDetails(ctx, input.ContainerID)
if err != nil {
return nil, huma.Error404NotFound(errors.WithMessage(err, "Failed to retrieve container").Error())
}
- return &GetContainerOutput{
+ return &handlerutil.Out[containertypes.Details]{
Body: base.ApiResponse[containertypes.Details]{
Success: true,
Data: details,
@@ -680,13 +644,13 @@ func (h *ContainerHandler) GetContainer(ctx context.Context, input *GetContainer
}, nil
}
-func (h *ContainerHandler) GenerateCompose(ctx context.Context, input *GenerateComposeInput) (*GenerateComposeOutput, error) {
+func (h *ContainerHandler) GenerateCompose(ctx context.Context, input *GenerateComposeInput) (*handlerutil.Out[containertypes.GenerateComposeResponse], error) {
composeContent, err := h.containerService.GenerateCompose(ctx, input.Body.ContainerIDs)
if err != nil {
return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to generate compose file").Error())
}
- return &GenerateComposeOutput{
+ return &handlerutil.Out[containertypes.GenerateComposeResponse]{
Body: base.ApiResponse[containertypes.GenerateComposeResponse]{
Success: true,
Data: containertypes.GenerateComposeResponse{ComposeContent: composeContent},
@@ -694,7 +658,7 @@ func (h *ContainerHandler) GenerateCompose(ctx context.Context, input *GenerateC
}, nil
}
-func (h *ContainerHandler) StartContainer(ctx context.Context, input *ContainerActionInput) (*ContainerActionOutput, error) {
+func (h *ContainerHandler) StartContainer(ctx context.Context, input *ContainerActionInput) (*handlerutil.Out[base.MessageResponse], error) {
return h.runContainerActionInternal(ctx, input, containerActionConfigInternal{
ActivityType: activitytypes.TypeContainerStart,
Step: "Starting container",
@@ -710,7 +674,7 @@ func (h *ContainerHandler) StartContainer(ctx context.Context, input *ContainerA
})
}
-func (h *ContainerHandler) StopContainer(ctx context.Context, input *ContainerActionInput) (*ContainerActionOutput, error) {
+func (h *ContainerHandler) StopContainer(ctx context.Context, input *ContainerActionInput) (*handlerutil.Out[base.MessageResponse], error) {
return h.runContainerActionInternal(ctx, input, containerActionConfigInternal{
ActivityType: activitytypes.TypeContainerStop,
Step: "Stopping container",
@@ -726,7 +690,7 @@ func (h *ContainerHandler) StopContainer(ctx context.Context, input *ContainerAc
})
}
-func (h *ContainerHandler) RestartContainer(ctx context.Context, input *ContainerActionInput) (*ContainerActionOutput, error) {
+func (h *ContainerHandler) RestartContainer(ctx context.Context, input *ContainerActionInput) (*handlerutil.Out[base.MessageResponse], error) {
return h.runContainerActionInternal(ctx, input, containerActionConfigInternal{
ActivityType: activitytypes.TypeContainerRestart,
Step: "Restarting container",
@@ -742,7 +706,7 @@ func (h *ContainerHandler) RestartContainer(ctx context.Context, input *Containe
})
}
-func (h *ContainerHandler) KillContainer(ctx context.Context, input *KillContainerInput) (*ContainerActionOutput, error) {
+func (h *ContainerHandler) KillContainer(ctx context.Context, input *KillContainerInput) (*handlerutil.Out[base.MessageResponse], error) {
signal := strings.TrimSpace(input.Signal)
return h.runContainerActionInternal(ctx, &ContainerActionInput{EnvironmentID: input.EnvironmentID, ContainerID: input.ContainerID}, containerActionConfigInternal{
ActivityType: activitytypes.TypeContainerKill,
@@ -759,7 +723,7 @@ func (h *ContainerHandler) KillContainer(ctx context.Context, input *KillContain
})
}
-func (h *ContainerHandler) PauseContainer(ctx context.Context, input *ContainerActionInput) (*ContainerActionOutput, error) {
+func (h *ContainerHandler) PauseContainer(ctx context.Context, input *ContainerActionInput) (*handlerutil.Out[base.MessageResponse], error) {
return h.runContainerActionInternal(ctx, input, containerActionConfigInternal{
ActivityType: activitytypes.TypeContainerPause,
Step: "Pausing container",
@@ -775,7 +739,7 @@ func (h *ContainerHandler) PauseContainer(ctx context.Context, input *ContainerA
})
}
-func (h *ContainerHandler) UnpauseContainer(ctx context.Context, input *ContainerActionInput) (*ContainerActionOutput, error) {
+func (h *ContainerHandler) UnpauseContainer(ctx context.Context, input *ContainerActionInput) (*handlerutil.Out[base.MessageResponse], error) {
return h.runContainerActionInternal(ctx, input, containerActionConfigInternal{
ActivityType: activitytypes.TypeContainerUnpause,
Step: "Unpausing container",
@@ -801,7 +765,7 @@ type containerActionConfigInternal struct {
Error func(error) error
}
-func (h *ContainerHandler) runContainerActionInternal(ctx context.Context, input *ContainerActionInput, cfg containerActionConfigInternal) (*ContainerActionOutput, error) {
+func (h *ContainerHandler) runContainerActionInternal(ctx context.Context, input *ContainerActionInput, cfg containerActionConfigInternal) (*handlerutil.Out[base.MessageResponse], error) {
user, err := handlerutil.RequireUser(ctx)
if err != nil {
return nil, err
@@ -815,7 +779,7 @@ func (h *ContainerHandler) runContainerActionInternal(ctx context.Context, input
}
activitylib.CompleteHandlerActivity(runtimeCtx, h.activityService, activityID, cfg.CompleteMessage, nil)
- return &ContainerActionOutput{
+ return &handlerutil.Out[base.MessageResponse]{
Body: base.ApiResponse[base.MessageResponse]{
Success: true,
Data: base.MessageResponse{Message: cfg.SuccessMessage, ActivityID: mo.EmptyableToOption(strings.TrimSpace(activityID)).ToPointer()},
@@ -823,7 +787,7 @@ func (h *ContainerHandler) runContainerActionInternal(ctx context.Context, input
}, nil
}
-func (h *ContainerHandler) CommitContainer(ctx context.Context, input *CommitContainerInput) (*CommitContainerOutput, error) {
+func (h *ContainerHandler) CommitContainer(ctx context.Context, input *CommitContainerInput) (*handlerutil.Out[containertypes.CommitResult], error) {
if strings.TrimSpace(input.ContainerID) == "" {
return nil, huma.Error400BadRequest("container ID is required")
}
@@ -838,7 +802,7 @@ func (h *ContainerHandler) CommitContainer(ctx context.Context, input *CommitCon
return nil, huma.Error500InternalServerError(fmt.Sprintf("failed to commit container: %v", err))
}
- return &CommitContainerOutput{
+ return &handlerutil.Out[containertypes.CommitResult]{
Body: base.ApiResponse[containertypes.CommitResult]{
Success: true,
Data: *out,
@@ -846,7 +810,7 @@ func (h *ContainerHandler) CommitContainer(ctx context.Context, input *CommitCon
}, nil
}
-func (h *ContainerHandler) RedeployContainer(ctx context.Context, input *ContainerActionInput) (*GetContainerOutput, error) {
+func (h *ContainerHandler) RedeployContainer(ctx context.Context, input *ContainerActionInput) (*handlerutil.Out[containertypes.Details], error) {
user, err := handlerutil.RequireUser(ctx)
if err != nil {
return nil, err
@@ -871,7 +835,7 @@ func (h *ContainerHandler) RedeployContainer(ctx context.Context, input *Contain
if inspectErr == nil {
details.ActivityID = mo.EmptyableToOption(strings.TrimSpace(activityID)).ToPointer()
- return &GetContainerOutput{
+ return &handlerutil.Out[containertypes.Details]{
Body: base.ApiResponse[containertypes.Details]{
Success: true,
Data: details,
@@ -881,7 +845,7 @@ func (h *ContainerHandler) RedeployContainer(ctx context.Context, input *Contain
// Container was redeployed successfully, but we couldn't fetch full details.
// Return minimal response with just the ID so frontend can still navigate.
- return &GetContainerOutput{
+ return &handlerutil.Out[containertypes.Details]{
Body: base.ApiResponse[containertypes.Details]{
Success: true,
Data: containertypes.Details{
@@ -892,13 +856,13 @@ func (h *ContainerHandler) RedeployContainer(ctx context.Context, input *Contain
}, nil
}
-func (h *ContainerHandler) GetContainerEditConfig(ctx context.Context, input *GetContainerEditConfigInput) (*GetContainerEditConfigOutput, error) {
+func (h *ContainerHandler) GetContainerEditConfig(ctx context.Context, input *GetContainerEditConfigInput) (*handlerutil.Out[containertypes.EditConfig], error) {
editConfig, err := h.containerService.GetContainerEditConfig(ctx, input.ContainerID)
if err != nil {
return nil, huma.Error404NotFound(errors.WithMessage(err, "Failed to retrieve container").Error())
}
- return &GetContainerEditConfigOutput{
+ return &handlerutil.Out[containertypes.EditConfig]{
Body: base.ApiResponse[containertypes.EditConfig]{
Success: true,
Data: editConfig,
@@ -917,7 +881,7 @@ func editContainerHTTPErrorInternal(err error) error {
}
}
-func (h *ContainerHandler) EditContainer(ctx context.Context, input *EditContainerInput) (*GetContainerOutput, error) {
+func (h *ContainerHandler) EditContainer(ctx context.Context, input *EditContainerInput) (*handlerutil.Out[containertypes.Details], error) {
user, err := handlerutil.RequireUser(ctx)
if err != nil {
return nil, err
@@ -942,7 +906,7 @@ func (h *ContainerHandler) EditContainer(ctx context.Context, input *EditContain
if inspectErr == nil {
details.ActivityID = mo.EmptyableToOption(strings.TrimSpace(activityID)).ToPointer()
- return &GetContainerOutput{
+ return &handlerutil.Out[containertypes.Details]{
Body: base.ApiResponse[containertypes.Details]{
Success: true,
Data: details,
@@ -952,7 +916,7 @@ func (h *ContainerHandler) EditContainer(ctx context.Context, input *EditContain
// Container was recreated successfully, but we couldn't fetch full details.
// Return minimal response with just the ID so frontend can still navigate.
- return &GetContainerOutput{
+ return &handlerutil.Out[containertypes.Details]{
Body: base.ApiResponse[containertypes.Details]{
Success: true,
Data: containertypes.Details{
@@ -963,7 +927,7 @@ func (h *ContainerHandler) EditContainer(ctx context.Context, input *EditContain
}, nil
}
-func (h *ContainerHandler) DeleteContainer(ctx context.Context, input *DeleteContainerInput) (*DeleteContainerOutput, error) {
+func (h *ContainerHandler) DeleteContainer(ctx context.Context, input *DeleteContainerInput) (*handlerutil.Out[base.MessageResponse], error) {
user, err := handlerutil.RequireUser(ctx)
if err != nil {
return nil, err
@@ -977,7 +941,7 @@ func (h *ContainerHandler) DeleteContainer(ctx context.Context, input *DeleteCon
}
activitylib.CompleteHandlerActivity(runtimeCtx, h.activityService, activityID, "Container deleted", nil)
- return &DeleteContainerOutput{
+ return &handlerutil.Out[base.MessageResponse]{
Body: base.ApiResponse[base.MessageResponse]{
Success: true,
Data: base.MessageResponse{Message: "Container deleted successfully", ActivityID: mo.EmptyableToOption(strings.TrimSpace(activityID)).ToPointer()},
@@ -985,7 +949,7 @@ func (h *ContainerHandler) DeleteContainer(ctx context.Context, input *DeleteCon
}, nil
}
-func (h *ContainerHandler) SetAutoUpdate(ctx context.Context, input *SetAutoUpdateInput) (*SetAutoUpdateOutput, error) {
+func (h *ContainerHandler) SetAutoUpdate(ctx context.Context, input *SetAutoUpdateInput) (*handlerutil.Out[base.MessageResponse], error) {
// Resolve container name from ID
containerName, err := h.containerService.GetContainerNameByID(ctx, input.ContainerID)
if err != nil {
@@ -1002,7 +966,7 @@ func (h *ContainerHandler) SetAutoUpdate(ctx context.Context, input *SetAutoUpda
msg = "Auto-update disabled"
}
- return &SetAutoUpdateOutput{
+ return &handlerutil.Out[base.MessageResponse]{
Body: base.ApiResponse[base.MessageResponse]{
Success: true,
Data: base.MessageResponse{Message: msg},
diff --git a/backend/internal/container/service.go b/backend/internal/container/service.go
index 7e127fd0f..d41363135 100644
--- a/backend/internal/container/service.go
+++ b/backend/internal/container/service.go
@@ -1480,7 +1480,7 @@ func (s *ContainerService) ListContainersPaginated(
ungroupedParams.Start = 0
ungroupedParams.Limit = -1
- result := pagination.SearchOrderAndPaginate(items, ungroupedParams, config)
+ result := config.SearchOrderAndPaginate(items, ungroupedParams)
groups, paginationResp := paginateContainerProjectGroupsInternal(result, params)
// Icons must be resolved before flattening: groups hold value copies,
@@ -1498,7 +1498,7 @@ func (s *ContainerService) ListContainersPaginated(
}, nil
}
- result := pagination.SearchOrderAndPaginate(items, params, config)
+ result := config.SearchOrderAndPaginate(items, params)
s.ApplySummaryIcons(ctx, result.Items, nil)
paginationResp := pagination.BuildResponse(result.TotalCount, result.TotalAvailable, params)
diff --git a/backend/internal/container/service_test.go b/backend/internal/container/service_test.go
index 9831dd710..f8bf95389 100644
--- a/backend/internal/container/service_test.go
+++ b/backend/internal/container/service_test.go
@@ -175,10 +175,9 @@ func TestBuildContainerFilterAccessors_FiltersStandaloneContainers(t *testing.T)
{ID: "compose", Labels: map[string]string{"com.docker.compose.project": "alpha"}, UpdateInfo: updateInfo},
}
- result := pagination.SearchOrderAndPaginate(
+ result := pagination.Config[containertypes.Summary]{FilterAccessors: service.buildContainerFilterAccessors()}.SearchOrderAndPaginate(
items,
pagination.QueryParams{Filters: map[string]string{"standalone": "true", "updates": "has_update"}},
- pagination.Config[containertypes.Summary]{FilterAccessors: service.buildContainerFilterAccessors()},
)
require.Len(t, result.Items, 1)
diff --git a/backend/internal/dashboard/handler.go b/backend/internal/dashboard/handler.go
index 13997e7a1..309efa7cf 100644
--- a/backend/internal/dashboard/handler.go
+++ b/backend/internal/dashboard/handler.go
@@ -38,10 +38,6 @@ type GetDashboardInput struct {
DebugAllGood bool `query:"debugAllGood" default:"false" doc:"Debug mode: force an empty action item list"`
}
-type GetDashboardOutput struct {
- Body base.ApiResponse[dashboardtypes.Snapshot]
-}
-
const (
dashboardStreamHeartbeatInterval = 15 * time.Second
dashboardStreamLocalPollInterval = 15 * time.Second
@@ -75,7 +71,7 @@ func RegisterDashboard(api huma.API, dashboardService *DashboardService, environ
}, authz.PermDashboardRead, h.GetDashboard)
}
-func (h *DashboardHandler) GetDashboard(ctx context.Context, input *GetDashboardInput) (*GetDashboardOutput, error) {
+func (h *DashboardHandler) GetDashboard(ctx context.Context, input *GetDashboardInput) (*handlerutil.Out[dashboardtypes.Snapshot], error) {
// EnvironmentID is consumed by env proxy/auth middleware for routing/validation.
_ = input.EnvironmentID
@@ -90,7 +86,7 @@ func (h *DashboardHandler) GetDashboard(ctx context.Context, input *GetDashboard
return nil, huma.Error500InternalServerError("dashboard snapshot not available")
}
- return &GetDashboardOutput{
+ return &handlerutil.Out[dashboardtypes.Snapshot]{
Body: base.ApiResponse[dashboardtypes.Snapshot]{
Success: true,
Data: *snapshot,
diff --git a/backend/internal/dashboard/service.go b/backend/internal/dashboard/service.go
index 398238c12..12114b257 100644
--- a/backend/internal/dashboard/service.go
+++ b/backend/internal/dashboard/service.go
@@ -204,7 +204,7 @@ func (s *DashboardService) buildSnapshotInternal(ctx context.Context, options Da
}
return containerItems[i].Created > containerItems[j].Created
})
- containerPage = limitDashboardItemsInternal(containerItems, dashboardSnapshotPreloadLimit)
+ containerPage = containerItems[:min(dashboardSnapshotPreloadLimit, len(containerItems))]
if s.containerService != nil {
s.containerService.ApplySummaryIcons(ctx, containerPage, nil)
}
@@ -223,7 +223,7 @@ func (s *DashboardService) buildSnapshotInternal(ctx context.Context, options Da
}
return imageItems[i].Size > imageItems[j].Size
})
- imagePage = limitDashboardItemsInternal(imageItems, dashboardSnapshotPreloadLimit)
+ imagePage = imageItems[:min(dashboardSnapshotPreloadLimit, len(imageItems))]
}
imageUsageCounts := docker.CountImageUsage(dockerImages, filteredContainers)
@@ -483,11 +483,3 @@ func buildDashboardPaginationResponseInternal(totalItems int, limit int) base.Pa
GrandTotalItems: int64(totalItems),
}
}
-
-func limitDashboardItemsInternal[T any](items []T, limit int) []T {
- if limit <= 0 || len(items) <= limit {
- return items
- }
-
- return items[:limit]
-}
diff --git a/backend/internal/database/model.go b/backend/internal/database/model.go
index da9ec53a3..32a99d404 100644
--- a/backend/internal/database/model.go
+++ b/backend/internal/database/model.go
@@ -6,6 +6,7 @@ import (
"time"
"uuid"
+ "emperror.dev/errors"
"gorm.io/gorm"
)
@@ -30,52 +31,50 @@ func (m *BaseModel) BeforeUpdate(_ *gorm.DB) (err error) {
return nil
}
-//nolint:recvcheck
-type JSON map[string]any
-
-func (j JSON) Value() (driver.Value, error) {
- if j == nil {
+// JSONValue marshals a JSON TEXT column value. isNil stores SQL NULL instead
+// of the JSON literal "null" for nil maps/slices.
+func JSONValue(isNil bool, value any) (driver.Value, error) {
+ if isNil {
return nil, nil
}
- return json.Marshal(j)
+ return json.Marshal(value)
}
-func (j *JSON) Scan(value any) error {
+// JSONScan unmarshals a JSON TEXT column into dest, treating NULL as the zero value.
+func JSONScan[T any](dest *T, value any) error {
if value == nil {
- *j = nil
+ var zero T
+ *dest = zero
return nil
}
switch v := value.(type) {
case []byte:
- return json.Unmarshal(v, j)
+ return json.Unmarshal(v, dest)
case string:
- return json.Unmarshal([]byte(v), j)
+ return json.Unmarshal([]byte(v), dest)
default:
- return json.Unmarshal(nil, j)
+ return errors.Errorf("unsupported scan type for %T: %T", *dest, value)
}
}
+//nolint:recvcheck
+type JSON map[string]any
+
+func (j JSON) Value() (driver.Value, error) {
+ return JSONValue(j == nil, j)
+}
+
+func (j *JSON) Scan(value any) error {
+ return JSONScan(j, value)
+}
+
//nolint:recvcheck
type StringSlice []string
func (s StringSlice) Value() (driver.Value, error) {
- if s == nil {
- return nil, nil
- }
- return json.Marshal(s)
+ return JSONValue(s == nil, s)
}
func (s *StringSlice) Scan(value any) error {
- if value == nil {
- *s = nil
- return nil
- }
- switch v := value.(type) {
- case []byte:
- return json.Unmarshal(v, s)
- case string:
- return json.Unmarshal([]byte(v), s)
- default:
- return json.Unmarshal(nil, s)
- }
+ return JSONScan(s, value)
}
diff --git a/backend/internal/environment/environment_listing.go b/backend/internal/environment/environment_listing.go
index 7595e6f17..71ecaf473 100644
--- a/backend/internal/environment/environment_listing.go
+++ b/backend/internal/environment/environment_listing.go
@@ -164,7 +164,7 @@ func (s *EnvironmentService) listEnvironmentsPaginatedWithRuntimeFiltersInternal
},
}
- result := pagination.SearchOrderAndPaginate(items, params, config)
+ result := config.SearchOrderAndPaginate(items, params)
paginationResp := pagination.BuildResponse(result.TotalCount, result.TotalAvailable, params)
return result.Items, paginationResp, nil
diff --git a/backend/internal/environment/environment_proxy.go b/backend/internal/environment/environment_proxy.go
index 5de69179f..b3965f5cd 100644
--- a/backend/internal/environment/environment_proxy.go
+++ b/backend/internal/environment/environment_proxy.go
@@ -281,8 +281,13 @@ func (s *EnvironmentService) proxyJSONRequestForTargetInternal(
if err := resp.RequireSuccess(); err != nil {
return err
}
- if err := resp.DecodeJSON(out); err != nil {
- return err
+ // This is the erased decode behind the RemoteJSONProxy func-value seam;
+ // typed callers go through RemoteJSONProxy.JSON or remenv's generic decode.
+ if out == nil {
+ return nil
+ }
+ if err := json.Unmarshal(resp.Body, out); err != nil {
+ return &remenv.DecodeError{Err: err}
}
return nil
@@ -330,7 +335,7 @@ func doRemoteEnvironmentTunnelRequestInternal(
// SyncRegistriesToEnvironment syncs all registries from this manager to a remote environment
func (s *EnvironmentService) SyncRegistriesToEnvironment(ctx context.Context, environmentID string) error {
- return fanOutSyncToEnvironmentInternal(ctx, s, environmentID, "registries", "/api/container-registries/sync",
+ return s.fanOutSyncToEnvironment(ctx, environmentID, "registries", "/api/container-registries/sync",
func(ctx context.Context, reg registry.ContainerRegistry) (containerregistry.Sync, bool, error) {
registryType, typeErr := registry.NormalizeRegistryType(reg.RegistryType)
if typeErr != nil {
@@ -380,7 +385,7 @@ func (s *EnvironmentService) SyncRegistriesToEnvironment(ctx context.Context, en
// SyncS3DestinationsToEnvironment sends manager-owned destinations to one remote environment.
func (s *EnvironmentService) SyncS3DestinationsToEnvironment(ctx context.Context, environmentID string) error {
- return fanOutSyncToEnvironmentInternal(ctx, s, environmentID, "S3 destinations", "/api/backups/s3/sync",
+ return s.fanOutSyncToEnvironment(ctx, environmentID, "S3 destinations", "/api/backups/s3/sync",
func(_ context.Context, destination s3domain.S3Destination) (backuptypes.S3DestinationSync, bool, error) {
secret, err := crypto.Decrypt(destination.SecretAccessKey)
if err != nil {
@@ -396,7 +401,7 @@ func (s *EnvironmentService) SyncS3DestinationsToEnvironment(ctx context.Context
// SyncRepositoriesToEnvironment syncs all git repositories from this manager to a remote environment
func (s *EnvironmentService) SyncRepositoriesToEnvironment(ctx context.Context, environmentID string) error {
- return fanOutSyncToEnvironmentInternal(ctx, s, environmentID, "git repositories", "/api/git-repositories/sync",
+ return s.fanOutSyncToEnvironment(ctx, environmentID, "git repositories", "/api/git-repositories/sync",
func(ctx context.Context, repo gitrepo.GitRepository) (gitops.RepositorySync, bool, error) {
item := gitops.RepositorySync{
ID: repo.ID,
@@ -438,14 +443,13 @@ func (s *EnvironmentService) SyncRepositoriesToEnvironment(ctx context.Context,
)
}
-// fanOutSyncToEnvironmentInternal pushes every row of Model held by this
+// fanOutSyncToEnvironment pushes every row of Model held by this
// manager to one remote environment. toSyncItem maps a row to its wire form and
// reports whether to keep it — rows whose credentials fail to decrypt are
// skipped rather than failing the whole batch — and wrap builds the request
// envelope the target endpoint expects.
-func fanOutSyncToEnvironmentInternal[Model any, Item any, Request any](
+func (s *EnvironmentService) fanOutSyncToEnvironment[Model any, Item any, Request any](
ctx context.Context,
- s *EnvironmentService,
environmentID string,
kind string,
path string,
diff --git a/backend/internal/environment/handler.go b/backend/internal/environment/handler.go
index 1412689fd..b72424a76 100644
--- a/backend/internal/environment/handler.go
+++ b/backend/internal/environment/handler.go
@@ -69,10 +69,6 @@ type ListEnvironmentsInput struct {
Type string `query:"type" doc:"Filter by environment type (comma-separated: http,edge,websocket,grpc,polling)"`
}
-type ListEnvironmentsOutput struct {
- Body base.Paginated[environment.Environment]
-}
-
type CreateEnvironmentInput struct {
Body environment.Create
}
@@ -83,77 +79,41 @@ type EnvironmentWithApiKey struct {
ApiKey *string `json:"apiKey,omitempty" doc:"API key for pairing (only shown once during creation)"`
}
-type CreateEnvironmentOutput struct {
- Body base.ApiResponse[EnvironmentWithApiKey]
-}
-
type GetEnvironmentInput struct {
ID string `path:"id" doc:"Environment ID"`
}
-type GetEnvironmentOutput struct {
- Body base.ApiResponse[environment.Environment]
-}
-
type UpdateEnvironmentInput struct {
ID string `path:"id" doc:"Environment ID"`
Body environment.Update
}
-type UpdateEnvironmentOutput struct {
- Body base.ApiResponse[environment.Environment]
-}
-
type DeleteEnvironmentInput struct {
ID string `path:"id" doc:"Environment ID"`
}
-type DeleteEnvironmentOutput struct {
- Body base.ApiResponse[base.MessageResponse]
-}
-
type TestConnectionInput struct {
ID string `path:"id" doc:"Environment ID"`
Body *environment.TestConnectionRequest `json:"body,omitempty"`
}
-type TestConnectionOutput struct {
- Body base.ApiResponse[environment.Test]
-}
-
type UpdateHeartbeatInput struct {
ID string `path:"id" doc:"Environment ID"`
}
-type UpdateHeartbeatOutput struct {
- Body base.ApiResponse[base.MessageResponse]
-}
-
type PairAgentInput struct {
ID string `path:"id" doc:"Environment ID (must be 0 for local)"`
Body *environment.AgentPairRequest `json:"body,omitempty"`
}
-type PairAgentOutput struct {
- Body base.ApiResponse[environment.AgentPairResponse]
-}
-
type SyncEnvironmentInput struct {
ID string `path:"id" doc:"Environment ID"`
}
-type SyncEnvironmentOutput struct {
- Body base.ApiResponse[base.MessageResponse]
-}
-
type PairEnvironmentInput struct {
XAPIKey string `header:"X-API-Key" doc:"API key for environment pairing"`
}
-type PairEnvironmentOutput struct {
- Body base.ApiResponse[base.MessageResponse]
-}
-
type DeploymentSnippet struct {
DockerRun string `json:"dockerRun" doc:"Docker run command snippet"`
DockerCompose string `json:"dockerCompose" doc:"Docker compose YAML snippet"`
@@ -164,18 +124,10 @@ type GetDeploymentSnippetsInput struct {
ID string `path:"id" doc:"Environment ID"`
}
-type GetDeploymentSnippetsOutput struct {
- Body base.ApiResponse[DeploymentSnippet]
-}
-
type GetEnvironmentVersionInput struct {
ID string `path:"id" doc:"Environment ID"`
}
-type GetEnvironmentVersionOutput struct {
- Body base.ApiResponse[version.Info]
-}
-
type DownloadEdgeMTLSCAInput struct{}
type DownloadEnvironmentMTLSBundleInput struct {
@@ -370,7 +322,7 @@ func RegisterEnvironments(api huma.API, h *EnvironmentHandler) {
// ============================================================================
// ListEnvironments returns a paginated list of environments.
-func (h *EnvironmentHandler) ListEnvironments(ctx context.Context, input *ListEnvironmentsInput) (*ListEnvironmentsOutput, error) {
+func (h *EnvironmentHandler) ListEnvironments(ctx context.Context, input *ListEnvironmentsInput) (*handlerutil.Page[environment.Environment], error) {
// The list endpoint backs both the environments management page and the
// environment switcher, so any authenticated caller may reach it. Global
// listers (sudo, global admins, or holders of the org-level
@@ -398,7 +350,7 @@ func (h *EnvironmentHandler) ListEnvironments(ctx context.Context, input *ListEn
h.applyEdgeRuntimeStateInternal(&envs[i])
}
- return &ListEnvironmentsOutput{
+ return &handlerutil.Page[environment.Environment]{
Body: base.Paginated[environment.Environment]{
Success: true,
Data: envs,
@@ -464,7 +416,7 @@ func (h *EnvironmentHandler) visibleEnvironmentsForInternal(ctx context.Context,
// the bytes for comparison — most ticks change nothing and the encoded snapshot
// was thrown away immediately.
func fingerprintEnvironmentsInternal(envs []environment.Environment) uint64 {
- return utils.FingerprintOf(envs, func(f *utils.Fingerprint, env *environment.Environment) {
+ return utils.NewFingerprint().Slice(envs, func(f *utils.Fingerprint, env *environment.Environment) {
f.String(env.ID).
String(env.Name).
String(env.ApiUrl).
@@ -494,7 +446,7 @@ func fingerprintEnvironmentsInternal(envs []environment.Environment) uint64 {
OptInt(cert.DaysRemaining).
Bool(cert.Expired).
Bool(cert.ExpiringSoon)
- })
+ }).Sum()
}
func (h *EnvironmentHandler) RunStreamProducer(ctx context.Context, ps *authz.PermissionSet, events chan<- environment.StreamEvent) {
@@ -556,7 +508,7 @@ func (h *EnvironmentHandler) RunStreamProducer(ctx context.Context, ps *authz.Pe
}
// CreateEnvironment creates a new environment.
-func (h *EnvironmentHandler) CreateEnvironment(ctx context.Context, input *CreateEnvironmentInput) (*CreateEnvironmentOutput, error) {
+func (h *EnvironmentHandler) CreateEnvironment(ctx context.Context, input *CreateEnvironmentInput) (*handlerutil.Out[EnvironmentWithApiKey], error) {
user, err := handlerutil.RequireUser(ctx)
if err != nil {
return nil, err
@@ -586,7 +538,7 @@ func (h *EnvironmentHandler) CreateEnvironment(ctx context.Context, input *Creat
return h.createEnvironmentLegacyInternal(ctx, env, user, input.Body)
}
-func (h *EnvironmentHandler) createEnvironmentWithApiKeyInternal(ctx context.Context, env *Environment, user *common.User) (*CreateEnvironmentOutput, error) {
+func (h *EnvironmentHandler) createEnvironmentWithApiKeyInternal(ctx context.Context, env *Environment, user *common.User) (*handlerutil.Out[EnvironmentWithApiKey], error) {
// New API key-based pairing flow
env.Status = string(EnvironmentStatusPending)
@@ -631,7 +583,7 @@ func (h *EnvironmentHandler) createEnvironmentWithApiKeyInternal(ctx context.Con
}
h.applyEdgeRuntimeStateInternal(&out)
- return &CreateEnvironmentOutput{
+ return &handlerutil.Out[EnvironmentWithApiKey]{
Body: base.ApiResponse[EnvironmentWithApiKey]{
Success: true,
Data: EnvironmentWithApiKey{
@@ -642,7 +594,7 @@ func (h *EnvironmentHandler) createEnvironmentWithApiKeyInternal(ctx context.Con
}, nil
}
-func (h *EnvironmentHandler) createEnvironmentLegacyInternal(ctx context.Context, env *Environment, user *common.User, body environment.Create) (*CreateEnvironmentOutput, error) {
+func (h *EnvironmentHandler) createEnvironmentLegacyInternal(ctx context.Context, env *Environment, user *common.User, body environment.Create) (*handlerutil.Out[EnvironmentWithApiKey], error) {
if body.AccessToken != nil && *body.AccessToken != "" {
env.AccessToken = body.AccessToken
}
@@ -663,7 +615,7 @@ func (h *EnvironmentHandler) createEnvironmentLegacyInternal(ctx context.Context
}
h.applyEdgeRuntimeStateInternal(&out)
- return &CreateEnvironmentOutput{
+ return &handlerutil.Out[EnvironmentWithApiKey]{
Body: base.ApiResponse[EnvironmentWithApiKey]{
Success: true,
Data: EnvironmentWithApiKey{
@@ -674,7 +626,7 @@ func (h *EnvironmentHandler) createEnvironmentLegacyInternal(ctx context.Context
}
// GetEnvironment returns an environment by ID.
-func (h *EnvironmentHandler) GetEnvironment(ctx context.Context, input *GetEnvironmentInput) (*GetEnvironmentOutput, error) {
+func (h *EnvironmentHandler) GetEnvironment(ctx context.Context, input *GetEnvironmentInput) (*handlerutil.Out[environment.Environment], error) {
env, err := h.environmentService.GetEnvironmentByID(ctx, input.ID)
if err != nil {
return nil, huma.Error404NotFound("Environment not found")
@@ -691,7 +643,7 @@ func (h *EnvironmentHandler) GetEnvironment(ctx context.Context, input *GetEnvir
}
}
- return &GetEnvironmentOutput{
+ return &handlerutil.Out[environment.Environment]{
Body: base.ApiResponse[environment.Environment]{
Success: true,
Data: out,
@@ -700,7 +652,7 @@ func (h *EnvironmentHandler) GetEnvironment(ctx context.Context, input *GetEnvir
}
// UpdateEnvironment updates an environment.
-func (h *EnvironmentHandler) UpdateEnvironment(ctx context.Context, input *UpdateEnvironmentInput) (*UpdateEnvironmentOutput, error) {
+func (h *EnvironmentHandler) UpdateEnvironment(ctx context.Context, input *UpdateEnvironmentInput) (*handlerutil.Out[environment.Environment], error) {
isLocalEnv := input.ID == localDockerEnvironmentID
updates := h.buildUpdateMapInternal(&input.Body, isLocalEnv)
@@ -791,7 +743,7 @@ func (h *EnvironmentHandler) UpdateEnvironment(ctx context.Context, input *Updat
// Set the API key on the response if regenerated
out.ApiKey = newApiKey
- return &UpdateEnvironmentOutput{
+ return &handlerutil.Out[environment.Environment]{
Body: base.ApiResponse[environment.Environment]{
Success: true,
Data: out,
@@ -804,7 +756,7 @@ func (h *EnvironmentHandler) applyEdgeRuntimeStateInternal(env *environment.Envi
}
// DeleteEnvironment deletes an environment.
-func (h *EnvironmentHandler) DeleteEnvironment(ctx context.Context, input *DeleteEnvironmentInput) (*DeleteEnvironmentOutput, error) {
+func (h *EnvironmentHandler) DeleteEnvironment(ctx context.Context, input *DeleteEnvironmentInput) (*handlerutil.Out[base.MessageResponse], error) {
if input.ID == localDockerEnvironmentID {
return nil, huma.Error400BadRequest("Cannot delete local environment")
}
@@ -819,7 +771,7 @@ func (h *EnvironmentHandler) DeleteEnvironment(ctx context.Context, input *Delet
return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to delete environment").Error())
}
- return &DeleteEnvironmentOutput{
+ return &handlerutil.Out[base.MessageResponse]{
Body: base.ApiResponse[base.MessageResponse]{
Success: true,
Data: base.MessageResponse{
@@ -830,7 +782,7 @@ func (h *EnvironmentHandler) DeleteEnvironment(ctx context.Context, input *Delet
}
// TestConnection tests connectivity to an environment.
-func (h *EnvironmentHandler) TestConnection(ctx context.Context, input *TestConnectionInput) (*TestConnectionOutput, error) {
+func (h *EnvironmentHandler) TestConnection(ctx context.Context, input *TestConnectionInput) (*handlerutil.Out[environment.Test], error) {
var apiUrl *string
if input.Body != nil {
apiUrl = input.Body.ApiUrl
@@ -851,7 +803,7 @@ func (h *EnvironmentHandler) TestConnection(ctx context.Context, input *TestConn
apiErr := common.ToAPIError(err)
err = huma.NewError(apiErr.HTTPStatus(), apiErr.Message)
}
- return &TestConnectionOutput{
+ return &handlerutil.Out[environment.Test]{
Body: base.ApiResponse[environment.Test]{
Success: false,
Data: resp,
@@ -859,7 +811,7 @@ func (h *EnvironmentHandler) TestConnection(ctx context.Context, input *TestConn
}, err
}
- return &TestConnectionOutput{
+ return &handlerutil.Out[environment.Test]{
Body: base.ApiResponse[environment.Test]{
Success: true,
Data: resp,
@@ -868,12 +820,12 @@ func (h *EnvironmentHandler) TestConnection(ctx context.Context, input *TestConn
}
// UpdateHeartbeat updates the heartbeat for an environment.
-func (h *EnvironmentHandler) UpdateHeartbeat(ctx context.Context, input *UpdateHeartbeatInput) (*UpdateHeartbeatOutput, error) {
+func (h *EnvironmentHandler) UpdateHeartbeat(ctx context.Context, input *UpdateHeartbeatInput) (*handlerutil.Out[base.MessageResponse], error) {
if err := h.environmentService.UpdateEnvironmentHeartbeat(ctx, input.ID); err != nil {
return nil, huma.Error500InternalServerError("Failed to update heartbeat")
}
- return &UpdateHeartbeatOutput{
+ return &handlerutil.Out[base.MessageResponse]{
Body: base.ApiResponse[base.MessageResponse]{
Success: true,
Data: base.MessageResponse{
@@ -884,7 +836,7 @@ func (h *EnvironmentHandler) UpdateHeartbeat(ctx context.Context, input *UpdateH
}
// PairAgent generates or rotates the local agent pairing token.
-func (h *EnvironmentHandler) PairAgent(ctx context.Context, input *PairAgentInput) (*PairAgentOutput, error) {
+func (h *EnvironmentHandler) PairAgent(ctx context.Context, input *PairAgentInput) (*handlerutil.Out[environment.AgentPairResponse], error) {
if input.ID != localDockerEnvironmentID {
return nil, huma.Error404NotFound("Not found")
}
@@ -898,7 +850,7 @@ func (h *EnvironmentHandler) PairAgent(ctx context.Context, input *PairAgentInpu
return nil, huma.Error500InternalServerError("Failed to persist agent token")
}
- return &PairAgentOutput{
+ return &handlerutil.Out[environment.AgentPairResponse]{
Body: base.ApiResponse[environment.AgentPairResponse]{
Success: true,
Data: environment.AgentPairResponse{
@@ -909,7 +861,7 @@ func (h *EnvironmentHandler) PairAgent(ctx context.Context, input *PairAgentInpu
}
// SyncEnvironment syncs manager-owned resources to an environment.
-func (h *EnvironmentHandler) SyncEnvironment(ctx context.Context, input *SyncEnvironmentInput) (*SyncEnvironmentOutput, error) {
+func (h *EnvironmentHandler) SyncEnvironment(ctx context.Context, input *SyncEnvironmentInput) (*handlerutil.Out[base.MessageResponse], error) {
// Sync registries
if err := h.environmentService.SyncRegistriesToEnvironment(ctx, input.ID); err != nil {
slog.WarnContext(ctx, "Failed to sync registries", "environmentID", input.ID, "error", err.Error())
@@ -924,7 +876,7 @@ func (h *EnvironmentHandler) SyncEnvironment(ctx context.Context, input *SyncEnv
slog.WarnContext(ctx, "Failed to sync git repositories", "environmentID", input.ID, "error", err.Error())
}
- return &SyncEnvironmentOutput{
+ return &handlerutil.Out[base.MessageResponse]{
Body: base.ApiResponse[base.MessageResponse]{
Success: true,
Data: base.MessageResponse{
@@ -1027,7 +979,7 @@ func (h *EnvironmentHandler) triggerEnvironmentResourceSyncInternal(ctx context.
}
// PairEnvironment handles agent pairing callback with API key.
-func (h *EnvironmentHandler) PairEnvironment(ctx context.Context, input *PairEnvironmentInput) (*PairEnvironmentOutput, error) {
+func (h *EnvironmentHandler) PairEnvironment(ctx context.Context, input *PairEnvironmentInput) (*handlerutil.Out[base.MessageResponse], error) {
if input.XAPIKey == "" {
return nil, huma.Error400BadRequest("X-API-Key header is required")
}
@@ -1064,7 +1016,7 @@ func (h *EnvironmentHandler) PairEnvironment(ctx context.Context, input *PairEnv
slog.InfoContext(ctx, "Environment pairing completed", "environmentID", *envID, "environmentName", env.Name)
h.triggerEnvironmentResourceSyncInternal(ctx, *envID, env.Name, "environment pairing")
- return &PairEnvironmentOutput{
+ return &handlerutil.Out[base.MessageResponse]{
Body: base.ApiResponse[base.MessageResponse]{
Success: true,
Data: base.MessageResponse{
@@ -1075,7 +1027,7 @@ func (h *EnvironmentHandler) PairEnvironment(ctx context.Context, input *PairEnv
}
// GetDeploymentSnippets returns deployment snippets for an environment.
-func (h *EnvironmentHandler) GetDeploymentSnippets(ctx context.Context, input *GetDeploymentSnippetsInput) (*GetDeploymentSnippetsOutput, error) {
+func (h *EnvironmentHandler) GetDeploymentSnippets(ctx context.Context, input *GetDeploymentSnippetsInput) (*handlerutil.Out[DeploymentSnippet], error) {
env, err := h.environmentService.GetEnvironmentByID(ctx, input.ID)
if err != nil {
return nil, huma.Error404NotFound("Environment not found")
@@ -1133,7 +1085,7 @@ func (h *EnvironmentHandler) GetDeploymentSnippets(ctx context.Context, input *G
}
}
- return &GetDeploymentSnippetsOutput{
+ return &handlerutil.Out[DeploymentSnippet]{
Body: base.ApiResponse[DeploymentSnippet]{
Success: true,
Data: DeploymentSnippet{
@@ -1146,7 +1098,7 @@ func (h *EnvironmentHandler) GetDeploymentSnippets(ctx context.Context, input *G
}
// GetEnvironmentVersion returns the version of a remote environment.
-func (h *EnvironmentHandler) GetEnvironmentVersion(ctx context.Context, input *GetEnvironmentVersionInput) (*GetEnvironmentVersionOutput, error) {
+func (h *EnvironmentHandler) GetEnvironmentVersion(ctx context.Context, input *GetEnvironmentVersionInput) (*handlerutil.Out[version.Info], error) {
env, err := h.environmentService.GetEnvironmentByID(ctx, input.ID)
if err != nil {
return nil, huma.Error404NotFound("Environment not found")
@@ -1213,7 +1165,7 @@ func (h *EnvironmentHandler) GetEnvironmentVersion(ctx context.Context, input *G
// Don't fail the request if heartbeat update fails
}
- return &GetEnvironmentVersionOutput{
+ return &handlerutil.Out[version.Info]{
Body: base.ApiResponse[version.Info]{
Success: true,
Data: versionInfo,
diff --git a/backend/internal/event/handler.go b/backend/internal/event/handler.go
index c403bad3a..c2f876011 100644
--- a/backend/internal/event/handler.go
+++ b/backend/internal/event/handler.go
@@ -39,16 +39,8 @@ type ListEventsInput struct {
Type string `query:"type" doc:"Filter by event type (exact type or category prefix, comma-separated)"`
}
-type ListEventsOutput struct {
- Body base.Paginated[eventtypes.Event]
-}
-
type GetEventStatsInput struct{}
-type GetEventStatsOutput struct {
- Body base.ApiResponse[EventSeverityCounts]
-}
-
type GetEventsByEnvironmentInput struct {
EnvironmentID string `path:"environmentId" doc:"Environment ID"`
Search string `query:"search" doc:"Search query"`
@@ -60,18 +52,10 @@ type GetEventsByEnvironmentInput struct {
Type string `query:"type" doc:"Filter by event type (exact type or category prefix, comma-separated)"`
}
-type GetEventsByEnvironmentOutput struct {
- Body base.Paginated[eventtypes.Event]
-}
-
type DeleteEventInput struct {
EventID string `path:"eventId" doc:"Event ID"`
}
-type DeleteEventOutput struct {
- Body base.ApiResponse[base.MessageResponse]
-}
-
// ============================================================================
// Registration
// ============================================================================
@@ -199,7 +183,7 @@ func RegisterEvents(api huma.API, eventService *EventService) {
// ============================================================================
// ListEvents returns a paginated list of events.
-func (h *EventHandler) ListEvents(ctx context.Context, input *ListEventsInput) (*ListEventsOutput, error) {
+func (h *EventHandler) ListEvents(ctx context.Context, input *ListEventsInput) (*handlerutil.Page[eventtypes.Event], error) {
params := handlerutil.PaginationParams(input.Start, input.Limit, input.Sort, input.Order, input.Search)
if input.Severity != "" {
@@ -214,7 +198,7 @@ func (h *EventHandler) ListEvents(ctx context.Context, input *ListEventsInput) (
return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to list events").Error())
}
- return &ListEventsOutput{
+ return &handlerutil.Page[eventtypes.Event]{
Body: base.Paginated[eventtypes.Event]{
Success: true,
Data: events,
@@ -224,13 +208,13 @@ func (h *EventHandler) ListEvents(ctx context.Context, input *ListEventsInput) (
}
// GetEventStats returns global event counts grouped by severity.
-func (h *EventHandler) GetEventStats(ctx context.Context, _ *GetEventStatsInput) (*GetEventStatsOutput, error) {
+func (h *EventHandler) GetEventStats(ctx context.Context, _ *GetEventStatsInput) (*handlerutil.Out[EventSeverityCounts], error) {
counts, err := h.eventService.GetEventSeverityCounts(ctx)
if err != nil {
return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to load event statistics").Error())
}
- return &GetEventStatsOutput{
+ return &handlerutil.Out[EventSeverityCounts]{
Body: base.ApiResponse[EventSeverityCounts]{
Success: true,
Data: counts,
@@ -239,7 +223,7 @@ func (h *EventHandler) GetEventStats(ctx context.Context, _ *GetEventStatsInput)
}
// GetEventsByEnvironment returns events for a specific environment.
-func (h *EventHandler) GetEventsByEnvironment(ctx context.Context, input *GetEventsByEnvironmentInput) (*GetEventsByEnvironmentOutput, error) {
+func (h *EventHandler) GetEventsByEnvironment(ctx context.Context, input *GetEventsByEnvironmentInput) (*handlerutil.Page[eventtypes.Event], error) {
if input.EnvironmentID == "" {
return nil, huma.Error400BadRequest("Environment ID is required")
}
@@ -258,7 +242,7 @@ func (h *EventHandler) GetEventsByEnvironment(ctx context.Context, input *GetEve
return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to list events").Error())
}
- return &GetEventsByEnvironmentOutput{
+ return &handlerutil.Page[eventtypes.Event]{
Body: base.Paginated[eventtypes.Event]{
Success: true,
Data: events,
@@ -268,7 +252,7 @@ func (h *EventHandler) GetEventsByEnvironment(ctx context.Context, input *GetEve
}
// DeleteEvent deletes an event.
-func (h *EventHandler) DeleteEvent(ctx context.Context, input *DeleteEventInput) (*DeleteEventOutput, error) {
+func (h *EventHandler) DeleteEvent(ctx context.Context, input *DeleteEventInput) (*handlerutil.Out[base.MessageResponse], error) {
if input.EventID == "" {
return nil, huma.Error400BadRequest("Event ID is required")
}
@@ -277,7 +261,7 @@ func (h *EventHandler) DeleteEvent(ctx context.Context, input *DeleteEventInput)
return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to delete event").Error())
}
- return &DeleteEventOutput{
+ return &handlerutil.Out[base.MessageResponse]{
Body: base.ApiResponse[base.MessageResponse]{
Success: true,
Data: base.MessageResponse{
diff --git a/backend/internal/federated/handler.go b/backend/internal/federated/handler.go
index 769a0f6a3..89383165b 100644
--- a/backend/internal/federated/handler.go
+++ b/backend/internal/federated/handler.go
@@ -34,43 +34,23 @@ type ListFederatedCredentialsInput struct {
Limit int `query:"limit" default:"20" doc:"Number of items per page"`
}
-type ListFederatedCredentialsOutput struct {
- Body base.Paginated[federatedtypes.FederatedCredential]
-}
-
type CreateFederatedCredentialInput struct {
Body federatedtypes.CreateFederatedCredential
}
-type CreateFederatedCredentialOutput struct {
- Body base.ApiResponse[federatedtypes.FederatedCredential]
-}
-
type GetFederatedCredentialInput struct {
ID string `path:"id" doc:"Federated credential ID"`
}
-type GetFederatedCredentialOutput struct {
- Body base.ApiResponse[federatedtypes.FederatedCredential]
-}
-
type UpdateFederatedCredentialInput struct {
ID string `path:"id" doc:"Federated credential ID"`
Body federatedtypes.UpdateFederatedCredential
}
-type UpdateFederatedCredentialOutput struct {
- Body base.ApiResponse[federatedtypes.FederatedCredential]
-}
-
type DeleteFederatedCredentialInput struct {
ID string `path:"id" doc:"Federated credential ID"`
}
-type DeleteFederatedCredentialOutput struct {
- Body base.ApiResponse[base.MessageResponse]
-}
-
// RegisterFederatedTokenExchange registers the public RFC 8693 token exchange
// endpoint. It intentionally uses Echo because the standard requires form
// encoding while the rest of Arcane's Huma API is JSON-first.
@@ -167,13 +147,13 @@ func RegisterFederatedCredentials(api huma.API, federatedCredentialService *Fede
}, h.DeleteFederatedCredential)
}
-func (h *FederatedCredentialHandler) ListFederatedCredentials(ctx context.Context, input *ListFederatedCredentialsInput) (*ListFederatedCredentialsOutput, error) {
+func (h *FederatedCredentialHandler) ListFederatedCredentials(ctx context.Context, input *ListFederatedCredentialsInput) (*handlerutil.Page[federatedtypes.FederatedCredential], error) {
credentials, paginationResp, err := h.federatedCredentialService.List(ctx, handlerutil.PaginationParams(input.Start, input.Limit, input.Sort, input.Order, input.Search))
if err != nil {
return nil, huma.Error500InternalServerError("failed to list federated credentials")
}
- return &ListFederatedCredentialsOutput{
+ return &handlerutil.Page[federatedtypes.FederatedCredential]{
Body: base.Paginated[federatedtypes.FederatedCredential]{
Success: true,
Data: credentials,
@@ -182,7 +162,7 @@ func (h *FederatedCredentialHandler) ListFederatedCredentials(ctx context.Contex
}, nil
}
-func (h *FederatedCredentialHandler) CreateFederatedCredential(ctx context.Context, input *CreateFederatedCredentialInput) (*CreateFederatedCredentialOutput, error) {
+func (h *FederatedCredentialHandler) CreateFederatedCredential(ctx context.Context, input *CreateFederatedCredentialInput) (*handlerutil.Out[federatedtypes.FederatedCredential], error) {
user, err := handlerutil.RequireUser(ctx)
if err != nil {
return nil, err
@@ -193,7 +173,7 @@ func (h *FederatedCredentialHandler) CreateFederatedCredential(ctx context.Conte
return nil, federatedCredentialManagementErrorInternal(err)
}
- return &CreateFederatedCredentialOutput{
+ return &handlerutil.Out[federatedtypes.FederatedCredential]{
Body: base.ApiResponse[federatedtypes.FederatedCredential]{
Success: true,
Data: *credential,
@@ -201,13 +181,13 @@ func (h *FederatedCredentialHandler) CreateFederatedCredential(ctx context.Conte
}, nil
}
-func (h *FederatedCredentialHandler) GetFederatedCredential(ctx context.Context, input *GetFederatedCredentialInput) (*GetFederatedCredentialOutput, error) {
+func (h *FederatedCredentialHandler) GetFederatedCredential(ctx context.Context, input *GetFederatedCredentialInput) (*handlerutil.Out[federatedtypes.FederatedCredential], error) {
credential, err := h.federatedCredentialService.Get(ctx, input.ID)
if err != nil {
return nil, federatedCredentialManagementErrorInternal(err)
}
- return &GetFederatedCredentialOutput{
+ return &handlerutil.Out[federatedtypes.FederatedCredential]{
Body: base.ApiResponse[federatedtypes.FederatedCredential]{
Success: true,
Data: *credential,
@@ -215,7 +195,7 @@ func (h *FederatedCredentialHandler) GetFederatedCredential(ctx context.Context,
}, nil
}
-func (h *FederatedCredentialHandler) UpdateFederatedCredential(ctx context.Context, input *UpdateFederatedCredentialInput) (*UpdateFederatedCredentialOutput, error) {
+func (h *FederatedCredentialHandler) UpdateFederatedCredential(ctx context.Context, input *UpdateFederatedCredentialInput) (*handlerutil.Out[federatedtypes.FederatedCredential], error) {
user, err := handlerutil.RequireUser(ctx)
if err != nil {
return nil, err
@@ -226,7 +206,7 @@ func (h *FederatedCredentialHandler) UpdateFederatedCredential(ctx context.Conte
return nil, federatedCredentialManagementErrorInternal(err)
}
- return &UpdateFederatedCredentialOutput{
+ return &handlerutil.Out[federatedtypes.FederatedCredential]{
Body: base.ApiResponse[federatedtypes.FederatedCredential]{
Success: true,
Data: *credential,
@@ -234,12 +214,12 @@ func (h *FederatedCredentialHandler) UpdateFederatedCredential(ctx context.Conte
}, nil
}
-func (h *FederatedCredentialHandler) DeleteFederatedCredential(ctx context.Context, input *DeleteFederatedCredentialInput) (*DeleteFederatedCredentialOutput, error) {
+func (h *FederatedCredentialHandler) DeleteFederatedCredential(ctx context.Context, input *DeleteFederatedCredentialInput) (*handlerutil.Out[base.MessageResponse], error) {
if err := h.federatedCredentialService.Delete(ctx, input.ID); err != nil {
return nil, federatedCredentialManagementErrorInternal(err)
}
- return &DeleteFederatedCredentialOutput{
+ return &handlerutil.Out[base.MessageResponse]{
Body: base.ApiResponse[base.MessageResponse]{
Success: true,
Data: base.MessageResponse{
diff --git a/backend/internal/federated/service.go b/backend/internal/federated/service.go
index 9b1a8a910..680002baf 100644
--- a/backend/internal/federated/service.go
+++ b/backend/internal/federated/service.go
@@ -570,7 +570,7 @@ func unverifiedTokenExchangeMetadataInternal(rawToken string) (string, string, [
if claims == nil {
return "", "", nil
}
- return stringClaimByPathInternal(claims, "iss"), stringClaimByPathInternal(claims, "sub"), stringSliceClaimInternal(claims, "aud")
+ return stringClaimByPathInternal(claims, "iss"), stringClaimByPathInternal(claims, "sub"), utils.UniqueNonEmptyStrings(jwtclaims.StringSliceFromValue(jwtclaims.GetByPath(claims, "aud").OrEmpty()))
}
func stringClaimByPathInternal(claims map[string]any, path string) string {
@@ -581,32 +581,6 @@ func stringClaimByPathInternal(claims map[string]any, path string) string {
return utils.ToString(value)
}
-func stringSliceClaimInternal(claims map[string]any, path string) []string {
- value, ok := jwtclaims.GetByPath(claims, path).Get()
- if !ok || value == nil {
- return nil
- }
- switch typed := value.(type) {
- case string:
- if strings.TrimSpace(typed) == "" {
- return nil
- }
- return []string{strings.TrimSpace(typed)}
- case []string:
- return utils.UniqueNonEmptyStrings(typed)
- case []any:
- out := make([]string, 0, len(typed))
- for _, item := range typed {
- if value := utils.ToString(item); value != "" {
- out = append(out, value)
- }
- }
- return utils.UniqueNonEmptyStrings(out)
- default:
- return nil
- }
-}
-
func normalizeCreateFederatedCredentialInternal(req federatedtypes.CreateFederatedCredential) (federatedtypes.CreateFederatedCredential, error) {
req.Name = strings.TrimSpace(req.Name)
req.IssuerURL = strings.TrimRight(strings.TrimSpace(req.IssuerURL), "/")
diff --git a/backend/internal/gitops/handler.go b/backend/internal/gitops/handler.go
index 1cce0f459..444165fdf 100644
--- a/backend/internal/gitops/handler.go
+++ b/backend/internal/gitops/handler.go
@@ -43,75 +43,43 @@ type CreateGitOpsSyncInput struct {
Body gitops.CreateSyncRequest
}
-type CreateGitOpsSyncOutput struct {
- Body base.ApiResponse[gitops.GitOpsSync]
-}
-
type GetGitOpsSyncInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
SyncID string `path:"syncId" doc:"Sync ID"`
}
-type GetGitOpsSyncOutput struct {
- Body base.ApiResponse[gitops.GitOpsSync]
-}
-
type UpdateGitOpsSyncInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
SyncID string `path:"syncId" doc:"Sync ID"`
Body gitops.UpdateSyncRequest
}
-type UpdateGitOpsSyncOutput struct {
- Body base.ApiResponse[gitops.GitOpsSync]
-}
-
type DeleteGitOpsSyncInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
SyncID string `path:"syncId" doc:"Sync ID"`
}
-type DeleteGitOpsSyncOutput struct {
- Body base.ApiResponse[base.MessageResponse]
-}
-
type PerformSyncInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
SyncID string `path:"syncId" doc:"Sync ID"`
}
-type PerformSyncOutput struct {
- Body base.ApiResponse[gitops.SyncResult]
-}
-
type GetSyncStatusInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
SyncID string `path:"syncId" doc:"Sync ID"`
}
-type GetSyncStatusOutput struct {
- Body base.ApiResponse[gitops.SyncStatus]
-}
-
type BrowseSyncFilesInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
SyncID string `path:"syncId" doc:"Sync ID"`
Path string `query:"path" doc:"Path to browse (optional)"`
}
-type BrowseSyncFilesOutput struct {
- Body base.ApiResponse[gitops.BrowseResponse]
-}
-
type ImportGitOpsSyncsInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
Body []gitops.ImportGitOpsSyncRequest
}
-type ImportGitOpsSyncsOutput struct {
- Body base.ApiResponse[gitops.ImportGitOpsSyncResponse]
-}
-
// ============================================================================
// Registration
// ============================================================================
@@ -177,7 +145,7 @@ func (h *GitOpsSyncHandler) ListSyncs(ctx context.Context, input *ListGitOpsSync
}
// CreateSync creates a new GitOps sync.
-func (h *GitOpsSyncHandler) CreateSync(ctx context.Context, input *CreateGitOpsSyncInput) (*CreateGitOpsSyncOutput, error) {
+func (h *GitOpsSyncHandler) CreateSync(ctx context.Context, input *CreateGitOpsSyncInput) (*handlerutil.Out[gitops.GitOpsSync], error) {
if err := requireLifecyclePermissionInternal(ctx, input.EnvironmentID, input.Body.HasPreDeployConfig()); err != nil {
return nil, err
}
@@ -197,13 +165,13 @@ func (h *GitOpsSyncHandler) CreateSync(ctx context.Context, input *CreateGitOpsS
return nil, mapErr
}
- return &CreateGitOpsSyncOutput{
+ return &handlerutil.Out[gitops.GitOpsSync]{
Body: body,
}, nil
}
// ImportSyncs imports multiple GitOps syncs.
-func (h *GitOpsSyncHandler) ImportSyncs(ctx context.Context, input *ImportGitOpsSyncsInput) (*ImportGitOpsSyncsOutput, error) {
+func (h *GitOpsSyncHandler) ImportSyncs(ctx context.Context, input *ImportGitOpsSyncsInput) (*handlerutil.Out[gitops.ImportGitOpsSyncResponse], error) {
actor := handlerutil.CurrentActor(ctx)
response, err := h.syncService.ImportSyncs(ctx, input.EnvironmentID, input.Body, actor)
@@ -211,7 +179,7 @@ func (h *GitOpsSyncHandler) ImportSyncs(ctx context.Context, input *ImportGitOps
return nil, huma.Error500InternalServerError(err.Error())
}
- return &ImportGitOpsSyncsOutput{
+ return &handlerutil.Out[gitops.ImportGitOpsSyncResponse]{
Body: base.ApiResponse[gitops.ImportGitOpsSyncResponse]{
Success: true,
Data: *response,
@@ -220,7 +188,7 @@ func (h *GitOpsSyncHandler) ImportSyncs(ctx context.Context, input *ImportGitOps
}
// GetSync returns a GitOps sync by ID.
-func (h *GitOpsSyncHandler) GetSync(ctx context.Context, input *GetGitOpsSyncInput) (*GetGitOpsSyncOutput, error) {
+func (h *GitOpsSyncHandler) GetSync(ctx context.Context, input *GetGitOpsSyncInput) (*handlerutil.Out[gitops.GitOpsSync], error) {
sync, err := h.syncService.GetSyncByID(ctx, input.EnvironmentID, input.SyncID)
if err != nil {
apiErr := common.ToAPIError(err)
@@ -234,13 +202,13 @@ func (h *GitOpsSyncHandler) GetSync(ctx context.Context, input *GetGitOpsSyncInp
return nil, mapErr
}
- return &GetGitOpsSyncOutput{
+ return &handlerutil.Out[gitops.GitOpsSync]{
Body: body,
}, nil
}
// UpdateSync updates an existing GitOps sync.
-func (h *GitOpsSyncHandler) UpdateSync(ctx context.Context, input *UpdateGitOpsSyncInput) (*UpdateGitOpsSyncOutput, error) {
+func (h *GitOpsSyncHandler) UpdateSync(ctx context.Context, input *UpdateGitOpsSyncInput) (*handlerutil.Out[gitops.GitOpsSync], error) {
if err := requireLifecyclePermissionInternal(ctx, input.EnvironmentID, input.Body.HasPreDeployConfig()); err != nil {
return nil, err
}
@@ -260,13 +228,13 @@ func (h *GitOpsSyncHandler) UpdateSync(ctx context.Context, input *UpdateGitOpsS
return nil, mapErr
}
- return &UpdateGitOpsSyncOutput{
+ return &handlerutil.Out[gitops.GitOpsSync]{
Body: body,
}, nil
}
// DeleteSync deletes a GitOps sync by ID.
-func (h *GitOpsSyncHandler) DeleteSync(ctx context.Context, input *DeleteGitOpsSyncInput) (*DeleteGitOpsSyncOutput, error) {
+func (h *GitOpsSyncHandler) DeleteSync(ctx context.Context, input *DeleteGitOpsSyncInput) (*handlerutil.Out[base.MessageResponse], error) {
actor := handlerutil.CurrentActor(ctx)
if err := h.syncService.DeleteSync(ctx, input.EnvironmentID, input.SyncID, actor); err != nil {
@@ -274,7 +242,7 @@ func (h *GitOpsSyncHandler) DeleteSync(ctx context.Context, input *DeleteGitOpsS
return nil, huma.NewError(apiErr.HTTPStatus(), "Failed to delete GitOps sync")
}
- return &DeleteGitOpsSyncOutput{
+ return &handlerutil.Out[base.MessageResponse]{
Body: base.ApiResponse[base.MessageResponse]{
Success: true,
Data: base.MessageResponse{
@@ -285,7 +253,7 @@ func (h *GitOpsSyncHandler) DeleteSync(ctx context.Context, input *DeleteGitOpsS
}
// PerformSync manually triggers a sync operation.
-func (h *GitOpsSyncHandler) PerformSync(ctx context.Context, input *PerformSyncInput) (*PerformSyncOutput, error) {
+func (h *GitOpsSyncHandler) PerformSync(ctx context.Context, input *PerformSyncInput) (*handlerutil.Out[gitops.SyncResult], error) {
actor := handlerutil.CurrentActor(ctx)
result, err := h.syncService.PerformSync(ctx, input.EnvironmentID, input.SyncID, actor)
@@ -294,7 +262,7 @@ func (h *GitOpsSyncHandler) PerformSync(ctx context.Context, input *PerformSyncI
return nil, huma.NewError(apiErr.HTTPStatus(), "Failed to perform GitOps sync")
}
- return &PerformSyncOutput{
+ return &handlerutil.Out[gitops.SyncResult]{
Body: base.ApiResponse[gitops.SyncResult]{
Success: result.Success,
Data: *result,
@@ -303,14 +271,14 @@ func (h *GitOpsSyncHandler) PerformSync(ctx context.Context, input *PerformSyncI
}
// GetStatus returns the current status of a GitOps sync.
-func (h *GitOpsSyncHandler) GetStatus(ctx context.Context, input *GetSyncStatusInput) (*GetSyncStatusOutput, error) {
+func (h *GitOpsSyncHandler) GetStatus(ctx context.Context, input *GetSyncStatusInput) (*handlerutil.Out[gitops.SyncStatus], error) {
status, err := h.syncService.GetSyncStatus(ctx, input.EnvironmentID, input.SyncID)
if err != nil {
apiErr := common.ToAPIError(err)
return nil, huma.NewError(apiErr.HTTPStatus(), "Failed to get GitOps sync status")
}
- return &GetSyncStatusOutput{
+ return &handlerutil.Out[gitops.SyncStatus]{
Body: base.ApiResponse[gitops.SyncStatus]{
Success: true,
Data: *status,
@@ -319,14 +287,14 @@ func (h *GitOpsSyncHandler) GetStatus(ctx context.Context, input *GetSyncStatusI
}
// BrowseFiles returns the file tree at the specified path in the repository.
-func (h *GitOpsSyncHandler) BrowseFiles(ctx context.Context, input *BrowseSyncFilesInput) (*BrowseSyncFilesOutput, error) {
+func (h *GitOpsSyncHandler) BrowseFiles(ctx context.Context, input *BrowseSyncFilesInput) (*handlerutil.Out[gitops.BrowseResponse], error) {
response, err := h.syncService.BrowseFiles(ctx, input.EnvironmentID, input.SyncID, input.Path)
if err != nil {
apiErr := common.ToAPIError(err)
return nil, huma.NewError(apiErr.HTTPStatus(), "Failed to browse GitOps sync files")
}
- return &BrowseSyncFilesOutput{
+ return &handlerutil.Out[gitops.BrowseResponse]{
Body: base.ApiResponse[gitops.BrowseResponse]{
Success: true,
Data: *response,
diff --git a/backend/internal/gitrepo/handler.go b/backend/internal/gitrepo/handler.go
index 306cf0666..dfc05ac5b 100644
--- a/backend/internal/gitrepo/handler.go
+++ b/backend/internal/gitrepo/handler.go
@@ -30,78 +30,42 @@ type ListGitRepositoriesInput struct {
Limit int `query:"limit" default:"20" doc:"Items per page"`
}
-type ListGitRepositoriesOutput struct {
- Body base.Paginated[gitops.GitRepository]
-}
-
type CreateGitRepositoryInput struct {
Body CreateGitRepositoryRequest
}
-type CreateGitRepositoryOutput struct {
- Body base.ApiResponse[gitops.GitRepository]
-}
-
type GetGitRepositoryInput struct {
ID string `path:"id" doc:"Repository ID"`
}
-type GetGitRepositoryOutput struct {
- Body base.ApiResponse[gitops.GitRepository]
-}
-
type UpdateGitRepositoryInput struct {
ID string `path:"id" doc:"Repository ID"`
Body UpdateGitRepositoryRequest
}
-type UpdateGitRepositoryOutput struct {
- Body base.ApiResponse[gitops.GitRepository]
-}
-
type DeleteGitRepositoryInput struct {
ID string `path:"id" doc:"Repository ID"`
}
-type DeleteGitRepositoryOutput struct {
- Body base.ApiResponse[base.MessageResponse]
-}
-
type TestGitRepositoryInput struct {
ID string `path:"id" doc:"Repository ID"`
Branch string `query:"branch" doc:"Branch to test (optional, uses repository default branch when omitted)"`
}
-type TestGitRepositoryOutput struct {
- Body base.ApiResponse[base.MessageResponse]
-}
-
type ListBranchesInput struct {
ID string `path:"id" doc:"Repository ID"`
}
-type ListBranchesOutput struct {
- Body base.ApiResponse[gitops.BranchesResponse]
-}
-
type BrowseFilesInput struct {
ID string `path:"id" doc:"Repository ID"`
Branch string `query:"branch" doc:"Branch to browse"`
Path string `query:"path" doc:"Path within repository (optional)"`
}
-type BrowseFilesOutput struct {
- Body base.ApiResponse[gitops.BrowseResponse]
-}
-
type SyncGitRepositoriesInput struct {
Body gitops.RepositorySyncRequest
}
-type SyncGitRepositoriesOutput struct {
- Body base.ApiResponse[base.MessageResponse]
-}
-
// ============================================================================
// Registration
// ============================================================================
@@ -126,7 +90,7 @@ func RegisterGitRepositories(api huma.API, repoService *GitRepositoryService) {
// ============================================================================
// ListRepositories returns a paginated list of git repositories.
-func (h *GitRepositoryHandler) ListRepositories(ctx context.Context, input *ListGitRepositoriesInput) (*ListGitRepositoriesOutput, error) {
+func (h *GitRepositoryHandler) ListRepositories(ctx context.Context, input *ListGitRepositoriesInput) (*handlerutil.Page[gitops.GitRepository], error) {
params := handlerutil.PaginationParams(input.Start, input.Limit, input.Sort, input.Order, input.Search)
repositories, paginationResp, err := h.repoService.GetRepositoriesPaginated(ctx, params)
@@ -134,7 +98,7 @@ func (h *GitRepositoryHandler) ListRepositories(ctx context.Context, input *List
return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to list git repositories").Error())
}
- return &ListGitRepositoriesOutput{
+ return &handlerutil.Page[gitops.GitRepository]{
Body: base.Paginated[gitops.GitRepository]{
Success: true,
Data: repositories,
@@ -144,7 +108,7 @@ func (h *GitRepositoryHandler) ListRepositories(ctx context.Context, input *List
}
// CreateRepository creates a new git repository.
-func (h *GitRepositoryHandler) CreateRepository(ctx context.Context, input *CreateGitRepositoryInput) (*CreateGitRepositoryOutput, error) {
+func (h *GitRepositoryHandler) CreateRepository(ctx context.Context, input *CreateGitRepositoryInput) (*handlerutil.Out[gitops.GitRepository], error) {
actor := handlerutil.CurrentActor(ctx)
repo, err := h.repoService.CreateRepository(ctx, input.Body, actor)
@@ -160,13 +124,13 @@ func (h *GitRepositoryHandler) CreateRepository(ctx context.Context, input *Crea
return nil, mapErr
}
- return &CreateGitRepositoryOutput{
+ return &handlerutil.Out[gitops.GitRepository]{
Body: body,
}, nil
}
// GetRepository returns a git repository by ID.
-func (h *GitRepositoryHandler) GetRepository(ctx context.Context, input *GetGitRepositoryInput) (*GetGitRepositoryOutput, error) {
+func (h *GitRepositoryHandler) GetRepository(ctx context.Context, input *GetGitRepositoryInput) (*handlerutil.Out[gitops.GitRepository], error) {
repo, err := h.repoService.GetRepositoryByID(ctx, input.ID)
if err != nil {
apiErr := common.ToAPIError(err)
@@ -180,13 +144,13 @@ func (h *GitRepositoryHandler) GetRepository(ctx context.Context, input *GetGitR
return nil, mapErr
}
- return &GetGitRepositoryOutput{
+ return &handlerutil.Out[gitops.GitRepository]{
Body: body,
}, nil
}
// UpdateRepository updates an existing git repository.
-func (h *GitRepositoryHandler) UpdateRepository(ctx context.Context, input *UpdateGitRepositoryInput) (*UpdateGitRepositoryOutput, error) {
+func (h *GitRepositoryHandler) UpdateRepository(ctx context.Context, input *UpdateGitRepositoryInput) (*handlerutil.Out[gitops.GitRepository], error) {
actor := handlerutil.CurrentActor(ctx)
repo, err := h.repoService.UpdateRepository(ctx, input.ID, input.Body, actor)
@@ -202,13 +166,13 @@ func (h *GitRepositoryHandler) UpdateRepository(ctx context.Context, input *Upda
return nil, mapErr
}
- return &UpdateGitRepositoryOutput{
+ return &handlerutil.Out[gitops.GitRepository]{
Body: body,
}, nil
}
// DeleteRepository deletes a git repository by ID.
-func (h *GitRepositoryHandler) DeleteRepository(ctx context.Context, input *DeleteGitRepositoryInput) (*DeleteGitRepositoryOutput, error) {
+func (h *GitRepositoryHandler) DeleteRepository(ctx context.Context, input *DeleteGitRepositoryInput) (*handlerutil.Out[base.MessageResponse], error) {
actor := handlerutil.CurrentActor(ctx)
if err := h.repoService.DeleteRepository(ctx, input.ID, actor); err != nil {
@@ -216,7 +180,7 @@ func (h *GitRepositoryHandler) DeleteRepository(ctx context.Context, input *Dele
return nil, huma.NewError(apiErr.HTTPStatus(), "Failed to delete git repository")
}
- return &DeleteGitRepositoryOutput{
+ return &handlerutil.Out[base.MessageResponse]{
Body: base.ApiResponse[base.MessageResponse]{
Success: true,
Data: base.MessageResponse{
@@ -227,14 +191,14 @@ func (h *GitRepositoryHandler) DeleteRepository(ctx context.Context, input *Dele
}
// TestRepository tests connectivity and authentication to a git repository.
-func (h *GitRepositoryHandler) TestRepository(ctx context.Context, input *TestGitRepositoryInput) (*TestGitRepositoryOutput, error) {
+func (h *GitRepositoryHandler) TestRepository(ctx context.Context, input *TestGitRepositoryInput) (*handlerutil.Out[base.MessageResponse], error) {
actor := handlerutil.CurrentActor(ctx)
if err := h.repoService.TestConnection(ctx, input.ID, input.Branch, actor); err != nil {
return nil, huma.Error400BadRequest(errors.WithMessage(err, "Failed to test git repository connection").Error())
}
- return &TestGitRepositoryOutput{
+ return &handlerutil.Out[base.MessageResponse]{
Body: base.ApiResponse[base.MessageResponse]{
Success: true,
Data: base.MessageResponse{
@@ -245,13 +209,13 @@ func (h *GitRepositoryHandler) TestRepository(ctx context.Context, input *TestGi
}
// ListBranches returns all branches from a git repository.
-func (h *GitRepositoryHandler) ListBranches(ctx context.Context, input *ListBranchesInput) (*ListBranchesOutput, error) {
+func (h *GitRepositoryHandler) ListBranches(ctx context.Context, input *ListBranchesInput) (*handlerutil.Out[gitops.BranchesResponse], error) {
branches, err := h.repoService.ListBranches(ctx, input.ID)
if err != nil {
return nil, huma.Error400BadRequest(errors.WithMessage(err, "Failed to test git repository connection").Error())
}
- return &ListBranchesOutput{
+ return &handlerutil.Out[gitops.BranchesResponse]{
Body: base.ApiResponse[gitops.BranchesResponse]{
Success: true,
Data: gitops.BranchesResponse{
@@ -262,7 +226,7 @@ func (h *GitRepositoryHandler) ListBranches(ctx context.Context, input *ListBran
}
// BrowseFiles returns files and directories from a git repository.
-func (h *GitRepositoryHandler) BrowseFiles(ctx context.Context, input *BrowseFilesInput) (*BrowseFilesOutput, error) {
+func (h *GitRepositoryHandler) BrowseFiles(ctx context.Context, input *BrowseFilesInput) (*handlerutil.Out[gitops.BrowseResponse], error) {
if input.Branch == "" {
return nil, huma.Error400BadRequest("branch parameter is required")
}
@@ -272,7 +236,7 @@ func (h *GitRepositoryHandler) BrowseFiles(ctx context.Context, input *BrowseFil
return nil, huma.Error400BadRequest(errors.WithMessage(err, "Failed to test git repository connection").Error())
}
- return &BrowseFilesOutput{
+ return &handlerutil.Out[gitops.BrowseResponse]{
Body: base.ApiResponse[gitops.BrowseResponse]{
Success: true,
Data: *result,
@@ -281,13 +245,13 @@ func (h *GitRepositoryHandler) BrowseFiles(ctx context.Context, input *BrowseFil
}
// SyncRepositories syncs git repositories from a manager to this agent instance.
-func (h *GitRepositoryHandler) SyncRepositories(ctx context.Context, input *SyncGitRepositoriesInput) (*SyncGitRepositoriesOutput, error) {
+func (h *GitRepositoryHandler) SyncRepositories(ctx context.Context, input *SyncGitRepositoriesInput) (*handlerutil.Out[base.MessageResponse], error) {
if err := h.repoService.SyncRepositories(ctx, input.Body.Repositories); err != nil {
apiErr := common.ToAPIError(err)
return nil, huma.NewError(apiErr.HTTPStatus(), errors.WithMessage(err, "Failed to sync git repositories").Error())
}
- return &SyncGitRepositoriesOutput{
+ return &handlerutil.Out[base.MessageResponse]{
Body: base.ApiResponse[base.MessageResponse]{
Success: true,
Data: base.MessageResponse{
diff --git a/backend/internal/gitrepo/service.go b/backend/internal/gitrepo/service.go
index f2effd09a..466e63771 100644
--- a/backend/internal/gitrepo/service.go
+++ b/backend/internal/gitrepo/service.go
@@ -50,7 +50,7 @@ func (s *GitRepositoryService) GetRepositoriesPaginated(ctx context.Context, par
q = pagination.ApplyBooleanFilter(q, "enabled", params.Filters["enabled"])
q = pagination.ApplyFilter(q, "auth_type", params.Filters["authType"])
- out, paginationResp, err := pagination.PaginateSortAndMapDB[GitRepository, gitops.GitRepository](params, q, &repositories)
+ out, paginationResp, err := params.PaginateSortAndMapDB[GitRepository, gitops.GitRepository](q, &repositories)
if err != nil {
return nil, pagination.Response{}, errors.WrapIf(err, "failed to list git repositories")
}
diff --git a/backend/internal/image/handler.go b/backend/internal/image/handler.go
index 5350aafde..66a72a8de 100644
--- a/backend/internal/image/handler.go
+++ b/backend/internal/image/handler.go
@@ -59,19 +59,11 @@ type ListImagesInput struct {
Updates string `query:"updates" doc:"Filter by update availability (true/false)"`
}
-type ListImagesOutput struct {
- Body base.Paginated[image.Summary]
-}
-
type GetImageInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
ImageID string `path:"imageId" doc:"Image ID"`
}
-type GetImageOutput struct {
- Body base.ApiResponse[image.DetailSummary]
-}
-
type GetImageAttestationsInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
ImageName string `path:"name" doc:"Image ID or image reference"`
@@ -80,38 +72,22 @@ type GetImageAttestationsInput struct {
WithStatement bool `query:"statement" default:"false" doc:"Include verbatim statement JSON bodies"`
}
-type GetImageAttestationsOutput struct {
- Body base.ApiResponse[image.AttestationList]
-}
-
type TagImageInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
ImageName string `path:"name" doc:"Image ID or image reference"`
Body image.TagRequest
}
-type TagImageOutput struct {
- Body base.ApiResponse[base.MessageResponse]
-}
-
type GetImageHistoryInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
ImageName string `path:"name" doc:"Image ID or image reference"`
}
-type GetImageHistoryOutput struct {
- Body base.ApiResponse[[]image.HistoryItem]
-}
-
type SearchImagesInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
Term string `query:"term" doc:"Search term"`
}
-type SearchImagesOutput struct {
- Body base.ApiResponse[[]image.SearchResult]
-}
-
type ExportImageInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
ImageName string `path:"name" doc:"Image ID or image reference"`
@@ -123,10 +99,6 @@ type RemoveImageInput struct {
Force bool `query:"force" doc:"Force removal"`
}
-type RemoveImageOutput struct {
- Body base.ApiResponse[base.MessageResponse]
-}
-
type PullImageInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
Body image.PullOptions
@@ -148,19 +120,11 @@ type ListImageBuildsInput struct {
Provider string `query:"provider" doc:"Filter by provider"`
}
-type ListImageBuildsOutput struct {
- Body base.Paginated[image.BuildRecord]
-}
-
type GetImageBuildInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
BuildID string `path:"buildId" doc:"Build ID"`
}
-type GetImageBuildOutput struct {
- Body base.ApiResponse[image.BuildRecord]
-}
-
type PruneImagesInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
Dangling bool `query:"dangling" doc:"Only remove dangling images"`
@@ -172,27 +136,15 @@ type PruneImagesInput struct {
}
}
-type PruneImagesOutput struct {
- Body base.ApiResponse[image.PruneReport]
-}
-
type GetImageUsageCountsInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
}
-type GetImageUsageCountsOutput struct {
- Body base.ApiResponse[image.UsageCounts]
-}
-
type UploadImageInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
Body uploadtypes.ConsumeRequest
}
-type UploadImageOutput struct {
- Body base.ApiResponse[image.LoadResult]
-}
-
// RegisterImages registers image management routes using Huma.
func RegisterImages(api huma.API, dockerService *docker.DockerClientService, imageService *ImageService, imageUpdateService *imageupdate.ImageUpdateService, settingsService *settings.SettingsService, buildService *build.BuildService, activityService *activity.ActivityService, uploadService *upload.UploadService, appCtx handlerutil.ActivityAppContext) {
h := &ImageHandler{
@@ -359,7 +311,7 @@ func RegisterImages(api huma.API, dockerService *docker.DockerClientService, ima
}
// ListImages returns a paginated list of images.
-func (h *ImageHandler) ListImages(ctx context.Context, input *ListImagesInput) (*ListImagesOutput, error) {
+func (h *ImageHandler) ListImages(ctx context.Context, input *ListImagesInput) (*handlerutil.Page[image.Summary], error) {
params := handlerutil.PaginationParams(input.Start, input.Limit, input.Sort, input.Order, input.Search)
if input.InUse != "" {
params.Filters["inUse"] = input.InUse
@@ -381,7 +333,7 @@ func (h *ImageHandler) ListImages(ctx context.Context, input *ListImagesInput) (
images = []image.Summary{}
}
- return &ListImagesOutput{
+ return &handlerutil.Page[image.Summary]{
Body: base.Paginated[image.Summary]{
Success: true,
Data: images,
@@ -391,13 +343,13 @@ func (h *ImageHandler) ListImages(ctx context.Context, input *ListImagesInput) (
}
// GetImage returns an image by ID.
-func (h *ImageHandler) GetImage(ctx context.Context, input *GetImageInput) (*GetImageOutput, error) {
+func (h *ImageHandler) GetImage(ctx context.Context, input *GetImageInput) (*handlerutil.Out[image.DetailSummary], error) {
out, err := h.imageService.GetImageDetail(ctx, input.ImageID)
if err != nil {
return nil, huma.Error404NotFound(errors.WithMessage(err, "Image not found").Error())
}
- return &GetImageOutput{
+ return &handlerutil.Out[image.DetailSummary]{
Body: base.ApiResponse[image.DetailSummary]{
Success: true,
Data: *out,
@@ -406,7 +358,7 @@ func (h *ImageHandler) GetImage(ctx context.Context, input *GetImageInput) (*Get
}
// GetImageAttestations returns in-toto attestation statements attached to an image.
-func (h *ImageHandler) GetImageAttestations(ctx context.Context, input *GetImageAttestationsInput) (*GetImageAttestationsOutput, error) {
+func (h *ImageHandler) GetImageAttestations(ctx context.Context, input *GetImageAttestationsInput) (*handlerutil.Out[image.AttestationList], error) {
imageName, err := validateImageNameInternal(input.ImageName)
if err != nil {
return nil, err
@@ -427,7 +379,7 @@ func (h *ImageHandler) GetImageAttestations(ctx context.Context, input *GetImage
return nil, huma.Error500InternalServerError(fmt.Sprintf("failed to get image attestations: %v", err))
}
- return &GetImageAttestationsOutput{
+ return &handlerutil.Out[image.AttestationList]{
Body: base.ApiResponse[image.AttestationList]{
Success: true,
Data: *out,
@@ -436,7 +388,7 @@ func (h *ImageHandler) GetImageAttestations(ctx context.Context, input *GetImage
}
// TagImage adds a repository tag to an image.
-func (h *ImageHandler) TagImage(ctx context.Context, input *TagImageInput) (*TagImageOutput, error) {
+func (h *ImageHandler) TagImage(ctx context.Context, input *TagImageInput) (*handlerutil.Out[base.MessageResponse], error) {
imageName, err := validateImageNameInternal(input.ImageName)
if err != nil {
return nil, err
@@ -454,7 +406,7 @@ func (h *ImageHandler) TagImage(ctx context.Context, input *TagImageInput) (*Tag
return nil, huma.Error500InternalServerError(fmt.Sprintf("failed to tag image: %v", err))
}
- return &TagImageOutput{
+ return &handlerutil.Out[base.MessageResponse]{
Body: base.ApiResponse[base.MessageResponse]{
Success: true,
Data: base.MessageResponse{Message: "Image tagged successfully"},
@@ -463,7 +415,7 @@ func (h *ImageHandler) TagImage(ctx context.Context, input *TagImageInput) (*Tag
}
// GetImageHistory returns Docker image layer history.
-func (h *ImageHandler) GetImageHistory(ctx context.Context, input *GetImageHistoryInput) (*GetImageHistoryOutput, error) {
+func (h *ImageHandler) GetImageHistory(ctx context.Context, input *GetImageHistoryInput) (*handlerutil.Out[[]image.HistoryItem], error) {
imageName, err := validateImageNameInternal(input.ImageName)
if err != nil {
return nil, err
@@ -477,7 +429,7 @@ func (h *ImageHandler) GetImageHistory(ctx context.Context, input *GetImageHisto
history = []image.HistoryItem{}
}
- return &GetImageHistoryOutput{
+ return &handlerutil.Out[[]image.HistoryItem]{
Body: base.ApiResponse[[]image.HistoryItem]{
Success: true,
Data: history,
@@ -486,7 +438,7 @@ func (h *ImageHandler) GetImageHistory(ctx context.Context, input *GetImageHisto
}
// SearchImages searches Docker Hub images.
-func (h *ImageHandler) SearchImages(ctx context.Context, input *SearchImagesInput) (*SearchImagesOutput, error) {
+func (h *ImageHandler) SearchImages(ctx context.Context, input *SearchImagesInput) (*handlerutil.Out[[]image.SearchResult], error) {
results, err := h.imageService.SearchImages(ctx, input.Term)
if err != nil {
if strings.Contains(err.Error(), "term is required") {
@@ -498,7 +450,7 @@ func (h *ImageHandler) SearchImages(ctx context.Context, input *SearchImagesInpu
results = []image.SearchResult{}
}
- return &SearchImagesOutput{
+ return &handlerutil.Out[[]image.SearchResult]{
Body: base.ApiResponse[[]image.SearchResult]{
Success: true,
Data: results,
@@ -548,7 +500,7 @@ func imageExportFileNameInternal(imageName string) string {
}
// RemoveImage removes a Docker image.
-func (h *ImageHandler) RemoveImage(ctx context.Context, input *RemoveImageInput) (*RemoveImageOutput, error) {
+func (h *ImageHandler) RemoveImage(ctx context.Context, input *RemoveImageInput) (*handlerutil.Out[base.MessageResponse], error) {
user, err := handlerutil.RequireUser(ctx)
if err != nil {
return nil, err
@@ -558,7 +510,7 @@ func (h *ImageHandler) RemoveImage(ctx context.Context, input *RemoveImageInput)
return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to remove image").Error())
}
- return &RemoveImageOutput{
+ return &handlerutil.Out[base.MessageResponse]{
Body: base.ApiResponse[base.MessageResponse]{
Success: true,
Data: base.MessageResponse{
@@ -685,7 +637,7 @@ func (h *ImageHandler) BuildImage(ctx context.Context, input *BuildImageInput) (
}
// ListImageBuilds returns a paginated list of image build history entries.
-func (h *ImageHandler) ListImageBuilds(ctx context.Context, input *ListImageBuildsInput) (*ListImageBuildsOutput, error) {
+func (h *ImageHandler) ListImageBuilds(ctx context.Context, input *ListImageBuildsInput) (*handlerutil.Page[image.BuildRecord], error) {
if input.EnvironmentID == "" {
return nil, huma.Error400BadRequest("Environment ID is required")
}
@@ -707,7 +659,7 @@ func (h *ImageHandler) ListImageBuilds(ctx context.Context, input *ListImageBuil
builds = []image.BuildRecord{}
}
- return &ListImageBuildsOutput{
+ return &handlerutil.Page[image.BuildRecord]{
Body: base.Paginated[image.BuildRecord]{
Success: true,
Data: builds,
@@ -717,7 +669,7 @@ func (h *ImageHandler) ListImageBuilds(ctx context.Context, input *ListImageBuil
}
// GetImageBuild returns a single build history entry.
-func (h *ImageHandler) GetImageBuild(ctx context.Context, input *GetImageBuildInput) (*GetImageBuildOutput, error) {
+func (h *ImageHandler) GetImageBuild(ctx context.Context, input *GetImageBuildInput) (*handlerutil.Out[image.BuildRecord], error) {
if input.EnvironmentID == "" {
return nil, huma.Error400BadRequest("Environment ID is required")
}
@@ -734,7 +686,7 @@ func (h *ImageHandler) GetImageBuild(ctx context.Context, input *GetImageBuildIn
return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to retrieve build history").Error())
}
- return &GetImageBuildOutput{
+ return &handlerutil.Out[image.BuildRecord]{
Body: base.ApiResponse[image.BuildRecord]{
Success: true,
Data: *buildRecord,
@@ -743,7 +695,7 @@ func (h *ImageHandler) GetImageBuild(ctx context.Context, input *GetImageBuildIn
}
// PruneImages removes unused Docker images.
-func (h *ImageHandler) PruneImages(ctx context.Context, input *PruneImagesInput) (*PruneImagesOutput, error) {
+func (h *ImageHandler) PruneImages(ctx context.Context, input *PruneImagesInput) (*handlerutil.Out[image.PruneReport], error) {
mode := resolvePruneImageModeInternal(input)
until := resolvePruneImageUntilInternal(input)
@@ -757,7 +709,7 @@ func (h *ImageHandler) PruneImages(ctx context.Context, input *PruneImagesInput)
out := image.NewPruneReport(*report)
- return &PruneImagesOutput{
+ return &handlerutil.Out[image.PruneReport]{
Body: base.ApiResponse[image.PruneReport]{
Success: true,
Data: out,
@@ -818,13 +770,13 @@ func resolveLegacyPruneImageModeInternal(dangling bool) string {
}
// GetImageUsageCounts returns counts of images by usage status.
-func (h *ImageHandler) GetImageUsageCounts(ctx context.Context, input *GetImageUsageCountsInput) (*GetImageUsageCountsOutput, error) {
+func (h *ImageHandler) GetImageUsageCounts(ctx context.Context, input *GetImageUsageCountsInput) (*handlerutil.Out[image.UsageCounts], error) {
_, counts, err := h.dockerService.GetAllImages(ctx)
if err != nil {
return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to get image usage counts").Error())
}
- return &GetImageUsageCountsOutput{
+ return &handlerutil.Out[image.UsageCounts]{
Body: base.ApiResponse[image.UsageCounts]{
Success: true,
Data: counts,
@@ -833,7 +785,7 @@ func (h *ImageHandler) GetImageUsageCounts(ctx context.Context, input *GetImageU
}
// UploadImage uploads a Docker image from a tar archive.
-func (h *ImageHandler) UploadImage(ctx context.Context, input *UploadImageInput) (*UploadImageOutput, error) {
+func (h *ImageHandler) UploadImage(ctx context.Context, input *UploadImageInput) (*handlerutil.Out[image.LoadResult], error) {
user, err := handlerutil.RequireUser(ctx)
if err != nil {
return nil, err
@@ -856,7 +808,7 @@ func (h *ImageHandler) UploadImage(ctx context.Context, input *UploadImageInput)
return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to load image").Error())
}
- return &UploadImageOutput{
+ return &handlerutil.Out[image.LoadResult]{
Body: base.ApiResponse[image.LoadResult]{
Success: true,
Data: *result,
diff --git a/backend/internal/image/image.go b/backend/internal/image/image.go
index 97d082c7b..d0e23229b 100644
--- a/backend/internal/image/image.go
+++ b/backend/internal/image/image.go
@@ -750,7 +750,7 @@ func (s *ImageService) ListImagesPaginated(ctx context.Context, params paginatio
config := s.getImagePaginationConfig()
- result := pagination.SearchOrderAndPaginate(items, params, config)
+ result := config.SearchOrderAndPaginate(items, params)
if s.vulnerabilityService != nil && len(result.Items) > 0 {
pageImageIDs := getImageIDsFromSummariesInternal(result.Items)
diff --git a/backend/internal/imagepatch/handler.go b/backend/internal/imagepatch/handler.go
index fcbe7063e..69c71c163 100644
--- a/backend/internal/imagepatch/handler.go
+++ b/backend/internal/imagepatch/handler.go
@@ -7,7 +7,6 @@ import (
"emperror.dev/errors"
"github.com/danielgtaylor/huma/v2"
"github.com/getarcaneapp/arcane/backend/v2/internal/common"
- "github.com/getarcaneapp/arcane/backend/v2/internal/middleware"
"github.com/getarcaneapp/arcane/backend/v2/pkg/authz"
"github.com/getarcaneapp/arcane/backend/v2/pkg/utils"
"github.com/getarcaneapp/arcane/backend/v2/pkg/utils/handlerutil"
@@ -27,10 +26,6 @@ type PatchImageInput struct {
Body imagepatch.PatchOptions
}
-type PatchImageOutput struct {
- Body base.ApiResponse[imagepatch.PatchRecord]
-}
-
type ListPatchTargetsInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
Search string `query:"search" doc:"Search query"`
@@ -40,10 +35,6 @@ type ListPatchTargetsInput struct {
Limit int `query:"limit" default:"20" doc:"Limit"`
}
-type ListPatchTargetsOutput struct {
- Body base.Paginated[imagepatch.PatchTarget]
-}
-
type ListImagePatchesInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
Search string `query:"search" doc:"Search query"`
@@ -54,10 +45,6 @@ type ListImagePatchesInput struct {
Status string `query:"status" doc:"Filter by patch status"`
}
-type ListImagePatchesOutput struct {
- Body base.Paginated[imagepatch.PatchRecord]
-}
-
// RegisterImagePatches registers image patching routes using Huma.
func RegisterImagePatches(api huma.API, imagePatchService *ImagePatchService, appCtx handlerutil.ActivityAppContext) {
h := &ImagePatchHandler{
@@ -65,39 +52,19 @@ func RegisterImagePatches(api huma.API, imagePatchService *ImagePatchService, ap
appCtx: appCtx.Context(),
}
- middleware.RegisterWithPermission(api, huma.Operation{
- OperationID: "list-image-patches",
- Method: http.MethodGet,
- Path: "/environments/{id}/images/patches",
- Summary: "List image patches",
- Description: "Retrieves the paginated image patch history for the environment",
- Tags: []string{"Images"},
- Security: handlerutil.DefaultOperationSecurity(),
- }, authz.PermImagesList, h.ListImagePatches)
-
- middleware.RegisterWithPermission(api, huma.Operation{
- OperationID: "list-image-patch-targets",
- Method: http.MethodGet,
- Path: "/environments/{id}/images/patch-targets",
- Summary: "List image patch targets",
- Description: "Retrieves scanned images with fixable vulnerability counts and their latest patch run",
- Tags: []string{"Images"},
- Security: handlerutil.DefaultOperationSecurity(),
- }, authz.PermVulnsRead, h.ListPatchTargets)
-
- middleware.RegisterWithPermission(api, huma.Operation{
- OperationID: "patch-image",
- Method: http.MethodPost,
- Path: "/environments/{id}/images/{imageId}/patch",
- Summary: "Patch image",
- Description: "Patches OS package vulnerabilities in the image using Copacetic, producing a new patched tag",
- Tags: []string{"Images"},
- Security: handlerutil.DefaultOperationSecurity(),
- }, authz.PermImagesPatch, h.PatchImage)
+ handlerutil.RegisterSecured(api,
+ handlerutil.Operation("list-image-patches", http.MethodGet, "/environments/{id}/images/patches", "List image patches", "Retrieves the paginated image patch history for the environment", "Images"),
+ authz.PermImagesList, h.ListImagePatches)
+ handlerutil.RegisterSecured(api,
+ handlerutil.Operation("list-image-patch-targets", http.MethodGet, "/environments/{id}/images/patch-targets", "List image patch targets", "Retrieves scanned images with fixable vulnerability counts and their latest patch run", "Images"),
+ authz.PermVulnsRead, h.ListPatchTargets)
+ handlerutil.RegisterSecured(api,
+ handlerutil.Operation("patch-image", http.MethodPost, "/environments/{id}/images/{imageId}/patch", "Patch image", "Patches OS package vulnerabilities in the image using Copacetic, producing a new patched tag", "Images"),
+ authz.PermImagesPatch, h.PatchImage)
}
// PatchImage starts a background patch run for an image.
-func (h *ImagePatchHandler) PatchImage(ctx context.Context, input *PatchImageInput) (*PatchImageOutput, error) {
+func (h *ImagePatchHandler) PatchImage(ctx context.Context, input *PatchImageInput) (*handlerutil.Out[imagepatch.PatchRecord], error) {
user, err := handlerutil.RequireUser(ctx)
if err != nil {
return nil, err
@@ -116,7 +83,7 @@ func (h *ImagePatchHandler) PatchImage(ctx context.Context, input *PatchImageInp
}
}
- return &PatchImageOutput{
+ return &handlerutil.Out[imagepatch.PatchRecord]{
Body: base.ApiResponse[imagepatch.PatchRecord]{
Success: true,
Data: *record,
@@ -125,7 +92,7 @@ func (h *ImagePatchHandler) PatchImage(ctx context.Context, input *PatchImageInp
}
// ListPatchTargets returns scanned images with fixable counts and latest patch runs.
-func (h *ImagePatchHandler) ListPatchTargets(ctx context.Context, input *ListPatchTargetsInput) (*ListPatchTargetsOutput, error) {
+func (h *ImagePatchHandler) ListPatchTargets(ctx context.Context, input *ListPatchTargetsInput) (*handlerutil.Page[imagepatch.PatchTarget], error) {
params := handlerutil.PaginationParams(input.Start, input.Limit, input.Sort, input.Order, input.Search)
targets, paginationResp, err := h.imagePatchService.ListPatchTargets(ctx, input.EnvironmentID, params)
@@ -136,7 +103,7 @@ func (h *ImagePatchHandler) ListPatchTargets(ctx context.Context, input *ListPat
targets = []imagepatch.PatchTarget{}
}
- return &ListPatchTargetsOutput{
+ return &handlerutil.Page[imagepatch.PatchTarget]{
Body: base.Paginated[imagepatch.PatchTarget]{
Success: true,
Data: targets,
@@ -146,7 +113,7 @@ func (h *ImagePatchHandler) ListPatchTargets(ctx context.Context, input *ListPat
}
// ListImagePatches returns the paginated patch history for the environment.
-func (h *ImagePatchHandler) ListImagePatches(ctx context.Context, input *ListImagePatchesInput) (*ListImagePatchesOutput, error) {
+func (h *ImagePatchHandler) ListImagePatches(ctx context.Context, input *ListImagePatchesInput) (*handlerutil.Page[imagepatch.PatchRecord], error) {
params := handlerutil.PaginationParams(input.Start, input.Limit, input.Sort, input.Order, input.Search)
if input.Status != "" {
params.Filters["status"] = input.Status
@@ -160,7 +127,7 @@ func (h *ImagePatchHandler) ListImagePatches(ctx context.Context, input *ListIma
records = []imagepatch.PatchRecord{}
}
- return &ListImagePatchesOutput{
+ return &handlerutil.Page[imagepatch.PatchRecord]{
Body: base.Paginated[imagepatch.PatchRecord]{
Success: true,
Data: records,
diff --git a/backend/internal/imagepatch/imagepatch.go b/backend/internal/imagepatch/imagepatch.go
index e31650d8d..65bfcf79c 100644
--- a/backend/internal/imagepatch/imagepatch.go
+++ b/backend/internal/imagepatch/imagepatch.go
@@ -2,7 +2,8 @@ package imagepatch
import (
"context"
- "encoding/json"
+ "encoding/json/jsontext"
+ "encoding/json/v2"
"log/slog"
"maps"
"os"
@@ -279,7 +280,7 @@ func (s *ImagePatchService) patchInBackgroundInternal(ctx context.Context, recor
if vexOutputPath != "" {
if data, err := acfs.ReadFile(ctx, filepath.Dir(vexOutputPath), "/"+filepath.Base(vexOutputPath)); err == nil {
var doc struct {
- Statements []json.RawMessage `json:"statements"`
+ Statements []jsontext.Value `json:"statements"`
}
if err := json.Unmarshal(data, &doc); err == nil {
count := len(doc.Statements)
@@ -390,7 +391,7 @@ func (s *ImagePatchService) writeRegistryAuthConfigInternal(ctx context.Context)
}
var arcane struct {
- Auths map[string]json.RawMessage `json:"auths"`
+ Auths map[string]jsontext.Value `json:"auths"`
}
if err := json.Unmarshal(arcaneConfig, &arcane); err != nil {
return
@@ -401,7 +402,7 @@ func (s *ImagePatchService) writeRegistryAuthConfigInternal(ctx context.Context)
return
}
- merged := map[string]json.RawMessage{}
+ merged := map[string]jsontext.Value{}
if existing, err := acfs.ReadFile(ctx, configDir, "/config.json"); err == nil {
if err := json.Unmarshal(existing, &merged); err != nil {
slog.WarnContext(ctx, "existing docker config is not valid JSON; leaving it untouched", "path", configDir, "error", err)
@@ -409,10 +410,10 @@ func (s *ImagePatchService) writeRegistryAuthConfigInternal(ctx context.Context)
}
}
- auths := map[string]json.RawMessage{}
+ auths := map[string]jsontext.Value{}
if raw, ok := merged["auths"]; ok {
if err := json.Unmarshal(raw, &auths); err != nil {
- auths = map[string]json.RawMessage{}
+ auths = map[string]jsontext.Value{}
}
}
maps.Copy(auths, arcane.Auths)
diff --git a/backend/internal/imageupdate/handler.go b/backend/internal/imageupdate/handler.go
index fd8859316..786e58a27 100644
--- a/backend/internal/imageupdate/handler.go
+++ b/backend/internal/imageupdate/handler.go
@@ -27,54 +27,30 @@ type CheckImageUpdateInput struct {
ImageRef string `query:"imageRef" doc:"Image reference"`
}
-type CheckImageUpdateOutput struct {
- Body base.ApiResponse[imageupdate.Response]
-}
-
type CheckImageUpdateByIDInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
ImageID string `path:"imageId" doc:"Image ID"`
}
-type CheckImageUpdateByIDOutput struct {
- Body base.ApiResponse[imageupdate.Response]
-}
-
type CheckMultipleImagesInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
Body imageupdate.BatchImageUpdateRequest
}
-type CheckMultipleImagesOutput struct {
- Body base.ApiResponse[imageupdate.BatchResponse]
-}
-
type CheckAllImagesInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
Body imageupdate.CheckAllImagesRequest
}
-type CheckAllImagesOutput struct {
- Body base.ApiResponse[imageupdate.BatchResponse]
-}
-
type GetUpdateInfoByRefsInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
ImageRefs string `query:"imageRefs" doc:"Comma-separated image references"`
}
-type GetUpdateInfoByRefsOutput struct {
- Body base.ApiResponse[map[string]*imagetypes.UpdateInfo]
-}
-
type GetUpdateSummaryInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
}
-type GetUpdateSummaryOutput struct {
- Body base.ApiResponse[imageupdate.Summary]
-}
-
// RegisterImageUpdates registers image update endpoints.
func RegisterImageUpdates(api huma.API, imageUpdateSvc *ImageUpdateService, getUpdateInfoByImageRefs func(context.Context, []string) (map[string]*imagetypes.UpdateInfo, error), appCtx handlerutil.ActivityAppContext) {
h := &ImageUpdateHandler{
@@ -147,7 +123,7 @@ func RegisterImageUpdates(api huma.API, imageUpdateSvc *ImageUpdateService, getU
}, authz.PermImageUpdatesRead, h.GetUpdateSummary)
}
-func (h *ImageUpdateHandler) CheckImageUpdate(ctx context.Context, input *CheckImageUpdateInput) (*CheckImageUpdateOutput, error) {
+func (h *ImageUpdateHandler) CheckImageUpdate(ctx context.Context, input *CheckImageUpdateInput) (*handlerutil.Out[imageupdate.Response], error) {
if input.ImageRef == "" {
return nil, huma.Error400BadRequest("imageRef query parameter is required")
}
@@ -158,7 +134,7 @@ func (h *ImageUpdateHandler) CheckImageUpdate(ctx context.Context, input *CheckI
return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to check image update").Error())
}
- return &CheckImageUpdateOutput{
+ return &handlerutil.Out[imageupdate.Response]{
Body: base.ApiResponse[imageupdate.Response]{
Success: true,
Data: *result,
@@ -166,7 +142,7 @@ func (h *ImageUpdateHandler) CheckImageUpdate(ctx context.Context, input *CheckI
}, nil
}
-func (h *ImageUpdateHandler) CheckImageUpdateByID(ctx context.Context, input *CheckImageUpdateByIDInput) (*CheckImageUpdateByIDOutput, error) {
+func (h *ImageUpdateHandler) CheckImageUpdateByID(ctx context.Context, input *CheckImageUpdateByIDInput) (*handlerutil.Out[imageupdate.Response], error) {
if input.ImageID == "" {
return nil, huma.Error400BadRequest("imageId parameter is required")
}
@@ -177,7 +153,7 @@ func (h *ImageUpdateHandler) CheckImageUpdateByID(ctx context.Context, input *Ch
return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to check image update").Error())
}
- return &CheckImageUpdateByIDOutput{
+ return &handlerutil.Out[imageupdate.Response]{
Body: base.ApiResponse[imageupdate.Response]{
Success: true,
Data: *result,
@@ -185,10 +161,10 @@ func (h *ImageUpdateHandler) CheckImageUpdateByID(ctx context.Context, input *Ch
}, nil
}
-func (h *ImageUpdateHandler) CheckMultipleImages(ctx context.Context, input *CheckMultipleImagesInput) (*CheckMultipleImagesOutput, error) {
+func (h *ImageUpdateHandler) CheckMultipleImages(ctx context.Context, input *CheckMultipleImagesInput) (*handlerutil.Out[imageupdate.BatchResponse], error) {
// Empty batch is valid - return empty results
if len(input.Body.ImageRefs) == 0 {
- return &CheckMultipleImagesOutput{
+ return &handlerutil.Out[imageupdate.BatchResponse]{
Body: base.ApiResponse[imageupdate.BatchResponse]{
Success: true,
Data: imageupdate.BatchResponse{},
@@ -202,7 +178,7 @@ func (h *ImageUpdateHandler) CheckMultipleImages(ctx context.Context, input *Che
return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to check image updates").Error())
}
- return &CheckMultipleImagesOutput{
+ return &handlerutil.Out[imageupdate.BatchResponse]{
Body: base.ApiResponse[imageupdate.BatchResponse]{
Success: true,
Data: results,
@@ -210,14 +186,14 @@ func (h *ImageUpdateHandler) CheckMultipleImages(ctx context.Context, input *Che
}, nil
}
-func (h *ImageUpdateHandler) CheckAllImages(ctx context.Context, input *CheckAllImagesInput) (*CheckAllImagesOutput, error) {
+func (h *ImageUpdateHandler) CheckAllImages(ctx context.Context, input *CheckAllImagesInput) (*handlerutil.Out[imageupdate.BatchResponse], error) {
runtimeCtx := utils.ActivityRuntimeContext(ctx, h.appCtx)
results, err := h.imageUpdateService.CheckAllImages(runtimeCtx, 0, input.Body.Credentials)
if err != nil {
return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to check all images").Error())
}
- return &CheckAllImagesOutput{
+ return &handlerutil.Out[imageupdate.BatchResponse]{
Body: base.ApiResponse[imageupdate.BatchResponse]{
Success: true,
Data: results,
@@ -225,10 +201,10 @@ func (h *ImageUpdateHandler) CheckAllImages(ctx context.Context, input *CheckAll
}, nil
}
-func (h *ImageUpdateHandler) GetUpdateInfoByRefs(ctx context.Context, input *GetUpdateInfoByRefsInput) (*GetUpdateInfoByRefsOutput, error) {
+func (h *ImageUpdateHandler) GetUpdateInfoByRefs(ctx context.Context, input *GetUpdateInfoByRefsInput) (*handlerutil.Out[map[string]*imagetypes.UpdateInfo], error) {
imageRefs := parseImageRefsQueryInternal(input.ImageRefs)
if len(imageRefs) == 0 {
- return &GetUpdateInfoByRefsOutput{
+ return &handlerutil.Out[map[string]*imagetypes.UpdateInfo]{
Body: base.ApiResponse[map[string]*imagetypes.UpdateInfo]{
Success: true,
Data: map[string]*imagetypes.UpdateInfo{},
@@ -241,7 +217,7 @@ func (h *ImageUpdateHandler) GetUpdateInfoByRefs(ctx context.Context, input *Get
return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to check image updates").Error())
}
- return &GetUpdateInfoByRefsOutput{
+ return &handlerutil.Out[map[string]*imagetypes.UpdateInfo]{
Body: base.ApiResponse[map[string]*imagetypes.UpdateInfo]{
Success: true,
Data: result,
@@ -249,13 +225,13 @@ func (h *ImageUpdateHandler) GetUpdateInfoByRefs(ctx context.Context, input *Get
}, nil
}
-func (h *ImageUpdateHandler) GetUpdateSummary(ctx context.Context, input *GetUpdateSummaryInput) (*GetUpdateSummaryOutput, error) {
+func (h *ImageUpdateHandler) GetUpdateSummary(ctx context.Context, input *GetUpdateSummaryInput) (*handlerutil.Out[imageupdate.Summary], error) {
summary, err := h.imageUpdateService.GetUpdateSummary(ctx)
if err != nil {
return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to get update summary").Error())
}
- return &GetUpdateSummaryOutput{
+ return &handlerutil.Out[imageupdate.Summary]{
Body: base.ApiResponse[imageupdate.Summary]{
Success: true,
Data: *summary,
diff --git a/backend/internal/job/handler.go b/backend/internal/job/handler.go
index eed8850c3..fffa2baff 100644
--- a/backend/internal/job/handler.go
+++ b/backend/internal/job/handler.go
@@ -26,10 +26,6 @@ type UpdateJobSchedulesInput struct {
Body jobschedule.Update `doc:"Job schedule update data"`
}
-type UpdateJobSchedulesOutput struct {
- Body base.ApiResponse[jobschedule.Config]
-}
-
type ListJobsInput struct {
ID string `path:"id" doc:"Environment ID"`
}
@@ -49,8 +45,8 @@ type RunJobOutput struct {
func RegisterJobSchedules(api huma.API, jobSvc *JobService, envSvc *environment.EnvironmentService) {
h := &JobSchedulesHandler{
- jobService: jobSvc,
- environmentService: envSvc,
+ jobService: jobSvc,
+ proxyRemoteJSON: envSvc.ProxyJSONRequest,
}
middleware.RegisterWithPermission(api, huma.Operation{
@@ -95,13 +91,13 @@ func RegisterJobSchedules(api huma.API, jobSvc *JobService, envSvc *environment.
}
type JobSchedulesHandler struct {
- jobService *JobService
- environmentService *environment.EnvironmentService
+ jobService *JobService
+ proxyRemoteJSON handlerutil.RemoteJSONProxy
}
func (h *JobSchedulesHandler) ListJobs(ctx context.Context, input *ListJobsInput) (*GetJobsOutput, error) {
if input.ID != "0" {
- jobs, err := handlerutil.ProxyRemoteJSON[jobschedule.JobListResponse](ctx, h.environmentService.ProxyJSONRequest, input.ID, http.MethodGet, "/api/environments/0/jobs", nil)
+ jobs, err := h.proxyRemoteJSON.JSON[jobschedule.JobListResponse](ctx, input.ID, http.MethodGet, "/api/environments/0/jobs", nil)
if err != nil {
return nil, err
}
@@ -118,7 +114,7 @@ func (h *JobSchedulesHandler) ListJobs(ctx context.Context, input *ListJobsInput
func (h *JobSchedulesHandler) RunJob(ctx context.Context, input *RunJobInput) (*RunJobOutput, error) {
if input.ID != "0" {
- runResp, err := handlerutil.ProxyRemoteJSON[jobschedule.JobRunResponse](ctx, h.environmentService.ProxyJSONRequest, input.ID, http.MethodPost, "/api/environments/0/jobs/"+input.JobID+"/run", nil)
+ runResp, err := h.proxyRemoteJSON.JSON[jobschedule.JobRunResponse](ctx, input.ID, http.MethodPost, "/api/environments/0/jobs/"+input.JobID+"/run", nil)
if err != nil {
return nil, err
}
@@ -140,7 +136,7 @@ func (h *JobSchedulesHandler) RunJob(ctx context.Context, input *RunJobInput) (*
func (h *JobSchedulesHandler) Get(ctx context.Context, input *GetJobSchedulesInput) (*GetJobSchedulesOutput, error) {
if input.ID != "0" {
- cfg, err := handlerutil.ProxyRemoteJSON[jobschedule.Config](ctx, h.environmentService.ProxyJSONRequest, input.ID, http.MethodGet, "/api/environments/0/job-schedules", nil)
+ cfg, err := h.proxyRemoteJSON.JSON[jobschedule.Config](ctx, input.ID, http.MethodGet, "/api/environments/0/job-schedules", nil)
if err != nil {
return nil, err
}
@@ -151,14 +147,14 @@ func (h *JobSchedulesHandler) Get(ctx context.Context, input *GetJobSchedulesInp
return &GetJobSchedulesOutput{Body: cfg}, nil
}
-func (h *JobSchedulesHandler) Update(ctx context.Context, input *UpdateJobSchedulesInput) (*UpdateJobSchedulesOutput, error) {
+func (h *JobSchedulesHandler) Update(ctx context.Context, input *UpdateJobSchedulesInput) (*handlerutil.Out[jobschedule.Config], error) {
if input.ID != "0" {
- apiResp, err := handlerutil.ProxyRemoteJSON[base.ApiResponse[jobschedule.Config]](ctx, h.environmentService.ProxyJSONRequest, input.ID, http.MethodPut, "/api/environments/0/job-schedules", input.Body)
+ apiResp, err := h.proxyRemoteJSON.JSON[base.ApiResponse[jobschedule.Config]](ctx, input.ID, http.MethodPut, "/api/environments/0/job-schedules", input.Body)
if err != nil {
return nil, err
}
- return &UpdateJobSchedulesOutput{Body: *apiResp}, nil
+ return &handlerutil.Out[jobschedule.Config]{Body: *apiResp}, nil
}
cfg, err := h.jobService.UpdateJobSchedules(ctx, input.Body)
@@ -166,7 +162,7 @@ func (h *JobSchedulesHandler) Update(ctx context.Context, input *UpdateJobSchedu
return nil, huma.Error400BadRequest(err.Error())
}
- return &UpdateJobSchedulesOutput{
+ return &handlerutil.Out[jobschedule.Config]{
Body: base.ApiResponse[jobschedule.Config]{
Success: true,
Data: cfg,
diff --git a/backend/internal/kv/service.go b/backend/internal/kv/service.go
index 969e32d79..e5dece753 100644
--- a/backend/internal/kv/service.go
+++ b/backend/internal/kv/service.go
@@ -65,42 +65,34 @@ func (s *KVService) ListByPrefix(ctx context.Context, prefix string) ([]KVEntry,
return entries, nil
}
-func (s *KVService) GetBool(ctx context.Context, key string, defaultValue bool) (bool, error) {
+// GetTyped loads one kv entry and parses it, returning defaultValue when the
+// key is absent or unreadable.
+func (s *KVService) GetTyped[T any](ctx context.Context, key string, defaultValue T, parse func(string) (T, error)) (T, error) {
rawValue, ok, err := s.Get(ctx, key)
- if err != nil {
+ if err != nil || !ok {
return defaultValue, err
}
- if !ok {
- return defaultValue, nil
- }
- parsedValue, err := strconv.ParseBool(rawValue)
+ parsedValue, err := parse(rawValue)
if err != nil {
- return defaultValue, errors.WrapIff(err, "failed to parse kv entry %q as bool", key)
+ return defaultValue, errors.WrapIff(err, "failed to parse kv entry %q as %T", key, defaultValue)
}
return parsedValue, nil
}
+func (s *KVService) GetBool(ctx context.Context, key string, defaultValue bool) (bool, error) {
+ return s.GetTyped(ctx, key, defaultValue, strconv.ParseBool)
+}
+
func (s *KVService) SetBool(ctx context.Context, key string, value bool) error {
return s.Set(ctx, key, strconv.FormatBool(value))
}
func (s *KVService) GetInt64(ctx context.Context, key string, defaultValue int64) (int64, error) {
- rawValue, ok, err := s.Get(ctx, key)
- if err != nil {
- return defaultValue, err
- }
- if !ok {
- return defaultValue, nil
- }
-
- parsedValue, err := strconv.ParseInt(rawValue, 10, 64)
- if err != nil {
- return defaultValue, errors.WrapIff(err, "failed to parse kv entry %q as int64", key)
- }
-
- return parsedValue, nil
+ return s.GetTyped(ctx, key, defaultValue, func(value string) (int64, error) {
+ return strconv.ParseInt(value, 10, 64)
+ })
}
func (s *KVService) IncrementInt64(ctx context.Context, key string, delta int64) (int64, error) {
diff --git a/backend/internal/network/handler.go b/backend/internal/network/handler.go
index 376e92f25..e08c91fb5 100644
--- a/backend/internal/network/handler.go
+++ b/backend/internal/network/handler.go
@@ -54,19 +54,11 @@ type GetNetworkCountsInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
}
-type GetNetworkCountsOutput struct {
- Body base.ApiResponse[networktypes.UsageCounts]
-}
-
type CreateNetworkInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
Body networktypes.CreateRequest
}
-type CreateNetworkOutput struct {
- Body base.ApiResponse[networktypes.CreateResponse]
-}
-
type GetNetworkInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
NetworkID string `path:"networkId" doc:"Network ID"`
@@ -74,27 +66,15 @@ type GetNetworkInput struct {
Order string `query:"order" default:"asc"`
}
-type GetNetworkOutput struct {
- Body base.ApiResponse[networktypes.Inspect]
-}
-
type GetNetworkTopologyInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
}
-type GetNetworkTopologyOutput struct {
- Body base.ApiResponse[networktypes.Topology]
-}
-
type DeleteNetworkInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
NetworkID string `path:"networkId" doc:"Network ID"`
}
-type DeleteNetworkOutput struct {
- Body base.ApiResponse[base.MessageResponse]
-}
-
type PruneNetworksInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
}
@@ -105,24 +85,12 @@ type ConnectContainerInput struct {
Body networktypes.ConnectContainerRequest
}
-type ConnectContainerOutput struct {
- Body base.ApiResponse[base.MessageResponse]
-}
-
type DisconnectContainerInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
NetworkID string `path:"networkId" doc:"Network ID"`
Body networktypes.DisconnectContainerRequest
}
-type DisconnectContainerOutput struct {
- Body base.ApiResponse[base.MessageResponse]
-}
-
-type PruneNetworksOutput struct {
- Body base.ApiResponse[networktypes.PruneReport]
-}
-
// RegisterNetworks registers network endpoints.
func RegisterNetworks(api huma.API, networkSvc *NetworkService, dockerSvc *docker.DockerClientService, activitySvc *activity.ActivityService, appCtx handlerutil.ActivityAppContext) {
h := &NetworkHandler{
@@ -235,13 +203,13 @@ func (h *NetworkHandler) ListNetworks(ctx context.Context, input *ListNetworksIn
}, nil
}
-func (h *NetworkHandler) GetNetworkCounts(ctx context.Context, input *GetNetworkCountsInput) (*GetNetworkCountsOutput, error) {
+func (h *NetworkHandler) GetNetworkCounts(ctx context.Context, input *GetNetworkCountsInput) (*handlerutil.Out[networktypes.UsageCounts], error) {
_, inuse, unused, total, err := h.dockerService.GetAllNetworks(ctx)
if err != nil {
return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to get network counts").Error())
}
- return &GetNetworkCountsOutput{
+ return &handlerutil.Out[networktypes.UsageCounts]{
Body: base.ApiResponse[networktypes.UsageCounts]{
Success: true,
Data: networktypes.UsageCounts{
@@ -253,7 +221,7 @@ func (h *NetworkHandler) GetNetworkCounts(ctx context.Context, input *GetNetwork
}, nil
}
-func (h *NetworkHandler) CreateNetwork(ctx context.Context, input *CreateNetworkInput) (*CreateNetworkOutput, error) {
+func (h *NetworkHandler) CreateNetwork(ctx context.Context, input *CreateNetworkInput) (*handlerutil.Out[networktypes.CreateResponse], error) {
user, err := handlerutil.RequireUser(ctx)
if err != nil {
return nil, err
@@ -293,7 +261,7 @@ func (h *NetworkHandler) CreateNetwork(ctx context.Context, input *CreateNetwork
}
out.ActivityID = mo.EmptyableToOption(strings.TrimSpace(activityID)).ToPointer()
- return &CreateNetworkOutput{
+ return &handlerutil.Out[networktypes.CreateResponse]{
Body: base.ApiResponse[networktypes.CreateResponse]{
Success: true,
Data: out,
@@ -301,7 +269,7 @@ func (h *NetworkHandler) CreateNetwork(ctx context.Context, input *CreateNetwork
}, nil
}
-func (h *NetworkHandler) GetNetwork(ctx context.Context, input *GetNetworkInput) (*GetNetworkOutput, error) {
+func (h *NetworkHandler) GetNetwork(ctx context.Context, input *GetNetworkInput) (*handlerutil.Out[networktypes.Inspect], error) {
networkInspect, err := h.networkService.GetNetworkByID(ctx, input.NetworkID)
if err != nil {
return nil, huma.Error404NotFound(errors.WithMessage(err, "Network not found").Error())
@@ -381,7 +349,7 @@ func (h *NetworkHandler) GetNetwork(ctx context.Context, input *GetNetworkInput)
return strings.ToLower(a.Name) < strings.ToLower(b.Name)
})
- return &GetNetworkOutput{
+ return &handlerutil.Out[networktypes.Inspect]{
Body: base.ApiResponse[networktypes.Inspect]{
Success: true,
Data: out,
@@ -389,13 +357,13 @@ func (h *NetworkHandler) GetNetwork(ctx context.Context, input *GetNetworkInput)
}, nil
}
-func (h *NetworkHandler) GetNetworkTopology(ctx context.Context, input *GetNetworkTopologyInput) (*GetNetworkTopologyOutput, error) {
+func (h *NetworkHandler) GetNetworkTopology(ctx context.Context, input *GetNetworkTopologyInput) (*handlerutil.Out[networktypes.Topology], error) {
topology, err := h.networkService.GetNetworkTopology(ctx)
if err != nil {
return nil, huma.Error500InternalServerError("failed to build network topology")
}
- return &GetNetworkTopologyOutput{
+ return &handlerutil.Out[networktypes.Topology]{
Body: base.ApiResponse[networktypes.Topology]{
Success: true,
Data: *topology,
@@ -403,7 +371,7 @@ func (h *NetworkHandler) GetNetworkTopology(ctx context.Context, input *GetNetwo
}, nil
}
-func (h *NetworkHandler) DeleteNetwork(ctx context.Context, input *DeleteNetworkInput) (*DeleteNetworkOutput, error) {
+func (h *NetworkHandler) DeleteNetwork(ctx context.Context, input *DeleteNetworkInput) (*handlerutil.Out[base.MessageResponse], error) {
user, err := handlerutil.RequireUser(ctx)
if err != nil {
return nil, err
@@ -430,7 +398,7 @@ func (h *NetworkHandler) DeleteNetwork(ctx context.Context, input *DeleteNetwork
return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to remove network").Error())
}
- return &DeleteNetworkOutput{
+ return &handlerutil.Out[base.MessageResponse]{
Body: base.ApiResponse[base.MessageResponse]{
Success: true,
Data: base.MessageResponse{Message: "Network removed successfully", ActivityID: mo.EmptyableToOption(strings.TrimSpace(activityID)).ToPointer()},
@@ -438,7 +406,7 @@ func (h *NetworkHandler) DeleteNetwork(ctx context.Context, input *DeleteNetwork
}, nil
}
-func (h *NetworkHandler) ConnectContainer(ctx context.Context, input *ConnectContainerInput) (*ConnectContainerOutput, error) {
+func (h *NetworkHandler) ConnectContainer(ctx context.Context, input *ConnectContainerInput) (*handlerutil.Out[base.MessageResponse], error) {
user, err := handlerutil.RequireUser(ctx)
if err != nil {
return nil, err
@@ -469,7 +437,7 @@ func (h *NetworkHandler) ConnectContainer(ctx context.Context, input *ConnectCon
return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to connect container to network").Error())
}
- return &ConnectContainerOutput{
+ return &handlerutil.Out[base.MessageResponse]{
Body: base.ApiResponse[base.MessageResponse]{
Success: true,
Data: base.MessageResponse{Message: "Container connected successfully", ActivityID: mo.EmptyableToOption(strings.TrimSpace(activityID)).ToPointer()},
@@ -477,7 +445,7 @@ func (h *NetworkHandler) ConnectContainer(ctx context.Context, input *ConnectCon
}, nil
}
-func (h *NetworkHandler) DisconnectContainer(ctx context.Context, input *DisconnectContainerInput) (*DisconnectContainerOutput, error) {
+func (h *NetworkHandler) DisconnectContainer(ctx context.Context, input *DisconnectContainerInput) (*handlerutil.Out[base.MessageResponse], error) {
user, err := handlerutil.RequireUser(ctx)
if err != nil {
return nil, err
@@ -506,7 +474,7 @@ func (h *NetworkHandler) DisconnectContainer(ctx context.Context, input *Disconn
return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to disconnect container from network").Error())
}
- return &DisconnectContainerOutput{
+ return &handlerutil.Out[base.MessageResponse]{
Body: base.ApiResponse[base.MessageResponse]{
Success: true,
Data: base.MessageResponse{Message: "Container disconnected successfully", ActivityID: mo.EmptyableToOption(strings.TrimSpace(activityID)).ToPointer()},
@@ -514,7 +482,7 @@ func (h *NetworkHandler) DisconnectContainer(ctx context.Context, input *Disconn
}, nil
}
-func (h *NetworkHandler) PruneNetworks(ctx context.Context, input *PruneNetworksInput) (*PruneNetworksOutput, error) {
+func (h *NetworkHandler) PruneNetworks(ctx context.Context, input *PruneNetworksInput) (*handlerutil.Out[networktypes.PruneReport], error) {
var report *dockernetwork.PruneReport
runtimeCtx := utils.ActivityRuntimeContext(ctx, h.appCtx)
activityID, err := activitylib.RunHandlerActivity(runtimeCtx, h.activityService, activitylib.HandlerOptions{
@@ -540,7 +508,7 @@ func (h *NetworkHandler) PruneNetworks(ctx context.Context, input *PruneNetworks
}
out.ActivityID = mo.EmptyableToOption(strings.TrimSpace(activityID)).ToPointer()
- return &PruneNetworksOutput{
+ return &handlerutil.Out[networktypes.PruneReport]{
Body: base.ApiResponse[networktypes.PruneReport]{
Success: true,
Data: out,
diff --git a/backend/internal/network/service.go b/backend/internal/network/service.go
index 321ae9b15..5f98d75de 100644
--- a/backend/internal/network/service.go
+++ b/backend/internal/network/service.go
@@ -370,7 +370,7 @@ func (s *NetworkService) ListNetworksPaginated(ctx context.Context, params pagin
items := s.convertToNetworkSummaries(rawNets, inUseByID, inUseByName)
config := s.buildNetworkPaginationConfig()
- result := pagination.SearchOrderAndPaginate(items, params, config)
+ result := config.SearchOrderAndPaginate(items, params)
counts := s.calculateNetworkUsageCounts(items)
paginationResp := pagination.BuildResponse(result.TotalCount, result.TotalAvailable, params)
diff --git a/backend/internal/notification/handler.go b/backend/internal/notification/handler.go
index 71b43e568..fc518c8c6 100644
--- a/backend/internal/notification/handler.go
+++ b/backend/internal/notification/handler.go
@@ -58,29 +58,17 @@ type DeleteNotificationSettingsInput struct {
Provider string `path:"provider" doc:"Provider"`
}
-type DeleteNotificationSettingsOutput struct {
- Body base.ApiResponse[base.MessageResponse]
-}
-
type TestNotificationInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
Provider string `path:"provider" doc:"Provider"`
Type string `query:"type" default:"simple"`
}
-type TestNotificationOutput struct {
- Body base.ApiResponse[notification.TestResponse]
-}
-
type DispatchNotificationInput struct {
APIKey string `header:"X-API-Key" doc:"Remote environment access token"`
Body notification.DispatchRequest
}
-type DispatchNotificationOutput struct {
- Body base.ApiResponse[notification.DispatchResponse]
-}
-
func normalizeNotificationTestType(testType string) string {
normalized := strings.TrimSpace(testType)
if normalized == "" {
@@ -241,7 +229,7 @@ func (h *NotificationHandler) CreateOrUpdateNotificationSettings(ctx context.Con
return &CreateOrUpdateNotificationSettingsOutput{Body: response}, nil
}
-func (h *NotificationHandler) DeleteNotificationSettings(ctx context.Context, input *DeleteNotificationSettingsInput) (*DeleteNotificationSettingsOutput, error) {
+func (h *NotificationHandler) DeleteNotificationSettings(ctx context.Context, input *DeleteNotificationSettingsInput) (*handlerutil.Out[base.MessageResponse], error) {
if err := h.rejectIfAgentModeInternal(); err != nil {
return nil, err
}
@@ -251,7 +239,7 @@ func (h *NotificationHandler) DeleteNotificationSettings(ctx context.Context, in
return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to delete notification settings").Error())
}
- return &DeleteNotificationSettingsOutput{
+ return &handlerutil.Out[base.MessageResponse]{
Body: base.ApiResponse[base.MessageResponse]{
Success: true,
Data: base.MessageResponse{Message: "Settings deleted successfully"},
@@ -259,7 +247,7 @@ func (h *NotificationHandler) DeleteNotificationSettings(ctx context.Context, in
}, nil
}
-func (h *NotificationHandler) TestNotification(ctx context.Context, input *TestNotificationInput) (*TestNotificationOutput, error) {
+func (h *NotificationHandler) TestNotification(ctx context.Context, input *TestNotificationInput) (*handlerutil.Out[notification.TestResponse], error) {
if err := h.rejectIfAgentModeInternal(); err != nil {
return nil, err
}
@@ -274,7 +262,7 @@ func (h *NotificationHandler) TestNotification(ctx context.Context, input *TestN
return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to send test notification").Error())
}
- return &TestNotificationOutput{
+ return &handlerutil.Out[notification.TestResponse]{
Body: base.ApiResponse[notification.TestResponse]{
Success: true,
Data: notification.TestResponse{
@@ -285,7 +273,7 @@ func (h *NotificationHandler) TestNotification(ctx context.Context, input *TestN
}, nil
}
-func (h *NotificationHandler) DispatchNotification(ctx context.Context, input *DispatchNotificationInput) (*DispatchNotificationOutput, error) {
+func (h *NotificationHandler) DispatchNotification(ctx context.Context, input *DispatchNotificationInput) (*handlerutil.Out[notification.DispatchResponse], error) {
if err := h.rejectIfAgentModeInternal(); err != nil {
return nil, err
}
@@ -303,7 +291,7 @@ func (h *NotificationHandler) DispatchNotification(ctx context.Context, input *D
return nil, huma.Error500InternalServerError("dispatch failed")
}
- return &DispatchNotificationOutput{
+ return &handlerutil.Out[notification.DispatchResponse]{
Body: base.ApiResponse[notification.DispatchResponse]{
Success: true,
Data: dispatchResponse,
diff --git a/backend/internal/oidc/handler.go b/backend/internal/oidc/handler.go
index f0340e8cd..e2ced27f4 100644
--- a/backend/internal/oidc/handler.go
+++ b/backend/internal/oidc/handler.go
@@ -25,7 +25,6 @@ import (
"github.com/getarcaneapp/arcane/backend/v2/pkg/utils/handlerutil"
"github.com/getarcaneapp/arcane/backend/v2/pkg/utils/httpx"
authtypes "github.com/getarcaneapp/arcane/types/v2/auth"
- "github.com/getarcaneapp/arcane/types/v2/base"
roletypes "github.com/getarcaneapp/arcane/types/v2/role"
)
@@ -109,27 +108,15 @@ type ExchangeDeviceTokenOutput struct {
type ListOidcRoleMappingsInput struct{}
-type ListOidcRoleMappingsOutput struct {
- Body base.ApiResponse[[]roletypes.OidcRoleMapping]
-}
-
type CreateOidcRoleMappingInput struct {
Body roletypes.CreateOidcRoleMapping
}
-type CreateOidcRoleMappingOutput struct {
- Body base.ApiResponse[roletypes.OidcRoleMapping]
-}
-
type UpdateOidcRoleMappingInput struct {
ID string `path:"id" doc:"Mapping ID"`
Body roletypes.UpdateOidcRoleMapping
}
-type UpdateOidcRoleMappingOutput struct {
- Body base.ApiResponse[roletypes.OidcRoleMapping]
-}
-
type DeleteOidcRoleMappingInput struct {
ID string `path:"id" doc:"Mapping ID"`
}
@@ -521,12 +508,12 @@ func (h *OidcHandler) ExchangeDeviceToken(ctx context.Context, input *ExchangeDe
// OIDC Role Mapping Handlers
// ============================================================================
-func (h *OidcHandler) ListOidcRoleMappings(ctx context.Context, _ *ListOidcRoleMappingsInput) (*ListOidcRoleMappingsOutput, error) {
+func (h *OidcHandler) ListOidcRoleMappings(ctx context.Context, _ *ListOidcRoleMappingsInput) (*handlerutil.Out[[]roletypes.OidcRoleMapping], error) {
rows, err := h.roleService.ListOidcMappings(ctx)
if err != nil {
return nil, huma.Error500InternalServerError("failed to list mappings: " + err.Error())
}
- out := &ListOidcRoleMappingsOutput{}
+ out := &handlerutil.Out[[]roletypes.OidcRoleMapping]{}
out.Body.Success = true
out.Body.Data = make([]roletypes.OidcRoleMapping, len(rows))
for i := range rows {
@@ -535,7 +522,7 @@ func (h *OidcHandler) ListOidcRoleMappings(ctx context.Context, _ *ListOidcRoleM
return out, nil
}
-func (h *OidcHandler) CreateOidcRoleMapping(ctx context.Context, input *CreateOidcRoleMappingInput) (*CreateOidcRoleMappingOutput, error) {
+func (h *OidcHandler) CreateOidcRoleMapping(ctx context.Context, input *CreateOidcRoleMappingInput) (*handlerutil.Out[roletypes.OidcRoleMapping], error) {
claimValue := strings.TrimSpace(input.Body.ClaimValue)
roleID := strings.TrimSpace(input.Body.RoleID)
if claimValue == "" {
@@ -551,13 +538,13 @@ func (h *OidcHandler) CreateOidcRoleMapping(ctx context.Context, input *CreateOi
}
return nil, huma.Error500InternalServerError("failed to create mapping: " + err.Error())
}
- out := &CreateOidcRoleMappingOutput{}
+ out := &handlerutil.Out[roletypes.OidcRoleMapping]{}
out.Body.Success = true
out.Body.Data = toOidcMappingDTO(mapping)
return out, nil
}
-func (h *OidcHandler) UpdateOidcRoleMapping(ctx context.Context, input *UpdateOidcRoleMappingInput) (*UpdateOidcRoleMappingOutput, error) {
+func (h *OidcHandler) UpdateOidcRoleMapping(ctx context.Context, input *UpdateOidcRoleMappingInput) (*handlerutil.Out[roletypes.OidcRoleMapping], error) {
claimValue := strings.TrimSpace(input.Body.ClaimValue)
roleID := strings.TrimSpace(input.Body.RoleID)
if claimValue == "" {
@@ -579,7 +566,7 @@ func (h *OidcHandler) UpdateOidcRoleMapping(ctx context.Context, input *UpdateOi
}
return nil, huma.Error500InternalServerError("failed to update mapping: " + err.Error())
}
- out := &UpdateOidcRoleMappingOutput{}
+ out := &handlerutil.Out[roletypes.OidcRoleMapping]{}
out.Body.Success = true
out.Body.Data = toOidcMappingDTO(mapping)
return out, nil
diff --git a/backend/internal/passkey/handler.go b/backend/internal/passkey/handler.go
index 3b0286926..5df42b0e6 100644
--- a/backend/internal/passkey/handler.go
+++ b/backend/internal/passkey/handler.go
@@ -6,7 +6,7 @@ import (
"github.com/getarcaneapp/arcane/backend/v2/internal/common"
"context"
- stdjson "encoding/json"
+ "encoding/json/v2"
"net/http"
"strings"
"time"
@@ -73,10 +73,6 @@ type passwordReauthBody struct {
Password string `json:"password" minLength:"1"`
}
-type PasskeyLoginBeginOutput struct {
- Body base.ApiResponse[passkeyBeginResponse]
-}
-
type PasskeyLoginFinishInput struct {
UserAgent string `header:"User-Agent"`
Body passkeyCredentialBody
@@ -91,10 +87,6 @@ type MobilePasskeyFinishInput struct {
Body mobilePasskeyFinishBody
}
-type MobilePasskeyFinishOutput struct {
- Body base.ApiResponse[authtypes.MobilePasskeyCompletion]
-}
-
type MobilePasskeyExchangeInput struct {
UserAgent string `header:"User-Agent"`
Body mobilePasskeyExchangeBody
@@ -109,10 +101,6 @@ type PasskeyMFAStartInput struct {
Body mfaBeginBody
}
-type PasskeyMFAStartOutput struct {
- Body base.ApiResponse[authtypes.MFAChallenge]
-}
-
type PasskeyMFAFinishInput struct {
Body mfaFinishBody
}
@@ -138,76 +126,36 @@ type passkeyBeginResponse struct {
ExpiresAt time.Time `json:"expiresAt"`
}
-type ListMyPasskeysOutput struct {
- Body base.ApiResponse[[]PasskeySummary]
-}
-
-type GetPasskeyCapabilitiesOutput struct {
- Body base.ApiResponse[PasskeyCapabilities]
-}
-
type BeginPasskeyRegistrationInput struct {
StepUpToken string `header:"X-Step-Up-Token"`
}
-type BeginPasskeyRegistrationOutput struct {
- Body base.ApiResponse[passkeyBeginResponse]
-}
-
type FinishPasskeyRegistrationInput struct {
UserAgent string `header:"User-Agent"`
Body passkeyCredentialBody
}
-type FinishPasskeyRegistrationOutput struct {
- Body base.ApiResponse[PasskeySummary]
-}
-
type RenamePasskeyInput struct {
ID string `path:"id"`
StepUpToken string `header:"X-Step-Up-Token"`
Body renamePasskeyBody
}
-type RenamePasskeyOutput struct {
- Body base.ApiResponse[PasskeySummary]
-}
-
type DeletePasskeyInput struct {
ID string `path:"id"`
StepUpToken string `header:"X-Step-Up-Token"`
}
-type DeletePasskeyOutput struct {
- Body base.ApiResponse[base.MessageResponse]
-}
-
type BeginStepUpInput struct{}
-type BeginStepUpOutput struct {
- Body base.ApiResponse[passkeyBeginResponse]
-}
-
type FinishStepUpInput struct {
Body stepUpFinishBody
}
-type FinishStepUpOutput struct {
- Body base.ApiResponse[StepUpGrant]
-}
-
type PasswordStepUpInput struct {
Body passwordReauthBody
}
-type PasswordStepUpOutput struct {
- Body base.ApiResponse[StepUpGrant]
-}
-
-type GetMFAStatusOutput struct {
- Body base.ApiResponse[MFAStatus]
-}
-
type MFASettingsInput struct {
StepUpToken string `header:"X-Step-Up-Token"`
}
@@ -216,10 +164,6 @@ type RecoveryCodesResponse struct {
Codes []string `json:"codes" doc:"Recovery codes; shown only once"`
}
-type MFARecoveryCodesOutput struct {
- Body base.ApiResponse[RecoveryCodesResponse]
-}
-
func RegisterPasskeys(api huma.API, passkeyService *PasskeyService, authService *auth.AuthService, userService *user.UserService) {
h := &PasskeyHandler{passkeyService: passkeyService, authService: authService, userService: userService}
public := []map[string][]string{}
@@ -397,12 +341,12 @@ func RegisterPasskeys(api huma.API, passkeyService *PasskeyService, authService
}, h.RegenerateRecoveryCodes)
}
-func (h *PasskeyHandler) BeginPasskeyLogin(ctx context.Context, _ *struct{}) (*PasskeyLoginBeginOutput, error) {
+func (h *PasskeyHandler) BeginPasskeyLogin(ctx context.Context, _ *struct{}) (*handlerutil.Out[passkeyBeginResponse], error) {
challenge, err := h.passkeyService.BeginPasskeyLogin(ctx)
if err != nil {
return nil, passkeyHTTPErrorInternal(err)
}
- return &PasskeyLoginBeginOutput{Body: base.ApiResponse[passkeyBeginResponse]{Success: true, Data: passkeyBeginResponseFromChallengeInternal(challenge)}}, nil
+ return &handlerutil.Out[passkeyBeginResponse]{Body: base.ApiResponse[passkeyBeginResponse]{Success: true, Data: passkeyBeginResponseFromChallengeInternal(challenge)}}, nil
}
func (h *PasskeyHandler) FinishPasskeyLogin(ctx context.Context, input *PasskeyLoginFinishInput) (*PasskeyLoginFinishOutput, error) {
@@ -429,7 +373,7 @@ func (h *PasskeyHandler) FinishPasskeyLogin(ctx context.Context, input *PasskeyL
}, nil
}
-func (h *PasskeyHandler) FinishMobilePasskeyLogin(ctx context.Context, input *MobilePasskeyFinishInput) (*MobilePasskeyFinishOutput, error) {
+func (h *PasskeyHandler) FinishMobilePasskeyLogin(ctx context.Context, input *MobilePasskeyFinishInput) (*handlerutil.Out[authtypes.MobilePasskeyCompletion], error) {
payload, err := marshalCredentialInternal(input.Body.Credential)
if err != nil {
return nil, huma.Error400BadRequest("invalid passkey response")
@@ -438,7 +382,7 @@ func (h *PasskeyHandler) FinishMobilePasskeyLogin(ctx context.Context, input *Mo
if err != nil {
return nil, passkeyHTTPErrorInternal(err)
}
- return &MobilePasskeyFinishOutput{Body: base.ApiResponse[authtypes.MobilePasskeyCompletion]{Success: true, Data: *completion}}, nil
+ return &handlerutil.Out[authtypes.MobilePasskeyCompletion]{Body: base.ApiResponse[authtypes.MobilePasskeyCompletion]{Success: true, Data: *completion}}, nil
}
func (h *PasskeyHandler) ExchangeMobilePasskeyLogin(ctx context.Context, input *MobilePasskeyExchangeInput) (*MobilePasskeyExchangeOutput, error) {
@@ -461,12 +405,12 @@ func (h *PasskeyHandler) ExchangeMobilePasskeyLogin(ctx context.Context, input *
}, nil
}
-func (h *PasskeyHandler) BeginMFA(ctx context.Context, input *PasskeyMFAStartInput) (*PasskeyMFAStartOutput, error) {
+func (h *PasskeyHandler) BeginMFA(ctx context.Context, input *PasskeyMFAStartInput) (*handlerutil.Out[authtypes.MFAChallenge], error) {
challenge, err := h.passkeyService.BeginMFAForTransaction(ctx, input.Body.TransactionID)
if err != nil {
return nil, passkeyHTTPErrorInternal(err)
}
- return &PasskeyMFAStartOutput{Body: base.ApiResponse[authtypes.MFAChallenge]{Success: true, Data: *challenge}}, nil
+ return &handlerutil.Out[authtypes.MFAChallenge]{Body: base.ApiResponse[authtypes.MFAChallenge]{Success: true, Data: *challenge}}, nil
}
func (h *PasskeyHandler) FinishMFA(ctx context.Context, input *PasskeyMFAFinishInput) (*PasskeyMFAFinishOutput, error) {
@@ -511,7 +455,7 @@ func (h *PasskeyHandler) UseRecoveryCode(ctx context.Context, input *PasskeyReco
}, nil
}
-func (h *PasskeyHandler) ListMyPasskeys(ctx context.Context, _ *struct{}) (*ListMyPasskeysOutput, error) {
+func (h *PasskeyHandler) ListMyPasskeys(ctx context.Context, _ *struct{}) (*handlerutil.Out[[]PasskeySummary], error) {
userModel, sessionID, err := requireInteractiveSessionInternal(ctx)
if err != nil {
return nil, err
@@ -521,10 +465,10 @@ func (h *PasskeyHandler) ListMyPasskeys(ctx context.Context, _ *struct{}) (*List
if err != nil {
return nil, passkeyHTTPErrorInternal(err)
}
- return &ListMyPasskeysOutput{Body: base.ApiResponse[[]PasskeySummary]{Success: true, Data: rows}}, nil
+ return &handlerutil.Out[[]PasskeySummary]{Body: base.ApiResponse[[]PasskeySummary]{Success: true, Data: rows}}, nil
}
-func (h *PasskeyHandler) GetCapabilities(ctx context.Context, _ *struct{}) (*GetPasskeyCapabilitiesOutput, error) {
+func (h *PasskeyHandler) GetCapabilities(ctx context.Context, _ *struct{}) (*handlerutil.Out[PasskeyCapabilities], error) {
userModel, _, err := requireInteractiveSessionInternal(ctx)
if err != nil {
return nil, err
@@ -537,10 +481,10 @@ func (h *PasskeyHandler) GetCapabilities(ctx context.Context, _ *struct{}) (*Get
if err != nil {
return nil, passkeyHTTPErrorInternal(err)
}
- return &GetPasskeyCapabilitiesOutput{Body: base.ApiResponse[PasskeyCapabilities]{Success: true, Data: *capabilities}}, nil
+ return &handlerutil.Out[PasskeyCapabilities]{Body: base.ApiResponse[PasskeyCapabilities]{Success: true, Data: *capabilities}}, nil
}
-func (h *PasskeyHandler) BeginRegistration(ctx context.Context, input *BeginPasskeyRegistrationInput) (*BeginPasskeyRegistrationOutput, error) {
+func (h *PasskeyHandler) BeginRegistration(ctx context.Context, input *BeginPasskeyRegistrationInput) (*handlerutil.Out[passkeyBeginResponse], error) {
userModel, sessionID, err := requireInteractiveSessionInternal(ctx)
if err != nil {
return nil, err
@@ -549,10 +493,10 @@ func (h *PasskeyHandler) BeginRegistration(ctx context.Context, input *BeginPass
if err != nil {
return nil, passkeyHTTPErrorInternal(err)
}
- return &BeginPasskeyRegistrationOutput{Body: base.ApiResponse[passkeyBeginResponse]{Success: true, Data: passkeyBeginResponseFromChallengeInternal(challenge)}}, nil
+ return &handlerutil.Out[passkeyBeginResponse]{Body: base.ApiResponse[passkeyBeginResponse]{Success: true, Data: passkeyBeginResponseFromChallengeInternal(challenge)}}, nil
}
-func (h *PasskeyHandler) FinishRegistration(ctx context.Context, input *FinishPasskeyRegistrationInput) (*FinishPasskeyRegistrationOutput, error) {
+func (h *PasskeyHandler) FinishRegistration(ctx context.Context, input *FinishPasskeyRegistrationInput) (*handlerutil.Out[PasskeySummary], error) {
userModel, sessionID, err := requireInteractiveSessionInternal(ctx)
if err != nil {
return nil, err
@@ -565,10 +509,10 @@ func (h *PasskeyHandler) FinishRegistration(ctx context.Context, input *FinishPa
if err != nil {
return nil, passkeyHTTPErrorInternal(err)
}
- return &FinishPasskeyRegistrationOutput{Body: base.ApiResponse[PasskeySummary]{Success: true, Data: *row}}, nil
+ return &handlerutil.Out[PasskeySummary]{Body: base.ApiResponse[PasskeySummary]{Success: true, Data: *row}}, nil
}
-func (h *PasskeyHandler) RenamePasskey(ctx context.Context, input *RenamePasskeyInput) (*RenamePasskeyOutput, error) {
+func (h *PasskeyHandler) RenamePasskey(ctx context.Context, input *RenamePasskeyInput) (*handlerutil.Out[PasskeySummary], error) {
userModel, sessionID, err := requireInteractiveSessionInternal(ctx)
if err != nil {
return nil, err
@@ -577,10 +521,10 @@ func (h *PasskeyHandler) RenamePasskey(ctx context.Context, input *RenamePasskey
if err != nil {
return nil, passkeyHTTPErrorInternal(err)
}
- return &RenamePasskeyOutput{Body: base.ApiResponse[PasskeySummary]{Success: true, Data: *row}}, nil
+ return &handlerutil.Out[PasskeySummary]{Body: base.ApiResponse[PasskeySummary]{Success: true, Data: *row}}, nil
}
-func (h *PasskeyHandler) DeletePasskey(ctx context.Context, input *DeletePasskeyInput) (*DeletePasskeyOutput, error) {
+func (h *PasskeyHandler) DeletePasskey(ctx context.Context, input *DeletePasskeyInput) (*handlerutil.Out[base.MessageResponse], error) {
userModel, sessionID, err := requireInteractiveSessionInternal(ctx)
if err != nil {
return nil, err
@@ -592,10 +536,10 @@ func (h *PasskeyHandler) DeletePasskey(ctx context.Context, input *DeletePasskey
if err := h.passkeyService.DeletePasskey(ctx, userModel.ID, input.ID, sessionID, input.StepUpToken, oidcEnabled); err != nil {
return nil, passkeyHTTPErrorInternal(err)
}
- return &DeletePasskeyOutput{Body: base.ApiResponse[base.MessageResponse]{Success: true, Data: base.MessageResponse{Message: "Passkey deleted"}}}, nil
+ return &handlerutil.Out[base.MessageResponse]{Body: base.ApiResponse[base.MessageResponse]{Success: true, Data: base.MessageResponse{Message: "Passkey deleted"}}}, nil
}
-func (h *PasskeyHandler) BeginStepUp(ctx context.Context, _ *BeginStepUpInput) (*BeginStepUpOutput, error) {
+func (h *PasskeyHandler) BeginStepUp(ctx context.Context, _ *BeginStepUpInput) (*handlerutil.Out[passkeyBeginResponse], error) {
userModel, sessionID, err := requireInteractiveSessionInternal(ctx)
if err != nil {
return nil, err
@@ -604,10 +548,10 @@ func (h *PasskeyHandler) BeginStepUp(ctx context.Context, _ *BeginStepUpInput) (
if err != nil {
return nil, passkeyHTTPErrorInternal(err)
}
- return &BeginStepUpOutput{Body: base.ApiResponse[passkeyBeginResponse]{Success: true, Data: passkeyBeginResponseFromChallengeInternal(challenge)}}, nil
+ return &handlerutil.Out[passkeyBeginResponse]{Body: base.ApiResponse[passkeyBeginResponse]{Success: true, Data: passkeyBeginResponseFromChallengeInternal(challenge)}}, nil
}
-func (h *PasskeyHandler) FinishStepUp(ctx context.Context, input *FinishStepUpInput) (*FinishStepUpOutput, error) {
+func (h *PasskeyHandler) FinishStepUp(ctx context.Context, input *FinishStepUpInput) (*handlerutil.Out[StepUpGrant], error) {
_, sessionID, err := requireInteractiveSessionInternal(ctx)
if err != nil {
return nil, err
@@ -620,10 +564,10 @@ func (h *PasskeyHandler) FinishStepUp(ctx context.Context, input *FinishStepUpIn
if err != nil {
return nil, passkeyHTTPErrorInternal(err)
}
- return &FinishStepUpOutput{Body: base.ApiResponse[StepUpGrant]{Success: true, Data: *grant}}, nil
+ return &handlerutil.Out[StepUpGrant]{Body: base.ApiResponse[StepUpGrant]{Success: true, Data: *grant}}, nil
}
-func (h *PasskeyHandler) PasswordStepUp(ctx context.Context, input *PasswordStepUpInput) (*PasswordStepUpOutput, error) {
+func (h *PasskeyHandler) PasswordStepUp(ctx context.Context, input *PasswordStepUpInput) (*handlerutil.Out[StepUpGrant], error) {
userModel, sessionID, err := requireInteractiveSessionInternal(ctx)
if err != nil {
return nil, err
@@ -638,10 +582,10 @@ func (h *PasskeyHandler) PasswordStepUp(ctx context.Context, input *PasswordStep
if err != nil {
return nil, passkeyHTTPErrorInternal(err)
}
- return &PasswordStepUpOutput{Body: base.ApiResponse[StepUpGrant]{Success: true, Data: *grant}}, nil
+ return &handlerutil.Out[StepUpGrant]{Body: base.ApiResponse[StepUpGrant]{Success: true, Data: *grant}}, nil
}
-func (h *PasskeyHandler) GetMFAStatus(ctx context.Context, _ *struct{}) (*GetMFAStatusOutput, error) {
+func (h *PasskeyHandler) GetMFAStatus(ctx context.Context, _ *struct{}) (*handlerutil.Out[MFAStatus], error) {
userModel, _, err := requireInteractiveSessionInternal(ctx)
if err != nil {
return nil, err
@@ -650,10 +594,10 @@ func (h *PasskeyHandler) GetMFAStatus(ctx context.Context, _ *struct{}) (*GetMFA
if err != nil {
return nil, passkeyHTTPErrorInternal(err)
}
- return &GetMFAStatusOutput{Body: base.ApiResponse[MFAStatus]{Success: true, Data: *status}}, nil
+ return &handlerutil.Out[MFAStatus]{Body: base.ApiResponse[MFAStatus]{Success: true, Data: *status}}, nil
}
-func (h *PasskeyHandler) EnableMFA(ctx context.Context, input *MFASettingsInput) (*MFARecoveryCodesOutput, error) {
+func (h *PasskeyHandler) EnableMFA(ctx context.Context, input *MFASettingsInput) (*handlerutil.Out[RecoveryCodesResponse], error) {
userModel, sessionID, err := requireInteractiveSessionInternal(ctx)
if err != nil {
return nil, err
@@ -662,10 +606,10 @@ func (h *PasskeyHandler) EnableMFA(ctx context.Context, input *MFASettingsInput)
if err != nil {
return nil, passkeyHTTPErrorInternal(err)
}
- return &MFARecoveryCodesOutput{Body: base.ApiResponse[RecoveryCodesResponse]{Success: true, Data: RecoveryCodesResponse{Codes: codes}}}, nil
+ return &handlerutil.Out[RecoveryCodesResponse]{Body: base.ApiResponse[RecoveryCodesResponse]{Success: true, Data: RecoveryCodesResponse{Codes: codes}}}, nil
}
-func (h *PasskeyHandler) DisableMFA(ctx context.Context, input *MFASettingsInput) (*DeletePasskeyOutput, error) {
+func (h *PasskeyHandler) DisableMFA(ctx context.Context, input *MFASettingsInput) (*handlerutil.Out[base.MessageResponse], error) {
userModel, sessionID, err := requireInteractiveSessionInternal(ctx)
if err != nil {
return nil, err
@@ -673,10 +617,10 @@ func (h *PasskeyHandler) DisableMFA(ctx context.Context, input *MFASettingsInput
if err := h.passkeyService.DisableMFA(ctx, userModel.ID, sessionID, input.StepUpToken); err != nil {
return nil, passkeyHTTPErrorInternal(err)
}
- return &DeletePasskeyOutput{Body: base.ApiResponse[base.MessageResponse]{Success: true, Data: base.MessageResponse{Message: "Passkey MFA disabled"}}}, nil
+ return &handlerutil.Out[base.MessageResponse]{Body: base.ApiResponse[base.MessageResponse]{Success: true, Data: base.MessageResponse{Message: "Passkey MFA disabled"}}}, nil
}
-func (h *PasskeyHandler) RegenerateRecoveryCodes(ctx context.Context, input *MFASettingsInput) (*MFARecoveryCodesOutput, error) {
+func (h *PasskeyHandler) RegenerateRecoveryCodes(ctx context.Context, input *MFASettingsInput) (*handlerutil.Out[RecoveryCodesResponse], error) {
userModel, sessionID, err := requireInteractiveSessionInternal(ctx)
if err != nil {
return nil, err
@@ -685,7 +629,7 @@ func (h *PasskeyHandler) RegenerateRecoveryCodes(ctx context.Context, input *MFA
if err != nil {
return nil, passkeyHTTPErrorInternal(err)
}
- return &MFARecoveryCodesOutput{Body: base.ApiResponse[RecoveryCodesResponse]{Success: true, Data: RecoveryCodesResponse{Codes: codes}}}, nil
+ return &handlerutil.Out[RecoveryCodesResponse]{Body: base.ApiResponse[RecoveryCodesResponse]{Success: true, Data: RecoveryCodesResponse{Codes: codes}}}, nil
}
func (h *PasskeyHandler) authenticationResponseInternal(ctx context.Context, userModel *common.User, tokenPair *auth.TokenPair) (*authtypes.AuthenticationResponse, error) {
@@ -732,7 +676,7 @@ func marshalCredentialInternal(credential map[string]any) ([]byte, error) {
if len(credential) == 0 {
return nil, errors.New("credential is required")
}
- return stdjson.Marshal(credential)
+ return json.Marshal(credential)
}
func tokenCookieInternal(ctx context.Context, tokenPair *auth.TokenPair) []string {
diff --git a/backend/internal/passkey/service.go b/backend/internal/passkey/service.go
index 050adad1d..73beb2db2 100644
--- a/backend/internal/passkey/service.go
+++ b/backend/internal/passkey/service.go
@@ -12,7 +12,7 @@ import (
"encoding/base32"
"encoding/base64"
"encoding/hex"
- "encoding/json"
+ "encoding/json/v2"
"log/slog"
"net/url"
"strings"
diff --git a/backend/internal/port/handler.go b/backend/internal/port/handler.go
index 43440609d..977fe06b7 100644
--- a/backend/internal/port/handler.go
+++ b/backend/internal/port/handler.go
@@ -25,10 +25,6 @@ type ListPortsInput struct {
Limit int `query:"limit" default:"20" doc:"Number of items per page"`
}
-type ListPortsOutput struct {
- Body base.Paginated[porttypes.PortMapping]
-}
-
func RegisterPorts(api huma.API, portSvc *PortService) {
h := &PortHandler{portService: portSvc}
@@ -42,7 +38,7 @@ func RegisterPorts(api huma.API, portSvc *PortService) {
}, authz.PermContainersList, h.ListPorts)
}
-func (h *PortHandler) ListPorts(ctx context.Context, input *ListPortsInput) (*ListPortsOutput, error) {
+func (h *PortHandler) ListPorts(ctx context.Context, input *ListPortsInput) (*handlerutil.Page[porttypes.PortMapping], error) {
params := handlerutil.PaginationParams(input.Start, input.Limit, input.Sort, input.Order, input.Search)
items, paginationResp, err := h.portService.ListPortsPaginated(ctx, params)
@@ -50,7 +46,7 @@ func (h *PortHandler) ListPorts(ctx context.Context, input *ListPortsInput) (*Li
return nil, huma.Error500InternalServerError("failed to list ports")
}
- return &ListPortsOutput{
+ return &handlerutil.Page[porttypes.PortMapping]{
Body: base.Paginated[porttypes.PortMapping]{
Success: true,
Data: items,
diff --git a/backend/internal/port/service.go b/backend/internal/port/service.go
index 92f7fefd0..eed929bce 100644
--- a/backend/internal/port/service.go
+++ b/backend/internal/port/service.go
@@ -51,7 +51,7 @@ func (s *PortService) ListPortsPaginated(ctx context.Context, params pagination.
}
}
- result := pagination.SearchOrderAndPaginate(items, params, s.buildPortPaginationConfig())
+ result := s.buildPortPaginationConfig().SearchOrderAndPaginate(items, params)
return result.Items, pagination.BuildResponse(result.TotalCount, result.TotalAvailable, params), nil
}
diff --git a/backend/internal/project/handler.go b/backend/internal/project/handler.go
index c64e0b8f6..8f2a56ec0 100644
--- a/backend/internal/project/handler.go
+++ b/backend/internal/project/handler.go
@@ -57,28 +57,15 @@ type ListProjectsInput struct {
Tags string `query:"tags" doc:"Filter by tag names (comma-separated, OR semantics)"`
}
-type ListProjectsOutput struct {
- Body base.Paginated[project.Details]
-}
-
type GetProjectStatusCountsInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
}
-type GetProjectStatusCountsOutput struct {
- Body base.ApiResponse[project.StatusCounts]
-}
-
// ListProjectTagsInput identifies the environment whose tag catalog is requested.
type ListProjectTagsInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
}
-// ListProjectTagsOutput contains the environment's distinct project tag options.
-type ListProjectTagsOutput struct {
- Body base.ApiResponse[[]project.TagOption]
-}
-
// UpdateProjectTagInput identifies a project and the UI tag mutation to apply.
type UpdateProjectTagInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
@@ -86,48 +73,27 @@ type UpdateProjectTagInput struct {
Body project.UpdateTag
}
-// UpdateProjectTagOutput contains the project's effective tags after mutation.
-type UpdateProjectTagOutput struct {
- Body base.ApiResponse[project.UpdateTagResponse]
-}
-
type DeployProjectInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
ProjectID string `path:"projectId" doc:"Project ID"`
Body *project.DeployOptions
}
-type DeployProjectOutput struct {
- Body base.ApiResponse[base.MessageResponse]
-}
-
type DownProjectInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
ProjectID string `path:"projectId" doc:"Project ID"`
}
-type DownProjectOutput struct {
- Body base.ApiResponse[base.MessageResponse]
-}
-
type CreateProjectInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
RawBody multipart.Form `contentType:"multipart/form-data"`
}
-type CreateProjectOutput struct {
- Body base.ApiResponse[project.CreateReponse]
-}
-
type GetProjectInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
ProjectID string `path:"projectId" doc:"Project ID"`
}
-type GetProjectOutput struct {
- Body base.ApiResponse[project.Details]
-}
-
type RedeployProjectInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
ProjectID string `path:"projectId" doc:"Project ID"`
@@ -140,30 +106,18 @@ type DestroyProjectInput struct {
Body *project.Destroy
}
-type DestroyProjectOutput struct {
- Body base.ApiResponse[base.MessageResponse]
-}
-
type UpdateProjectInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
ProjectID string `path:"projectId" doc:"Project ID"`
Body project.UpdateProject
}
-type UpdateProjectOutput struct {
- Body base.ApiResponse[project.Details]
-}
-
type RestartProjectInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
ProjectID string `path:"projectId" doc:"Project ID"`
Services []string `query:"services" doc:"Service names to restart; empty restarts all services"`
}
-type RestartProjectOutput struct {
- Body base.ApiResponse[base.MessageResponse]
-}
-
type UpdateProjectServicesInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
ProjectID string `path:"projectId" doc:"Project ID"`
@@ -172,28 +126,16 @@ type UpdateProjectServicesInput struct {
}
}
-type UpdateProjectServicesOutput struct {
- Body base.ApiResponse[base.MessageResponse]
-}
-
type ArchiveProjectInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
ProjectID string `path:"projectId" doc:"Project ID"`
}
-type ArchiveProjectOutput struct {
- Body base.ApiResponse[base.MessageResponse]
-}
-
type UnarchiveProjectInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
ProjectID string `path:"projectId" doc:"Project ID"`
}
-type UnarchiveProjectOutput struct {
- Body base.ApiResponse[base.MessageResponse]
-}
-
type PullProjectImagesInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
ProjectID string `path:"projectId" doc:"Project ID"`
@@ -437,7 +379,7 @@ func RegisterProjects(api huma.API, projectService *ProjectService, activityServ
}
// ListProjects returns a paginated list of projects.
-func (h *ProjectHandler) ListProjects(ctx context.Context, input *ListProjectsInput) (*ListProjectsOutput, error) {
+func (h *ProjectHandler) ListProjects(ctx context.Context, input *ListProjectsInput) (*handlerutil.Page[project.Details], error) {
params := handlerutil.PaginationParams(input.Start, input.Limit, input.Sort, input.Order, input.Search)
if input.Status != "" {
params.Filters["status"] = input.Status
@@ -464,7 +406,7 @@ func (h *ProjectHandler) ListProjects(ctx context.Context, input *ListProjectsIn
projects = []project.Details{}
}
- return &ListProjectsOutput{
+ return &handlerutil.Page[project.Details]{
Body: base.Paginated[project.Details]{
Success: true,
Data: projects,
@@ -474,13 +416,13 @@ func (h *ProjectHandler) ListProjects(ctx context.Context, input *ListProjectsIn
}
// GetProjectStatusCounts returns counts of projects by status.
-func (h *ProjectHandler) GetProjectStatusCounts(ctx context.Context, input *GetProjectStatusCountsInput) (*GetProjectStatusCountsOutput, error) {
+func (h *ProjectHandler) GetProjectStatusCounts(ctx context.Context, input *GetProjectStatusCountsInput) (*handlerutil.Out[project.StatusCounts], error) {
_, running, stopped, total, archived, err := h.projectService.GetProjectStatusCounts(ctx)
if err != nil {
return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to get project status counts").Error())
}
- return &GetProjectStatusCountsOutput{
+ return &handlerutil.Out[project.StatusCounts]{
Body: base.ApiResponse[project.StatusCounts]{
Success: true,
Data: project.StatusCounts{
@@ -494,7 +436,7 @@ func (h *ProjectHandler) GetProjectStatusCounts(ctx context.Context, input *GetP
}
// ListProjectTags returns the reusable project tag catalog for an environment.
-func (h *ProjectHandler) ListProjectTags(ctx context.Context, _ *ListProjectTagsInput) (*ListProjectTagsOutput, error) {
+func (h *ProjectHandler) ListProjectTags(ctx context.Context, _ *ListProjectTagsInput) (*handlerutil.Out[[]project.TagOption], error) {
options, err := h.projectService.ListProjectTagOptions(ctx)
if err != nil {
return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to list project tags").Error())
@@ -502,11 +444,11 @@ func (h *ProjectHandler) ListProjectTags(ctx context.Context, _ *ListProjectTags
if options == nil {
options = []project.TagOption{}
}
- return &ListProjectTagsOutput{Body: base.ApiResponse[[]project.TagOption]{Success: true, Data: options}}, nil
+ return &handlerutil.Out[[]project.TagOption]{Body: base.ApiResponse[[]project.TagOption]{Success: true, Data: options}}, nil
}
// UpdateProjectTag applies one UI-managed project tag association change.
-func (h *ProjectHandler) UpdateProjectTag(ctx context.Context, input *UpdateProjectTagInput) (*UpdateProjectTagOutput, error) {
+func (h *ProjectHandler) UpdateProjectTag(ctx context.Context, input *UpdateProjectTagInput) (*handlerutil.Out[project.UpdateTagResponse], error) {
user, err := handlerutil.RequireUser(ctx)
if err != nil {
return nil, err
@@ -541,7 +483,7 @@ func (h *ProjectHandler) UpdateProjectTag(ctx context.Context, input *UpdateProj
}
}
- return &UpdateProjectTagOutput{Body: base.ApiResponse[project.UpdateTagResponse]{
+ return &handlerutil.Out[project.UpdateTagResponse]{Body: base.ApiResponse[project.UpdateTagResponse]{
Success: true,
Data: project.UpdateTagResponse{
Tags: tags,
@@ -647,7 +589,7 @@ func (h *ProjectHandler) DeployProject(ctx context.Context, input *DeployProject
}
// DownProject brings down a Docker Compose project.
-func (h *ProjectHandler) DownProject(ctx context.Context, input *DownProjectInput) (*DownProjectOutput, error) {
+func (h *ProjectHandler) DownProject(ctx context.Context, input *DownProjectInput) (*handlerutil.Out[base.MessageResponse], error) {
user, err := handlerutil.RequireUser(ctx)
if err != nil {
return nil, err
@@ -668,7 +610,7 @@ func (h *ProjectHandler) DownProject(ctx context.Context, input *DownProjectInpu
activitylib.FlushWriter(activityWriter)
activitylib.CompleteHandlerActivity(runtimeCtx, h.activityService, activityID, "Project stopped", nil)
- return &DownProjectOutput{
+ return &handlerutil.Out[base.MessageResponse]{
Body: base.ApiResponse[base.MessageResponse]{
Success: true,
Data: base.MessageResponse{
@@ -708,7 +650,7 @@ func projectWorkspaceRequestHTTPErrorInternal(err error) error {
}
// CreateProject creates a new Docker Compose project.
-func (h *ProjectHandler) CreateProject(ctx context.Context, input *CreateProjectInput) (*CreateProjectOutput, error) {
+func (h *ProjectHandler) CreateProject(ctx context.Context, input *CreateProjectInput) (*handlerutil.Out[project.CreateReponse], error) {
projectInput, err := handlerutil.ParseMultipartJSONPart[project.CreateProject](input.RawBody, "project")
if err != nil {
return nil, err
@@ -774,7 +716,7 @@ func (h *ProjectHandler) CreateProject(ctx context.Context, input *CreateProject
return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to load project tags").Error())
}
- return &CreateProjectOutput{
+ return &handlerutil.Out[project.CreateReponse]{
Body: base.ApiResponse[project.CreateReponse]{
Success: true,
Data: response,
@@ -783,7 +725,7 @@ func (h *ProjectHandler) CreateProject(ctx context.Context, input *CreateProject
}
// GetProject returns a project by ID.
-func (h *ProjectHandler) GetProject(ctx context.Context, input *GetProjectInput) (*GetProjectOutput, error) {
+func (h *ProjectHandler) GetProject(ctx context.Context, input *GetProjectInput) (*handlerutil.Out[project.Details], error) {
if input.ProjectID == "" {
return nil, huma.Error400BadRequest("Project ID is required")
}
@@ -793,7 +735,7 @@ func (h *ProjectHandler) GetProject(ctx context.Context, input *GetProjectInput)
return nil, huma.Error404NotFound(errors.WithMessage(err, "Failed to get project details").Error())
}
- return &GetProjectOutput{
+ return &handlerutil.Out[project.Details]{
Body: base.ApiResponse[project.Details]{
Success: true,
Data: details,
@@ -801,7 +743,7 @@ func (h *ProjectHandler) GetProject(ctx context.Context, input *GetProjectInput)
}, nil
}
-func (h *ProjectHandler) getProjectDetailsWithOptionsInternal(ctx context.Context, input *GetProjectInput, opts project.DetailsOptions) (*GetProjectOutput, error) {
+func (h *ProjectHandler) getProjectDetailsWithOptionsInternal(ctx context.Context, input *GetProjectInput, opts project.DetailsOptions) (*handlerutil.Out[project.Details], error) {
if input.ProjectID == "" {
return nil, huma.Error400BadRequest("Project ID is required")
}
@@ -811,7 +753,7 @@ func (h *ProjectHandler) getProjectDetailsWithOptionsInternal(ctx context.Contex
return nil, huma.Error404NotFound(errors.WithMessage(err, "Failed to get project details").Error())
}
- return &GetProjectOutput{
+ return &handlerutil.Out[project.Details]{
Body: base.ApiResponse[project.Details]{
Success: true,
Data: details,
@@ -819,7 +761,7 @@ func (h *ProjectHandler) getProjectDetailsWithOptionsInternal(ctx context.Contex
}, nil
}
-func (h *ProjectHandler) GetProjectCompose(ctx context.Context, input *GetProjectInput) (*GetProjectOutput, error) {
+func (h *ProjectHandler) GetProjectCompose(ctx context.Context, input *GetProjectInput) (*handlerutil.Out[project.Details], error) {
return h.getProjectDetailsWithOptionsInternal(ctx, input, project.DetailsOptions{
IncludeComposeContent: true,
IncludeEnvState: true,
@@ -828,13 +770,13 @@ func (h *ProjectHandler) GetProjectCompose(ctx context.Context, input *GetProjec
})
}
-func (h *ProjectHandler) GetProjectRuntime(ctx context.Context, input *GetProjectInput) (*GetProjectOutput, error) {
+func (h *ProjectHandler) GetProjectRuntime(ctx context.Context, input *GetProjectInput) (*handlerutil.Out[project.Details], error) {
return h.getProjectDetailsWithOptionsInternal(ctx, input, project.DetailsOptions{
IncludeRuntimeServices: true,
})
}
-func (h *ProjectHandler) GetProjectUpdates(ctx context.Context, input *GetProjectInput) (*GetProjectOutput, error) {
+func (h *ProjectHandler) GetProjectUpdates(ctx context.Context, input *GetProjectInput) (*handlerutil.Out[project.Details], error) {
return h.getProjectDetailsWithOptionsInternal(ctx, input, project.DetailsOptions{
IncludeServiceConfigs: true,
IncludeUpdateInfo: true,
@@ -868,7 +810,7 @@ func (h *ProjectHandler) RedeployProject(ctx context.Context, input *RedeployPro
}
// DestroyProject destroys a Docker Compose project.
-func (h *ProjectHandler) DestroyProject(ctx context.Context, input *DestroyProjectInput) (*DestroyProjectOutput, error) {
+func (h *ProjectHandler) DestroyProject(ctx context.Context, input *DestroyProjectInput) (*handlerutil.Out[base.MessageResponse], error) {
user, err := handlerutil.RequireUser(ctx)
if err != nil {
return nil, err
@@ -902,7 +844,7 @@ func (h *ProjectHandler) DestroyProject(ctx context.Context, input *DestroyProje
activitylib.FlushWriter(activityWriter)
activitylib.CompleteHandlerActivity(runtimeCtx, h.activityService, activityID, "Project destroyed", nil)
- return &DestroyProjectOutput{
+ return &handlerutil.Out[base.MessageResponse]{
Body: base.ApiResponse[base.MessageResponse]{
Success: true,
Data: base.MessageResponse{
@@ -914,7 +856,7 @@ func (h *ProjectHandler) DestroyProject(ctx context.Context, input *DestroyProje
}
// UpdateProject updates a Docker Compose project.
-func (h *ProjectHandler) UpdateProject(ctx context.Context, input *UpdateProjectInput) (*UpdateProjectOutput, error) {
+func (h *ProjectHandler) UpdateProject(ctx context.Context, input *UpdateProjectInput) (*handlerutil.Out[project.Details], error) {
if input.ProjectID == "" {
return nil, huma.Error400BadRequest("Project ID is required")
}
@@ -960,7 +902,7 @@ func (h *ProjectHandler) UpdateProject(ctx context.Context, input *UpdateProject
}
details.ActivityID = mo.EmptyableToOption(strings.TrimSpace(activityID)).ToPointer()
- return &UpdateProjectOutput{
+ return &handlerutil.Out[project.Details]{
Body: base.ApiResponse[project.Details]{
Success: true,
Data: details,
@@ -970,19 +912,19 @@ func (h *ProjectHandler) UpdateProject(ctx context.Context, input *UpdateProject
// RestartProject restarts the given services in a project (all services when none
// are specified).
-func (h *ProjectHandler) RestartProject(ctx context.Context, input *RestartProjectInput) (*RestartProjectOutput, error) {
+func (h *ProjectHandler) RestartProject(ctx context.Context, input *RestartProjectInput) (*handlerutil.Out[base.MessageResponse], error) {
response, err := h.runProjectActivityActionResponseInternal(ctx, input.EnvironmentID, input.ProjectID, h.restartProjectActivityConfigInternal(input.Services))
if err != nil {
return nil, err
}
- return &RestartProjectOutput{
+ return &handlerutil.Out[base.MessageResponse]{
Body: response,
}, nil
}
// UpdateProjectServices pulls the latest images for the given services and recreates them.
-func (h *ProjectHandler) UpdateProjectServices(ctx context.Context, input *UpdateProjectServicesInput) (*UpdateProjectServicesOutput, error) {
+func (h *ProjectHandler) UpdateProjectServices(ctx context.Context, input *UpdateProjectServicesInput) (*handlerutil.Out[base.MessageResponse], error) {
var serviceNames []string
if input.Body != nil {
serviceNames = input.Body.Services
@@ -993,7 +935,7 @@ func (h *ProjectHandler) UpdateProjectServices(ctx context.Context, input *Updat
return nil, err
}
- return &UpdateProjectServicesOutput{
+ return &handlerutil.Out[base.MessageResponse]{
Body: response,
}, nil
}
@@ -1110,7 +1052,7 @@ func (h *ProjectHandler) runProjectActivityActionInternal(ctx context.Context, e
}, nil
}
-func (h *ProjectHandler) ArchiveProject(ctx context.Context, input *ArchiveProjectInput) (*ArchiveProjectOutput, error) {
+func (h *ProjectHandler) ArchiveProject(ctx context.Context, input *ArchiveProjectInput) (*handlerutil.Out[base.MessageResponse], error) {
if input.ProjectID == "" {
return nil, huma.Error400BadRequest("Project ID is required")
}
@@ -1127,7 +1069,7 @@ func (h *ProjectHandler) ArchiveProject(ctx context.Context, input *ArchiveProje
return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to archive project").Error())
}
- return &ArchiveProjectOutput{
+ return &handlerutil.Out[base.MessageResponse]{
Body: base.ApiResponse[base.MessageResponse]{
Success: true,
Data: base.MessageResponse{Message: "Project archived successfully"},
@@ -1135,7 +1077,7 @@ func (h *ProjectHandler) ArchiveProject(ctx context.Context, input *ArchiveProje
}, nil
}
-func (h *ProjectHandler) UnarchiveProject(ctx context.Context, input *UnarchiveProjectInput) (*UnarchiveProjectOutput, error) {
+func (h *ProjectHandler) UnarchiveProject(ctx context.Context, input *UnarchiveProjectInput) (*handlerutil.Out[base.MessageResponse], error) {
if input.ProjectID == "" {
return nil, huma.Error400BadRequest("Project ID is required")
}
@@ -1149,7 +1091,7 @@ func (h *ProjectHandler) UnarchiveProject(ctx context.Context, input *UnarchiveP
return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to unarchive project").Error())
}
- return &UnarchiveProjectOutput{
+ return &handlerutil.Out[base.MessageResponse]{
Body: base.ApiResponse[base.MessageResponse]{
Success: true,
Data: base.MessageResponse{Message: "Project unarchived successfully"},
diff --git a/backend/internal/project/project_listing.go b/backend/internal/project/project_listing.go
index 7286dd28c..32ea12988 100644
--- a/backend/internal/project/project_listing.go
+++ b/backend/internal/project/project_listing.go
@@ -310,7 +310,7 @@ func (s *ProjectService) filterProjectsWithDerivedFiltersInternal(
s.enrichProjectsWithUpdateInfoInternal(ctx, projectsArray, items)
items = s.appendDiscoveredComposeProjectUpdatesInternal(ctx, params, projectsArray, items)
- return pagination.SearchOrderAndPaginate(items, withoutProjectDBFiltersInternal(params), s.buildProjectDerivedPaginationConfigInternal()), nil
+ return s.buildProjectDerivedPaginationConfigInternal().SearchOrderAndPaginate(items, withoutProjectDBFiltersInternal(params)), nil
}
func withoutProjectDBFiltersInternal(params pagination.QueryParams) pagination.QueryParams {
diff --git a/backend/internal/project/workspace_handler.go b/backend/internal/project/workspace_handler.go
index e8fa28f30..623f51978 100644
--- a/backend/internal/project/workspace_handler.go
+++ b/backend/internal/project/workspace_handler.go
@@ -31,30 +31,18 @@ type GetProjectWorkspaceInput struct {
ProjectID string `path:"projectId" doc:"Project ID"`
}
-type GetProjectWorkspaceOutput struct {
- Body base.ApiResponse[workspacetypes.Workspace]
-}
-
type GetProjectWorkspaceFileInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
ProjectID string `path:"projectId" doc:"Project ID"`
RelativePath string `query:"relativePath" doc:"Path relative to the project workspace root"`
}
-type GetProjectWorkspaceFileOutput struct {
- Body base.ApiResponse[workspacetypes.FileContent]
-}
-
type UpdateProjectWorkspaceInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
ProjectID string `path:"projectId" doc:"Project ID"`
RawBody multipart.Form `contentType:"multipart/form-data"`
}
-type UpdateProjectWorkspaceOutput struct {
- Body base.ApiResponse[workspacetypes.Workspace]
-}
-
func registerProjectWorkspaceRoutesInternal(api huma.API, h *ProjectHandler) {
basePath := "/environments/{id}/projects/{projectId}/workspace"
tag := "Project Workspace"
@@ -83,20 +71,20 @@ func projectWorkspaceHTTPErrorInternal(err error) error {
}
}
-func (h *ProjectHandler) GetProjectWorkspace(ctx context.Context, input *GetProjectWorkspaceInput) (*GetProjectWorkspaceOutput, error) {
+func (h *ProjectHandler) GetProjectWorkspace(ctx context.Context, input *GetProjectWorkspaceInput) (*handlerutil.Out[workspacetypes.Workspace], error) {
result, err := h.projectService.GetProjectWorkspace(ctx, input.ProjectID)
if err != nil {
return nil, projectWorkspaceHTTPErrorInternal(err)
}
- return &GetProjectWorkspaceOutput{Body: base.ApiResponse[workspacetypes.Workspace]{Success: true, Data: *result}}, nil
+ return &handlerutil.Out[workspacetypes.Workspace]{Body: base.ApiResponse[workspacetypes.Workspace]{Success: true, Data: *result}}, nil
}
-func (h *ProjectHandler) GetProjectWorkspaceFile(ctx context.Context, input *GetProjectWorkspaceFileInput) (*GetProjectWorkspaceFileOutput, error) {
+func (h *ProjectHandler) GetProjectWorkspaceFile(ctx context.Context, input *GetProjectWorkspaceFileInput) (*handlerutil.Out[workspacetypes.FileContent], error) {
result, err := h.projectService.GetProjectWorkspaceFile(ctx, input.ProjectID, input.RelativePath)
if err != nil {
return nil, projectWorkspaceHTTPErrorInternal(err)
}
- return &GetProjectWorkspaceFileOutput{Body: base.ApiResponse[workspacetypes.FileContent]{Success: true, Data: *result}}, nil
+ return &handlerutil.Out[workspacetypes.FileContent]{Body: base.ApiResponse[workspacetypes.FileContent]{Success: true, Data: *result}}, nil
}
func (h *ProjectHandler) DownloadProjectWorkspaceFile(ctx context.Context, input *GetProjectWorkspaceFileInput) (*huma.StreamResponse, error) {
@@ -113,7 +101,7 @@ func (h *ProjectHandler) DownloadProjectWorkspaceFile(ctx context.Context, input
}}, nil
}
-func (h *ProjectHandler) UpdateProjectWorkspace(ctx context.Context, input *UpdateProjectWorkspaceInput) (*UpdateProjectWorkspaceOutput, error) {
+func (h *ProjectHandler) UpdateProjectWorkspace(ctx context.Context, input *UpdateProjectWorkspaceInput) (*handlerutil.Out[workspacetypes.Workspace], error) {
manifest, err := handlerutil.ParseMultipartJSONPart[projecttypes.WorkspaceUpdateManifest](input.RawBody, "manifest")
if err != nil {
return nil, err
@@ -145,5 +133,5 @@ func (h *ProjectHandler) UpdateProjectWorkspace(ctx context.Context, input *Upda
return nil, projectWorkspaceHTTPErrorInternal(err)
}
result.ActivityID = mo.EmptyableToOption(strings.TrimSpace(activityID)).ToPointer()
- return &UpdateProjectWorkspaceOutput{Body: base.ApiResponse[workspacetypes.Workspace]{Success: true, Data: *result}}, nil
+ return &handlerutil.Out[workspacetypes.Workspace]{Body: base.ApiResponse[workspacetypes.Workspace]{Success: true, Data: *result}}, nil
}
diff --git a/backend/internal/registry/handler.go b/backend/internal/registry/handler.go
index 17ffb4a7b..d3d948885 100644
--- a/backend/internal/registry/handler.go
+++ b/backend/internal/registry/handler.go
@@ -12,7 +12,6 @@ import (
"github.com/getarcaneapp/arcane/backend/v2/internal/middleware"
"github.com/getarcaneapp/arcane/backend/v2/pkg/authz"
"github.com/getarcaneapp/arcane/backend/v2/pkg/utils/handlerutil"
- "github.com/getarcaneapp/arcane/backend/v2/pkg/utils/mapper"
"github.com/getarcaneapp/arcane/types/v2/base"
"github.com/getarcaneapp/arcane/types/v2/containerregistry"
"go.getarcane.app/sys/crypto"
@@ -38,63 +37,31 @@ type ListContainerRegistriesInput struct {
Limit int `query:"limit" default:"20" doc:"Items per page"`
}
-type ListContainerRegistriesOutput struct {
- Body base.Paginated[containerregistry.ContainerRegistry]
-}
-
type CreateContainerRegistryInput struct {
Body CreateContainerRegistryRequest
}
-type CreateContainerRegistryOutput struct {
- Body base.ApiResponse[containerregistry.ContainerRegistry]
-}
-
type GetContainerRegistryInput struct {
ID string `path:"id" doc:"Registry ID"`
}
-type GetContainerRegistryOutput struct {
- Body base.ApiResponse[containerregistry.ContainerRegistry]
-}
-
type UpdateContainerRegistryInput struct {
ID string `path:"id" doc:"Registry ID"`
Body UpdateContainerRegistryRequest
}
-type UpdateContainerRegistryOutput struct {
- Body base.ApiResponse[containerregistry.ContainerRegistry]
-}
-
type DeleteContainerRegistryInput struct {
ID string `path:"id" doc:"Registry ID"`
}
-type DeleteContainerRegistryOutput struct {
- Body base.ApiResponse[base.MessageResponse]
-}
-
type TestContainerRegistryInput struct {
ID string `path:"id" doc:"Registry ID"`
}
-type TestContainerRegistryOutput struct {
- Body base.ApiResponse[base.MessageResponse]
-}
-
-type GetContainerRegistryPullUsageOutput struct {
- Body base.ApiResponse[containerregistry.PullUsageResponse]
-}
-
type SyncContainerRegistriesInput struct {
Body containerregistry.SyncRequest
}
-type SyncContainerRegistriesOutput struct {
- Body base.ApiResponse[base.MessageResponse]
-}
-
// ============================================================================
// Registration
// ============================================================================
@@ -199,7 +166,7 @@ func RegisterContainerRegistries(api huma.API, h *ContainerRegistryHandler) {
// ============================================================================
// ListRegistries returns a paginated list of container registries.
-func (h *ContainerRegistryHandler) ListRegistries(ctx context.Context, input *ListContainerRegistriesInput) (*ListContainerRegistriesOutput, error) {
+func (h *ContainerRegistryHandler) ListRegistries(ctx context.Context, input *ListContainerRegistriesInput) (*handlerutil.Page[containerregistry.ContainerRegistry], error) {
params := handlerutil.PaginationParams(input.Start, input.Limit, input.Sort, input.Order, input.Search)
registries, paginationResp, err := h.registryService.GetRegistriesPaginated(ctx, params)
@@ -207,7 +174,7 @@ func (h *ContainerRegistryHandler) ListRegistries(ctx context.Context, input *Li
return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to list registries").Error())
}
- return &ListContainerRegistriesOutput{
+ return &handlerutil.Page[containerregistry.ContainerRegistry]{
Body: base.Paginated[containerregistry.ContainerRegistry]{
Success: true,
Data: registries,
@@ -217,13 +184,13 @@ func (h *ContainerRegistryHandler) ListRegistries(ctx context.Context, input *Li
}
// GetPullUsage returns pull usage visibility for configured registries.
-func (h *ContainerRegistryHandler) GetPullUsage(ctx context.Context, input *struct{}) (*GetContainerRegistryPullUsageOutput, error) {
+func (h *ContainerRegistryHandler) GetPullUsage(ctx context.Context, input *struct{}) (*handlerutil.Out[containerregistry.PullUsageResponse], error) {
usage, err := h.registryService.GetRegistryPullUsage(ctx)
if err != nil {
return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to retrieve registry").Error())
}
- return &GetContainerRegistryPullUsageOutput{
+ return &handlerutil.Out[containerregistry.PullUsageResponse]{
Body: base.ApiResponse[containerregistry.PullUsageResponse]{
Success: true,
Data: usage,
@@ -232,7 +199,7 @@ func (h *ContainerRegistryHandler) GetPullUsage(ctx context.Context, input *stru
}
// CreateRegistry creates a new container registry.
-func (h *ContainerRegistryHandler) CreateRegistry(ctx context.Context, input *CreateContainerRegistryInput) (*CreateContainerRegistryOutput, error) {
+func (h *ContainerRegistryHandler) CreateRegistry(ctx context.Context, input *CreateContainerRegistryInput) (*handlerutil.Out[containerregistry.ContainerRegistry], error) {
reg, err := h.registryService.CreateRegistry(ctx, input.Body)
if err != nil {
apiErr := common.ToAPIError(err)
@@ -241,42 +208,36 @@ func (h *ContainerRegistryHandler) CreateRegistry(ctx context.Context, input *Cr
h.triggerRemoteRegistrySync(ctx, "registry creation")
- out, mapErr := mapper.MapOne[*ContainerRegistry, containerregistry.ContainerRegistry](reg)
+ body, mapErr := handlerutil.MapOneAPIResponse[*ContainerRegistry, containerregistry.ContainerRegistry](reg, func(error) string {
+ return "Failed to map registry"
+ })
if mapErr != nil {
- return nil, huma.Error500InternalServerError(errors.WithMessage(mapErr, "Failed to map registry").Error())
+ return nil, mapErr
}
- return &CreateContainerRegistryOutput{
- Body: base.ApiResponse[containerregistry.ContainerRegistry]{
- Success: true,
- Data: out,
- },
- }, nil
+ return &handlerutil.Out[containerregistry.ContainerRegistry]{Body: body}, nil
}
// GetRegistry returns a container registry by ID.
-func (h *ContainerRegistryHandler) GetRegistry(ctx context.Context, input *GetContainerRegistryInput) (*GetContainerRegistryOutput, error) {
+func (h *ContainerRegistryHandler) GetRegistry(ctx context.Context, input *GetContainerRegistryInput) (*handlerutil.Out[containerregistry.ContainerRegistry], error) {
reg, err := h.registryService.GetRegistryByID(ctx, input.ID)
if err != nil {
apiErr := common.ToAPIError(err)
return nil, huma.NewError(apiErr.HTTPStatus(), errors.WithMessage(err, "Failed to retrieve registry").Error())
}
- out, mapErr := mapper.MapOne[*ContainerRegistry, containerregistry.ContainerRegistry](reg)
+ body, mapErr := handlerutil.MapOneAPIResponse[*ContainerRegistry, containerregistry.ContainerRegistry](reg, func(error) string {
+ return "Failed to map registry"
+ })
if mapErr != nil {
- return nil, huma.Error500InternalServerError(errors.WithMessage(mapErr, "Failed to map registry").Error())
+ return nil, mapErr
}
- return &GetContainerRegistryOutput{
- Body: base.ApiResponse[containerregistry.ContainerRegistry]{
- Success: true,
- Data: out,
- },
- }, nil
+ return &handlerutil.Out[containerregistry.ContainerRegistry]{Body: body}, nil
}
// UpdateRegistry updates a container registry.
-func (h *ContainerRegistryHandler) UpdateRegistry(ctx context.Context, input *UpdateContainerRegistryInput) (*UpdateContainerRegistryOutput, error) {
+func (h *ContainerRegistryHandler) UpdateRegistry(ctx context.Context, input *UpdateContainerRegistryInput) (*handlerutil.Out[containerregistry.ContainerRegistry], error) {
reg, err := h.registryService.UpdateRegistry(ctx, input.ID, input.Body)
if err != nil {
apiErr := common.ToAPIError(err)
@@ -285,21 +246,18 @@ func (h *ContainerRegistryHandler) UpdateRegistry(ctx context.Context, input *Up
h.triggerRemoteRegistrySync(ctx, "registry update")
- out, mapErr := mapper.MapOne[*ContainerRegistry, containerregistry.ContainerRegistry](reg)
+ body, mapErr := handlerutil.MapOneAPIResponse[*ContainerRegistry, containerregistry.ContainerRegistry](reg, func(error) string {
+ return "Failed to map registry"
+ })
if mapErr != nil {
- return nil, huma.Error500InternalServerError(errors.WithMessage(mapErr, "Failed to map registry").Error())
+ return nil, mapErr
}
- return &UpdateContainerRegistryOutput{
- Body: base.ApiResponse[containerregistry.ContainerRegistry]{
- Success: true,
- Data: out,
- },
- }, nil
+ return &handlerutil.Out[containerregistry.ContainerRegistry]{Body: body}, nil
}
// DeleteRegistry deletes a container registry.
-func (h *ContainerRegistryHandler) DeleteRegistry(ctx context.Context, input *DeleteContainerRegistryInput) (*DeleteContainerRegistryOutput, error) {
+func (h *ContainerRegistryHandler) DeleteRegistry(ctx context.Context, input *DeleteContainerRegistryInput) (*handlerutil.Out[base.MessageResponse], error) {
if err := h.registryService.DeleteRegistry(ctx, input.ID); err != nil {
apiErr := common.ToAPIError(err)
return nil, huma.NewError(apiErr.HTTPStatus(), errors.WithMessage(err, "Failed to delete registry").Error())
@@ -307,7 +265,7 @@ func (h *ContainerRegistryHandler) DeleteRegistry(ctx context.Context, input *De
h.triggerRemoteRegistrySync(ctx, "registry deletion")
- return &DeleteContainerRegistryOutput{
+ return &handlerutil.Out[base.MessageResponse]{
Body: base.ApiResponse[base.MessageResponse]{
Success: true,
Data: base.MessageResponse{
@@ -318,7 +276,7 @@ func (h *ContainerRegistryHandler) DeleteRegistry(ctx context.Context, input *De
}
// TestRegistry tests connectivity to a container registry.
-func (h *ContainerRegistryHandler) TestRegistry(ctx context.Context, input *TestContainerRegistryInput) (*TestContainerRegistryOutput, error) {
+func (h *ContainerRegistryHandler) TestRegistry(ctx context.Context, input *TestContainerRegistryInput) (*handlerutil.Out[base.MessageResponse], error) {
reg, err := h.registryService.GetRegistryByID(ctx, input.ID)
if err != nil {
apiErr := common.ToAPIError(err)
@@ -330,7 +288,7 @@ func (h *ContainerRegistryHandler) TestRegistry(ctx context.Context, input *Test
if err := h.registryService.TestECRRegistry(ctx, reg); err != nil {
return nil, huma.Error400BadRequest(errors.WithMessage(err, "Registry test failed").Error())
}
- return &TestContainerRegistryOutput{
+ return &handlerutil.Out[base.MessageResponse]{
Body: base.ApiResponse[base.MessageResponse]{
Success: true,
Data: base.MessageResponse{
@@ -354,7 +312,7 @@ func (h *ContainerRegistryHandler) TestRegistry(ctx context.Context, input *Test
msg = "Registry saved (no credentials to test)"
}
- return &TestContainerRegistryOutput{
+ return &handlerutil.Out[base.MessageResponse]{
Body: base.ApiResponse[base.MessageResponse]{
Success: true,
Data: base.MessageResponse{
@@ -365,13 +323,13 @@ func (h *ContainerRegistryHandler) TestRegistry(ctx context.Context, input *Test
}
// SyncRegistries syncs container registries from a remote source.
-func (h *ContainerRegistryHandler) SyncRegistries(ctx context.Context, input *SyncContainerRegistriesInput) (*SyncContainerRegistriesOutput, error) {
+func (h *ContainerRegistryHandler) SyncRegistries(ctx context.Context, input *SyncContainerRegistriesInput) (*handlerutil.Out[base.MessageResponse], error) {
if err := h.registryService.SyncRegistries(ctx, input.Body.Registries); err != nil {
apiErr := common.ToAPIError(err)
return nil, huma.NewError(apiErr.HTTPStatus(), errors.WithMessage(err, "Failed to sync registries").Error())
}
- return &SyncContainerRegistriesOutput{
+ return &handlerutil.Out[base.MessageResponse]{
Body: base.ApiResponse[base.MessageResponse]{
Success: true,
Data: base.MessageResponse{
diff --git a/backend/internal/registry/service.go b/backend/internal/registry/service.go
index d3a2365dd..75a7d2299 100644
--- a/backend/internal/registry/service.go
+++ b/backend/internal/registry/service.go
@@ -156,7 +156,7 @@ func (s *ContainerRegistryService) GetRegistriesPaginated(ctx context.Context, p
q = pagination.ApplyBooleanFilter(q, "enabled", params.Filters["enabled"])
q = pagination.ApplyBooleanFilter(q, "insecure", params.Filters["insecure"])
- out, paginationResp, err := pagination.PaginateSortAndMapDB[ContainerRegistry, containerregistry.ContainerRegistry](params, q, &registries)
+ out, paginationResp, err := params.PaginateSortAndMapDB[ContainerRegistry, containerregistry.ContainerRegistry](q, &registries)
if err != nil {
return nil, pagination.Response{}, errors.WrapIf(err, "failed to list container registries")
}
diff --git a/backend/internal/role/handler.go b/backend/internal/role/handler.go
index 764da5002..d31eb993f 100644
--- a/backend/internal/role/handler.go
+++ b/backend/internal/role/handler.go
@@ -28,64 +28,32 @@ type ListRolesInput struct {
Limit int `query:"limit" default:"20" doc:"Items per page"`
}
-type ListRolesOutput struct {
- Body base.Paginated[roletypes.Role]
-}
-
type GetRoleInput struct {
ID string `path:"id" doc:"Role ID"`
}
-type GetRoleOutput struct {
- Body base.ApiResponse[roletypes.Role]
-}
-
type CreateRoleInput struct {
Body roletypes.CreateRole
}
-type CreateRoleOutput struct {
- Body base.ApiResponse[roletypes.Role]
-}
-
type UpdateRoleInput struct {
ID string `path:"id" doc:"Role ID"`
Body roletypes.UpdateRole
}
-type UpdateRoleOutput struct {
- Body base.ApiResponse[roletypes.Role]
-}
-
type DeleteRoleInput struct {
ID string `path:"id" doc:"Role ID"`
}
-type DeleteRoleOutput struct {
- Body base.ApiResponse[base.MessageResponse]
-}
-
-type PermissionsManifestOutput struct {
- Body base.ApiResponse[roletypes.PermissionsManifest]
-}
-
type ListUserRoleAssignmentsInput struct {
UserID string `path:"userId" doc:"User ID"`
}
-type ListUserRoleAssignmentsOutput struct {
- Body base.ApiResponse[[]roletypes.RoleAssignment]
-}
-
type SetUserRoleAssignmentsInput struct {
UserID string `path:"userId" doc:"User ID"`
Body roletypes.SetUserAssignments
}
-type SetUserRoleAssignmentsOutput struct {
- Body base.ApiResponse[[]roletypes.RoleAssignment]
-}
-
// ---------- Registration ----------
func RegisterRoles(api huma.API, roleService *RoleService) {
@@ -180,7 +148,7 @@ func RegisterRoles(api huma.API, roleService *RoleService) {
// ---------- Handler implementations ----------
-func (h *RoleHandler) ListRoles(ctx context.Context, input *ListRolesInput) (*ListRolesOutput, error) {
+func (h *RoleHandler) ListRoles(ctx context.Context, input *ListRolesInput) (*handlerutil.Page[roletypes.Role], error) {
params := handlerutil.PaginationParams(input.Start, input.Limit, input.Sort, input.Order, input.Search)
roles, paginationResp, err := h.roleService.ListRoles(ctx, params)
if err != nil {
@@ -190,7 +158,7 @@ func (h *RoleHandler) ListRoles(ctx context.Context, input *ListRolesInput) (*Li
for i := range roles {
dtos[i] = h.toRoleDTO(ctx, &roles[i])
}
- return &ListRolesOutput{
+ return &handlerutil.Page[roletypes.Role]{
Body: base.Paginated[roletypes.Role]{
Success: true,
Data: dtos,
@@ -199,7 +167,7 @@ func (h *RoleHandler) ListRoles(ctx context.Context, input *ListRolesInput) (*Li
}, nil
}
-func (h *RoleHandler) GetRole(ctx context.Context, input *GetRoleInput) (*GetRoleOutput, error) {
+func (h *RoleHandler) GetRole(ctx context.Context, input *GetRoleInput) (*handlerutil.Out[roletypes.Role], error) {
role, err := h.roleService.GetRole(ctx, input.ID)
if err != nil {
if errors.Is(err, common.ErrRoleNotFound) {
@@ -207,12 +175,12 @@ func (h *RoleHandler) GetRole(ctx context.Context, input *GetRoleInput) (*GetRol
}
return nil, huma.Error500InternalServerError("failed to get role: " + err.Error())
}
- return &GetRoleOutput{
+ return &handlerutil.Out[roletypes.Role]{
Body: base.ApiResponse[roletypes.Role]{Success: true, Data: h.toRoleDTO(ctx, role)},
}, nil
}
-func (h *RoleHandler) CreateRole(ctx context.Context, input *CreateRoleInput) (*CreateRoleOutput, error) {
+func (h *RoleHandler) CreateRole(ctx context.Context, input *CreateRoleInput) (*handlerutil.Out[roletypes.Role], error) {
callerPS, _ := middleware.PermissionsFromContext(ctx)
if err := h.roleService.ValidatePermissionsAgainstCaller(callerPS, input.Body.Permissions); err != nil {
switch {
@@ -233,12 +201,12 @@ func (h *RoleHandler) CreateRole(ctx context.Context, input *CreateRoleInput) (*
}
return nil, huma.Error500InternalServerError("failed to create role: " + err.Error())
}
- return &CreateRoleOutput{
+ return &handlerutil.Out[roletypes.Role]{
Body: base.ApiResponse[roletypes.Role]{Success: true, Data: h.toRoleDTO(ctx, role)},
}, nil
}
-func (h *RoleHandler) UpdateRole(ctx context.Context, input *UpdateRoleInput) (*UpdateRoleOutput, error) {
+func (h *RoleHandler) UpdateRole(ctx context.Context, input *UpdateRoleInput) (*handlerutil.Out[roletypes.Role], error) {
callerPS, _ := middleware.PermissionsFromContext(ctx)
if err := h.roleService.ValidatePermissionsAgainstCaller(callerPS, input.Body.Permissions); err != nil {
switch {
@@ -263,12 +231,12 @@ func (h *RoleHandler) UpdateRole(ctx context.Context, input *UpdateRoleInput) (*
}
return nil, huma.Error500InternalServerError("failed to update role: " + err.Error())
}
- return &UpdateRoleOutput{
+ return &handlerutil.Out[roletypes.Role]{
Body: base.ApiResponse[roletypes.Role]{Success: true, Data: h.toRoleDTO(ctx, role)},
}, nil
}
-func (h *RoleHandler) DeleteRole(ctx context.Context, input *DeleteRoleInput) (*DeleteRoleOutput, error) {
+func (h *RoleHandler) DeleteRole(ctx context.Context, input *DeleteRoleInput) (*handlerutil.Out[base.MessageResponse], error) {
if err := h.roleService.DeleteRole(ctx, input.ID); err != nil {
switch {
case errors.Is(err, common.ErrRoleNotFound):
@@ -280,18 +248,18 @@ func (h *RoleHandler) DeleteRole(ctx context.Context, input *DeleteRoleInput) (*
}
return nil, huma.Error500InternalServerError("failed to delete role: " + err.Error())
}
- return &DeleteRoleOutput{
+ return &handlerutil.Out[base.MessageResponse]{
Body: base.ApiResponse[base.MessageResponse]{Success: true, Data: base.MessageResponse{Message: "role deleted"}},
}, nil
}
-func (h *RoleHandler) GetPermissionsManifest(_ context.Context, _ *struct{}) (*PermissionsManifestOutput, error) {
- return &PermissionsManifestOutput{
+func (h *RoleHandler) GetPermissionsManifest(_ context.Context, _ *struct{}) (*handlerutil.Out[roletypes.PermissionsManifest], error) {
+ return &handlerutil.Out[roletypes.PermissionsManifest]{
Body: base.ApiResponse[roletypes.PermissionsManifest]{Success: true, Data: buildPermissionsManifestInternal()},
}, nil
}
-func (h *RoleHandler) ListUserRoleAssignments(ctx context.Context, input *ListUserRoleAssignmentsInput) (*ListUserRoleAssignmentsOutput, error) {
+func (h *RoleHandler) ListUserRoleAssignments(ctx context.Context, input *ListUserRoleAssignmentsInput) (*handlerutil.Out[[]roletypes.RoleAssignment], error) {
rows, err := h.roleService.ListUserAssignments(ctx, input.UserID)
if err != nil {
return nil, huma.Error500InternalServerError("failed to list assignments: " + err.Error())
@@ -300,12 +268,12 @@ func (h *RoleHandler) ListUserRoleAssignments(ctx context.Context, input *ListUs
for i := range rows {
dtos[i] = toAssignmentDTOInternal(&rows[i])
}
- return &ListUserRoleAssignmentsOutput{
+ return &handlerutil.Out[[]roletypes.RoleAssignment]{
Body: base.ApiResponse[[]roletypes.RoleAssignment]{Success: true, Data: dtos},
}, nil
}
-func (h *RoleHandler) SetUserRoleAssignments(ctx context.Context, input *SetUserRoleAssignmentsInput) (*SetUserRoleAssignmentsOutput, error) {
+func (h *RoleHandler) SetUserRoleAssignments(ctx context.Context, input *SetUserRoleAssignmentsInput) (*handlerutil.Out[[]roletypes.RoleAssignment], error) {
desired := make([]UserRoleAssignment, len(input.Body.Assignments))
for i, a := range input.Body.Assignments {
desired[i] = UserRoleAssignment{RoleID: a.RoleID, EnvironmentID: a.EnvironmentID}
@@ -329,7 +297,7 @@ func (h *RoleHandler) SetUserRoleAssignments(ctx context.Context, input *SetUser
for i := range rows {
dtos[i] = toAssignmentDTOInternal(&rows[i])
}
- return &SetUserRoleAssignmentsOutput{
+ return &handlerutil.Out[[]roletypes.RoleAssignment]{
Body: base.ApiResponse[[]roletypes.RoleAssignment]{Success: true, Data: dtos},
}, nil
}
diff --git a/backend/internal/s3/handler.go b/backend/internal/s3/handler.go
index 38ebcc006..b65bebb73 100644
--- a/backend/internal/s3/handler.go
+++ b/backend/internal/s3/handler.go
@@ -34,13 +34,6 @@ type listS3DestinationsInputInternal struct {
Limit int `query:"limit" default:"20" doc:"Limit"`
}
-type listS3DestinationsOutputInternal struct {
- Body struct {
- Data []backuptypes.S3Destination `json:"data"`
- Pagination base.PaginationResponse `json:"pagination"`
- }
-}
-
type listAllS3DestinationsOutputInternal struct {
Body []backuptypes.S3Destination
}
@@ -62,10 +55,6 @@ type s3DestinationOutputInternal struct {
Body backuptypes.S3Destination
}
-type s3DestinationMessageOutputInternal struct {
- Body base.ApiResponse[base.MessageResponse]
-}
-
type testS3DestinationInputInternal struct {
ID string `path:"id" doc:"S3 destination ID"`
Body *backuptypes.UpdateS3Destination `json:"body,omitempty"`
@@ -130,16 +119,19 @@ func (h *s3DestinationHandlerInternal) inUseInternal(ctx context.Context, input
return output, nil
}
-func (h *s3DestinationHandlerInternal) listInternal(ctx context.Context, input *listS3DestinationsInputInternal) (*listS3DestinationsOutputInternal, error) {
+func (h *s3DestinationHandlerInternal) listInternal(ctx context.Context, input *listS3DestinationsInputInternal) (*handlerutil.Page[backuptypes.S3Destination], error) {
params := handlerutil.PaginationParams(input.Start, input.Limit, input.Sort, input.Order, input.Search)
destinations, paginationResponse, err := h.service.ListS3Destinations(ctx, params)
if err != nil {
return nil, huma.Error500InternalServerError(err.Error())
}
- output := &listS3DestinationsOutputInternal{}
- output.Body.Data = destinations
- output.Body.Pagination = handlerutil.PaginationResponse(paginationResponse)
- return output, nil
+ return &handlerutil.Page[backuptypes.S3Destination]{
+ Body: base.Paginated[backuptypes.S3Destination]{
+ Success: true,
+ Data: destinations,
+ Pagination: handlerutil.PaginationResponse(paginationResponse),
+ },
+ }, nil
}
func (h *s3DestinationHandlerInternal) listAllInternal(ctx context.Context, _ *struct{}) (*listAllS3DestinationsOutputInternal, error) {
@@ -150,7 +142,7 @@ func (h *s3DestinationHandlerInternal) listAllInternal(ctx context.Context, _ *s
return &listAllS3DestinationsOutputInternal{Body: destinations}, nil
}
-func (h *s3DestinationHandlerInternal) getInternal(ctx context.Context, input *s3DestinationIDInputInternal) (*s3DestinationOutputInternal, error) {
+func (h *s3DestinationHandlerInternal) getInternal(ctx context.Context, input *s3DestinationIDInputInternal) (*handlerutil.Out[backuptypes.S3Destination], error) {
destination, err := h.service.GetS3Destination(ctx, input.ID)
if errors.Is(err, ErrS3DestinationNotFound) {
return nil, huma.Error404NotFound(err.Error())
@@ -158,7 +150,7 @@ func (h *s3DestinationHandlerInternal) getInternal(ctx context.Context, input *s
if err != nil {
return nil, huma.Error500InternalServerError(err.Error())
}
- return &s3DestinationOutputInternal{Body: *destination}, nil
+ return &handlerutil.Out[backuptypes.S3Destination]{Body: base.ApiResponse[backuptypes.S3Destination]{Success: true, Data: *destination}}, nil
}
func (h *s3DestinationHandlerInternal) createInternal(ctx context.Context, input *createS3DestinationInputInternal) (*s3DestinationOutputInternal, error) {
@@ -191,7 +183,7 @@ func (h *s3DestinationHandlerInternal) updateInternal(ctx context.Context, input
return &s3DestinationOutputInternal{Body: *destination}, nil
}
-func (h *s3DestinationHandlerInternal) deleteInternal(ctx context.Context, input *s3DestinationIDInputInternal) (*s3DestinationMessageOutputInternal, error) {
+func (h *s3DestinationHandlerInternal) deleteInternal(ctx context.Context, input *s3DestinationIDInputInternal) (*handlerutil.Out[base.MessageResponse], error) {
err := h.service.DeleteS3Destination(ctx, input.ID)
if errors.Is(err, ErrS3DestinationNotFound) {
return nil, huma.Error404NotFound(err.Error())
@@ -203,17 +195,17 @@ func (h *s3DestinationHandlerInternal) deleteInternal(ctx context.Context, input
return nil, huma.Error500InternalServerError(err.Error())
}
h.triggerRemoteSyncInternal(ctx, "S3 destination deletion")
- return &s3DestinationMessageOutputInternal{Body: successMessageResponseInternal("S3 destination deleted successfully")}, nil
+ return &handlerutil.Out[base.MessageResponse]{Body: successMessageResponseInternal("S3 destination deleted successfully")}, nil
}
-func (h *s3DestinationHandlerInternal) testInternal(ctx context.Context, input *testS3DestinationInputInternal) (*s3DestinationMessageOutputInternal, error) {
+func (h *s3DestinationHandlerInternal) testInternal(ctx context.Context, input *testS3DestinationInputInternal) (*handlerutil.Out[base.MessageResponse], error) {
if err := h.service.TestS3Destination(ctx, input.ID, input.Body); err != nil {
if errors.Is(err, ErrS3DestinationNotFound) {
return nil, huma.Error404NotFound(err.Error())
}
return nil, huma.Error400BadRequest(err.Error())
}
- return &s3DestinationMessageOutputInternal{Body: successMessageResponseInternal(s3ConnectionTestSuccessInternal)}, nil
+ return &handlerutil.Out[base.MessageResponse]{Body: successMessageResponseInternal(s3ConnectionTestSuccessInternal)}, nil
}
func successMessageResponseInternal(message string) base.ApiResponse[base.MessageResponse] {
@@ -232,16 +224,16 @@ func (h *s3DestinationHandlerInternal) triggerRemoteSyncInternal(ctx context.Con
}(detachedCtx, reason)
}
-func (h *s3DestinationHandlerInternal) testConfigurationInternal(ctx context.Context, input *testS3DestinationConfigurationInputInternal) (*s3DestinationMessageOutputInternal, error) {
+func (h *s3DestinationHandlerInternal) testConfigurationInternal(ctx context.Context, input *testS3DestinationConfigurationInputInternal) (*handlerutil.Out[base.MessageResponse], error) {
if err := h.service.TestS3DestinationConfiguration(ctx, input.Body); err != nil {
return nil, huma.Error400BadRequest(err.Error())
}
- return &s3DestinationMessageOutputInternal{Body: successMessageResponseInternal(s3ConnectionTestSuccessInternal)}, nil
+ return &handlerutil.Out[base.MessageResponse]{Body: successMessageResponseInternal(s3ConnectionTestSuccessInternal)}, nil
}
-func (h *s3DestinationHandlerInternal) syncInternal(ctx context.Context, input *syncS3DestinationsInputInternal) (*s3DestinationMessageOutputInternal, error) {
+func (h *s3DestinationHandlerInternal) syncInternal(ctx context.Context, input *syncS3DestinationsInputInternal) (*handlerutil.Out[base.MessageResponse], error) {
if err := h.service.SyncS3Destinations(ctx, input.Body.Destinations); err != nil {
return nil, huma.Error400BadRequest(err.Error())
}
- return &s3DestinationMessageOutputInternal{Body: successMessageResponseInternal("S3 destinations synced successfully")}, nil
+ return &handlerutil.Out[base.MessageResponse]{Body: successMessageResponseInternal("S3 destinations synced successfully")}, nil
}
diff --git a/backend/internal/search/customize_service.go b/backend/internal/search/customize_service.go
index 5ef56373d..b4e579580 100644
--- a/backend/internal/search/customize_service.go
+++ b/backend/internal/search/customize_service.go
@@ -37,7 +37,7 @@ func (s *CustomizeSearchService) GetCustomizeCategories() []category.Category {
func (s *CustomizeSearchService) buildCategoriesFromModel() []category.Category {
// Extract category metadata from struct tags (catmeta)
- catMetaMap := utils.ExtractCategoryMetadata(CustomizeItem{}, nil)
+ catMetaMap := utils.ExtractCategoryMetadata[CustomizeItem]()
// map category id -> list of customizations
categories := map[string][]meta.Metadata{}
diff --git a/backend/internal/settings/handler.go b/backend/internal/settings/handler.go
index 542ae746c..d73374969 100644
--- a/backend/internal/settings/handler.go
+++ b/backend/internal/settings/handler.go
@@ -63,10 +63,6 @@ type UpdateSettingsInput struct {
Body settingstypes.Update `doc:"Settings update data"`
}
-type UpdateSettingsOutput struct {
- Body base.ApiResponse[[]settingstypes.SettingDto]
-}
-
type SearchSettingsInput struct {
Body searchtypes.Request `doc:"Search query"`
}
@@ -276,7 +272,7 @@ func (h *SettingsHandler) appendRuntimeSettingsInternal(settingsDto []settingsty
// GetPublicSettings returns public settings for an environment.
func (h *SettingsHandler) GetPublicSettings(ctx context.Context, input *GetPublicSettingsInput) (*GetPublicSettingsOutput, error) {
if input.EnvironmentID != "0" {
- settingsDto, err := handlerutil.ProxyRemoteJSON[[]settingstypes.PublicSetting](ctx, h.proxyRemoteJSON, input.EnvironmentID, http.MethodGet, "/api/environments/0/settings/public", nil)
+ settingsDto, err := h.proxyRemoteJSON.JSON[[]settingstypes.PublicSetting](ctx, input.EnvironmentID, http.MethodGet, "/api/environments/0/settings/public", nil)
if err != nil {
return nil, err
}
@@ -303,7 +299,7 @@ func (h *SettingsHandler) GetSettings(ctx context.Context, input *GetSettingsInp
}
if input.EnvironmentID != "0" {
- settingsDto, err := handlerutil.ProxyRemoteJSON[[]settingstypes.PublicSetting](ctx, h.proxyRemoteJSON, input.EnvironmentID, http.MethodGet, "/api/environments/0/settings", nil)
+ settingsDto, err := h.proxyRemoteJSON.JSON[[]settingstypes.PublicSetting](ctx, input.EnvironmentID, http.MethodGet, "/api/environments/0/settings", nil)
if err != nil {
return nil, err
}
@@ -336,7 +332,7 @@ func (h *SettingsHandler) GetSettings(ctx context.Context, input *GetSettingsInp
}
// UpdateSettings updates settings for an environment.
-func (h *SettingsHandler) UpdateSettings(ctx context.Context, input *UpdateSettingsInput) (*UpdateSettingsOutput, error) {
+func (h *SettingsHandler) UpdateSettings(ctx context.Context, input *UpdateSettingsInput) (*handlerutil.Out[[]settingstypes.SettingDto], error) {
if err := h.validateSettingsUpdateInput(input.Body); err != nil {
return nil, err
}
@@ -380,21 +376,21 @@ func (h *SettingsHandler) validateSettingsUpdateInput(input settingstypes.Update
return nil
}
-func (h *SettingsHandler) updateSettingsForRemoteEnvironment(ctx context.Context, input *UpdateSettingsInput) (*UpdateSettingsOutput, error) {
+func (h *SettingsHandler) updateSettingsForRemoteEnvironment(ctx context.Context, input *UpdateSettingsInput) (*handlerutil.Out[[]settingstypes.SettingDto], error) {
// Check if trying to update auth settings on non-local environment.
if hasAuthSettingsUpdateInternal(input.Body) {
return nil, huma.Error403Forbidden("Authentication settings can only be updated from the main environment")
}
- apiResp, err := handlerutil.ProxyRemoteJSON[base.ApiResponse[[]settingstypes.SettingDto]](ctx, h.proxyRemoteJSON, input.EnvironmentID, http.MethodPut, "/api/environments/0/settings", input.Body)
+ apiResp, err := h.proxyRemoteJSON.JSON[base.ApiResponse[[]settingstypes.SettingDto]](ctx, input.EnvironmentID, http.MethodPut, "/api/environments/0/settings", input.Body)
if err != nil {
return nil, err
}
- return &UpdateSettingsOutput{Body: *apiResp}, nil
+ return &handlerutil.Out[[]settingstypes.SettingDto]{Body: *apiResp}, nil
}
-func (h *SettingsHandler) updateSettingsForLocalEnvironment(ctx context.Context, input settingstypes.Update) (*UpdateSettingsOutput, error) {
+func (h *SettingsHandler) updateSettingsForLocalEnvironment(ctx context.Context, input settingstypes.Update) (*handlerutil.Out[[]settingstypes.SettingDto], error) {
if input.ProjectsDirectory != nil && *input.ProjectsDirectory != "" {
currentDir := h.settingsService.GetSettingsConfig().ProjectsDirectory.Value
if *input.ProjectsDirectory != currentDir {
@@ -432,7 +428,7 @@ func (h *SettingsHandler) updateSettingsForLocalEnvironment(ctx context.Context,
})
}
- return &UpdateSettingsOutput{
+ return &handlerutil.Out[[]settingstypes.SettingDto]{
Body: base.ApiResponse[[]settingstypes.SettingDto]{
Success: true,
Data: settingDtos,
diff --git a/backend/internal/settings/service.go b/backend/internal/settings/service.go
index abeb66025..b152de4ff 100644
--- a/backend/internal/settings/service.go
+++ b/backend/internal/settings/service.go
@@ -125,7 +125,7 @@ func (s *SettingsService) SubscribeSettingsChanges(keys []string, callback func(
}
}
if len(matching) > 0 {
- _, err := actors.Submit(context.WithoutCancel(s.lifecycleCtx), s.effects, "apply settings change effects", func(context.Context) (actors.NoPayload, error) {
+ _, err := s.effects.Submit(context.WithoutCancel(s.lifecycleCtx), "apply settings change effects", func(context.Context) (actors.NoPayload, error) {
callback(matching)
return actors.NoPayload{}, nil
}, nil)
@@ -139,7 +139,7 @@ func (s *SettingsService) SubscribeSettingsChanges(keys []string, callback func(
// NotifySettingsChanges publishes current values for keys through the settings
// actor. It is used when another settings-table workflow performs persistence.
func (s *SettingsService) NotifySettingsChanges(ctx context.Context, keys ...string) error {
- _, err := actors.Execute(ctx, s.writes, "notify settings changes", func(context.Context) ([]libarcane.SettingUpdate, error) {
+ _, err := s.writes.Execute(ctx, "notify settings changes", func(context.Context) ([]libarcane.SettingUpdate, error) {
updates := make([]libarcane.SettingUpdate, 0, len(keys))
cfg := s.GetSettingsConfig()
for _, key := range keys {
@@ -498,7 +498,7 @@ func (s *SettingsService) UpdateSetting(ctx context.Context, key, value string)
if err := libarcane.ValidateCronSetting(key, value); err != nil {
return errors.WrapIff(err, "invalid cron expression for %s", key)
}
- _, err := actors.Execute(ctx, s.writes, "update setting", func(writeCtx context.Context) (actors.NoPayload, error) {
+ _, err := s.writes.Execute(ctx, "update setting", func(writeCtx context.Context) (actors.NoPayload, error) {
if err := s.updateSettingValueNoRefreshInternal(writeCtx, key, value); err != nil {
return actors.NoPayload{}, err
}
@@ -514,7 +514,7 @@ func (s *SettingsService) UpdateSettingValues(ctx context.Context, updates []lib
for _, update := range updates {
values = append(values, SettingVariable{Key: update.Key, Value: update.Value})
}
- _, err := actors.Execute(ctx, s.writes, "update setting values", func(writeCtx context.Context) (actors.NoPayload, error) {
+ _, err := s.writes.Execute(ctx, "update setting values", func(writeCtx context.Context) (actors.NoPayload, error) {
if err := s.persistSettings(writeCtx, values); err != nil {
return actors.NoPayload{}, err
}
@@ -536,7 +536,7 @@ func (s *SettingsService) updateSettingValueNoRefreshInternal(ctx context.Contex
// UpdateSettings publishes the refreshed snapshot before returning. Each
// subscriber's effects remain ordered and may finish after this method returns.
func (s *SettingsService) UpdateSettings(ctx context.Context, updates settingstypes.Update) ([]SettingVariable, error) {
- result, err := actors.Execute(ctx, s.writes, "update settings", func(writeCtx context.Context) (settingsUpdateResultInternal, error) {
+ result, err := s.writes.Execute(ctx, "update settings", func(writeCtx context.Context) (settingsUpdateResultInternal, error) {
return s.updateSettingsInternal(writeCtx, updates)
}, func(result settingsUpdateResultInternal, err error) {
if err == nil && len(result.changes) > 0 {
@@ -716,7 +716,7 @@ func (s *SettingsService) persistSettings(ctx context.Context, values []SettingV
}
func (s *SettingsService) EnsureDefaultSettings(ctx context.Context) error {
- _, err := actors.Execute(ctx, s.writes, "ensure default settings", func(writeCtx context.Context) (actors.NoPayload, error) {
+ _, err := s.writes.Execute(ctx, "ensure default settings", func(writeCtx context.Context) (actors.NoPayload, error) {
defaultSettings := s.getDefaultSettings()
defaultSettingVars := defaultSettings.ToSettingVariableSlice(SettingVisibilityAll, false)
@@ -748,7 +748,7 @@ func (s *SettingsService) EnsureDefaultSettings(ctx context.Context) error {
}
func (s *SettingsService) PruneUnknownSettings(ctx context.Context) error {
- _, err := actors.Execute(ctx, s.writes, "prune unknown settings", func(writeCtx context.Context) (actors.NoPayload, error) {
+ _, err := s.writes.Execute(ctx, "prune unknown settings", func(writeCtx context.Context) (actors.NoPayload, error) {
allowedKeys := allowedSettingKeys()
if len(allowedKeys) == 0 {
return actors.NoPayload{}, nil
@@ -772,7 +772,7 @@ func (s *SettingsService) PruneUnknownSettings(ctx context.Context) error {
}
func (s *SettingsService) PersistEnvSettingsIfMissing(ctx context.Context) error {
- _, err := actors.Execute(ctx, s.writes, "persist environment settings", func(writeCtx context.Context) (actors.NoPayload, error) {
+ _, err := s.writes.Execute(ctx, "persist environment settings", func(writeCtx context.Context) (actors.NoPayload, error) {
rt := reflect.TypeFor[Settings]()
appCfg := config.Load()
isEnvOnlyMode := appCfg.AgentMode || appCfg.UIConfigurationDisabled
@@ -907,7 +907,7 @@ func (s *SettingsService) setupInstanceID(ctx context.Context) error {
return nil
}
-func settingValueInternal[T any](ctx context.Context, s *SettingsService, key string, parse func(string) (T, error)) mo.Option[T] {
+func (s *SettingsService) settingValue[T any](ctx context.Context, key string, parse func(string) (T, error)) mo.Option[T] {
cfg := s.getEffectiveSettingsConfigInternal(ctx)
value, _, _, err := cfg.FieldByKey(key)
if err != nil || value == "" {
@@ -922,15 +922,15 @@ func settingValueInternal[T any](ctx context.Context, s *SettingsService, key st
}
func (s *SettingsService) GetBoolSetting(ctx context.Context, key string, defaultValue bool) bool {
- return settingValueInternal(ctx, s, key, strconv.ParseBool).OrElse(defaultValue)
+ return s.settingValue(ctx, key, strconv.ParseBool).OrElse(defaultValue)
}
func (s *SettingsService) GetIntSetting(ctx context.Context, key string, defaultValue int) int {
- return settingValueInternal(ctx, s, key, strconv.Atoi).OrElse(defaultValue)
+ return s.settingValue(ctx, key, strconv.Atoi).OrElse(defaultValue)
}
func (s *SettingsService) GetStringSetting(ctx context.Context, key, defaultValue string) string {
- return settingValueInternal(ctx, s, key, func(value string) (string, error) { return value, nil }).OrElse(defaultValue)
+ return s.settingValue(ctx, key, func(value string) (string, error) { return value, nil }).OrElse(defaultValue)
}
func (s *SettingsService) SetBoolSetting(ctx context.Context, key string, value bool) error {
@@ -966,7 +966,7 @@ func ParseExcludedContainerNames(raw string) []string {
// the autoUpdateExcludedContainers setting. When excluded is true the container
// is added to the list; when false it is removed.
func (s *SettingsService) SetContainerAutoUpdateExclusionInternal(ctx context.Context, containerName string, excluded bool) error {
- _, err := actors.Execute(ctx, s.writes, "update container auto-update exclusion", func(writeCtx context.Context) (actors.NoPayload, error) {
+ _, err := s.writes.Execute(ctx, "update container auto-update exclusion", func(writeCtx context.Context) (actors.NoPayload, error) {
ordered := ParseExcludedContainerNames(s.GetStringSetting(writeCtx, "autoUpdateExcludedContainers", ""))
if excluded {
@@ -992,7 +992,7 @@ func (s *SettingsService) SetContainerAutoUpdateExclusionInternal(ctx context.Co
}
func (s *SettingsService) EnsureEncryptionKey(ctx context.Context) (string, error) {
- return actors.Execute(ctx, s.writes, "ensure encryption key", func(writeCtx context.Context) (string, error) {
+ return s.writes.Execute(ctx, "ensure encryption key", func(writeCtx context.Context) (string, error) {
const keyName = "encryptionKey"
var key string
@@ -1037,7 +1037,7 @@ func (s *SettingsService) EnsureEncryptionKey(ctx context.Context) (string, erro
}
func (s *SettingsService) EnsureJwtSigningKey(ctx context.Context) (*mldsa.PrivateKey, error) {
- return actors.Execute(ctx, s.writes, "ensure jwt signing key", func(writeCtx context.Context) (*mldsa.PrivateKey, error) {
+ return s.writes.Execute(ctx, "ensure jwt signing key", func(writeCtx context.Context) (*mldsa.PrivateKey, error) {
const keyName = "jwtSigningKeySeed"
var key *mldsa.PrivateKey
@@ -1094,7 +1094,7 @@ func (s *SettingsService) NormalizeProjectsDirectory(ctx context.Context, projec
return nil
}
- _, err := actors.Execute(ctx, s.writes, "normalize projects directory", func(writeCtx context.Context) (string, error) {
+ _, err := s.writes.Execute(ctx, "normalize projects directory", func(writeCtx context.Context) (string, error) {
var projectsDirSetting SettingVariable
err := s.db.WithContext(writeCtx).Where("key = ?", "projectsDirectory").First(&projectsDirSetting).Error
if errors.Is(err, gorm.ErrRecordNotFound) {
@@ -1142,7 +1142,7 @@ func (s *SettingsService) NormalizeBuildsDirectory(ctx context.Context) error {
return nil
}
- _, err := actors.Execute(ctx, s.writes, "normalize builds directory", func(writeCtx context.Context) (string, error) {
+ _, err := s.writes.Execute(ctx, "normalize builds directory", func(writeCtx context.Context) (string, error) {
var buildsDirSetting SettingVariable
err := s.db.WithContext(writeCtx).Where("key = ?", buildsKey).First(&buildsDirSetting).Error
if errors.Is(err, gorm.ErrRecordNotFound) {
diff --git a/backend/internal/settings/service_test.go b/backend/internal/settings/service_test.go
index 657e4e380..ebe36d7c4 100644
--- a/backend/internal/settings/service_test.go
+++ b/backend/internal/settings/service_test.go
@@ -66,11 +66,11 @@ func newAdmissionGateForTestInternal(t testing.TB) *actors.Gate[actors.Admission
func waitForSettingsNotificationsInternal(t *testing.T, svc *SettingsService) {
t.Helper()
- _, err := actors.Execute(t.Context(), svc.writes, "wait for settings notification submission", func(context.Context) (actors.NoPayload, error) {
+ _, err := svc.writes.Execute(t.Context(), "wait for settings notification submission", func(context.Context) (actors.NoPayload, error) {
return actors.NoPayload{}, nil
}, nil)
require.NoError(t, err)
- _, err = actors.Execute(t.Context(), svc.effects, "wait for settings notifications", func(context.Context) (actors.NoPayload, error) {
+ _, err = svc.effects.Execute(t.Context(), "wait for settings notifications", func(context.Context) (actors.NoPayload, error) {
return actors.NoPayload{}, nil
}, nil)
require.NoError(t, err)
diff --git a/backend/internal/settings/settings_search.go b/backend/internal/settings/settings_search.go
index 472850445..62685edd8 100644
--- a/backend/internal/settings/settings_search.go
+++ b/backend/internal/settings/settings_search.go
@@ -37,7 +37,7 @@ func (s *SettingsSearchService) GetSettingsCategories() []category.Category {
func (s *SettingsSearchService) buildCategoriesFromModel() []category.Category {
// Extract category metadata from struct tags (catmeta)
- catMetaMap := utils.ExtractCategoryMetadata(Settings{}, nil)
+ catMetaMap := utils.ExtractCategoryMetadata[Settings]()
// map category id -> list of settings
categories := map[string][]meta.Metadata{}
diff --git a/backend/internal/swarm/handler.go b/backend/internal/swarm/handler.go
index 27e108311..a223e92be 100644
--- a/backend/internal/swarm/handler.go
+++ b/backend/internal/swarm/handler.go
@@ -41,47 +41,27 @@ type ListSwarmServicesInput struct {
Limit int `query:"limit" default:"20" doc:"Number of items per page"`
}
-type ListSwarmServicesOutput struct {
- Body base.Paginated[swarmtypes.ServiceSummary]
-}
-
type GetSwarmServiceInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
ServiceID string `path:"serviceId" doc:"Service ID"`
}
-type GetSwarmServiceOutput struct {
- Body base.ApiResponse[swarmtypes.ServiceInspect]
-}
-
type CreateSwarmServiceInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
Body swarmtypes.ServiceCreateRequest `doc:"Service creation request"`
}
-type CreateSwarmServiceOutput struct {
- Body base.ApiResponse[swarmtypes.ServiceCreateResponse]
-}
-
type UpdateSwarmServiceInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
ServiceID string `path:"serviceId" doc:"Service ID"`
Body swarmtypes.ServiceUpdateRequest
}
-type UpdateSwarmServiceOutput struct {
- Body base.ApiResponse[swarmtypes.ServiceUpdateResponse]
-}
-
type DeleteSwarmServiceInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
ServiceID string `path:"serviceId" doc:"Service ID"`
}
-type DeleteSwarmServiceOutput struct {
- Body base.ApiResponse[base.MessageResponse]
-}
-
type ListSwarmServiceTasksInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
ServiceID string `path:"serviceId" doc:"Service ID"`
@@ -92,29 +72,17 @@ type ListSwarmServiceTasksInput struct {
Limit int `query:"limit" default:"20" doc:"Number of items per page"`
}
-type ListSwarmServiceTasksOutput struct {
- Body base.Paginated[swarmtypes.TaskSummary]
-}
-
type RollbackSwarmServiceInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
ServiceID string `path:"serviceId" doc:"Service ID"`
}
-type RollbackSwarmServiceOutput struct {
- Body base.ApiResponse[swarmtypes.ServiceUpdateResponse]
-}
-
type ScaleSwarmServiceInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
ServiceID string `path:"serviceId" doc:"Service ID"`
Body swarmtypes.ServiceScaleRequest
}
-type ScaleSwarmServiceOutput struct {
- Body base.ApiResponse[swarmtypes.ServiceUpdateResponse]
-}
-
type ListSwarmNodesInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
Search string `query:"search" doc:"Search query"`
@@ -124,19 +92,11 @@ type ListSwarmNodesInput struct {
Limit int `query:"limit" default:"20" doc:"Number of items per page"`
}
-type ListSwarmNodesOutput struct {
- Body base.Paginated[swarmtypes.NodeSummary]
-}
-
type GetSwarmNodeInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
NodeID string `path:"nodeId" doc:"Node ID"`
}
-type GetSwarmNodeOutput struct {
- Body base.ApiResponse[swarmtypes.NodeSummary]
-}
-
type GetSwarmNodeAgentDeploymentInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
NodeID string `path:"nodeId" doc:"Node ID"`
@@ -152,91 +112,51 @@ type SwarmNodeAgentDeployment struct {
Agent swarmtypes.NodeAgentStatus `json:"agent"`
}
-type GetSwarmNodeAgentDeploymentOutput struct {
- Body base.ApiResponse[SwarmNodeAgentDeployment]
-}
-
type ReconcileSwarmNodeAgentsInput struct {
Body swarmtypes.NodeAgentReconcileRequest
EnvironmentID string `path:"id" doc:"Environment ID"`
}
-type ReconcileSwarmNodeAgentsOutput struct {
- Body base.ApiResponse[swarmtypes.NodeAgentReconcileResponse]
-}
-
type PutSwarmNodeAgentBindingInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
NodeID string `path:"nodeId" doc:"Node ID"`
Body swarmtypes.NodeAgentBindingRequest
}
-type PutSwarmNodeAgentBindingOutput struct {
- Body base.ApiResponse[swarmtypes.NodeSummary]
-}
-
type DeleteSwarmNodeAgentBindingInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
NodeID string `path:"nodeId" doc:"Node ID"`
}
-type DeleteSwarmNodeAgentBindingOutput struct {
- Body base.ApiResponse[base.MessageResponse]
-}
-
type DeleteSwarmNodeAgentDeploymentInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
NodeID string `path:"nodeId" doc:"Node ID"`
}
-type DeleteSwarmNodeAgentDeploymentOutput struct {
- Body base.ApiResponse[base.MessageResponse]
-}
-
type GetSwarmNodeIdentityInput struct{}
-type GetSwarmNodeIdentityOutput struct {
- Body base.ApiResponse[SwarmNodeIdentity]
-}
-
type UpdateSwarmNodeInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
NodeID string `path:"nodeId" doc:"Node ID"`
Body swarmtypes.NodeUpdateRequest
}
-type UpdateSwarmNodeOutput struct {
- Body base.ApiResponse[base.MessageResponse]
-}
-
type DeleteSwarmNodeInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
NodeID string `path:"nodeId" doc:"Node ID"`
Force bool `query:"force" default:"false" doc:"Force node removal"`
}
-type DeleteSwarmNodeOutput struct {
- Body base.ApiResponse[base.MessageResponse]
-}
-
type PromoteSwarmNodeInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
NodeID string `path:"nodeId" doc:"Node ID"`
}
-type PromoteSwarmNodeOutput struct {
- Body base.ApiResponse[base.MessageResponse]
-}
-
type DemoteSwarmNodeInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
NodeID string `path:"nodeId" doc:"Node ID"`
}
-type DemoteSwarmNodeOutput struct {
- Body base.ApiResponse[base.MessageResponse]
-}
-
type ListSwarmNodeTasksInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
NodeID string `path:"nodeId" doc:"Node ID"`
@@ -247,10 +167,6 @@ type ListSwarmNodeTasksInput struct {
Limit int `query:"limit" default:"20" doc:"Number of items per page"`
}
-type ListSwarmNodeTasksOutput struct {
- Body base.Paginated[swarmtypes.TaskSummary]
-}
-
type ListSwarmTasksInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
Search string `query:"search" doc:"Search query"`
@@ -260,10 +176,6 @@ type ListSwarmTasksInput struct {
Limit int `query:"limit" default:"20" doc:"Number of items per page"`
}
-type ListSwarmTasksOutput struct {
- Body base.Paginated[swarmtypes.TaskSummary]
-}
-
type ListSwarmStacksInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
Search string `query:"search" doc:"Search query"`
@@ -273,56 +185,32 @@ type ListSwarmStacksInput struct {
Limit int `query:"limit" default:"20" doc:"Number of items per page"`
}
-type ListSwarmStacksOutput struct {
- Body base.Paginated[swarmtypes.StackSummary]
-}
-
type DeploySwarmStackInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
Body swarmtypes.StackDeployRequest
}
-type DeploySwarmStackOutput struct {
- Body base.ApiResponse[swarmtypes.StackDeployResponse]
-}
-
type GetSwarmStackInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
Name string `path:"name" doc:"Stack name"`
}
-type GetSwarmStackOutput struct {
- Body base.ApiResponse[swarmtypes.StackInspect]
-}
-
type GetSwarmStackSourceInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
Name string `path:"name" doc:"Stack name"`
}
-type GetSwarmStackSourceOutput struct {
- Body base.ApiResponse[swarmtypes.StackSource]
-}
-
type UpdateSwarmStackSourceInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
Name string `path:"name" doc:"Stack name"`
Body swarmtypes.StackSourceUpdateRequest
}
-type UpdateSwarmStackSourceOutput struct {
- Body base.ApiResponse[swarmtypes.StackSource]
-}
-
type DeleteSwarmStackInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
Name string `path:"name" doc:"Stack name"`
}
-type DeleteSwarmStackOutput struct {
- Body base.ApiResponse[base.MessageResponse]
-}
-
type ListSwarmStackServicesInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
Name string `path:"name" doc:"Stack name"`
@@ -333,10 +221,6 @@ type ListSwarmStackServicesInput struct {
Limit int `query:"limit" default:"20" doc:"Number of items per page"`
}
-type ListSwarmStackServicesOutput struct {
- Body base.Paginated[swarmtypes.ServiceSummary]
-}
-
type ListSwarmStackTasksInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
Name string `path:"name" doc:"Stack name"`
@@ -347,192 +231,104 @@ type ListSwarmStackTasksInput struct {
Limit int `query:"limit" default:"20" doc:"Number of items per page"`
}
-type ListSwarmStackTasksOutput struct {
- Body base.Paginated[swarmtypes.TaskSummary]
-}
-
type RenderSwarmStackConfigInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
Body swarmtypes.StackRenderConfigRequest
}
-type RenderSwarmStackConfigOutput struct {
- Body base.ApiResponse[swarmtypes.StackRenderConfigResponse]
-}
-
type GetSwarmInfoInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
}
-type GetSwarmInfoOutput struct {
- Body base.ApiResponse[swarmtypes.SwarmInfo]
-}
-
type GetSwarmStatusInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
}
-type GetSwarmStatusOutput struct {
- Body base.ApiResponse[swarmtypes.RuntimeStatus]
-}
-
type InitSwarmInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
Body swarmtypes.SwarmInitRequest
}
-type InitSwarmOutput struct {
- Body base.ApiResponse[swarmtypes.SwarmInitResponse]
-}
-
type JoinSwarmInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
Body swarmtypes.SwarmJoinRequest
}
-type JoinSwarmOutput struct {
- Body base.ApiResponse[base.MessageResponse]
-}
-
type GetSwarmJoinCandidatesInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
}
-type GetSwarmJoinCandidatesOutput struct {
- Body base.ApiResponse[[]swarmtypes.SwarmJoinCandidate]
-}
-
type JoinSwarmEnvironmentsInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
Body swarmtypes.SwarmJoinEnvironmentsRequest
}
-type JoinSwarmEnvironmentsOutput struct {
- Body base.ApiResponse[swarmtypes.SwarmJoinEnvironmentsResponse]
-}
-
type LeaveSwarmInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
Body swarmtypes.SwarmLeaveRequest
}
-type LeaveSwarmOutput struct {
- Body base.ApiResponse[base.MessageResponse]
-}
-
type UnlockSwarmInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
Body swarmtypes.SwarmUnlockRequest
}
-type UnlockSwarmOutput struct {
- Body base.ApiResponse[base.MessageResponse]
-}
-
type GetSwarmUnlockKeyInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
}
-type GetSwarmUnlockKeyOutput struct {
- Body base.ApiResponse[swarmtypes.SwarmUnlockKeyResponse]
-}
-
type GetSwarmJoinTokensInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
}
-type GetSwarmJoinTokensOutput struct {
- Body base.ApiResponse[swarmtypes.SwarmJoinTokensResponse]
-}
-
type RotateSwarmJoinTokensInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
Body swarmtypes.SwarmRotateJoinTokensRequest
}
-type RotateSwarmJoinTokensOutput struct {
- Body base.ApiResponse[base.MessageResponse]
-}
-
type UpdateSwarmSpecInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
Body swarmtypes.SwarmUpdateRequest
}
-type UpdateSwarmSpecOutput struct {
- Body base.ApiResponse[base.MessageResponse]
-}
-
type ListSwarmConfigsInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
}
-type ListSwarmConfigsOutput struct {
- Body base.ApiResponse[[]swarmtypes.ConfigSummary]
-}
-
type GetSwarmConfigInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
ConfigID string `path:"configId" doc:"Config ID"`
}
-type GetSwarmConfigOutput struct {
- Body base.ApiResponse[swarmtypes.ConfigSummary]
-}
-
type CreateSwarmConfigInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
Body swarmtypes.ConfigCreateRequest
}
-type CreateSwarmConfigOutput struct {
- Body base.ApiResponse[swarmtypes.ConfigSummary]
-}
-
type DeleteSwarmConfigInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
ConfigID string `path:"configId" doc:"Config ID"`
}
-type DeleteSwarmConfigOutput struct {
- Body base.ApiResponse[base.MessageResponse]
-}
-
type ListSwarmSecretsInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
}
-type ListSwarmSecretsOutput struct {
- Body base.ApiResponse[[]swarmtypes.SecretSummary]
-}
-
type GetSwarmSecretInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
SecretID string `path:"secretId" doc:"Secret ID"`
}
-type GetSwarmSecretOutput struct {
- Body base.ApiResponse[swarmtypes.SecretSummary]
-}
-
type CreateSwarmSecretInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
Body swarmtypes.SecretCreateRequest
}
-type CreateSwarmSecretOutput struct {
- Body base.ApiResponse[swarmtypes.SecretSummary]
-}
-
type DeleteSwarmSecretInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
SecretID string `path:"secretId" doc:"Secret ID"`
}
-type DeleteSwarmSecretOutput struct {
- Body base.ApiResponse[base.MessageResponse]
-}
-
// RegisterSwarm registers the Docker Swarm HTTP operations on the provided Huma API.
//
// It wires a SwarmHandler with the supplied services and publishes the full
@@ -623,7 +419,7 @@ func RegisterSwarm(api huma.API, swarmSvc *SwarmService, environmentSvc *environ
// Returns a successful response containing service summaries and pagination metadata.
// Returns an HTTP-shaped error if the swarm service is unavailable or if the
// underlying swarm lookup fails.
-func (h *SwarmHandler) ListServices(ctx context.Context, input *ListSwarmServicesInput) (*ListSwarmServicesOutput, error) {
+func (h *SwarmHandler) ListServices(ctx context.Context, input *ListSwarmServicesInput) (*handlerutil.Page[swarmtypes.ServiceSummary], error) {
params := handlerutil.PaginationParams(input.Start, input.Limit, input.Sort, input.Order, input.Search)
items, paginationResp, err := h.swarmService.ListServicesPaginated(ctx, params)
if err != nil {
@@ -633,7 +429,7 @@ func (h *SwarmHandler) ListServices(ctx context.Context, input *ListSwarmService
items = []swarmtypes.ServiceSummary{}
}
- return &ListSwarmServicesOutput{Body: base.Paginated[swarmtypes.ServiceSummary]{Success: true, Data: items, Pagination: handlerutil.PaginationResponse(paginationResp)}}, nil
+ return &handlerutil.Page[swarmtypes.ServiceSummary]{Body: base.Paginated[swarmtypes.ServiceSummary]{Success: true, Data: items, Pagination: handlerutil.PaginationResponse(paginationResp)}}, nil
}
// GetService returns detailed information for a single swarm service.
@@ -647,7 +443,7 @@ func (h *SwarmHandler) ListServices(ctx context.Context, input *ListSwarmService
// Returns a successful response containing the service inspection payload.
// Returns `404 Not Found` when the service does not exist and other mapped HTTP
// errors when the inspection fails.
-func (h *SwarmHandler) GetService(ctx context.Context, input *GetSwarmServiceInput) (*GetSwarmServiceOutput, error) {
+func (h *SwarmHandler) GetService(ctx context.Context, input *GetSwarmServiceInput) (*handlerutil.Out[swarmtypes.ServiceInspect], error) {
service, err := h.swarmService.GetService(ctx, input.ServiceID)
if err != nil {
if errdefs.IsNotFound(err) {
@@ -656,7 +452,7 @@ func (h *SwarmHandler) GetService(ctx context.Context, input *GetSwarmServiceInp
return nil, mapSwarmServiceError(err, errors.WithMessage(err, "Swarm service not found").Error())
}
- return &GetSwarmServiceOutput{Body: base.ApiResponse[swarmtypes.ServiceInspect]{Success: true, Data: *service}}, nil
+ return &handlerutil.Out[swarmtypes.ServiceInspect]{Body: base.ApiResponse[swarmtypes.ServiceInspect]{Success: true, Data: *service}}, nil
}
// CreateService creates a new swarm service in the target environment.
@@ -670,7 +466,7 @@ func (h *SwarmHandler) GetService(ctx context.Context, input *GetSwarmServiceInp
// Returns a successful response containing the created service ID and any Docker warnings.
// Returns an authorization error for non-admin callers or mapped HTTP errors
// when validation or creation fails.
-func (h *SwarmHandler) CreateService(ctx context.Context, input *CreateSwarmServiceInput) (*CreateSwarmServiceOutput, error) {
+func (h *SwarmHandler) CreateService(ctx context.Context, input *CreateSwarmServiceInput) (*handlerutil.Out[swarmtypes.ServiceCreateResponse], error) {
resp, err := h.swarmService.CreateService(ctx, input.Body)
if err != nil {
return nil, mapSwarmServiceError(err, errors.WithMessage(err, "Failed to create swarm service").Error())
@@ -678,7 +474,7 @@ func (h *SwarmHandler) CreateService(ctx context.Context, input *CreateSwarmServ
h.auditSwarmMutation(ctx, input.EnvironmentID, "service.create", "swarm_service", resp.ID, "", map[string]any{"serviceId": resp.ID})
- return &CreateSwarmServiceOutput{Body: base.ApiResponse[swarmtypes.ServiceCreateResponse]{Success: true, Data: *resp}}, nil
+ return &handlerutil.Out[swarmtypes.ServiceCreateResponse]{Body: base.ApiResponse[swarmtypes.ServiceCreateResponse]{Success: true, Data: *resp}}, nil
}
// UpdateService updates an existing swarm service.
@@ -692,7 +488,7 @@ func (h *SwarmHandler) CreateService(ctx context.Context, input *CreateSwarmServ
// Returns a successful response containing any Docker warnings.
// Returns an authorization error for non-admin callers or mapped HTTP errors
// when the update request is invalid or the underlying update fails.
-func (h *SwarmHandler) UpdateService(ctx context.Context, input *UpdateSwarmServiceInput) (*UpdateSwarmServiceOutput, error) {
+func (h *SwarmHandler) UpdateService(ctx context.Context, input *UpdateSwarmServiceInput) (*handlerutil.Out[swarmtypes.ServiceUpdateResponse], error) {
resp, err := h.swarmService.UpdateService(ctx, input.ServiceID, input.Body)
if err != nil {
return nil, mapSwarmServiceError(err, errors.WithMessage(err, "Failed to update swarm service").Error())
@@ -700,7 +496,7 @@ func (h *SwarmHandler) UpdateService(ctx context.Context, input *UpdateSwarmServ
h.auditSwarmMutation(ctx, input.EnvironmentID, "service.update", "swarm_service", input.ServiceID, "", map[string]any{"serviceId": input.ServiceID})
- return &UpdateSwarmServiceOutput{Body: base.ApiResponse[swarmtypes.ServiceUpdateResponse]{Success: true, Data: *resp}}, nil
+ return &handlerutil.Out[swarmtypes.ServiceUpdateResponse]{Body: base.ApiResponse[swarmtypes.ServiceUpdateResponse]{Success: true, Data: *resp}}, nil
}
// DeleteService removes a swarm service.
@@ -715,7 +511,7 @@ func (h *SwarmHandler) UpdateService(ctx context.Context, input *UpdateSwarmServ
// Returns a successful response with a confirmation message.
// Returns an authorization error for non-admin callers, `404 Not Found` when
// the service does not exist, or another mapped HTTP error when removal fails.
-func (h *SwarmHandler) DeleteService(ctx context.Context, input *DeleteSwarmServiceInput) (*DeleteSwarmServiceOutput, error) {
+func (h *SwarmHandler) DeleteService(ctx context.Context, input *DeleteSwarmServiceInput) (*handlerutil.Out[base.MessageResponse], error) {
if err := h.swarmService.RemoveService(ctx, input.ServiceID); err != nil {
if errdefs.IsNotFound(err) {
return nil, huma.Error404NotFound(errors.WithMessage(err, "Swarm service not found").Error())
@@ -725,7 +521,7 @@ func (h *SwarmHandler) DeleteService(ctx context.Context, input *DeleteSwarmServ
h.auditSwarmMutation(ctx, input.EnvironmentID, "service.delete", "swarm_service", input.ServiceID, "", map[string]any{"serviceId": input.ServiceID})
- return &DeleteSwarmServiceOutput{Body: base.ApiResponse[base.MessageResponse]{Success: true, Data: base.MessageResponse{Message: "Swarm service removed successfully"}}}, nil
+ return &handlerutil.Out[base.MessageResponse]{Body: base.ApiResponse[base.MessageResponse]{Success: true, Data: base.MessageResponse{Message: "Swarm service removed successfully"}}}, nil
}
// ListServiceTasks lists tasks belonging to a specific swarm service.
@@ -738,7 +534,7 @@ func (h *SwarmHandler) DeleteService(ctx context.Context, input *DeleteSwarmServ
//
// Returns a paginated list of task summaries for the service.
// Returns a mapped HTTP error when the swarm task lookup fails.
-func (h *SwarmHandler) ListServiceTasks(ctx context.Context, input *ListSwarmServiceTasksInput) (*ListSwarmServiceTasksOutput, error) {
+func (h *SwarmHandler) ListServiceTasks(ctx context.Context, input *ListSwarmServiceTasksInput) (*handlerutil.Page[swarmtypes.TaskSummary], error) {
params := handlerutil.PaginationParams(input.Start, input.Limit, input.Sort, input.Order, input.Search)
items, paginationResp, err := h.swarmService.ListServiceTasksPaginated(ctx, input.ServiceID, params)
if err != nil {
@@ -748,7 +544,7 @@ func (h *SwarmHandler) ListServiceTasks(ctx context.Context, input *ListSwarmSer
items = []swarmtypes.TaskSummary{}
}
- return &ListSwarmServiceTasksOutput{Body: base.Paginated[swarmtypes.TaskSummary]{Success: true, Data: items, Pagination: handlerutil.PaginationResponse(paginationResp)}}, nil
+ return &handlerutil.Page[swarmtypes.TaskSummary]{Body: base.Paginated[swarmtypes.TaskSummary]{Success: true, Data: items, Pagination: handlerutil.PaginationResponse(paginationResp)}}, nil
}
// RollbackService requests a server-side rollback for a swarm service.
@@ -762,7 +558,7 @@ func (h *SwarmHandler) ListServiceTasks(ctx context.Context, input *ListSwarmSer
// Returns a successful response containing any warnings reported by Docker.
// Returns an authorization error for non-admin callers or mapped HTTP errors
// when the rollback cannot be performed.
-func (h *SwarmHandler) RollbackService(ctx context.Context, input *RollbackSwarmServiceInput) (*RollbackSwarmServiceOutput, error) {
+func (h *SwarmHandler) RollbackService(ctx context.Context, input *RollbackSwarmServiceInput) (*handlerutil.Out[swarmtypes.ServiceUpdateResponse], error) {
resp, err := h.swarmService.RollbackService(ctx, input.ServiceID)
if err != nil {
return nil, mapSwarmServiceError(err, errors.WithMessage(err, "Failed to update swarm service").Error())
@@ -770,7 +566,7 @@ func (h *SwarmHandler) RollbackService(ctx context.Context, input *RollbackSwarm
h.auditSwarmMutation(ctx, input.EnvironmentID, "service.rollback", "swarm_service", input.ServiceID, "", map[string]any{"serviceId": input.ServiceID})
- return &RollbackSwarmServiceOutput{Body: base.ApiResponse[swarmtypes.ServiceUpdateResponse]{Success: true, Data: *resp}}, nil
+ return &handlerutil.Out[swarmtypes.ServiceUpdateResponse]{Body: base.ApiResponse[swarmtypes.ServiceUpdateResponse]{Success: true, Data: *resp}}, nil
}
// ScaleService changes the replica count of a swarm service.
@@ -784,7 +580,7 @@ func (h *SwarmHandler) RollbackService(ctx context.Context, input *RollbackSwarm
// Returns a successful response containing any warnings reported by Docker.
// Returns an authorization error for non-admin callers or mapped HTTP errors
// when scaling is invalid or the update fails.
-func (h *SwarmHandler) ScaleService(ctx context.Context, input *ScaleSwarmServiceInput) (*ScaleSwarmServiceOutput, error) {
+func (h *SwarmHandler) ScaleService(ctx context.Context, input *ScaleSwarmServiceInput) (*handlerutil.Out[swarmtypes.ServiceUpdateResponse], error) {
resp, err := h.swarmService.ScaleService(ctx, input.ServiceID, input.Body.Replicas)
if err != nil {
return nil, mapSwarmServiceError(err, errors.WithMessage(err, "Failed to update swarm service").Error())
@@ -792,7 +588,7 @@ func (h *SwarmHandler) ScaleService(ctx context.Context, input *ScaleSwarmServic
h.auditSwarmMutation(ctx, input.EnvironmentID, "service.scale", "swarm_service", input.ServiceID, "", map[string]any{"serviceId": input.ServiceID, "replicas": input.Body.Replicas})
- return &ScaleSwarmServiceOutput{Body: base.ApiResponse[swarmtypes.ServiceUpdateResponse]{Success: true, Data: *resp}}, nil
+ return &handlerutil.Out[swarmtypes.ServiceUpdateResponse]{Body: base.ApiResponse[swarmtypes.ServiceUpdateResponse]{Success: true, Data: *resp}}, nil
}
// ListNodes lists swarm nodes for an environment and returns a paginated response.
@@ -805,7 +601,7 @@ func (h *SwarmHandler) ScaleService(ctx context.Context, input *ScaleSwarmServic
//
// Returns a paginated list of node summaries.
// Returns a mapped HTTP error when node enumeration fails.
-func (h *SwarmHandler) ListNodes(ctx context.Context, input *ListSwarmNodesInput) (*ListSwarmNodesOutput, error) {
+func (h *SwarmHandler) ListNodes(ctx context.Context, input *ListSwarmNodesInput) (*handlerutil.Page[swarmtypes.NodeSummary], error) {
params := handlerutil.PaginationParams(input.Start, input.Limit, input.Sort, input.Order, input.Search)
items, paginationResp, err := h.swarmService.ListNodesPaginated(ctx, input.EnvironmentID, params)
if err != nil {
@@ -815,7 +611,7 @@ func (h *SwarmHandler) ListNodes(ctx context.Context, input *ListSwarmNodesInput
items = []swarmtypes.NodeSummary{}
}
- return &ListSwarmNodesOutput{Body: base.Paginated[swarmtypes.NodeSummary]{Success: true, Data: items, Pagination: handlerutil.PaginationResponse(paginationResp)}}, nil
+ return &handlerutil.Page[swarmtypes.NodeSummary]{Body: base.Paginated[swarmtypes.NodeSummary]{Success: true, Data: items, Pagination: handlerutil.PaginationResponse(paginationResp)}}, nil
}
// GetNode returns detailed information for a single swarm node.
@@ -829,7 +625,7 @@ func (h *SwarmHandler) ListNodes(ctx context.Context, input *ListSwarmNodesInput
// Returns a successful response containing the node summary.
// Returns `404 Not Found` when the node does not exist or another mapped HTTP
// error when the inspection fails.
-func (h *SwarmHandler) GetNode(ctx context.Context, input *GetSwarmNodeInput) (*GetSwarmNodeOutput, error) {
+func (h *SwarmHandler) GetNode(ctx context.Context, input *GetSwarmNodeInput) (*handlerutil.Out[swarmtypes.NodeSummary], error) {
node, err := h.swarmService.GetNode(ctx, input.EnvironmentID, input.NodeID)
if err != nil {
if errdefs.IsNotFound(err) {
@@ -838,7 +634,7 @@ func (h *SwarmHandler) GetNode(ctx context.Context, input *GetSwarmNodeInput) (*
return nil, mapSwarmServiceError(err, errors.WithMessage(err, "Swarm node not found").Error())
}
- return &GetSwarmNodeOutput{Body: base.ApiResponse[swarmtypes.NodeSummary]{Success: true, Data: *node}}, nil
+ return &handlerutil.Out[swarmtypes.NodeSummary]{Body: base.ApiResponse[swarmtypes.NodeSummary]{Success: true, Data: *node}}, nil
}
// GetNodeAgentDeployment returns deployment snippets for attaching an Arcane Remote Environment to a swarm node.
@@ -857,7 +653,7 @@ func (h *SwarmHandler) GetNode(ctx context.Context, input *GetSwarmNodeInput) (*
// when the current user cannot be resolved, `404 Not Found` when the node does
// not exist, or `500 Internal Server Error` when environment provisioning or
// snippet generation fails.
-func (h *SwarmHandler) GetNodeAgentDeployment(ctx context.Context, input *GetSwarmNodeAgentDeploymentInput) (*GetSwarmNodeAgentDeploymentOutput, error) {
+func (h *SwarmHandler) GetNodeAgentDeployment(ctx context.Context, input *GetSwarmNodeAgentDeploymentInput) (*handlerutil.Out[SwarmNodeAgentDeployment], error) {
node, err := h.swarmService.GetNode(ctx, input.EnvironmentID, input.NodeID)
if err != nil {
if errdefs.IsNotFound(err) {
@@ -904,7 +700,7 @@ func (h *SwarmHandler) GetNodeAgentDeployment(ctx context.Context, input *GetSwa
return nil, huma.Error500InternalServerError(err.Error())
}
- return &GetSwarmNodeAgentDeploymentOutput{
+ return &handlerutil.Out[SwarmNodeAgentDeployment]{
Body: base.ApiResponse[SwarmNodeAgentDeployment]{
Success: true,
Data: SwarmNodeAgentDeployment{
@@ -920,16 +716,16 @@ func (h *SwarmHandler) GetNodeAgentDeployment(ctx context.Context, input *GetSwa
}
// ReconcileNodeAgents verifies and persists unique visible-environment node bindings.
-func (h *SwarmHandler) ReconcileNodeAgents(ctx context.Context, input *ReconcileSwarmNodeAgentsInput) (*ReconcileSwarmNodeAgentsOutput, error) {
+func (h *SwarmHandler) ReconcileNodeAgents(ctx context.Context, input *ReconcileSwarmNodeAgentsInput) (*handlerutil.Out[swarmtypes.NodeAgentReconcileResponse], error) {
result, err := h.swarmService.ReconcileNodeAgents(ctx, input.EnvironmentID)
if err != nil {
return nil, mapSwarmServiceError(err, "Failed to reconcile swarm node agents")
}
- return &ReconcileSwarmNodeAgentsOutput{Body: base.ApiResponse[swarmtypes.NodeAgentReconcileResponse]{Success: true, Data: *result}}, nil
+ return &handlerutil.Out[swarmtypes.NodeAgentReconcileResponse]{Body: base.ApiResponse[swarmtypes.NodeAgentReconcileResponse]{Success: true, Data: *result}}, nil
}
// PutNodeAgentBinding verifies and attaches an existing visible environment.
-func (h *SwarmHandler) PutNodeAgentBinding(ctx context.Context, input *PutSwarmNodeAgentBindingInput) (*PutSwarmNodeAgentBindingOutput, error) {
+func (h *SwarmHandler) PutNodeAgentBinding(ctx context.Context, input *PutSwarmNodeAgentBindingInput) (*handlerutil.Out[swarmtypes.NodeSummary], error) {
if _, err := h.swarmService.BindNodeAgent(ctx, input.EnvironmentID, input.NodeID, input.Body); err != nil {
return nil, huma.Error400BadRequest(err.Error())
}
@@ -947,19 +743,19 @@ func (h *SwarmHandler) PutNodeAgentBinding(ctx context.Context, input *PutSwarmN
if err != nil {
return nil, mapSwarmServiceError(err, "Failed to refresh swarm node binding")
}
- return &PutSwarmNodeAgentBindingOutput{Body: base.ApiResponse[swarmtypes.NodeSummary]{Success: true, Data: *node}}, nil
+ return &handlerutil.Out[swarmtypes.NodeSummary]{Body: base.ApiResponse[swarmtypes.NodeSummary]{Success: true, Data: *node}}, nil
}
// DeleteNodeAgentBinding detaches the visible environment currently bound to a node.
-func (h *SwarmHandler) DeleteNodeAgentBinding(ctx context.Context, input *DeleteSwarmNodeAgentBindingInput) (*DeleteSwarmNodeAgentBindingOutput, error) {
+func (h *SwarmHandler) DeleteNodeAgentBinding(ctx context.Context, input *DeleteSwarmNodeAgentBindingInput) (*handlerutil.Out[base.MessageResponse], error) {
if err := h.environmentService.DetachSwarmNodeEnvironment(ctx, input.EnvironmentID, input.NodeID); err != nil {
return nil, huma.Error500InternalServerError(err.Error())
}
- return &DeleteSwarmNodeAgentBindingOutput{Body: base.ApiResponse[base.MessageResponse]{Success: true, Data: base.MessageResponse{Message: "Swarm node environment detached"}}}, nil
+ return &handlerutil.Out[base.MessageResponse]{Body: base.ApiResponse[base.MessageResponse]{Success: true, Data: base.MessageResponse{Message: "Swarm node environment detached"}}}, nil
}
// DeleteNodeAgentDeployment removes a dedicated hidden node-agent registration.
-func (h *SwarmHandler) DeleteNodeAgentDeployment(ctx context.Context, input *DeleteSwarmNodeAgentDeploymentInput) (*DeleteSwarmNodeAgentDeploymentOutput, error) {
+func (h *SwarmHandler) DeleteNodeAgentDeployment(ctx context.Context, input *DeleteSwarmNodeAgentDeploymentInput) (*handlerutil.Out[base.MessageResponse], error) {
user, err := handlerutil.RequireUser(ctx)
if err != nil {
return nil, err
@@ -967,7 +763,7 @@ func (h *SwarmHandler) DeleteNodeAgentDeployment(ctx context.Context, input *Del
if err := h.environmentService.DeleteSwarmNodeAgentDeployment(ctx, input.EnvironmentID, input.NodeID, &user.ID, &user.Username); err != nil {
return nil, huma.Error500InternalServerError(err.Error())
}
- return &DeleteSwarmNodeAgentDeploymentOutput{Body: base.ApiResponse[base.MessageResponse]{Success: true, Data: base.MessageResponse{Message: "Dedicated swarm node agent registration removed"}}}, nil
+ return &handlerutil.Out[base.MessageResponse]{Body: base.ApiResponse[base.MessageResponse]{Success: true, Data: base.MessageResponse{Message: "Dedicated swarm node agent registration removed"}}}, nil
}
// GetNodeIdentity returns the swarm identity of the node serving the current request.
@@ -981,13 +777,13 @@ func (h *SwarmHandler) DeleteNodeAgentDeployment(ctx context.Context, input *Del
// Returns the local swarm node identity when it can be determined.
// Returns `500 Internal Server Error` when the swarm service is unavailable or
// identity discovery fails.
-func (h *SwarmHandler) GetNodeIdentity(ctx context.Context, _ *GetSwarmNodeIdentityInput) (*GetSwarmNodeIdentityOutput, error) {
+func (h *SwarmHandler) GetNodeIdentity(ctx context.Context, _ *GetSwarmNodeIdentityInput) (*handlerutil.Out[SwarmNodeIdentity], error) {
identity, err := h.swarmService.GetLocalNodeIdentity(ctx)
if err != nil {
return nil, huma.Error500InternalServerError(err.Error())
}
- return &GetSwarmNodeIdentityOutput{
+ return &handlerutil.Out[SwarmNodeIdentity]{
Body: base.ApiResponse[SwarmNodeIdentity]{
Success: true,
Data: *identity,
@@ -1006,14 +802,14 @@ func (h *SwarmHandler) GetNodeIdentity(ctx context.Context, _ *GetSwarmNodeIdent
// Returns a confirmation response when the update succeeds.
// Returns an authorization error for non-admin callers or a mapped HTTP error
// when the node update fails.
-func (h *SwarmHandler) UpdateNode(ctx context.Context, input *UpdateSwarmNodeInput) (*UpdateSwarmNodeOutput, error) {
+func (h *SwarmHandler) UpdateNode(ctx context.Context, input *UpdateSwarmNodeInput) (*handlerutil.Out[base.MessageResponse], error) {
if err := h.swarmService.UpdateNode(ctx, input.NodeID, input.Body); err != nil {
return nil, mapSwarmServiceError(err, errors.WithMessage(err, "Swarm node not found").Error())
}
h.auditSwarmMutation(ctx, input.EnvironmentID, "node.update", "swarm_node", input.NodeID, "", map[string]any{"nodeId": input.NodeID})
- return &UpdateSwarmNodeOutput{Body: base.ApiResponse[base.MessageResponse]{Success: true, Data: base.MessageResponse{Message: "Swarm node updated successfully"}}}, nil
+ return &handlerutil.Out[base.MessageResponse]{Body: base.ApiResponse[base.MessageResponse]{Success: true, Data: base.MessageResponse{Message: "Swarm node updated successfully"}}}, nil
}
// DeleteNode removes a swarm node from the cluster.
@@ -1027,14 +823,14 @@ func (h *SwarmHandler) UpdateNode(ctx context.Context, input *UpdateSwarmNodeInp
// Returns a confirmation response when the node is removed.
// Returns an authorization error for non-admin callers or a mapped HTTP error
// when the node cannot be removed.
-func (h *SwarmHandler) DeleteNode(ctx context.Context, input *DeleteSwarmNodeInput) (*DeleteSwarmNodeOutput, error) {
+func (h *SwarmHandler) DeleteNode(ctx context.Context, input *DeleteSwarmNodeInput) (*handlerutil.Out[base.MessageResponse], error) {
if err := h.swarmService.RemoveNode(ctx, input.NodeID, input.Force); err != nil {
return nil, mapSwarmServiceError(err, errors.WithMessage(err, "Swarm node not found").Error())
}
h.auditSwarmMutation(ctx, input.EnvironmentID, "node.delete", "swarm_node", input.NodeID, "", map[string]any{"nodeId": input.NodeID, "force": input.Force})
- return &DeleteSwarmNodeOutput{Body: base.ApiResponse[base.MessageResponse]{Success: true, Data: base.MessageResponse{Message: "Swarm node removed successfully"}}}, nil
+ return &handlerutil.Out[base.MessageResponse]{Body: base.ApiResponse[base.MessageResponse]{Success: true, Data: base.MessageResponse{Message: "Swarm node removed successfully"}}}, nil
}
// PromoteNode promotes a swarm worker to manager.
@@ -1048,14 +844,14 @@ func (h *SwarmHandler) DeleteNode(ctx context.Context, input *DeleteSwarmNodeInp
// Returns a confirmation response when the promotion succeeds.
// Returns an authorization error for non-admin callers or a mapped HTTP error
// when the promotion fails.
-func (h *SwarmHandler) PromoteNode(ctx context.Context, input *PromoteSwarmNodeInput) (*PromoteSwarmNodeOutput, error) {
+func (h *SwarmHandler) PromoteNode(ctx context.Context, input *PromoteSwarmNodeInput) (*handlerutil.Out[base.MessageResponse], error) {
if err := h.swarmService.PromoteNode(ctx, input.NodeID); err != nil {
return nil, mapSwarmServiceError(err, errors.WithMessage(err, "Swarm node not found").Error())
}
h.auditSwarmMutation(ctx, input.EnvironmentID, "node.promote", "swarm_node", input.NodeID, "", map[string]any{"nodeId": input.NodeID})
- return &PromoteSwarmNodeOutput{Body: base.ApiResponse[base.MessageResponse]{Success: true, Data: base.MessageResponse{Message: "Swarm node promoted successfully"}}}, nil
+ return &handlerutil.Out[base.MessageResponse]{Body: base.ApiResponse[base.MessageResponse]{Success: true, Data: base.MessageResponse{Message: "Swarm node promoted successfully"}}}, nil
}
// DemoteNode demotes a swarm manager to worker.
@@ -1069,14 +865,14 @@ func (h *SwarmHandler) PromoteNode(ctx context.Context, input *PromoteSwarmNodeI
// Returns a confirmation response when the demotion succeeds.
// Returns an authorization error for non-admin callers or a mapped HTTP error
// when the demotion fails.
-func (h *SwarmHandler) DemoteNode(ctx context.Context, input *DemoteSwarmNodeInput) (*DemoteSwarmNodeOutput, error) {
+func (h *SwarmHandler) DemoteNode(ctx context.Context, input *DemoteSwarmNodeInput) (*handlerutil.Out[base.MessageResponse], error) {
if err := h.swarmService.DemoteNode(ctx, input.NodeID); err != nil {
return nil, mapSwarmServiceError(err, errors.WithMessage(err, "Swarm node not found").Error())
}
h.auditSwarmMutation(ctx, input.EnvironmentID, "node.demote", "swarm_node", input.NodeID, "", map[string]any{"nodeId": input.NodeID})
- return &DemoteSwarmNodeOutput{Body: base.ApiResponse[base.MessageResponse]{Success: true, Data: base.MessageResponse{Message: "Swarm node demoted successfully"}}}, nil
+ return &handlerutil.Out[base.MessageResponse]{Body: base.ApiResponse[base.MessageResponse]{Success: true, Data: base.MessageResponse{Message: "Swarm node demoted successfully"}}}, nil
}
// ListNodeTasks lists tasks currently associated with a swarm node.
@@ -1089,7 +885,7 @@ func (h *SwarmHandler) DemoteNode(ctx context.Context, input *DemoteSwarmNodeInp
//
// Returns a paginated list of node task summaries.
// Returns a mapped HTTP error when the underlying lookup fails.
-func (h *SwarmHandler) ListNodeTasks(ctx context.Context, input *ListSwarmNodeTasksInput) (*ListSwarmNodeTasksOutput, error) {
+func (h *SwarmHandler) ListNodeTasks(ctx context.Context, input *ListSwarmNodeTasksInput) (*handlerutil.Page[swarmtypes.TaskSummary], error) {
params := handlerutil.PaginationParams(input.Start, input.Limit, input.Sort, input.Order, input.Search)
items, paginationResp, err := h.swarmService.ListNodeTasksPaginated(ctx, input.NodeID, params)
if err != nil {
@@ -1099,7 +895,7 @@ func (h *SwarmHandler) ListNodeTasks(ctx context.Context, input *ListSwarmNodeTa
items = []swarmtypes.TaskSummary{}
}
- return &ListSwarmNodeTasksOutput{Body: base.Paginated[swarmtypes.TaskSummary]{Success: true, Data: items, Pagination: handlerutil.PaginationResponse(paginationResp)}}, nil
+ return &handlerutil.Page[swarmtypes.TaskSummary]{Body: base.Paginated[swarmtypes.TaskSummary]{Success: true, Data: items, Pagination: handlerutil.PaginationResponse(paginationResp)}}, nil
}
// ListTasks lists swarm tasks across the current environment.
@@ -1112,7 +908,7 @@ func (h *SwarmHandler) ListNodeTasks(ctx context.Context, input *ListSwarmNodeTa
//
// Returns a paginated task listing for the environment.
// Returns a mapped HTTP error when task enumeration fails.
-func (h *SwarmHandler) ListTasks(ctx context.Context, input *ListSwarmTasksInput) (*ListSwarmTasksOutput, error) {
+func (h *SwarmHandler) ListTasks(ctx context.Context, input *ListSwarmTasksInput) (*handlerutil.Page[swarmtypes.TaskSummary], error) {
params := handlerutil.PaginationParams(input.Start, input.Limit, input.Sort, input.Order, input.Search)
items, paginationResp, err := h.swarmService.ListTasksPaginated(ctx, params)
if err != nil {
@@ -1122,7 +918,7 @@ func (h *SwarmHandler) ListTasks(ctx context.Context, input *ListSwarmTasksInput
items = []swarmtypes.TaskSummary{}
}
- return &ListSwarmTasksOutput{Body: base.Paginated[swarmtypes.TaskSummary]{Success: true, Data: items, Pagination: handlerutil.PaginationResponse(paginationResp)}}, nil
+ return &handlerutil.Page[swarmtypes.TaskSummary]{Body: base.Paginated[swarmtypes.TaskSummary]{Success: true, Data: items, Pagination: handlerutil.PaginationResponse(paginationResp)}}, nil
}
// ListStacks lists swarm stacks for the current environment.
@@ -1135,7 +931,7 @@ func (h *SwarmHandler) ListTasks(ctx context.Context, input *ListSwarmTasksInput
//
// Returns a paginated list of stack summaries.
// Returns a mapped HTTP error when stack enumeration fails.
-func (h *SwarmHandler) ListStacks(ctx context.Context, input *ListSwarmStacksInput) (*ListSwarmStacksOutput, error) {
+func (h *SwarmHandler) ListStacks(ctx context.Context, input *ListSwarmStacksInput) (*handlerutil.Page[swarmtypes.StackSummary], error) {
params := handlerutil.PaginationParams(input.Start, input.Limit, input.Sort, input.Order, input.Search)
items, paginationResp, err := h.swarmService.ListStacksPaginated(ctx, input.EnvironmentID, params)
if err != nil {
@@ -1145,7 +941,7 @@ func (h *SwarmHandler) ListStacks(ctx context.Context, input *ListSwarmStacksInp
items = []swarmtypes.StackSummary{}
}
- return &ListSwarmStacksOutput{Body: base.Paginated[swarmtypes.StackSummary]{Success: true, Data: items, Pagination: handlerutil.PaginationResponse(paginationResp)}}, nil
+ return &handlerutil.Page[swarmtypes.StackSummary]{Body: base.Paginated[swarmtypes.StackSummary]{Success: true, Data: items, Pagination: handlerutil.PaginationResponse(paginationResp)}}, nil
}
// DeployStack deploys or updates a swarm stack.
@@ -1160,7 +956,7 @@ func (h *SwarmHandler) ListStacks(ctx context.Context, input *ListSwarmStacksInp
// Returns the deployment response reported by the swarm service.
// Returns an authorization error for non-admin callers or mapped HTTP errors
// when rendering, validation, or deployment fails.
-func (h *SwarmHandler) DeployStack(ctx context.Context, input *DeploySwarmStackInput) (*DeploySwarmStackOutput, error) {
+func (h *SwarmHandler) DeployStack(ctx context.Context, input *DeploySwarmStackInput) (*handlerutil.Out[swarmtypes.StackDeployResponse], error) {
resp, err := h.swarmService.DeployStack(ctx, input.EnvironmentID, input.Body)
if err != nil {
return nil, mapSwarmServiceError(err, errors.WithMessage(err, "Failed to deploy swarm stack").Error())
@@ -1168,7 +964,7 @@ func (h *SwarmHandler) DeployStack(ctx context.Context, input *DeploySwarmStackI
h.auditSwarmMutation(ctx, input.EnvironmentID, "stack.deploy", "swarm_stack", input.Body.Name, input.Body.Name, map[string]any{"stack": input.Body.Name})
- return &DeploySwarmStackOutput{Body: base.ApiResponse[swarmtypes.StackDeployResponse]{Success: true, Data: *resp}}, nil
+ return &handlerutil.Out[swarmtypes.StackDeployResponse]{Body: base.ApiResponse[swarmtypes.StackDeployResponse]{Success: true, Data: *resp}}, nil
}
// GetStack returns detailed information for a specific swarm stack.
@@ -1182,7 +978,7 @@ func (h *SwarmHandler) DeployStack(ctx context.Context, input *DeploySwarmStackI
// Returns the stack inspection payload when the stack exists.
// Returns `404 Not Found` when the stack does not exist or another mapped HTTP
// error when inspection fails.
-func (h *SwarmHandler) GetStack(ctx context.Context, input *GetSwarmStackInput) (*GetSwarmStackOutput, error) {
+func (h *SwarmHandler) GetStack(ctx context.Context, input *GetSwarmStackInput) (*handlerutil.Out[swarmtypes.StackInspect], error) {
stack, err := h.swarmService.GetStack(ctx, input.EnvironmentID, input.Name)
if err != nil {
if errdefs.IsNotFound(err) {
@@ -1191,7 +987,7 @@ func (h *SwarmHandler) GetStack(ctx context.Context, input *GetSwarmStackInput)
return nil, mapSwarmServiceError(err, "Failed to inspect swarm stack")
}
- return &GetSwarmStackOutput{Body: base.ApiResponse[swarmtypes.StackInspect]{Success: true, Data: *stack}}, nil
+ return &handlerutil.Out[swarmtypes.StackInspect]{Body: base.ApiResponse[swarmtypes.StackInspect]{Success: true, Data: *stack}}, nil
}
// GetStackSource returns the stored source content for a swarm stack.
@@ -1205,7 +1001,7 @@ func (h *SwarmHandler) GetStack(ctx context.Context, input *GetSwarmStackInput)
// Returns the stored compose and environment source for the stack.
// Returns an authorization error for non-admin callers, `404 Not Found` when
// no saved source exists, or another mapped HTTP error when loading fails.
-func (h *SwarmHandler) GetStackSource(ctx context.Context, input *GetSwarmStackSourceInput) (*GetSwarmStackSourceOutput, error) {
+func (h *SwarmHandler) GetStackSource(ctx context.Context, input *GetSwarmStackSourceInput) (*handlerutil.Out[swarmtypes.StackSource], error) {
source, err := h.swarmService.GetStackSource(ctx, input.EnvironmentID, input.Name)
if err != nil {
if errdefs.IsNotFound(err) {
@@ -1214,7 +1010,7 @@ func (h *SwarmHandler) GetStackSource(ctx context.Context, input *GetSwarmStackS
return nil, mapSwarmServiceError(err, "Failed to load swarm stack source")
}
- return &GetSwarmStackSourceOutput{Body: base.ApiResponse[swarmtypes.StackSource]{Success: true, Data: *source}}, nil
+ return &handlerutil.Out[swarmtypes.StackSource]{Body: base.ApiResponse[swarmtypes.StackSource]{Success: true, Data: *source}}, nil
}
// UpdateStackSource persists the saved compose and env source for a swarm
@@ -1223,7 +1019,7 @@ func (h *SwarmHandler) GetStackSource(ctx context.Context, input *GetSwarmStackS
// It requires admin privileges because stack source content can include
// sensitive configuration. The stack name comes from the route, and the body
// contains the replacement source files to save.
-func (h *SwarmHandler) UpdateStackSource(ctx context.Context, input *UpdateSwarmStackSourceInput) (*UpdateSwarmStackSourceOutput, error) {
+func (h *SwarmHandler) UpdateStackSource(ctx context.Context, input *UpdateSwarmStackSourceInput) (*handlerutil.Out[swarmtypes.StackSource], error) {
source, err := h.swarmService.UpdateStackSource(ctx, input.EnvironmentID, input.Name, input.Body)
if err != nil {
return nil, mapSwarmServiceError(err, "Failed to update swarm stack source")
@@ -1231,7 +1027,7 @@ func (h *SwarmHandler) UpdateStackSource(ctx context.Context, input *UpdateSwarm
h.auditSwarmMutation(ctx, input.EnvironmentID, "stack.source.update", "swarm_stack", input.Name, input.Name, map[string]any{"stack": input.Name})
- return &UpdateSwarmStackSourceOutput{Body: base.ApiResponse[swarmtypes.StackSource]{Success: true, Data: *source}}, nil
+ return &handlerutil.Out[swarmtypes.StackSource]{Body: base.ApiResponse[swarmtypes.StackSource]{Success: true, Data: *source}}, nil
}
// DeleteStack removes a swarm stack and its managed resources.
@@ -1246,7 +1042,7 @@ func (h *SwarmHandler) UpdateStackSource(ctx context.Context, input *UpdateSwarm
// Returns a confirmation response when the stack is removed.
// Returns an authorization error for non-admin callers, `404 Not Found` when
// the stack does not exist, or another mapped HTTP error when removal fails.
-func (h *SwarmHandler) DeleteStack(ctx context.Context, input *DeleteSwarmStackInput) (*DeleteSwarmStackOutput, error) {
+func (h *SwarmHandler) DeleteStack(ctx context.Context, input *DeleteSwarmStackInput) (*handlerutil.Out[base.MessageResponse], error) {
if err := h.swarmService.RemoveStack(ctx, input.EnvironmentID, input.Name); err != nil {
if errdefs.IsNotFound(err) {
return nil, huma.Error404NotFound("Swarm stack not found")
@@ -1256,7 +1052,7 @@ func (h *SwarmHandler) DeleteStack(ctx context.Context, input *DeleteSwarmStackI
h.auditSwarmMutation(ctx, input.EnvironmentID, "stack.delete", "swarm_stack", input.Name, input.Name, map[string]any{"stack": input.Name})
- return &DeleteSwarmStackOutput{Body: base.ApiResponse[base.MessageResponse]{Success: true, Data: base.MessageResponse{Message: "Swarm stack removed successfully"}}}, nil
+ return &handlerutil.Out[base.MessageResponse]{Body: base.ApiResponse[base.MessageResponse]{Success: true, Data: base.MessageResponse{Message: "Swarm stack removed successfully"}}}, nil
}
// ListStackServices lists services belonging to a swarm stack.
@@ -1270,7 +1066,7 @@ func (h *SwarmHandler) DeleteStack(ctx context.Context, input *DeleteSwarmStackI
// Returns a paginated list of service summaries for the stack.
// Returns `404 Not Found` when the stack does not exist or another mapped HTTP
// error when the lookup fails.
-func (h *SwarmHandler) ListStackServices(ctx context.Context, input *ListSwarmStackServicesInput) (*ListSwarmStackServicesOutput, error) {
+func (h *SwarmHandler) ListStackServices(ctx context.Context, input *ListSwarmStackServicesInput) (*handlerutil.Page[swarmtypes.ServiceSummary], error) {
params := handlerutil.PaginationParams(input.Start, input.Limit, input.Sort, input.Order, input.Search)
items, paginationResp, err := h.swarmService.ListStackServicesPaginated(ctx, input.Name, params)
if err != nil {
@@ -1283,7 +1079,7 @@ func (h *SwarmHandler) ListStackServices(ctx context.Context, input *ListSwarmSt
items = []swarmtypes.ServiceSummary{}
}
- return &ListSwarmStackServicesOutput{Body: base.Paginated[swarmtypes.ServiceSummary]{Success: true, Data: items, Pagination: handlerutil.PaginationResponse(paginationResp)}}, nil
+ return &handlerutil.Page[swarmtypes.ServiceSummary]{Body: base.Paginated[swarmtypes.ServiceSummary]{Success: true, Data: items, Pagination: handlerutil.PaginationResponse(paginationResp)}}, nil
}
// ListStackTasks lists tasks belonging to a swarm stack.
@@ -1297,7 +1093,7 @@ func (h *SwarmHandler) ListStackServices(ctx context.Context, input *ListSwarmSt
// Returns a paginated list of task summaries for the stack.
// Returns `404 Not Found` when the stack does not exist or another mapped HTTP
// error when the lookup fails.
-func (h *SwarmHandler) ListStackTasks(ctx context.Context, input *ListSwarmStackTasksInput) (*ListSwarmStackTasksOutput, error) {
+func (h *SwarmHandler) ListStackTasks(ctx context.Context, input *ListSwarmStackTasksInput) (*handlerutil.Page[swarmtypes.TaskSummary], error) {
params := handlerutil.PaginationParams(input.Start, input.Limit, input.Sort, input.Order, input.Search)
items, paginationResp, err := h.swarmService.ListStackTasksPaginated(ctx, input.Name, params)
if err != nil {
@@ -1310,7 +1106,7 @@ func (h *SwarmHandler) ListStackTasks(ctx context.Context, input *ListSwarmStack
items = []swarmtypes.TaskSummary{}
}
- return &ListSwarmStackTasksOutput{Body: base.Paginated[swarmtypes.TaskSummary]{Success: true, Data: items, Pagination: handlerutil.PaginationResponse(paginationResp)}}, nil
+ return &handlerutil.Page[swarmtypes.TaskSummary]{Body: base.Paginated[swarmtypes.TaskSummary]{Success: true, Data: items, Pagination: handlerutil.PaginationResponse(paginationResp)}}, nil
}
// RenderStackConfig renders and validates a swarm stack configuration without deploying it.
@@ -1323,13 +1119,13 @@ func (h *SwarmHandler) ListStackTasks(ctx context.Context, input *ListSwarmStack
//
// Returns the rendered compose content together with discovered resource names.
// Returns a mapped HTTP error when parsing, interpolation, or rendering fails.
-func (h *SwarmHandler) RenderStackConfig(ctx context.Context, input *RenderSwarmStackConfigInput) (*RenderSwarmStackConfigOutput, error) {
+func (h *SwarmHandler) RenderStackConfig(ctx context.Context, input *RenderSwarmStackConfigInput) (*handlerutil.Out[swarmtypes.StackRenderConfigResponse], error) {
resp, err := h.swarmService.RenderStackConfig(ctx, input.EnvironmentID, input.Body)
if err != nil {
return nil, mapSwarmServiceError(err, "Failed to render swarm stack config")
}
- return &RenderSwarmStackConfigOutput{Body: base.ApiResponse[swarmtypes.StackRenderConfigResponse]{Success: true, Data: *resp}}, nil
+ return &handlerutil.Out[swarmtypes.StackRenderConfigResponse]{Body: base.ApiResponse[swarmtypes.StackRenderConfigResponse]{Success: true, Data: *resp}}, nil
}
// GetSwarmStatus returns the current swarm cluster metadata for an environment.
@@ -1342,13 +1138,13 @@ func (h *SwarmHandler) RenderStackConfig(ctx context.Context, input *RenderSwarm
//
// Returns the current swarm information when swarm mode is available.
// Returns a mapped HTTP error when swarm inspection fails.
-func (h *SwarmHandler) GetSwarmStatus(ctx context.Context, input *GetSwarmStatusInput) (*GetSwarmStatusOutput, error) {
+func (h *SwarmHandler) GetSwarmStatus(ctx context.Context, input *GetSwarmStatusInput) (*handlerutil.Out[swarmtypes.RuntimeStatus], error) {
enabled, err := h.swarmService.IsEnabled(ctx)
if err != nil {
return nil, huma.Error500InternalServerError("failed to read swarm status")
}
- return &GetSwarmStatusOutput{
+ return &handlerutil.Out[swarmtypes.RuntimeStatus]{
Body: base.ApiResponse[swarmtypes.RuntimeStatus]{
Success: true,
Data: swarmtypes.RuntimeStatus{Enabled: enabled},
@@ -1366,13 +1162,13 @@ func (h *SwarmHandler) GetSwarmStatus(ctx context.Context, input *GetSwarmStatus
//
// Returns the current swarm information when swarm mode is available.
// Returns a mapped HTTP error when swarm inspection fails.
-func (h *SwarmHandler) GetSwarmInfo(ctx context.Context, input *GetSwarmInfoInput) (*GetSwarmInfoOutput, error) {
+func (h *SwarmHandler) GetSwarmInfo(ctx context.Context, input *GetSwarmInfoInput) (*handlerutil.Out[swarmtypes.SwarmInfo], error) {
info, err := h.swarmService.GetSwarmInfo(ctx)
if err != nil {
return nil, mapSwarmServiceError(err, errors.WithMessage(err, "Failed to inspect swarm").Error())
}
- return &GetSwarmInfoOutput{Body: base.ApiResponse[swarmtypes.SwarmInfo]{Success: true, Data: *info}}, nil
+ return &handlerutil.Out[swarmtypes.SwarmInfo]{Body: base.ApiResponse[swarmtypes.SwarmInfo]{Success: true, Data: *info}}, nil
}
// InitSwarm initializes swarm mode on the target engine.
@@ -1386,7 +1182,7 @@ func (h *SwarmHandler) GetSwarmInfo(ctx context.Context, input *GetSwarmInfoInpu
// Returns the initialized swarm node ID and any other initialization details.
// Returns an authorization error for non-admin callers or mapped HTTP errors
// when initialization fails.
-func (h *SwarmHandler) InitSwarm(ctx context.Context, input *InitSwarmInput) (*InitSwarmOutput, error) {
+func (h *SwarmHandler) InitSwarm(ctx context.Context, input *InitSwarmInput) (*handlerutil.Out[swarmtypes.SwarmInitResponse], error) {
resp, err := h.swarmService.InitSwarm(ctx, input.Body)
if err != nil {
return nil, mapSwarmServiceError(err, "Failed to initialize swarm")
@@ -1394,7 +1190,7 @@ func (h *SwarmHandler) InitSwarm(ctx context.Context, input *InitSwarmInput) (*I
h.auditSwarmMutation(ctx, input.EnvironmentID, "lifecycle.init", "swarm", "cluster", "cluster", map[string]any{"nodeId": resp.NodeID})
- return &InitSwarmOutput{Body: base.ApiResponse[swarmtypes.SwarmInitResponse]{Success: true, Data: *resp}}, nil
+ return &handlerutil.Out[swarmtypes.SwarmInitResponse]{Body: base.ApiResponse[swarmtypes.SwarmInitResponse]{Success: true, Data: *resp}}, nil
}
// JoinSwarm joins the target engine to an existing swarm cluster.
@@ -1408,18 +1204,18 @@ func (h *SwarmHandler) InitSwarm(ctx context.Context, input *InitSwarmInput) (*I
// Returns a confirmation response when the engine joins successfully.
// Returns an authorization error for non-admin callers or mapped HTTP errors
// when the join operation fails.
-func (h *SwarmHandler) JoinSwarm(ctx context.Context, input *JoinSwarmInput) (*JoinSwarmOutput, error) {
+func (h *SwarmHandler) JoinSwarm(ctx context.Context, input *JoinSwarmInput) (*handlerutil.Out[base.MessageResponse], error) {
if err := h.swarmService.JoinSwarm(ctx, input.Body); err != nil {
return nil, mapSwarmServiceError(err, "Failed to join swarm")
}
h.auditSwarmMutation(ctx, input.EnvironmentID, "lifecycle.join", "swarm", "cluster", "cluster", map[string]any{"remoteAddrs": input.Body.RemoteAddrs})
- return &JoinSwarmOutput{Body: base.ApiResponse[base.MessageResponse]{Success: true, Data: base.MessageResponse{Message: "Joined swarm successfully"}}}, nil
+ return &handlerutil.Out[base.MessageResponse]{Body: base.ApiResponse[base.MessageResponse]{Success: true, Data: base.MessageResponse{Message: "Joined swarm successfully"}}}, nil
}
// GetJoinCandidates lists enabled visible environments the caller can join.
-func (h *SwarmHandler) GetJoinCandidates(ctx context.Context, input *GetSwarmJoinCandidatesInput) (*GetSwarmJoinCandidatesOutput, error) {
+func (h *SwarmHandler) GetJoinCandidates(ctx context.Context, input *GetSwarmJoinCandidatesInput) (*handlerutil.Out[[]swarmtypes.SwarmJoinCandidate], error) {
if err := requireEasyJoinManagerPermissionsInternal(ctx, input.EnvironmentID); err != nil {
return nil, err
}
@@ -1459,11 +1255,11 @@ func (h *SwarmHandler) GetJoinCandidates(ctx context.Context, input *GetSwarmJoi
})
}
- return &GetSwarmJoinCandidatesOutput{Body: base.ApiResponse[[]swarmtypes.SwarmJoinCandidate]{Success: true, Data: candidates}}, nil
+ return &handlerutil.Out[[]swarmtypes.SwarmJoinCandidate]{Body: base.ApiResponse[[]swarmtypes.SwarmJoinCandidate]{Success: true, Data: candidates}}, nil
}
// JoinEnvironments performs Easy Join without returning manager join tokens.
-func (h *SwarmHandler) JoinEnvironments(ctx context.Context, input *JoinSwarmEnvironmentsInput) (*JoinSwarmEnvironmentsOutput, error) {
+func (h *SwarmHandler) JoinEnvironments(ctx context.Context, input *JoinSwarmEnvironmentsInput) (*handlerutil.Out[swarmtypes.SwarmJoinEnvironmentsResponse], error) {
if err := requireEasyJoinManagerPermissionsInternal(ctx, input.EnvironmentID); err != nil {
return nil, err
}
@@ -1497,7 +1293,7 @@ func (h *SwarmHandler) JoinEnvironments(ctx context.Context, input *JoinSwarmEnv
if err != nil {
return nil, mapSwarmServiceError(err, "Failed to join swarm environments")
}
- return &JoinSwarmEnvironmentsOutput{Body: base.ApiResponse[swarmtypes.SwarmJoinEnvironmentsResponse]{Success: true, Data: *result}}, nil
+ return &handlerutil.Out[swarmtypes.SwarmJoinEnvironmentsResponse]{Body: base.ApiResponse[swarmtypes.SwarmJoinEnvironmentsResponse]{Success: true, Data: *result}}, nil
}
func requireEasyJoinManagerPermissionsInternal(ctx context.Context, environmentID string) error {
@@ -1519,14 +1315,14 @@ func requireEasyJoinManagerPermissionsInternal(ctx context.Context, environmentI
// Returns a confirmation response when the engine leaves successfully.
// Returns an authorization error for non-admin callers or mapped HTTP errors
// when the leave operation fails.
-func (h *SwarmHandler) LeaveSwarm(ctx context.Context, input *LeaveSwarmInput) (*LeaveSwarmOutput, error) {
+func (h *SwarmHandler) LeaveSwarm(ctx context.Context, input *LeaveSwarmInput) (*handlerutil.Out[base.MessageResponse], error) {
if err := h.swarmService.LeaveSwarm(ctx, input.Body); err != nil {
return nil, mapSwarmServiceError(err, "Failed to leave swarm")
}
h.auditSwarmMutation(ctx, input.EnvironmentID, "lifecycle.leave", "swarm", "cluster", "cluster", map[string]any{"force": input.Body.Force})
- return &LeaveSwarmOutput{Body: base.ApiResponse[base.MessageResponse]{Success: true, Data: base.MessageResponse{Message: "Left swarm successfully"}}}, nil
+ return &handlerutil.Out[base.MessageResponse]{Body: base.ApiResponse[base.MessageResponse]{Success: true, Data: base.MessageResponse{Message: "Left swarm successfully"}}}, nil
}
// UnlockSwarm unlocks a swarm manager using the supplied unlock key.
@@ -1540,14 +1336,14 @@ func (h *SwarmHandler) LeaveSwarm(ctx context.Context, input *LeaveSwarmInput) (
// Returns a confirmation response when the manager is unlocked.
// Returns an authorization error for non-admin callers or mapped HTTP errors
// when the unlock operation fails.
-func (h *SwarmHandler) UnlockSwarm(ctx context.Context, input *UnlockSwarmInput) (*UnlockSwarmOutput, error) {
+func (h *SwarmHandler) UnlockSwarm(ctx context.Context, input *UnlockSwarmInput) (*handlerutil.Out[base.MessageResponse], error) {
if err := h.swarmService.UnlockSwarm(ctx, input.Body); err != nil {
return nil, mapSwarmServiceError(err, "Failed to unlock swarm")
}
h.auditSwarmMutation(ctx, input.EnvironmentID, "lifecycle.unlock", "swarm", "cluster", "cluster", map[string]any{})
- return &UnlockSwarmOutput{Body: base.ApiResponse[base.MessageResponse]{Success: true, Data: base.MessageResponse{Message: "Swarm unlocked successfully"}}}, nil
+ return &handlerutil.Out[base.MessageResponse]{Body: base.ApiResponse[base.MessageResponse]{Success: true, Data: base.MessageResponse{Message: "Swarm unlocked successfully"}}}, nil
}
// GetUnlockKey returns the current swarm manager unlock key.
@@ -1560,13 +1356,13 @@ func (h *SwarmHandler) UnlockSwarm(ctx context.Context, input *UnlockSwarmInput)
//
// Returns the current manager unlock key.
// Returns a mapped HTTP error when the unlock key cannot be retrieved.
-func (h *SwarmHandler) GetUnlockKey(ctx context.Context, input *GetSwarmUnlockKeyInput) (*GetSwarmUnlockKeyOutput, error) {
+func (h *SwarmHandler) GetUnlockKey(ctx context.Context, input *GetSwarmUnlockKeyInput) (*handlerutil.Out[swarmtypes.SwarmUnlockKeyResponse], error) {
resp, err := h.swarmService.GetSwarmUnlockKey(ctx)
if err != nil {
return nil, mapSwarmServiceError(err, "Failed to get swarm unlock key")
}
- return &GetSwarmUnlockKeyOutput{Body: base.ApiResponse[swarmtypes.SwarmUnlockKeyResponse]{Success: true, Data: *resp}}, nil
+ return &handlerutil.Out[swarmtypes.SwarmUnlockKeyResponse]{Body: base.ApiResponse[swarmtypes.SwarmUnlockKeyResponse]{Success: true, Data: *resp}}, nil
}
// GetJoinTokens returns the current swarm worker and manager join tokens.
@@ -1579,13 +1375,13 @@ func (h *SwarmHandler) GetUnlockKey(ctx context.Context, input *GetSwarmUnlockKe
//
// Returns the current worker and manager join tokens.
// Returns a mapped HTTP error when token lookup fails.
-func (h *SwarmHandler) GetJoinTokens(ctx context.Context, input *GetSwarmJoinTokensInput) (*GetSwarmJoinTokensOutput, error) {
+func (h *SwarmHandler) GetJoinTokens(ctx context.Context, input *GetSwarmJoinTokensInput) (*handlerutil.Out[swarmtypes.SwarmJoinTokensResponse], error) {
resp, err := h.swarmService.GetSwarmJoinTokens(ctx)
if err != nil {
return nil, mapSwarmServiceError(err, "Failed to get swarm join tokens")
}
- return &GetSwarmJoinTokensOutput{Body: base.ApiResponse[swarmtypes.SwarmJoinTokensResponse]{Success: true, Data: *resp}}, nil
+ return &handlerutil.Out[swarmtypes.SwarmJoinTokensResponse]{Body: base.ApiResponse[swarmtypes.SwarmJoinTokensResponse]{Success: true, Data: *resp}}, nil
}
// RotateJoinTokens rotates the swarm worker and or manager join tokens.
@@ -1599,14 +1395,14 @@ func (h *SwarmHandler) GetJoinTokens(ctx context.Context, input *GetSwarmJoinTok
// Returns a confirmation response when rotation succeeds.
// Returns an authorization error for non-admin callers or mapped HTTP errors
// when token rotation fails.
-func (h *SwarmHandler) RotateJoinTokens(ctx context.Context, input *RotateSwarmJoinTokensInput) (*RotateSwarmJoinTokensOutput, error) {
+func (h *SwarmHandler) RotateJoinTokens(ctx context.Context, input *RotateSwarmJoinTokensInput) (*handlerutil.Out[base.MessageResponse], error) {
if err := h.swarmService.RotateSwarmJoinTokens(ctx, input.Body); err != nil {
return nil, mapSwarmServiceError(err, "Failed to rotate swarm join tokens")
}
h.auditSwarmMutation(ctx, input.EnvironmentID, "lifecycle.rotate_tokens", "swarm", "cluster", "cluster", map[string]any{"rotateWorker": input.Body.RotateWorkerToken, "rotateManager": input.Body.RotateManagerToken})
- return &RotateSwarmJoinTokensOutput{Body: base.ApiResponse[base.MessageResponse]{Success: true, Data: base.MessageResponse{Message: "Swarm join tokens rotated successfully"}}}, nil
+ return &handlerutil.Out[base.MessageResponse]{Body: base.ApiResponse[base.MessageResponse]{Success: true, Data: base.MessageResponse{Message: "Swarm join tokens rotated successfully"}}}, nil
}
// UpdateSwarmSpec updates the swarm cluster specification.
@@ -1620,14 +1416,14 @@ func (h *SwarmHandler) RotateJoinTokens(ctx context.Context, input *RotateSwarmJ
// Returns a confirmation response when the spec update succeeds.
// Returns an authorization error for non-admin callers or mapped HTTP errors
// when the spec update fails.
-func (h *SwarmHandler) UpdateSwarmSpec(ctx context.Context, input *UpdateSwarmSpecInput) (*UpdateSwarmSpecOutput, error) {
+func (h *SwarmHandler) UpdateSwarmSpec(ctx context.Context, input *UpdateSwarmSpecInput) (*handlerutil.Out[base.MessageResponse], error) {
if err := h.swarmService.UpdateSwarmSpec(ctx, input.Body); err != nil {
return nil, mapSwarmServiceError(err, "Failed to update swarm spec")
}
h.auditSwarmMutation(ctx, input.EnvironmentID, "lifecycle.update_spec", "swarm", "cluster", "cluster", map[string]any{})
- return &UpdateSwarmSpecOutput{Body: base.ApiResponse[base.MessageResponse]{Success: true, Data: base.MessageResponse{Message: "Swarm spec updated successfully"}}}, nil
+ return &handlerutil.Out[base.MessageResponse]{Body: base.ApiResponse[base.MessageResponse]{Success: true, Data: base.MessageResponse{Message: "Swarm spec updated successfully"}}}, nil
}
// ListConfigs lists swarm configs in the current environment.
@@ -1640,7 +1436,7 @@ func (h *SwarmHandler) UpdateSwarmSpec(ctx context.Context, input *UpdateSwarmSp
//
// Returns the current swarm configs.
// Returns a mapped HTTP error when config enumeration fails.
-func (h *SwarmHandler) ListConfigs(ctx context.Context, input *ListSwarmConfigsInput) (*ListSwarmConfigsOutput, error) {
+func (h *SwarmHandler) ListConfigs(ctx context.Context, input *ListSwarmConfigsInput) (*handlerutil.Out[[]swarmtypes.ConfigSummary], error) {
items, err := h.swarmService.ListConfigs(ctx)
if err != nil {
return nil, mapSwarmServiceError(err, "Failed to list swarm configs")
@@ -1649,7 +1445,7 @@ func (h *SwarmHandler) ListConfigs(ctx context.Context, input *ListSwarmConfigsI
items = []swarmtypes.ConfigSummary{}
}
- return &ListSwarmConfigsOutput{Body: base.ApiResponse[[]swarmtypes.ConfigSummary]{Success: true, Data: items}}, nil
+ return &handlerutil.Out[[]swarmtypes.ConfigSummary]{Body: base.ApiResponse[[]swarmtypes.ConfigSummary]{Success: true, Data: items}}, nil
}
// GetConfig returns details for a single swarm config.
@@ -1663,7 +1459,7 @@ func (h *SwarmHandler) ListConfigs(ctx context.Context, input *ListSwarmConfigsI
// Returns the config summary when the config exists.
// Returns `404 Not Found` when the config does not exist or another mapped HTTP
// error when inspection fails.
-func (h *SwarmHandler) GetConfig(ctx context.Context, input *GetSwarmConfigInput) (*GetSwarmConfigOutput, error) {
+func (h *SwarmHandler) GetConfig(ctx context.Context, input *GetSwarmConfigInput) (*handlerutil.Out[swarmtypes.ConfigSummary], error) {
cfg, err := h.swarmService.GetConfig(ctx, input.ConfigID)
if err != nil {
if errdefs.IsNotFound(err) {
@@ -1672,7 +1468,7 @@ func (h *SwarmHandler) GetConfig(ctx context.Context, input *GetSwarmConfigInput
return nil, mapSwarmServiceError(err, "Failed to inspect swarm config")
}
- return &GetSwarmConfigOutput{Body: base.ApiResponse[swarmtypes.ConfigSummary]{Success: true, Data: *cfg}}, nil
+ return &handlerutil.Out[swarmtypes.ConfigSummary]{Body: base.ApiResponse[swarmtypes.ConfigSummary]{Success: true, Data: *cfg}}, nil
}
// CreateConfig creates a new swarm config.
@@ -1686,7 +1482,7 @@ func (h *SwarmHandler) GetConfig(ctx context.Context, input *GetSwarmConfigInput
// Returns the created config summary.
// Returns an authorization error for non-admin callers or mapped HTTP errors
// when validation or creation fails.
-func (h *SwarmHandler) CreateConfig(ctx context.Context, input *CreateSwarmConfigInput) (*CreateSwarmConfigOutput, error) {
+func (h *SwarmHandler) CreateConfig(ctx context.Context, input *CreateSwarmConfigInput) (*handlerutil.Out[swarmtypes.ConfigSummary], error) {
cfg, err := h.swarmService.CreateConfig(ctx, input.Body)
if err != nil {
return nil, mapSwarmServiceError(err, "Failed to create swarm config")
@@ -1694,7 +1490,7 @@ func (h *SwarmHandler) CreateConfig(ctx context.Context, input *CreateSwarmConfi
h.auditSwarmMutation(ctx, input.EnvironmentID, "config.create", "swarm_config", cfg.ID, cfg.Spec.Name, map[string]any{"configId": cfg.ID, "name": cfg.Spec.Name})
- return &CreateSwarmConfigOutput{Body: base.ApiResponse[swarmtypes.ConfigSummary]{Success: true, Data: *cfg}}, nil
+ return &handlerutil.Out[swarmtypes.ConfigSummary]{Body: base.ApiResponse[swarmtypes.ConfigSummary]{Success: true, Data: *cfg}}, nil
}
// DeleteConfig removes a swarm config.
@@ -1708,7 +1504,7 @@ func (h *SwarmHandler) CreateConfig(ctx context.Context, input *CreateSwarmConfi
// Returns a confirmation response when the config is removed.
// Returns an authorization error for non-admin callers, `404 Not Found` when
// the config does not exist, or another mapped HTTP error when removal fails.
-func (h *SwarmHandler) DeleteConfig(ctx context.Context, input *DeleteSwarmConfigInput) (*DeleteSwarmConfigOutput, error) {
+func (h *SwarmHandler) DeleteConfig(ctx context.Context, input *DeleteSwarmConfigInput) (*handlerutil.Out[base.MessageResponse], error) {
if err := h.swarmService.RemoveConfig(ctx, input.ConfigID); err != nil {
if errdefs.IsNotFound(err) {
return nil, huma.Error404NotFound("Swarm config not found")
@@ -1718,7 +1514,7 @@ func (h *SwarmHandler) DeleteConfig(ctx context.Context, input *DeleteSwarmConfi
h.auditSwarmMutation(ctx, input.EnvironmentID, "config.delete", "swarm_config", input.ConfigID, "", map[string]any{"configId": input.ConfigID})
- return &DeleteSwarmConfigOutput{Body: base.ApiResponse[base.MessageResponse]{Success: true, Data: base.MessageResponse{Message: "Swarm config removed successfully"}}}, nil
+ return &handlerutil.Out[base.MessageResponse]{Body: base.ApiResponse[base.MessageResponse]{Success: true, Data: base.MessageResponse{Message: "Swarm config removed successfully"}}}, nil
}
// ListSecrets lists swarm secrets in the current environment.
@@ -1731,7 +1527,7 @@ func (h *SwarmHandler) DeleteConfig(ctx context.Context, input *DeleteSwarmConfi
//
// Returns the current swarm secrets.
// Returns a mapped HTTP error when secret enumeration fails.
-func (h *SwarmHandler) ListSecrets(ctx context.Context, input *ListSwarmSecretsInput) (*ListSwarmSecretsOutput, error) {
+func (h *SwarmHandler) ListSecrets(ctx context.Context, input *ListSwarmSecretsInput) (*handlerutil.Out[[]swarmtypes.SecretSummary], error) {
items, err := h.swarmService.ListSecrets(ctx)
if err != nil {
return nil, mapSwarmServiceError(err, "Failed to list swarm secrets")
@@ -1740,7 +1536,7 @@ func (h *SwarmHandler) ListSecrets(ctx context.Context, input *ListSwarmSecretsI
items = []swarmtypes.SecretSummary{}
}
- return &ListSwarmSecretsOutput{Body: base.ApiResponse[[]swarmtypes.SecretSummary]{Success: true, Data: items}}, nil
+ return &handlerutil.Out[[]swarmtypes.SecretSummary]{Body: base.ApiResponse[[]swarmtypes.SecretSummary]{Success: true, Data: items}}, nil
}
// GetSecret returns details for a single swarm secret.
@@ -1754,7 +1550,7 @@ func (h *SwarmHandler) ListSecrets(ctx context.Context, input *ListSwarmSecretsI
// Returns the secret summary when the secret exists.
// Returns `404 Not Found` when the secret does not exist or another mapped HTTP
// error when inspection fails.
-func (h *SwarmHandler) GetSecret(ctx context.Context, input *GetSwarmSecretInput) (*GetSwarmSecretOutput, error) {
+func (h *SwarmHandler) GetSecret(ctx context.Context, input *GetSwarmSecretInput) (*handlerutil.Out[swarmtypes.SecretSummary], error) {
secret, err := h.swarmService.GetSecret(ctx, input.SecretID)
if err != nil {
if errdefs.IsNotFound(err) {
@@ -1763,7 +1559,7 @@ func (h *SwarmHandler) GetSecret(ctx context.Context, input *GetSwarmSecretInput
return nil, mapSwarmServiceError(err, "Failed to inspect swarm secret")
}
- return &GetSwarmSecretOutput{Body: base.ApiResponse[swarmtypes.SecretSummary]{Success: true, Data: *secret}}, nil
+ return &handlerutil.Out[swarmtypes.SecretSummary]{Body: base.ApiResponse[swarmtypes.SecretSummary]{Success: true, Data: *secret}}, nil
}
// CreateSecret creates a new swarm secret.
@@ -1777,7 +1573,7 @@ func (h *SwarmHandler) GetSecret(ctx context.Context, input *GetSwarmSecretInput
// Returns the created secret summary.
// Returns an authorization error for non-admin callers or mapped HTTP errors
// when validation or creation fails.
-func (h *SwarmHandler) CreateSecret(ctx context.Context, input *CreateSwarmSecretInput) (*CreateSwarmSecretOutput, error) {
+func (h *SwarmHandler) CreateSecret(ctx context.Context, input *CreateSwarmSecretInput) (*handlerutil.Out[swarmtypes.SecretSummary], error) {
secret, err := h.swarmService.CreateSecret(ctx, input.Body)
if err != nil {
return nil, mapSwarmServiceError(err, "Failed to create swarm secret")
@@ -1785,7 +1581,7 @@ func (h *SwarmHandler) CreateSecret(ctx context.Context, input *CreateSwarmSecre
h.auditSwarmMutation(ctx, input.EnvironmentID, "secret.create", "swarm_secret", secret.ID, secret.Spec.Name, map[string]any{"secretId": secret.ID, "name": secret.Spec.Name})
- return &CreateSwarmSecretOutput{Body: base.ApiResponse[swarmtypes.SecretSummary]{Success: true, Data: *secret}}, nil
+ return &handlerutil.Out[swarmtypes.SecretSummary]{Body: base.ApiResponse[swarmtypes.SecretSummary]{Success: true, Data: *secret}}, nil
}
// DeleteSecret removes a swarm secret.
@@ -1799,7 +1595,7 @@ func (h *SwarmHandler) CreateSecret(ctx context.Context, input *CreateSwarmSecre
// Returns a confirmation response when the secret is removed.
// Returns an authorization error for non-admin callers, `404 Not Found` when
// the secret does not exist, or another mapped HTTP error when removal fails.
-func (h *SwarmHandler) DeleteSecret(ctx context.Context, input *DeleteSwarmSecretInput) (*DeleteSwarmSecretOutput, error) {
+func (h *SwarmHandler) DeleteSecret(ctx context.Context, input *DeleteSwarmSecretInput) (*handlerutil.Out[base.MessageResponse], error) {
if err := h.swarmService.RemoveSecret(ctx, input.SecretID); err != nil {
if errdefs.IsNotFound(err) {
return nil, huma.Error404NotFound("Swarm secret not found")
@@ -1809,7 +1605,7 @@ func (h *SwarmHandler) DeleteSecret(ctx context.Context, input *DeleteSwarmSecre
h.auditSwarmMutation(ctx, input.EnvironmentID, "secret.delete", "swarm_secret", input.SecretID, "", map[string]any{"secretId": input.SecretID})
- return &DeleteSwarmSecretOutput{Body: base.ApiResponse[base.MessageResponse]{Success: true, Data: base.MessageResponse{Message: "Swarm secret removed successfully"}}}, nil
+ return &handlerutil.Out[base.MessageResponse]{Body: base.ApiResponse[base.MessageResponse]{Success: true, Data: base.MessageResponse{Message: "Swarm secret removed successfully"}}}, nil
}
// auditSwarmMutation writes an informational event for a completed swarm mutation.
diff --git a/backend/internal/swarm/swarm.go b/backend/internal/swarm/swarm.go
index 9723db419..c9ab657ec 100644
--- a/backend/internal/swarm/swarm.go
+++ b/backend/internal/swarm/swarm.go
@@ -189,7 +189,7 @@ func (s *SwarmService) ListServicesPaginated(ctx context.Context, params paginat
}
config := s.buildServicePaginationConfigInternal()
- result := pagination.SearchOrderAndPaginate(items, params, config)
+ result := config.SearchOrderAndPaginate(items, params)
paginationResp := pagination.BuildResponse(result.TotalCount, result.TotalAvailable, params)
return result.Items, paginationResp, nil
@@ -501,7 +501,7 @@ func (s *SwarmService) ListNodesPaginated(ctx context.Context, environmentID str
}
s.enrichNodeAgentStatusesInternal(ctx, environmentID, remote.Data)
- result := pagination.SearchOrderAndPaginate(remote.Data, params, s.buildNodePaginationConfigInternal())
+ result := s.buildNodePaginationConfigInternal().SearchOrderAndPaginate(remote.Data, params)
return result.Items, pagination.BuildResponse(result.TotalCount, result.TotalAvailable, params), nil
}
@@ -528,7 +528,7 @@ func (s *SwarmService) ListNodesPaginated(ctx context.Context, environmentID str
s.enrichNodeAgentStatusesInternal(ctx, environmentID, items)
config := s.buildNodePaginationConfigInternal()
- result := pagination.SearchOrderAndPaginate(items, params, config)
+ result := config.SearchOrderAndPaginate(items, params)
paginationResp := pagination.BuildResponse(result.TotalCount, result.TotalAvailable, params)
return result.Items, paginationResp, nil
@@ -1183,7 +1183,7 @@ func (s *SwarmService) ListTasksPaginated(ctx context.Context, params pagination
}
config := s.buildTaskPaginationConfigInternal()
- result := pagination.SearchOrderAndPaginate(items, params, config)
+ result := config.SearchOrderAndPaginate(items, params)
paginationResp := pagination.BuildResponse(result.TotalCount, result.TotalAvailable, params)
return result.Items, paginationResp, nil
@@ -1251,7 +1251,7 @@ func (s *SwarmService) ListStacksPaginated(ctx context.Context, environmentID st
}
config := s.buildStackPaginationConfigInternal()
- result := pagination.SearchOrderAndPaginate(items, params, config)
+ result := config.SearchOrderAndPaginate(items, params)
paginationResp := pagination.BuildResponse(result.TotalCount, result.TotalAvailable, params)
return result.Items, paginationResp, nil
@@ -2042,7 +2042,7 @@ func (s *SwarmService) ListStackServicesPaginated(ctx context.Context, stackName
}
config := s.buildServicePaginationConfigInternal()
- result := pagination.SearchOrderAndPaginate(summaries, params, config)
+ result := config.SearchOrderAndPaginate(summaries, params)
paginationResp := pagination.BuildResponse(result.TotalCount, result.TotalAvailable, params)
return result.Items, paginationResp, nil
}
@@ -2323,7 +2323,7 @@ func (s *SwarmService) listTasksPaginatedWithFiltersInternal(ctx context.Context
}
config := s.buildTaskPaginationConfigInternal()
- result := pagination.SearchOrderAndPaginate(items, params, config)
+ result := config.SearchOrderAndPaginate(items, params)
paginationResp := pagination.BuildResponse(result.TotalCount, result.TotalAvailable, params)
return result.Items, paginationResp, nil
}
diff --git a/backend/internal/system/handler.go b/backend/internal/system/handler.go
index dabe3304b..72202d157 100644
--- a/backend/internal/system/handler.go
+++ b/backend/internal/system/handler.go
@@ -60,34 +60,18 @@ type PruneAllInput struct {
Body system.PruneAllRequest `doc:"Prune options"`
}
-type PruneAllOutput struct {
- Body base.ApiResponse[system.PruneAllResult]
-}
-
type StartAllContainersInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
}
-type StartAllContainersOutput struct {
- Body base.ApiResponse[containertypes.ActionResult]
-}
-
type StartAllStoppedContainersInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
}
-type StartAllStoppedContainersOutput struct {
- Body base.ApiResponse[containertypes.ActionResult]
-}
-
type StopAllContainersInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
}
-type StopAllContainersOutput struct {
- Body base.ApiResponse[containertypes.ActionResult]
-}
-
type ConvertDockerRunInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
Body system.ConvertDockerRunRequest `doc:"Docker run command"`
@@ -129,26 +113,14 @@ type TriggerUpgradeData struct {
UpToDate bool `json:"upToDate" doc:"Environment already runs the newest image, so no restart is expected"`
}
-type TriggerUpgradeOutput struct {
- Body base.ApiResponse[TriggerUpgradeData]
-}
-
type TriggerUpdateAllInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
}
-type TriggerUpdateAllOutput struct {
- Body base.ApiResponse[EnvironmentUpdateJob]
-}
-
type UpdateAllStatusInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
}
-type UpdateAllStatusOutput struct {
- Body base.ApiResponse[EnvironmentUpdateJob]
-}
-
// RegisterSystem registers system management endpoints using Huma.
// WebSocket statistics endpoints live in api/ws.
func RegisterSystem(api huma.API, dockerService *docker.DockerClientService, systemService *SystemService, upgradeService *SystemUpgradeService, environmentService *environment.EnvironmentService, cfg *config.Config, activityService *activity.ActivityService, appCtx handlerutil.ActivityAppContext) {
@@ -388,7 +360,7 @@ func extractVersionDetailsFromComponents(components []dockersystem.ComponentVers
}
// PruneAll removes unused Docker resources.
-func (h *SystemHandler) PruneAll(ctx context.Context, input *PruneAllInput) (*PruneAllOutput, error) {
+func (h *SystemHandler) PruneAll(ctx context.Context, input *PruneAllInput) (*handlerutil.Out[system.PruneAllResult], error) {
slog.InfoContext(ctx, "System prune operation initiated",
"containers", input.Body.Containers,
"images", input.Body.Images,
@@ -401,7 +373,7 @@ func (h *SystemHandler) PruneAll(ctx context.Context, input *PruneAllInput) (*Pr
slog.InfoContext(runtimeCtx, "System prune background activity started", "activityId", result.ActivityID)
- return &PruneAllOutput{
+ return &handlerutil.Out[system.PruneAllResult]{
Body: base.ApiResponse[system.PruneAllResult]{
Success: true,
Data: *result,
@@ -410,14 +382,14 @@ func (h *SystemHandler) PruneAll(ctx context.Context, input *PruneAllInput) (*Pr
}
// StartAllContainers starts all Docker containers.
-func (h *SystemHandler) StartAllContainers(ctx context.Context, input *StartAllContainersInput) (*StartAllContainersOutput, error) {
+func (h *SystemHandler) StartAllContainers(ctx context.Context, input *StartAllContainersInput) (*handlerutil.Out[containertypes.ActionResult], error) {
runtimeCtx := utils.ActivityRuntimeContext(ctx, h.appCtx)
result, err := h.systemService.StartAllContainers(runtimeCtx, input.EnvironmentID)
if err != nil {
return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to start containers").Error())
}
- return &StartAllContainersOutput{
+ return &handlerutil.Out[containertypes.ActionResult]{
Body: base.ApiResponse[containertypes.ActionResult]{
Success: true,
Data: *result,
@@ -426,14 +398,14 @@ func (h *SystemHandler) StartAllContainers(ctx context.Context, input *StartAllC
}
// StartAllStoppedContainers starts all stopped Docker containers.
-func (h *SystemHandler) StartAllStoppedContainers(ctx context.Context, input *StartAllStoppedContainersInput) (*StartAllStoppedContainersOutput, error) {
+func (h *SystemHandler) StartAllStoppedContainers(ctx context.Context, input *StartAllStoppedContainersInput) (*handlerutil.Out[containertypes.ActionResult], error) {
runtimeCtx := utils.ActivityRuntimeContext(ctx, h.appCtx)
result, err := h.systemService.StartAllStoppedContainers(runtimeCtx, input.EnvironmentID)
if err != nil {
return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to start stopped containers").Error())
}
- return &StartAllStoppedContainersOutput{
+ return &handlerutil.Out[containertypes.ActionResult]{
Body: base.ApiResponse[containertypes.ActionResult]{
Success: true,
Data: *result,
@@ -442,14 +414,14 @@ func (h *SystemHandler) StartAllStoppedContainers(ctx context.Context, input *St
}
// StopAllContainers stops all running Docker containers.
-func (h *SystemHandler) StopAllContainers(ctx context.Context, input *StopAllContainersInput) (*StopAllContainersOutput, error) {
+func (h *SystemHandler) StopAllContainers(ctx context.Context, input *StopAllContainersInput) (*handlerutil.Out[containertypes.ActionResult], error) {
runtimeCtx := utils.ActivityRuntimeContext(ctx, h.appCtx)
result, err := h.systemService.StopAllContainers(runtimeCtx, input.EnvironmentID)
if err != nil {
return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to stop containers").Error())
}
- return &StopAllContainersOutput{
+ return &handlerutil.Out[containertypes.ActionResult]{
Body: base.ApiResponse[containertypes.ActionResult]{
Success: true,
Data: *result,
@@ -506,7 +478,7 @@ func (h *SystemHandler) CheckUpgradeAvailable(ctx context.Context, input *CheckU
}
// TriggerUpgrade triggers a system upgrade.
-func (h *SystemHandler) TriggerUpgrade(ctx context.Context, input *TriggerUpgradeInput) (*TriggerUpgradeOutput, error) {
+func (h *SystemHandler) TriggerUpgrade(ctx context.Context, input *TriggerUpgradeInput) (*handlerutil.Out[TriggerUpgradeData], error) {
user, err := handlerutil.RequireUser(ctx)
if err != nil {
return nil, err
@@ -539,7 +511,7 @@ func (h *SystemHandler) TriggerUpgrade(ctx context.Context, input *TriggerUpgrad
message = "Already running the newest image. The upgrade pulls it again and leaves the container in place."
}
- return &TriggerUpgradeOutput{
+ return &handlerutil.Out[TriggerUpgradeData]{
Body: base.ApiResponse[TriggerUpgradeData]{
Success: true,
Data: TriggerUpgradeData{
@@ -552,7 +524,7 @@ func (h *SystemHandler) TriggerUpgrade(ctx context.Context, input *TriggerUpgrad
// TriggerUpdateAll starts a fleet-wide update, upgrading the manager first and then
// the remote agents (the latter resume after the manager restarts).
-func (h *SystemHandler) TriggerUpdateAll(ctx context.Context, input *TriggerUpdateAllInput) (*TriggerUpdateAllOutput, error) {
+func (h *SystemHandler) TriggerUpdateAll(ctx context.Context, input *TriggerUpdateAllInput) (*handlerutil.Out[EnvironmentUpdateJob], error) {
if err := h.rejectIfAgentModeInternal(); err != nil {
return nil, err
}
@@ -576,7 +548,7 @@ func (h *SystemHandler) TriggerUpdateAll(ctx context.Context, input *TriggerUpda
return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to initiate upgrade").Error())
}
- return &TriggerUpdateAllOutput{
+ return &handlerutil.Out[EnvironmentUpdateJob]{
Body: base.ApiResponse[EnvironmentUpdateJob]{
Success: true,
Data: *job,
@@ -585,7 +557,7 @@ func (h *SystemHandler) TriggerUpdateAll(ctx context.Context, input *TriggerUpda
}
// GetUpdateAllStatus returns the latest update-all job for live progress polling.
-func (h *SystemHandler) GetUpdateAllStatus(ctx context.Context, input *UpdateAllStatusInput) (*UpdateAllStatusOutput, error) {
+func (h *SystemHandler) GetUpdateAllStatus(ctx context.Context, input *UpdateAllStatusInput) (*handlerutil.Out[EnvironmentUpdateJob], error) {
if err := h.rejectIfAgentModeInternal(); err != nil {
return nil, err
}
@@ -598,7 +570,7 @@ func (h *SystemHandler) GetUpdateAllStatus(ctx context.Context, input *UpdateAll
return nil, huma.Error404NotFound("no update-all job found")
}
- return &UpdateAllStatusOutput{
+ return &handlerutil.Out[EnvironmentUpdateJob]{
Body: base.ApiResponse[EnvironmentUpdateJob]{
Success: true,
Data: *job,
diff --git a/backend/internal/system/model.go b/backend/internal/system/model.go
index e686e7f5e..e60c9ef64 100644
--- a/backend/internal/system/model.go
+++ b/backend/internal/system/model.go
@@ -4,10 +4,7 @@ import (
"github.com/getarcaneapp/arcane/backend/v2/internal/database"
"database/sql/driver"
- "encoding/json/v2"
"time"
-
- "emperror.dev/errors"
)
// EnvironmentUpdateJobStatus is the lifecycle status of a fleet-wide "update all
@@ -71,25 +68,11 @@ type EnvironmentUpdateResult struct {
type EnvironmentUpdateResults []EnvironmentUpdateResult
func (r EnvironmentUpdateResults) Value() (driver.Value, error) {
- if r == nil {
- return nil, nil
- }
- return json.Marshal(r)
+ return database.JSONValue(r == nil, r)
}
func (r *EnvironmentUpdateResults) Scan(value any) error {
- if value == nil {
- *r = nil
- return nil
- }
- switch v := value.(type) {
- case []byte:
- return json.Unmarshal(v, r)
- case string:
- return json.Unmarshal([]byte(v), r)
- default:
- return errors.Errorf("unsupported scan type for EnvironmentUpdateResults: %T", value)
- }
+ return database.JSONScan(r, value)
}
// EnvironmentUpdateJob is a persisted fleet-wide update orchestration record. It
diff --git a/backend/internal/systembackup/handler.go b/backend/internal/systembackup/handler.go
index 146335239..f9328a88d 100644
--- a/backend/internal/systembackup/handler.go
+++ b/backend/internal/systembackup/handler.go
@@ -45,13 +45,6 @@ type ListBackupHistoryInput struct {
Type string `query:"type"`
}
-type ListBackupHistoryOutput struct {
- Body struct {
- Data []backuptypes.HistoryEntry `json:"data"`
- Pagination base.PaginationResponse `json:"pagination"`
- }
-}
-
type SystemVolumeBackupConfigOutput struct {
Body backuptypes.SystemVolumeBackupPolicyCollection
}
@@ -72,13 +65,6 @@ type RunSystemVolumeBackupsInput struct {
Body *backuptypes.RunSystemVolumeBackupsRequest `json:"body,omitempty"`
}
-type ListSystemBackupsOutput struct {
- Body struct {
- Data []backuptypes.SystemBackupRun `json:"data"`
- Pagination base.PaginationResponse `json:"pagination"`
- }
-}
-
type SystemBackupPoliciesOutput struct {
Body backuptypes.SystemBackupPolicyCollection
}
@@ -113,11 +99,6 @@ type BrowseSystemBackupFilesInput struct {
Body backuptypes.SystemBackupRecoveryKey
}
-// BrowseSystemBackupFilesOutput contains a page of project files and folders.
-type BrowseSystemBackupFilesOutput struct {
- Body base.Paginated[backuptypes.BackupFileEntry]
-}
-
// RestoreSystemBackupFilesInput selects project files to restore from a system backup.
type RestoreSystemBackupFilesInput struct {
ID string `path:"id"`
@@ -134,10 +115,6 @@ type DeleteSystemBackupInput struct {
type DiscoverSystemBackupsInput struct {
Body backuptypes.DiscoverSystemBackupsRequest
}
-type DiscoverSystemBackupsOutput struct{ Body base.ApiResponse[int] }
-type SystemBackupMessageOutput struct {
- Body base.ApiResponse[base.MessageResponse]
-}
func RegisterSystemBackups(api huma.API, service *SystemBackupService, activityService *activity.ActivityService, appCtx handlerutil.ActivityAppContext) {
h := &SystemBackupHandler{service: service, activity: activityService, appCtx: appCtx.Context()}
@@ -161,16 +138,20 @@ func RegisterSystemBackups(api huma.API, service *SystemBackupService, activityS
middleware.RegisterWithPermission(api, huma.Operation{OperationID: "delete-system-backup", Method: http.MethodDelete, Path: "/backups/{id}", Summary: "Delete Arcane system backup", Tags: []string{"System Backups"}, Middlewares: adminOnly}, authz.PermSystemBackupsManage, h.Delete)
}
-func (h *SystemBackupHandler) ListHistory(ctx context.Context, input *ListBackupHistoryInput) (*ListBackupHistoryOutput, error) {
+func (h *SystemBackupHandler) ListHistory(ctx context.Context, input *ListBackupHistoryInput) (*handlerutil.Page[backuptypes.HistoryEntry], error) {
params := handlerutil.PaginationParams(input.Start, input.Limit, input.Sort, input.Order, input.Search)
params.Filters = map[string]string{"type": input.Type}
history, page, err := h.service.ListBackupHistory(ctx, params)
if err != nil {
return nil, huma.Error500InternalServerError(err.Error())
}
- out := &ListBackupHistoryOutput{}
- out.Body.Data, out.Body.Pagination = history, handlerutil.PaginationResponse(page)
- return out, nil
+ return &handlerutil.Page[backuptypes.HistoryEntry]{
+ Body: base.Paginated[backuptypes.HistoryEntry]{
+ Success: true,
+ Data: history,
+ Pagination: handlerutil.PaginationResponse(page),
+ },
+ }, nil
}
func (h *SystemBackupHandler) GetSystemVolumeConfig(ctx context.Context, _ *struct{}) (*SystemVolumeBackupConfigOutput, error) {
@@ -212,15 +193,19 @@ func (h *SystemBackupHandler) RunSystemVolumeBackups(ctx context.Context, input
return &SystemVolumeBackupRunOutput{Body: *result}, nil
}
-func (h *SystemBackupHandler) List(ctx context.Context, input *ListSystemBackupsInput) (*ListSystemBackupsOutput, error) {
+func (h *SystemBackupHandler) List(ctx context.Context, input *ListSystemBackupsInput) (*handlerutil.Page[backuptypes.SystemBackupRun], error) {
params := handlerutil.PaginationParams(input.Start, input.Limit, input.Sort, input.Order, input.Search)
runs, page, err := h.service.ListBackups(ctx, params)
if err != nil {
return nil, huma.Error500InternalServerError(err.Error())
}
- out := &ListSystemBackupsOutput{}
- out.Body.Data, out.Body.Pagination = runs, handlerutil.PaginationResponse(page)
- return out, nil
+ return &handlerutil.Page[backuptypes.SystemBackupRun]{
+ Body: base.Paginated[backuptypes.SystemBackupRun]{
+ Success: true,
+ Data: runs,
+ Pagination: handlerutil.PaginationResponse(page),
+ },
+ }, nil
}
func (h *SystemBackupHandler) GetPolicies(ctx context.Context, _ *struct{}) (*SystemBackupPoliciesOutput, error) {
@@ -281,7 +266,7 @@ func (h *SystemBackupHandler) SetRecoveryKey(ctx context.Context, input *SetSyst
return &SystemBackupRecoveryKeyOutput{Body: *status}, nil
}
-func (h *SystemBackupHandler) Discover(ctx context.Context, input *DiscoverSystemBackupsInput) (*DiscoverSystemBackupsOutput, error) {
+func (h *SystemBackupHandler) Discover(ctx context.Context, input *DiscoverSystemBackupsInput) (*handlerutil.Out[int], error) {
user, err := handlerutil.RequireUser(ctx)
if err != nil {
return nil, err
@@ -299,7 +284,7 @@ func (h *SystemBackupHandler) Discover(ctx context.Context, input *DiscoverSyste
if err != nil {
return nil, huma.Error400BadRequest(err.Error())
}
- return &DiscoverSystemBackupsOutput{Body: base.ApiResponse[int]{Success: true, Data: count}}, nil
+ return &handlerutil.Out[int]{Body: base.ApiResponse[int]{Success: true, Data: count}}, nil
}
func (h *SystemBackupHandler) Create(ctx context.Context, input *CreateSystemBackupInput) (*SystemBackupOutput, error) {
@@ -327,7 +312,7 @@ func (h *SystemBackupHandler) Create(ctx context.Context, input *CreateSystemBac
return &SystemBackupOutput{Body: dto}, nil
}
-func (h *SystemBackupHandler) Restore(ctx context.Context, input *RestoreSystemBackupInput) (*SystemBackupMessageOutput, error) {
+func (h *SystemBackupHandler) Restore(ctx context.Context, input *RestoreSystemBackupInput) (*handlerutil.Out[base.MessageResponse], error) {
user, err := handlerutil.RequireUser(ctx)
if err != nil {
return nil, err
@@ -346,19 +331,19 @@ func (h *SystemBackupHandler) Restore(ctx context.Context, input *RestoreSystemB
}
// BrowseFiles returns one lazy-loaded project tree page.
-func (h *SystemBackupHandler) BrowseFiles(ctx context.Context, input *BrowseSystemBackupFilesInput) (*BrowseSystemBackupFilesOutput, error) {
+func (h *SystemBackupHandler) BrowseFiles(ctx context.Context, input *BrowseSystemBackupFilesInput) (*handlerutil.Page[backuptypes.BackupFileEntry], error) {
params := handlerutil.PaginationParams(input.Start, input.Limit, "", "", input.Search)
items, page, err := h.service.BrowseBackupFiles(ctx, input.ID, input.Body.RecoveryKey, input.Path, params)
if err != nil {
return nil, huma.Error400BadRequest(err.Error())
}
- return &BrowseSystemBackupFilesOutput{Body: base.Paginated[backuptypes.BackupFileEntry]{
+ return &handlerutil.Page[backuptypes.BackupFileEntry]{Body: base.Paginated[backuptypes.BackupFileEntry]{
Success: true, Data: items, Pagination: handlerutil.PaginationResponse(page),
}}, nil
}
// RestoreFiles restores selected project files from a system backup.
-func (h *SystemBackupHandler) RestoreFiles(ctx context.Context, input *RestoreSystemBackupFilesInput) (*SystemBackupMessageOutput, error) {
+func (h *SystemBackupHandler) RestoreFiles(ctx context.Context, input *RestoreSystemBackupFilesInput) (*handlerutil.Out[base.MessageResponse], error) {
user, err := handlerutil.RequireUser(ctx)
if err != nil {
return nil, err
@@ -404,7 +389,7 @@ func (h *SystemBackupHandler) Upload(ctx context.Context, input *UploadSystemBac
return &SystemBackupOutput{Body: dto}, nil
}
-func (h *SystemBackupHandler) Delete(ctx context.Context, input *DeleteSystemBackupInput) (*SystemBackupMessageOutput, error) {
+func (h *SystemBackupHandler) Delete(ctx context.Context, input *DeleteSystemBackupInput) (*handlerutil.Out[base.MessageResponse], error) {
user, err := handlerutil.RequireUser(ctx)
if err != nil {
return nil, err
@@ -422,6 +407,6 @@ func (h *SystemBackupHandler) Delete(ctx context.Context, input *DeleteSystemBac
return messageOutputInternal("Arcane system backup deleted successfully", activityID), nil
}
-func messageOutputInternal(message, activityID string) *SystemBackupMessageOutput {
- return &SystemBackupMessageOutput{Body: base.ApiResponse[base.MessageResponse]{Success: true, Data: base.MessageResponse{Message: message, ActivityID: mo.EmptyableToOption(strings.TrimSpace(activityID)).ToPointer()}}}
+func messageOutputInternal(message, activityID string) *handlerutil.Out[base.MessageResponse] {
+ return &handlerutil.Out[base.MessageResponse]{Body: base.ApiResponse[base.MessageResponse]{Success: true, Data: base.MessageResponse{Message: message, ActivityID: mo.EmptyableToOption(strings.TrimSpace(activityID)).ToPointer()}}}
}
diff --git a/backend/internal/systembackup/service.go b/backend/internal/systembackup/service.go
index fc4643b60..0ca654cd1 100644
--- a/backend/internal/systembackup/service.go
+++ b/backend/internal/systembackup/service.go
@@ -4,7 +4,8 @@ import (
"context"
"crypto/rand"
"encoding/base32"
- "encoding/json"
+ "encoding/json/jsontext"
+ "encoding/json/v2"
"fmt"
"log/slog"
"maps"
@@ -187,7 +188,7 @@ func (s *SystemBackupService) manifestPathInternal() (string, error) {
func (s *SystemBackupService) writeManifestInternal(ctx context.Context, backupID string) error {
manifest := recoverytypes.Manifest{FormatVersion: 1, ArcaneVersion: config.Version, BackupID: backupID, ActivityID: activitylib.IDFromContext(ctx), CreatedAt: time.Now().UTC(), Environment: s.recoveryEnvironmentInternal(ctx)}
- data, err := json.MarshalIndent(manifest, "", " ")
+ data, err := json.Marshal(manifest, jsontext.WithIndent(" "))
if err != nil {
return fmt.Errorf("failed to encode recovery manifest: %w", err)
}
diff --git a/backend/internal/systembackup/system_volume.go b/backend/internal/systembackup/system_volume.go
index 8e616f52f..445ae94fb 100644
--- a/backend/internal/systembackup/system_volume.go
+++ b/backend/internal/systembackup/system_volume.go
@@ -4,7 +4,7 @@ import (
"context"
"crypto/sha256"
"encoding/hex"
- "encoding/json"
+ "encoding/json/v2"
"fmt"
"log/slog"
"slices"
diff --git a/backend/internal/template/handler.go b/backend/internal/template/handler.go
index 7ebd69117..fea964bc9 100644
--- a/backend/internal/template/handler.go
+++ b/backend/internal/template/handler.go
@@ -33,118 +33,58 @@ type ListTemplatesInput struct {
Type string `query:"type" doc:"Filter by template type (comma-separated: false,true)"`
}
-type ListTemplatesOutput struct {
- Body base.Paginated[templatetypes.Template]
-}
-
type GetAllTemplatesInput struct{}
-type GetAllTemplatesOutput struct {
- Body base.ApiResponse[[]templatetypes.Template]
-}
-
type GetTemplateInput struct {
ID string `path:"id" doc:"Template ID"`
}
-type GetTemplateOutput struct {
- Body base.ApiResponse[templatetypes.Template]
-}
-
type GetTemplateContentInput struct {
ID string `path:"id" doc:"Template ID"`
}
-type GetTemplateContentOutput struct {
- Body base.ApiResponse[templatetypes.TemplateContent]
-}
-
type CreateTemplateInput struct {
Body templatetypes.CreateRequest
}
-type CreateTemplateOutput struct {
- Body base.ApiResponse[templatetypes.Template]
-}
-
type UpdateTemplateInput struct {
ID string `path:"id" doc:"Template ID"`
Body templatetypes.UpdateRequest
}
-type UpdateTemplateOutput struct {
- Body base.ApiResponse[templatetypes.Template]
-}
-
type DeleteTemplateInput struct {
ID string `path:"id" doc:"Template ID"`
}
-type DeleteTemplateOutput struct {
- Body base.ApiResponse[base.MessageResponse]
-}
-
type DownloadTemplateInput struct {
ID string `path:"id" doc:"Template ID"`
}
-type DownloadTemplateOutput struct {
- Body base.ApiResponse[templatetypes.Template]
-}
-
type GetDefaultTemplatesInput struct{}
-type GetDefaultTemplatesOutput struct {
- Body base.ApiResponse[templatetypes.DefaultTemplatesResponse]
-}
-
type SaveDefaultTemplatesInput struct {
Body templatetypes.SaveDefaultTemplatesRequest
}
-type SaveDefaultTemplatesOutput struct {
- Body base.ApiResponse[base.MessageResponse]
-}
-
type GetTemplateRegistriesInput struct{}
-type GetTemplateRegistriesOutput struct {
- Body base.ApiResponse[[]templatetypes.TemplateRegistry]
-}
-
type CreateTemplateRegistryInput struct {
Body templatetypes.CreateRegistryRequest
}
-type CreateTemplateRegistryOutput struct {
- Body base.ApiResponse[templatetypes.TemplateRegistry]
-}
-
type UpdateTemplateRegistryInput struct {
ID string `path:"id" doc:"Registry ID"`
Body templatetypes.UpdateRegistryRequest
}
-type UpdateTemplateRegistryOutput struct {
- Body base.ApiResponse[base.MessageResponse]
-}
-
type DeleteTemplateRegistryInput struct {
ID string `path:"id" doc:"Registry ID"`
}
-type DeleteTemplateRegistryOutput struct {
- Body base.ApiResponse[base.MessageResponse]
-}
-
type FetchTemplateRegistryInput struct {
URL string `query:"url" required:"true" doc:"Registry URL"`
}
-type FetchTemplateRegistryOutput struct {
- Body base.ApiResponse[templatetypes.RemoteRegistry]
-}
-
// ============================================================================
// Registration
// ============================================================================
@@ -322,7 +262,7 @@ func RegisterTemplates(api huma.API, templateService *TemplateService) {
// ============================================================================
// ListTemplates returns a paginated list of templates.
-func (h *TemplateHandler) ListTemplates(ctx context.Context, input *ListTemplatesInput) (*ListTemplatesOutput, error) {
+func (h *TemplateHandler) ListTemplates(ctx context.Context, input *ListTemplatesInput) (*handlerutil.Page[templatetypes.Template], error) {
params := handlerutil.PaginationParams(input.Start, input.Limit, input.Sort, input.Order, input.Search)
if params.Limit == 0 {
params.Limit = 20
@@ -336,7 +276,7 @@ func (h *TemplateHandler) ListTemplates(ctx context.Context, input *ListTemplate
return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to get templates").Error())
}
- return &ListTemplatesOutput{
+ return &handlerutil.Page[templatetypes.Template]{
Body: base.Paginated[templatetypes.Template]{
Success: true,
Data: templates,
@@ -346,7 +286,7 @@ func (h *TemplateHandler) ListTemplates(ctx context.Context, input *ListTemplate
}
// GetAllTemplates returns all templates without pagination.
-func (h *TemplateHandler) GetAllTemplates(ctx context.Context, _ *GetAllTemplatesInput) (*GetAllTemplatesOutput, error) {
+func (h *TemplateHandler) GetAllTemplates(ctx context.Context, _ *GetAllTemplatesInput) (*handlerutil.Out[[]templatetypes.Template], error) {
templates, err := h.templateService.GetAllTemplates(ctx)
if err != nil {
return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to get templates").Error())
@@ -357,7 +297,7 @@ func (h *TemplateHandler) GetAllTemplates(ctx context.Context, _ *GetAllTemplate
return nil, huma.Error500InternalServerError(errors.WithMessage(mapErr, "Failed to map templates").Error())
}
- return &GetAllTemplatesOutput{
+ return &handlerutil.Out[[]templatetypes.Template]{
Body: base.ApiResponse[[]templatetypes.Template]{
Success: true,
Data: out,
@@ -366,7 +306,7 @@ func (h *TemplateHandler) GetAllTemplates(ctx context.Context, _ *GetAllTemplate
}
// GetTemplate returns a template by ID.
-func (h *TemplateHandler) GetTemplate(ctx context.Context, input *GetTemplateInput) (*GetTemplateOutput, error) {
+func (h *TemplateHandler) GetTemplate(ctx context.Context, input *GetTemplateInput) (*handlerutil.Out[templatetypes.Template], error) {
if input.ID == "" {
return nil, huma.Error400BadRequest("Template ID is required")
}
@@ -384,7 +324,7 @@ func (h *TemplateHandler) GetTemplate(ctx context.Context, input *GetTemplateInp
return nil, huma.Error500InternalServerError(errors.WithMessage(mapErr, "Failed to map templates").Error())
}
- return &GetTemplateOutput{
+ return &handlerutil.Out[templatetypes.Template]{
Body: base.ApiResponse[templatetypes.Template]{
Success: true,
Data: out,
@@ -393,7 +333,7 @@ func (h *TemplateHandler) GetTemplate(ctx context.Context, input *GetTemplateInp
}
// GetTemplateContent returns template content with parsed data.
-func (h *TemplateHandler) GetTemplateContent(ctx context.Context, input *GetTemplateContentInput) (*GetTemplateContentOutput, error) {
+func (h *TemplateHandler) GetTemplateContent(ctx context.Context, input *GetTemplateContentInput) (*handlerutil.Out[templatetypes.TemplateContent], error) {
if input.ID == "" {
return nil, huma.Error400BadRequest("Template ID is required")
}
@@ -406,7 +346,7 @@ func (h *TemplateHandler) GetTemplateContent(ctx context.Context, input *GetTemp
return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to get template content").Error())
}
- return &GetTemplateContentOutput{
+ return &handlerutil.Out[templatetypes.TemplateContent]{
Body: base.ApiResponse[templatetypes.TemplateContent]{
Success: true,
Data: *contentData,
@@ -415,7 +355,7 @@ func (h *TemplateHandler) GetTemplateContent(ctx context.Context, input *GetTemp
}
// CreateTemplate creates a new templatetypes.
-func (h *TemplateHandler) CreateTemplate(ctx context.Context, input *CreateTemplateInput) (*CreateTemplateOutput, error) {
+func (h *TemplateHandler) CreateTemplate(ctx context.Context, input *CreateTemplateInput) (*handlerutil.Out[templatetypes.Template], error) {
tmpl := &ComposeTemplate{
Name: input.Body.Name,
Description: input.Body.Description,
@@ -436,7 +376,7 @@ func (h *TemplateHandler) CreateTemplate(ctx context.Context, input *CreateTempl
return nil, huma.Error500InternalServerError(errors.WithMessage(mapErr, "Failed to map templates").Error())
}
- return &CreateTemplateOutput{
+ return &handlerutil.Out[templatetypes.Template]{
Body: base.ApiResponse[templatetypes.Template]{
Success: true,
Data: out,
@@ -445,7 +385,7 @@ func (h *TemplateHandler) CreateTemplate(ctx context.Context, input *CreateTempl
}
// UpdateTemplate updates a templatetypes.
-func (h *TemplateHandler) UpdateTemplate(ctx context.Context, input *UpdateTemplateInput) (*UpdateTemplateOutput, error) {
+func (h *TemplateHandler) UpdateTemplate(ctx context.Context, input *UpdateTemplateInput) (*handlerutil.Out[templatetypes.Template], error) {
if input.ID == "" {
return nil, huma.Error400BadRequest("Template ID is required")
}
@@ -478,7 +418,7 @@ func (h *TemplateHandler) UpdateTemplate(ctx context.Context, input *UpdateTempl
return nil, huma.Error500InternalServerError(errors.WithMessage(mapErr, "Failed to map templates").Error())
}
- return &UpdateTemplateOutput{
+ return &handlerutil.Out[templatetypes.Template]{
Body: base.ApiResponse[templatetypes.Template]{
Success: true,
Data: out,
@@ -487,7 +427,7 @@ func (h *TemplateHandler) UpdateTemplate(ctx context.Context, input *UpdateTempl
}
// DeleteTemplate deletes a templatetypes.
-func (h *TemplateHandler) DeleteTemplate(ctx context.Context, input *DeleteTemplateInput) (*DeleteTemplateOutput, error) {
+func (h *TemplateHandler) DeleteTemplate(ctx context.Context, input *DeleteTemplateInput) (*handlerutil.Out[base.MessageResponse], error) {
if input.ID == "" {
return nil, huma.Error400BadRequest("Template ID is required")
}
@@ -499,7 +439,7 @@ func (h *TemplateHandler) DeleteTemplate(ctx context.Context, input *DeleteTempl
return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to delete template").Error())
}
- return &DeleteTemplateOutput{
+ return &handlerutil.Out[base.MessageResponse]{
Body: base.ApiResponse[base.MessageResponse]{
Success: true,
Data: base.MessageResponse{
@@ -510,7 +450,7 @@ func (h *TemplateHandler) DeleteTemplate(ctx context.Context, input *DeleteTempl
}
// DownloadTemplate downloads a remote template to local storage.
-func (h *TemplateHandler) DownloadTemplate(ctx context.Context, input *DownloadTemplateInput) (*DownloadTemplateOutput, error) {
+func (h *TemplateHandler) DownloadTemplate(ctx context.Context, input *DownloadTemplateInput) (*handlerutil.Out[templatetypes.Template], error) {
if input.ID == "" {
return nil, huma.Error400BadRequest("Template ID is required")
}
@@ -536,7 +476,7 @@ func (h *TemplateHandler) DownloadTemplate(ctx context.Context, input *DownloadT
return nil, huma.Error500InternalServerError(errors.WithMessage(mapErr, "Failed to map templates").Error())
}
- return &DownloadTemplateOutput{
+ return &handlerutil.Out[templatetypes.Template]{
Body: base.ApiResponse[templatetypes.Template]{
Success: true,
Data: out,
@@ -545,13 +485,13 @@ func (h *TemplateHandler) DownloadTemplate(ctx context.Context, input *DownloadT
}
// GetDefaultTemplates returns the default compose and env templates.
-func (h *TemplateHandler) GetDefaultTemplates(ctx context.Context, _ *GetDefaultTemplatesInput) (*GetDefaultTemplatesOutput, error) {
+func (h *TemplateHandler) GetDefaultTemplates(ctx context.Context, _ *GetDefaultTemplatesInput) (*handlerutil.Out[templatetypes.DefaultTemplatesResponse], error) {
composeTemplate := h.templateService.GetComposeTemplate(ctx)
swarmStackTemplate := h.templateService.GetSwarmStackTemplate(ctx)
swarmStackEnvTemplate := h.templateService.GetSwarmStackEnvTemplate(ctx)
envTemplate := h.templateService.GetEnvTemplate(ctx)
- return &GetDefaultTemplatesOutput{
+ return &handlerutil.Out[templatetypes.DefaultTemplatesResponse]{
Body: base.ApiResponse[templatetypes.DefaultTemplatesResponse]{
Success: true,
Data: templatetypes.DefaultTemplatesResponse{
@@ -565,7 +505,7 @@ func (h *TemplateHandler) GetDefaultTemplates(ctx context.Context, _ *GetDefault
}
// SaveDefaultTemplates saves the default compose and env templates.
-func (h *TemplateHandler) SaveDefaultTemplates(ctx context.Context, input *SaveDefaultTemplatesInput) (*SaveDefaultTemplatesOutput, error) {
+func (h *TemplateHandler) SaveDefaultTemplates(ctx context.Context, input *SaveDefaultTemplatesInput) (*handlerutil.Out[base.MessageResponse], error) {
if err := h.templateService.SaveComposeTemplate(ctx, input.Body.ComposeContent); err != nil {
return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to save default template").Error())
}
@@ -574,7 +514,7 @@ func (h *TemplateHandler) SaveDefaultTemplates(ctx context.Context, input *SaveD
return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to save default template").Error())
}
- return &SaveDefaultTemplatesOutput{
+ return &handlerutil.Out[base.MessageResponse]{
Body: base.ApiResponse[base.MessageResponse]{
Success: true,
Data: base.MessageResponse{
@@ -585,7 +525,7 @@ func (h *TemplateHandler) SaveDefaultTemplates(ctx context.Context, input *SaveD
}
// GetRegistries returns all template registries.
-func (h *TemplateHandler) GetRegistries(ctx context.Context, _ *GetTemplateRegistriesInput) (*GetTemplateRegistriesOutput, error) {
+func (h *TemplateHandler) GetRegistries(ctx context.Context, _ *GetTemplateRegistriesInput) (*handlerutil.Out[[]templatetypes.TemplateRegistry], error) {
registries, err := h.templateService.GetRegistries(ctx)
if err != nil {
return nil, huma.Error500InternalServerError("Failed to fetch registry")
@@ -606,7 +546,7 @@ func (h *TemplateHandler) GetRegistries(ctx context.Context, _ *GetTemplateRegis
}
}
- return &GetTemplateRegistriesOutput{
+ return &handlerutil.Out[[]templatetypes.TemplateRegistry]{
Body: base.ApiResponse[[]templatetypes.TemplateRegistry]{
Success: true,
Data: out,
@@ -615,7 +555,7 @@ func (h *TemplateHandler) GetRegistries(ctx context.Context, _ *GetTemplateRegis
}
// CreateRegistry creates a new template registry.
-func (h *TemplateHandler) CreateRegistry(ctx context.Context, input *CreateTemplateRegistryInput) (*CreateTemplateRegistryOutput, error) {
+func (h *TemplateHandler) CreateRegistry(ctx context.Context, input *CreateTemplateRegistryInput) (*handlerutil.Out[templatetypes.TemplateRegistry], error) {
registry := &TemplateRegistry{
Name: input.Body.Name,
URL: input.Body.URL,
@@ -631,7 +571,7 @@ func (h *TemplateHandler) CreateRegistry(ctx context.Context, input *CreateTempl
return nil, huma.Error500InternalServerError(errors.WithMessage(mapErr, "Failed to map registry").Error())
}
- return &CreateTemplateRegistryOutput{
+ return &handlerutil.Out[templatetypes.TemplateRegistry]{
Body: base.ApiResponse[templatetypes.TemplateRegistry]{
Success: true,
Data: out,
@@ -640,7 +580,7 @@ func (h *TemplateHandler) CreateRegistry(ctx context.Context, input *CreateTempl
}
// UpdateRegistry updates a template registry.
-func (h *TemplateHandler) UpdateRegistry(ctx context.Context, input *UpdateTemplateRegistryInput) (*UpdateTemplateRegistryOutput, error) {
+func (h *TemplateHandler) UpdateRegistry(ctx context.Context, input *UpdateTemplateRegistryInput) (*handlerutil.Out[base.MessageResponse], error) {
if input.ID == "" {
return nil, huma.Error400BadRequest("Registry ID is required")
}
@@ -658,7 +598,7 @@ func (h *TemplateHandler) UpdateRegistry(ctx context.Context, input *UpdateTempl
return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to update registry").Error())
}
- return &UpdateTemplateRegistryOutput{
+ return &handlerutil.Out[base.MessageResponse]{
Body: base.ApiResponse[base.MessageResponse]{
Success: true,
Data: base.MessageResponse{
@@ -669,7 +609,7 @@ func (h *TemplateHandler) UpdateRegistry(ctx context.Context, input *UpdateTempl
}
// DeleteRegistry deletes a template registry.
-func (h *TemplateHandler) DeleteRegistry(ctx context.Context, input *DeleteTemplateRegistryInput) (*DeleteTemplateRegistryOutput, error) {
+func (h *TemplateHandler) DeleteRegistry(ctx context.Context, input *DeleteTemplateRegistryInput) (*handlerutil.Out[base.MessageResponse], error) {
if input.ID == "" {
return nil, huma.Error400BadRequest("Registry ID is required")
}
@@ -681,7 +621,7 @@ func (h *TemplateHandler) DeleteRegistry(ctx context.Context, input *DeleteTempl
return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to delete registry").Error())
}
- return &DeleteTemplateRegistryOutput{
+ return &handlerutil.Out[base.MessageResponse]{
Body: base.ApiResponse[base.MessageResponse]{
Success: true,
Data: base.MessageResponse{
@@ -692,7 +632,7 @@ func (h *TemplateHandler) DeleteRegistry(ctx context.Context, input *DeleteTempl
}
// FetchRegistry fetches templates from a remote registry URL.
-func (h *TemplateHandler) FetchRegistry(ctx context.Context, input *FetchTemplateRegistryInput) (*FetchTemplateRegistryOutput, error) {
+func (h *TemplateHandler) FetchRegistry(ctx context.Context, input *FetchTemplateRegistryInput) (*handlerutil.Out[templatetypes.RemoteRegistry], error) {
if input.URL == "" {
return nil, huma.Error400BadRequest("Query parameter is required")
}
@@ -707,7 +647,7 @@ func (h *TemplateHandler) FetchRegistry(ctx context.Context, input *FetchTemplat
return nil, huma.Error502BadGateway("Invalid JSON response")
}
- return &FetchTemplateRegistryOutput{
+ return &handlerutil.Out[templatetypes.RemoteRegistry]{
Body: base.ApiResponse[templatetypes.RemoteRegistry]{
Success: true,
Data: registry,
diff --git a/backend/internal/template/service.go b/backend/internal/template/service.go
index 7242eca8b..03a2eb089 100644
--- a/backend/internal/template/service.go
+++ b/backend/internal/template/service.go
@@ -232,7 +232,7 @@ func (s *TemplateService) GetAllTemplatesPaginated(ctx context.Context, params p
},
}
- result := pagination.SearchOrderAndPaginate(items, params, config)
+ result := config.SearchOrderAndPaginate(items, params)
paginationResp := pagination.BuildResponse(result.TotalCount, result.TotalAvailable, params)
return result.Items, paginationResp, nil
diff --git a/backend/internal/updater/handler.go b/backend/internal/updater/handler.go
index cf20aec77..6aa9575ad 100644
--- a/backend/internal/updater/handler.go
+++ b/backend/internal/updater/handler.go
@@ -28,36 +28,20 @@ type RunUpdaterInput struct {
Body *updater.Options `doc:"Updater run options"`
}
-type RunUpdaterOutput struct {
- Body base.ApiResponse[*updater.Result]
-}
-
type UpdateContainerInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
ContainerID string `path:"containerId" doc:"Container ID to update"`
}
-type UpdateContainerOutput struct {
- Body base.ApiResponse[*updater.Result]
-}
-
type GetUpdaterStatusInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
}
-type GetUpdaterStatusOutput struct {
- Body base.ApiResponse[updater.Status]
-}
-
type GetUpdaterHistoryInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
Limit int `query:"limit" default:"50" doc:"Number of history entries to return"`
}
-type GetUpdaterHistoryOutput struct {
- Body base.ApiResponse[[]AutoUpdateRecord]
-}
-
// RegisterUpdater registers updater management routes using Huma.
func RegisterUpdater(api huma.API, updaterService *UpdaterService, appCtx handlerutil.ActivityAppContext) {
h := &UpdaterHandler{
@@ -107,7 +91,7 @@ func RegisterUpdater(api huma.API, updaterService *UpdaterService, appCtx handle
}
// RunUpdater applies pending container updates.
-func (h *UpdaterHandler) RunUpdater(ctx context.Context, input *RunUpdaterInput) (*RunUpdaterOutput, error) {
+func (h *UpdaterHandler) RunUpdater(ctx context.Context, input *RunUpdaterInput) (*handlerutil.Out[*updater.Result], error) {
options := updater.Options{}
if input.Body != nil {
options = *input.Body
@@ -122,7 +106,7 @@ func (h *UpdaterHandler) RunUpdater(ctx context.Context, input *RunUpdaterInput)
return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to run updater").Error())
}
- return &RunUpdaterOutput{
+ return &handlerutil.Out[*updater.Result]{
Body: base.ApiResponse[*updater.Result]{
Success: true,
Data: out,
@@ -131,10 +115,10 @@ func (h *UpdaterHandler) RunUpdater(ctx context.Context, input *RunUpdaterInput)
}
// GetUpdaterStatus returns the current status of the updater.
-func (h *UpdaterHandler) GetUpdaterStatus(ctx context.Context, input *GetUpdaterStatusInput) (*GetUpdaterStatusOutput, error) {
+func (h *UpdaterHandler) GetUpdaterStatus(ctx context.Context, input *GetUpdaterStatusInput) (*handlerutil.Out[updater.Status], error) {
status := h.updaterService.GetStatus()
- return &GetUpdaterStatusOutput{
+ return &handlerutil.Out[updater.Status]{
Body: base.ApiResponse[updater.Status]{
Success: true,
Data: status,
@@ -143,7 +127,7 @@ func (h *UpdaterHandler) GetUpdaterStatus(ctx context.Context, input *GetUpdater
}
// GetUpdaterHistory returns the history of update operations.
-func (h *UpdaterHandler) GetUpdaterHistory(ctx context.Context, input *GetUpdaterHistoryInput) (*GetUpdaterHistoryOutput, error) {
+func (h *UpdaterHandler) GetUpdaterHistory(ctx context.Context, input *GetUpdaterHistoryInput) (*handlerutil.Out[[]AutoUpdateRecord], error) {
limit := input.Limit
if limit <= 0 {
limit = 50
@@ -154,7 +138,7 @@ func (h *UpdaterHandler) GetUpdaterHistory(ctx context.Context, input *GetUpdate
return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to get updater history").Error())
}
- return &GetUpdaterHistoryOutput{
+ return &handlerutil.Out[[]AutoUpdateRecord]{
Body: base.ApiResponse[[]AutoUpdateRecord]{
Success: true,
Data: history,
@@ -163,14 +147,14 @@ func (h *UpdaterHandler) GetUpdaterHistory(ctx context.Context, input *GetUpdate
}
// UpdateContainer updates a single container by pulling the latest image and applying the appropriate update flow.
-func (h *UpdaterHandler) UpdateContainer(ctx context.Context, input *UpdateContainerInput) (*UpdateContainerOutput, error) {
+func (h *UpdaterHandler) UpdateContainer(ctx context.Context, input *UpdateContainerInput) (*handlerutil.Out[*updater.Result], error) {
runtimeCtx := utils.ActivityRuntimeContext(ctx, h.appCtx)
out, err := h.updaterService.UpdateSingleContainer(runtimeCtx, input.ContainerID)
if err != nil {
return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to run updater").Error())
}
- return &UpdateContainerOutput{
+ return &handlerutil.Out[*updater.Result]{
Body: base.ApiResponse[*updater.Result]{
Success: true,
Data: out,
diff --git a/backend/internal/upload/handler.go b/backend/internal/upload/handler.go
index 5801f09d3..029d45732 100644
--- a/backend/internal/upload/handler.go
+++ b/backend/internal/upload/handler.go
@@ -54,14 +54,6 @@ type DeleteUploadSessionInput struct {
UploadID string `path:"uploadId"`
}
-type UploadSessionOutput struct {
- Body base.ApiResponse[uploadtypes.Session]
-}
-
-type DeleteUploadSessionOutput struct {
- Body base.ApiResponse[base.MessageResponse]
-}
-
// SessionHTTPError maps upload-session errors to HTTP errors for this package
// and the domain endpoints that consume sessions. It returns nil for errors
// that are not upload-session errors.
@@ -95,8 +87,8 @@ func requireUploadPermissionInternal(ctx context.Context, kind, environmentID st
return nil
}
-func sessionResponseInternal(session *uploadtypes.Session) *UploadSessionOutput {
- return &UploadSessionOutput{
+func sessionResponseInternal(session *uploadtypes.Session) *handlerutil.Out[uploadtypes.Session] {
+ return &handlerutil.Out[uploadtypes.Session]{
Body: base.ApiResponse[uploadtypes.Session]{
Success: true,
Data: *session,
@@ -104,7 +96,7 @@ func sessionResponseInternal(session *uploadtypes.Session) *UploadSessionOutput
}
}
-func (h *UploadHandler) CreateSession(ctx context.Context, input *CreateUploadSessionInput) (*UploadSessionOutput, error) {
+func (h *UploadHandler) CreateSession(ctx context.Context, input *CreateUploadSessionInput) (*handlerutil.Out[uploadtypes.Session], error) {
if err := requireUploadPermissionInternal(ctx, input.Kind, input.EnvironmentID); err != nil {
return nil, err
}
@@ -118,7 +110,7 @@ func (h *UploadHandler) CreateSession(ctx context.Context, input *CreateUploadSe
return sessionResponseInternal(session), nil
}
-func (h *UploadHandler) UploadChunk(ctx context.Context, input *UploadChunkInput) (*UploadSessionOutput, error) {
+func (h *UploadHandler) UploadChunk(ctx context.Context, input *UploadChunkInput) (*handlerutil.Out[uploadtypes.Session], error) {
if err := requireUploadPermissionInternal(ctx, input.Kind, input.EnvironmentID); err != nil {
return nil, err
}
@@ -132,7 +124,7 @@ func (h *UploadHandler) UploadChunk(ctx context.Context, input *UploadChunkInput
return sessionResponseInternal(session), nil
}
-func (h *UploadHandler) GetSession(ctx context.Context, input *GetUploadSessionInput) (*UploadSessionOutput, error) {
+func (h *UploadHandler) GetSession(ctx context.Context, input *GetUploadSessionInput) (*handlerutil.Out[uploadtypes.Session], error) {
if err := requireUploadPermissionInternal(ctx, input.Kind, input.EnvironmentID); err != nil {
return nil, err
}
@@ -146,7 +138,7 @@ func (h *UploadHandler) GetSession(ctx context.Context, input *GetUploadSessionI
return sessionResponseInternal(session), nil
}
-func (h *UploadHandler) DeleteSession(ctx context.Context, input *DeleteUploadSessionInput) (*DeleteUploadSessionOutput, error) {
+func (h *UploadHandler) DeleteSession(ctx context.Context, input *DeleteUploadSessionInput) (*handlerutil.Out[base.MessageResponse], error) {
if err := requireUploadPermissionInternal(ctx, input.Kind, input.EnvironmentID); err != nil {
return nil, err
}
@@ -156,7 +148,7 @@ func (h *UploadHandler) DeleteSession(ctx context.Context, input *DeleteUploadSe
}
return nil, huma.Error500InternalServerError(err.Error())
}
- return &DeleteUploadSessionOutput{
+ return &handlerutil.Out[base.MessageResponse]{
Body: base.ApiResponse[base.MessageResponse]{
Success: true,
Data: base.MessageResponse{Message: "Upload session deleted"},
diff --git a/backend/internal/user/handler.go b/backend/internal/user/handler.go
index 311054c67..c9fa0b2fd 100644
--- a/backend/internal/user/handler.go
+++ b/backend/internal/user/handler.go
@@ -37,43 +37,23 @@ type ListUsersInput struct {
Limit int `query:"limit" default:"20" doc:"Items per page"`
}
-type ListUsersOutput struct {
- Body base.Paginated[usertypes.User]
-}
-
type CreateUserInput struct {
Body usertypes.CreateUser
}
-type CreateUserOutput struct {
- Body base.ApiResponse[usertypes.User]
-}
-
type GetUserInput struct {
UserID string `path:"userId" doc:"User ID"`
}
-type GetUserOutput struct {
- Body base.ApiResponse[usertypes.User]
-}
-
type UpdateUserInput struct {
UserID string `path:"userId" doc:"User ID"`
Body usertypes.UpdateUser
}
-type UpdateUserOutput struct {
- Body base.ApiResponse[usertypes.User]
-}
-
type DeleteUserInput struct {
UserID string `path:"userId" doc:"User ID"`
}
-type DeleteUserOutput struct {
- Body base.ApiResponse[base.MessageResponse]
-}
-
type GetUserAvatarInput struct {
UserID string `path:"userId" doc:"User ID"`
}
@@ -166,7 +146,7 @@ func RegisterUsers(api huma.API, userService *UserService, invalidateUserTokenCa
// ============================================================================
// ListUsers returns a paginated list of users.
-func (h *UserHandler) ListUsers(ctx context.Context, input *ListUsersInput) (*ListUsersOutput, error) {
+func (h *UserHandler) ListUsers(ctx context.Context, input *ListUsersInput) (*handlerutil.Page[usertypes.User], error) {
params := handlerutil.PaginationParams(input.Start, input.Limit, input.Sort, input.Order, input.Search)
users, paginationResp, err := h.userService.ListUsersPaginated(ctx, params)
@@ -174,7 +154,7 @@ func (h *UserHandler) ListUsers(ctx context.Context, input *ListUsersInput) (*Li
return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to list users").Error())
}
- return &ListUsersOutput{
+ return &handlerutil.Page[usertypes.User]{
Body: base.Paginated[usertypes.User]{
Success: true,
Data: users,
@@ -184,7 +164,7 @@ func (h *UserHandler) ListUsers(ctx context.Context, input *ListUsersInput) (*Li
}
// CreateUser creates a new usertypes.
-func (h *UserHandler) CreateUser(ctx context.Context, input *CreateUserInput) (*CreateUserOutput, error) {
+func (h *UserHandler) CreateUser(ctx context.Context, input *CreateUserInput) (*handlerutil.Out[usertypes.User], error) {
normalizedEmail, err := NormalizeOptionalEmail(input.Body.Email)
if err != nil {
return nil, huma.Error400BadRequest(err.Error())
@@ -223,7 +203,7 @@ func (h *UserHandler) CreateUser(ctx context.Context, input *CreateUserInput) (*
return nil, huma.Error500InternalServerError("Failed to map user")
}
- return &CreateUserOutput{
+ return &handlerutil.Out[usertypes.User]{
Body: base.ApiResponse[usertypes.User]{
Success: true,
Data: out,
@@ -232,7 +212,7 @@ func (h *UserHandler) CreateUser(ctx context.Context, input *CreateUserInput) (*
}
// GetUser returns a user by ID.
-func (h *UserHandler) GetUser(ctx context.Context, input *GetUserInput) (*GetUserOutput, error) {
+func (h *UserHandler) GetUser(ctx context.Context, input *GetUserInput) (*handlerutil.Out[usertypes.User], error) {
userModel, err := h.userService.GetUserByID(ctx, input.UserID)
if err != nil {
return nil, huma.Error404NotFound("User not found")
@@ -243,7 +223,7 @@ func (h *UserHandler) GetUser(ctx context.Context, input *GetUserInput) (*GetUse
return nil, huma.Error500InternalServerError("Failed to map user")
}
- return &GetUserOutput{
+ return &handlerutil.Out[usertypes.User]{
Body: base.ApiResponse[usertypes.User]{
Success: true,
Data: out,
@@ -252,7 +232,7 @@ func (h *UserHandler) GetUser(ctx context.Context, input *GetUserInput) (*GetUse
}
// UpdateUser updates a usertypes.
-func (h *UserHandler) UpdateUser(ctx context.Context, input *UpdateUserInput) (*UpdateUserOutput, error) {
+func (h *UserHandler) UpdateUser(ctx context.Context, input *UpdateUserInput) (*handlerutil.Out[usertypes.User], error) {
userModel, err := h.userService.GetUserByID(ctx, input.UserID)
if err != nil {
return nil, huma.Error404NotFound("User not found")
@@ -321,7 +301,7 @@ func (h *UserHandler) UpdateUser(ctx context.Context, input *UpdateUserInput) (*
return nil, huma.Error500InternalServerError("Failed to map user")
}
- return &UpdateUserOutput{
+ return &handlerutil.Out[usertypes.User]{
Body: base.ApiResponse[usertypes.User]{
Success: true,
Data: out,
@@ -330,7 +310,7 @@ func (h *UserHandler) UpdateUser(ctx context.Context, input *UpdateUserInput) (*
}
// DeleteUser deletes a usertypes.
-func (h *UserHandler) DeleteUser(ctx context.Context, input *DeleteUserInput) (*DeleteUserOutput, error) {
+func (h *UserHandler) DeleteUser(ctx context.Context, input *DeleteUserInput) (*handlerutil.Out[base.MessageResponse], error) {
// Privilege ordering: a non-admin caller may not delete a global admin
// target. The service enforces the same check; this pre-check produces a
// clean 403 without entering the delete path.
@@ -363,7 +343,7 @@ func (h *UserHandler) DeleteUser(ctx context.Context, input *DeleteUserInput) (*
h.invalidateUserTokenCache(input.UserID)
}
- return &DeleteUserOutput{
+ return &handlerutil.Out[base.MessageResponse]{
Body: base.ApiResponse[base.MessageResponse]{
Success: true,
Data: base.MessageResponse{
diff --git a/backend/internal/variable/handler.go b/backend/internal/variable/handler.go
index 73611bc5a..c8543a464 100644
--- a/backend/internal/variable/handler.go
+++ b/backend/internal/variable/handler.go
@@ -18,8 +18,8 @@ import (
// VariableHandler handles manager-level global variables and the separate
// agent-only materialization channel used to push effective values.
type VariableHandler struct {
- variableService *VariableService
- environmentService *environment.EnvironmentService
+ variableService *VariableService
+ proxyRemoteJSON handlerutil.RemoteJSONProxy
}
// ============================================================================
@@ -28,70 +28,38 @@ type VariableHandler struct {
type ListGlobalVariablesInput struct{}
-type ListGlobalVariablesOutput struct {
- Body base.ApiResponse[[]env.GlobalVariable]
-}
-
type CreateGlobalVariableInput struct {
Body env.CreateGlobalVariableRequest
}
-type CreateGlobalVariableOutput struct {
- Body base.ApiResponse[env.GlobalVariableMutationResponse]
-}
-
type UpdateGlobalVariableInput struct {
ID string `path:"id" doc:"Variable ID"`
Body env.UpdateGlobalVariableRequest
}
-type UpdateGlobalVariableOutput struct {
- Body base.ApiResponse[env.GlobalVariableMutationResponse]
-}
-
type DeleteGlobalVariableInput struct {
ID string `path:"id" doc:"Variable ID"`
}
-type DeleteGlobalVariableOutput struct {
- Body base.ApiResponse[env.GlobalVariableMutationResponse]
-}
-
type SyncGlobalVariablesInput struct{}
-type SyncGlobalVariablesOutput struct {
- Body base.ApiResponse[[]env.EnvironmentSyncStatus]
-}
-
type GetGlobalVariableSyncStatusInput struct{}
-type GetGlobalVariableSyncStatusOutput struct {
- Body base.ApiResponse[[]env.EnvironmentSyncStatus]
-}
-
type GetGlobalVariablesInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
}
-type GetGlobalVariablesOutput struct {
- Body base.ApiResponse[[]env.Variable]
-}
-
type UpdateGlobalVariablesInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
Body env.Summary
}
-type UpdateGlobalVariablesOutput struct {
- Body base.ApiResponse[base.MessageResponse]
-}
-
// ============================================================================
// Route Registration
// ============================================================================
func RegisterVariables(api huma.API, variableService *VariableService, environmentService *environment.EnvironmentService) {
- h := &VariableHandler{variableService: variableService, environmentService: environmentService}
+ h := &VariableHandler{variableService: variableService, proxyRemoteJSON: environmentService.ProxyJSONRequest}
middleware.RegisterWithPermission(api, huma.Operation{
OperationID: "listVariables",
@@ -158,7 +126,7 @@ func RegisterVariables(api huma.API, variableService *VariableService, environme
// channel on agents. It must never be registered on a manager API because its
// response intentionally contains decrypted values for .env.global.
func RegisterMaterializedVariables(api huma.API, variableService *VariableService, environmentService *environment.EnvironmentService) {
- h := &VariableHandler{variableService: variableService, environmentService: environmentService}
+ h := &VariableHandler{variableService: variableService, proxyRemoteJSON: environmentService.ProxyJSONRequest}
huma.Register(api, huma.Operation{
OperationID: "getGlobalVariables",
@@ -187,13 +155,13 @@ func RegisterMaterializedVariables(api huma.API, variableService *VariableServic
// Handler Methods
// ============================================================================
-func (h *VariableHandler) ListVariables(ctx context.Context, _ *ListGlobalVariablesInput) (*ListGlobalVariablesOutput, error) {
+func (h *VariableHandler) ListVariables(ctx context.Context, _ *ListGlobalVariablesInput) (*handlerutil.Out[[]env.GlobalVariable], error) {
variables, err := h.variableService.ListVariables(ctx)
if err != nil {
return nil, huma.Error500InternalServerError(err.Error())
}
- return &ListGlobalVariablesOutput{
+ return &handlerutil.Out[[]env.GlobalVariable]{
Body: base.ApiResponse[[]env.GlobalVariable]{
Success: true,
Data: variables,
@@ -201,13 +169,13 @@ func (h *VariableHandler) ListVariables(ctx context.Context, _ *ListGlobalVariab
}, nil
}
-func (h *VariableHandler) CreateVariable(ctx context.Context, input *CreateGlobalVariableInput) (*CreateGlobalVariableOutput, error) {
+func (h *VariableHandler) CreateVariable(ctx context.Context, input *CreateGlobalVariableInput) (*handlerutil.Out[env.GlobalVariableMutationResponse], error) {
variable, err := h.variableService.CreateVariable(ctx, input.Body)
if err != nil {
return nil, variableMutationHTTPErrorInternal(err)
}
- return &CreateGlobalVariableOutput{
+ return &handlerutil.Out[env.GlobalVariableMutationResponse]{
Body: base.ApiResponse[env.GlobalVariableMutationResponse]{
Success: true,
Data: env.GlobalVariableMutationResponse{
@@ -218,13 +186,13 @@ func (h *VariableHandler) CreateVariable(ctx context.Context, input *CreateGloba
}, nil
}
-func (h *VariableHandler) UpdateVariable(ctx context.Context, input *UpdateGlobalVariableInput) (*UpdateGlobalVariableOutput, error) {
+func (h *VariableHandler) UpdateVariable(ctx context.Context, input *UpdateGlobalVariableInput) (*handlerutil.Out[env.GlobalVariableMutationResponse], error) {
variable, err := h.variableService.UpdateVariable(ctx, input.ID, input.Body)
if err != nil {
return nil, variableMutationHTTPErrorInternal(err)
}
- return &UpdateGlobalVariableOutput{
+ return &handlerutil.Out[env.GlobalVariableMutationResponse]{
Body: base.ApiResponse[env.GlobalVariableMutationResponse]{
Success: true,
Data: env.GlobalVariableMutationResponse{
@@ -235,12 +203,12 @@ func (h *VariableHandler) UpdateVariable(ctx context.Context, input *UpdateGloba
}, nil
}
-func (h *VariableHandler) DeleteVariable(ctx context.Context, input *DeleteGlobalVariableInput) (*DeleteGlobalVariableOutput, error) {
+func (h *VariableHandler) DeleteVariable(ctx context.Context, input *DeleteGlobalVariableInput) (*handlerutil.Out[env.GlobalVariableMutationResponse], error) {
if err := h.variableService.DeleteVariable(ctx, input.ID); err != nil {
return nil, variableMutationHTTPErrorInternal(err)
}
- return &DeleteGlobalVariableOutput{
+ return &handlerutil.Out[env.GlobalVariableMutationResponse]{
Body: base.ApiResponse[env.GlobalVariableMutationResponse]{
Success: true,
Data: env.GlobalVariableMutationResponse{
@@ -250,8 +218,8 @@ func (h *VariableHandler) DeleteVariable(ctx context.Context, input *DeleteGloba
}, nil
}
-func (h *VariableHandler) SyncVariables(ctx context.Context, _ *SyncGlobalVariablesInput) (*SyncGlobalVariablesOutput, error) {
- return &SyncGlobalVariablesOutput{
+func (h *VariableHandler) SyncVariables(ctx context.Context, _ *SyncGlobalVariablesInput) (*handlerutil.Out[[]env.EnvironmentSyncStatus], error) {
+ return &handlerutil.Out[[]env.EnvironmentSyncStatus]{
Body: base.ApiResponse[[]env.EnvironmentSyncStatus]{
Success: true,
Data: h.variableService.SyncAll(ctx),
@@ -259,8 +227,8 @@ func (h *VariableHandler) SyncVariables(ctx context.Context, _ *SyncGlobalVariab
}, nil
}
-func (h *VariableHandler) GetSyncStatus(_ context.Context, _ *GetGlobalVariableSyncStatusInput) (*GetGlobalVariableSyncStatusOutput, error) {
- return &GetGlobalVariableSyncStatusOutput{
+func (h *VariableHandler) GetSyncStatus(_ context.Context, _ *GetGlobalVariableSyncStatusInput) (*handlerutil.Out[[]env.EnvironmentSyncStatus], error) {
+ return &handlerutil.Out[[]env.EnvironmentSyncStatus]{
Body: base.ApiResponse[[]env.EnvironmentSyncStatus]{
Success: true,
Data: h.variableService.SyncStatuses(),
@@ -270,13 +238,13 @@ func (h *VariableHandler) GetSyncStatus(_ context.Context, _ *GetGlobalVariableS
// GetMaterializedVariables returns the environment's materialized .env.global
// content (local file for environment "0", proxied to the agent otherwise).
-func (h *VariableHandler) GetMaterializedVariables(ctx context.Context, input *GetGlobalVariablesInput) (*GetGlobalVariablesOutput, error) {
+func (h *VariableHandler) GetMaterializedVariables(ctx context.Context, input *GetGlobalVariablesInput) (*handlerutil.Out[[]env.Variable], error) {
if input.EnvironmentID != "0" {
- response, err := handlerutil.ProxyRemoteJSON[base.ApiResponse[[]env.Variable]](ctx, h.environmentService.ProxyJSONRequest, input.EnvironmentID, http.MethodGet, "/api/environments/0/templates/variables", nil)
+ response, err := h.proxyRemoteJSON.JSON[base.ApiResponse[[]env.Variable]](ctx, input.EnvironmentID, http.MethodGet, "/api/environments/0/templates/variables", nil)
if err != nil {
return nil, err
}
- return &GetGlobalVariablesOutput{Body: *response}, nil
+ return &handlerutil.Out[[]env.Variable]{Body: *response}, nil
}
vars, err := h.variableService.ReadLocalEnvFile(ctx)
@@ -284,7 +252,7 @@ func (h *VariableHandler) GetMaterializedVariables(ctx context.Context, input *G
return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to retrieve global variables").Error())
}
- return &GetGlobalVariablesOutput{
+ return &handlerutil.Out[[]env.Variable]{
Body: base.ApiResponse[[]env.Variable]{
Success: true,
Data: vars,
@@ -294,13 +262,13 @@ func (h *VariableHandler) GetMaterializedVariables(ctx context.Context, input *G
// UpdateMaterializedVariables replaces the environment's materialized
// .env.global content (local file for environment "0", proxied otherwise).
-func (h *VariableHandler) UpdateMaterializedVariables(ctx context.Context, input *UpdateGlobalVariablesInput) (*UpdateGlobalVariablesOutput, error) {
+func (h *VariableHandler) UpdateMaterializedVariables(ctx context.Context, input *UpdateGlobalVariablesInput) (*handlerutil.Out[base.MessageResponse], error) {
if input.EnvironmentID != "0" {
- response, err := handlerutil.ProxyRemoteJSON[base.ApiResponse[base.MessageResponse]](ctx, h.environmentService.ProxyJSONRequest, input.EnvironmentID, http.MethodPut, "/api/environments/0/templates/variables", input.Body)
+ response, err := h.proxyRemoteJSON.JSON[base.ApiResponse[base.MessageResponse]](ctx, input.EnvironmentID, http.MethodPut, "/api/environments/0/templates/variables", input.Body)
if err != nil {
return nil, err
}
- return &UpdateGlobalVariablesOutput{Body: *response}, nil
+ return &handlerutil.Out[base.MessageResponse]{Body: *response}, nil
}
if err := h.variableService.WriteLocalEnvFile(ctx, input.Body.Variables); err != nil {
@@ -310,7 +278,7 @@ func (h *VariableHandler) UpdateMaterializedVariables(ctx context.Context, input
return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to update global variables").Error())
}
- return &UpdateGlobalVariablesOutput{
+ return &handlerutil.Out[base.MessageResponse]{
Body: base.ApiResponse[base.MessageResponse]{
Success: true,
Data: base.MessageResponse{
diff --git a/backend/internal/volume/handler.go b/backend/internal/volume/handler.go
index 30ce7a6af..3792f2d71 100644
--- a/backend/internal/volume/handler.go
+++ b/backend/internal/volume/handler.go
@@ -75,39 +75,23 @@ type GetVolumeInput struct {
VolumeName string `path:"volumeName" doc:"Volume name"`
}
-type GetVolumeOutput struct {
- Body base.ApiResponse[*volumetypes.Volume]
-}
-
type CreateVolumeInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
Body volumetypes.Create `doc:"Volume creation data"`
}
-type CreateVolumeOutput struct {
- Body base.ApiResponse[*volumetypes.Volume]
-}
-
type RenameVolumeInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
VolumeName string `path:"volumeName" doc:"Current volume name"`
Body volumetypes.Rename `doc:"Volume rename data"`
}
-type RenameVolumeOutput struct {
- Body base.ApiResponse[*volumetypes.Volume]
-}
-
type RemoveVolumeInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
VolumeName string `path:"volumeName" doc:"Volume name"`
Force bool `query:"force" doc:"Force removal"`
}
-type RemoveVolumeOutput struct {
- Body base.ApiResponse[base.MessageResponse]
-}
-
type PruneVolumesInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
}
@@ -120,10 +104,6 @@ type VolumePruneReportData struct {
ActivityID *string `json:"activityId,omitempty"`
}
-type PruneVolumesOutput struct {
- Body base.ApiResponse[VolumePruneReportData]
-}
-
type GetVolumeUsageInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
VolumeName string `path:"volumeName" doc:"Volume name"`
@@ -135,19 +115,11 @@ type VolumeUsageResponse struct {
Containers []string `json:"containers"`
}
-type GetVolumeUsageOutput struct {
- Body base.ApiResponse[VolumeUsageResponse]
-}
-
type GetVolumeUsageCountsInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
IncludeInternal bool `query:"includeInternal" default:"false" doc:"Include internal volumes"`
}
-type GetVolumeUsageCountsOutput struct {
- Body base.ApiResponse[VolumeUsageCountsData]
-}
-
type GetVolumeSizesInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
}
@@ -159,10 +131,6 @@ type VolumeSizeInfo struct {
RefCount int64 `json:"refCount"`
}
-type GetVolumeSizesOutput struct {
- Body base.ApiResponse[[]VolumeSizeInfo]
-}
-
// --- Volume Backup ---
type ListBackupsInput struct {
@@ -193,39 +161,23 @@ type CreateBackupInput struct {
Body *volumetypes.CreateBackupRequest `json:"body,omitempty"`
}
-type CreateBackupOutput struct {
- Body base.ApiResponse[*VolumeBackup]
-}
-
type GetVolumeBackupPolicyInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
VolumeName string `path:"volumeName" doc:"Volume name"`
}
-type GetVolumeBackupPolicyOutput struct {
- Body base.ApiResponse[volumetypes.BackupPolicyCollection]
-}
-
type UpdateVolumeBackupPolicyInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
VolumeName string `path:"volumeName" doc:"Volume name"`
Body volumetypes.UpdateBackupPolicies `doc:"Scheduled volume backup policies"`
}
-type UpdateVolumeBackupPolicyOutput struct {
- Body base.ApiResponse[volumetypes.BackupPolicyCollection]
-}
-
type RestoreBackupInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
VolumeName string `path:"volumeName" doc:"Volume name"`
BackupID string `path:"backupId" doc:"Backup ID"`
}
-type RestoreBackupOutput struct {
- Body base.ApiResponse[base.MessageResponse]
-}
-
type RestoreBackupFilesInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
VolumeName string `path:"volumeName" doc:"Volume name"`
@@ -233,10 +185,6 @@ type RestoreBackupFilesInput struct {
Body backuptypes.RestoreSelection
}
-type RestoreBackupFilesOutput struct {
- Body base.ApiResponse[base.MessageResponse]
-}
-
type BackupHasPathInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
BackupID string `path:"backupId" doc:"Backup ID"`
@@ -247,19 +195,11 @@ type BackupHasPathResponse struct {
Exists bool `json:"exists"`
}
-type BackupHasPathOutput struct {
- Body base.ApiResponse[BackupHasPathResponse]
-}
-
type ListBackupFilesInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
BackupID string `path:"backupId" doc:"Backup ID"`
}
-type ListBackupFilesOutput struct {
- Body base.ApiResponse[[]string]
-}
-
type BrowseBackupFilesInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
BackupID string `path:"backupId" doc:"Backup ID"`
@@ -268,11 +208,6 @@ type BrowseBackupFilesInput struct {
Start int `query:"start" default:"0" doc:"Start index for the page"`
Limit int `query:"limit" default:"20" doc:"Requested page size"`
}
-
-type BrowseBackupFilesOutput struct {
- Body base.Paginated[backuptypes.BackupFileEntry]
-}
-
type DeleteBackupInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
BackupID string `path:"backupId" doc:"Backup ID"`
@@ -283,30 +218,18 @@ type DownloadBackupInput struct {
BackupID string `path:"backupId" doc:"Backup ID"`
}
-type DeleteBackupOutput struct {
- Body base.ApiResponse[base.MessageResponse]
-}
-
type UploadAndRestoreInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
VolumeName string `path:"volumeName" doc:"Volume name"`
Body uploadtypes.ConsumeRequest
}
-type UploadAndRestoreOutput struct {
- Body base.ApiResponse[base.MessageResponse]
-}
-
type UploadBackupInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
BackupID string `path:"backupId" doc:"Backup ID"`
Body volumetypes.UploadBackupRequest
}
-type UploadBackupOutput struct {
- Body base.ApiResponse[*VolumeBackup]
-}
-
// RegisterVolumes registers volume management routes using Huma.
func RegisterVolumes(api huma.API, dockerService *docker.DockerClientService, volumeService *VolumeService, activityService *activity.ActivityService, environmentService *environment.EnvironmentService, uploadService *upload.UploadService, appCtx handlerutil.ActivityAppContext) {
h := &VolumeHandler{
@@ -556,27 +479,27 @@ func (h *VolumeHandler) DownloadBackup(ctx context.Context, input *DownloadBacku
}, nil
}
-func (h *VolumeHandler) GetBackupPolicy(ctx context.Context, input *GetVolumeBackupPolicyInput) (*GetVolumeBackupPolicyOutput, error) {
+func (h *VolumeHandler) GetBackupPolicy(ctx context.Context, input *GetVolumeBackupPolicyInput) (*handlerutil.Out[volumetypes.BackupPolicyCollection], error) {
if input.EnvironmentID != "0" {
if h.environmentService == nil {
return nil, huma.Error500InternalServerError("environment service not available")
}
remotePath := fmt.Sprintf("/api/environments/0/volumes/%s/backup-policy", url.PathEscape(input.VolumeName))
- response, err := handlerutil.ProxyRemoteJSON[base.ApiResponse[volumetypes.BackupPolicyCollection]](ctx, h.environmentService.ProxyJSONRequest, input.EnvironmentID, http.MethodGet, remotePath, nil)
+ response, err := handlerutil.RemoteJSONProxy(h.environmentService.ProxyJSONRequest).JSON[base.ApiResponse[volumetypes.BackupPolicyCollection]](ctx, input.EnvironmentID, http.MethodGet, remotePath, nil)
if err != nil {
return nil, err
}
- return &GetVolumeBackupPolicyOutput{Body: *response}, nil
+ return &handlerutil.Out[volumetypes.BackupPolicyCollection]{Body: *response}, nil
}
policies, err := h.volumeService.GetBackupPolicies(ctx, input.VolumeName)
if err != nil {
return nil, huma.Error500InternalServerError(err.Error())
}
- return &GetVolumeBackupPolicyOutput{Body: base.ApiResponse[volumetypes.BackupPolicyCollection]{Success: true, Data: *policies}}, nil
+ return &handlerutil.Out[volumetypes.BackupPolicyCollection]{Body: base.ApiResponse[volumetypes.BackupPolicyCollection]{Success: true, Data: *policies}}, nil
}
-func (h *VolumeHandler) UpdateBackupPolicy(ctx context.Context, input *UpdateVolumeBackupPolicyInput) (*UpdateVolumeBackupPolicyOutput, error) {
+func (h *VolumeHandler) UpdateBackupPolicy(ctx context.Context, input *UpdateVolumeBackupPolicyInput) (*handlerutil.Out[volumetypes.BackupPolicyCollection], error) {
user, _ := common.CurrentUserFromContext(ctx)
var policies *volumetypes.BackupPolicyCollection
var remoteResponse *base.ApiResponse[volumetypes.BackupPolicyCollection]
@@ -621,7 +544,7 @@ func (h *VolumeHandler) UpdateBackupPolicy(ctx context.Context, input *UpdateVol
}
remotePath := fmt.Sprintf("/api/environments/0/volumes/%s/backup-policy", url.PathEscape(input.VolumeName))
var proxyErr error
- remoteResponse, proxyErr = handlerutil.ProxyRemoteJSON[base.ApiResponse[volumetypes.BackupPolicyCollection]](activityCtx, h.environmentService.ProxyJSONRequest, input.EnvironmentID, http.MethodPut, remotePath, input.Body)
+ remoteResponse, proxyErr = handlerutil.RemoteJSONProxy(h.environmentService.ProxyJSONRequest).JSON[base.ApiResponse[volumetypes.BackupPolicyCollection]](activityCtx, input.EnvironmentID, http.MethodPut, remotePath, input.Body)
if proxyErr != nil {
errorStatus = http.StatusBadGateway
}
@@ -641,9 +564,9 @@ func (h *VolumeHandler) UpdateBackupPolicy(ctx context.Context, input *UpdateVol
return nil, huma.Error400BadRequest(err.Error())
}
if remoteResponse != nil {
- return &UpdateVolumeBackupPolicyOutput{Body: *remoteResponse}, nil
+ return &handlerutil.Out[volumetypes.BackupPolicyCollection]{Body: *remoteResponse}, nil
}
- return &UpdateVolumeBackupPolicyOutput{Body: base.ApiResponse[volumetypes.BackupPolicyCollection]{Success: true, Data: *policies}}, nil
+ return &handlerutil.Out[volumetypes.BackupPolicyCollection]{Body: base.ApiResponse[volumetypes.BackupPolicyCollection]{Success: true, Data: *policies}}, nil
}
// ListVolumes returns a paginated list of volumes.
@@ -681,13 +604,13 @@ func (h *VolumeHandler) ListVolumes(ctx context.Context, input *ListVolumesInput
}
// GetVolume returns a volume by name.
-func (h *VolumeHandler) GetVolume(ctx context.Context, input *GetVolumeInput) (*GetVolumeOutput, error) {
+func (h *VolumeHandler) GetVolume(ctx context.Context, input *GetVolumeInput) (*handlerutil.Out[*volumetypes.Volume], error) {
vol, err := h.volumeService.GetVolumeByName(ctx, input.VolumeName)
if err != nil {
return nil, huma.Error404NotFound(errors.WithMessage(err, "Volume not found").Error())
}
- return &GetVolumeOutput{
+ return &handlerutil.Out[*volumetypes.Volume]{
Body: base.ApiResponse[*volumetypes.Volume]{
Success: true,
Data: vol,
@@ -696,7 +619,7 @@ func (h *VolumeHandler) GetVolume(ctx context.Context, input *GetVolumeInput) (*
}
// CreateVolume creates a new Docker volume.
-func (h *VolumeHandler) CreateVolume(ctx context.Context, input *CreateVolumeInput) (*CreateVolumeOutput, error) {
+func (h *VolumeHandler) CreateVolume(ctx context.Context, input *CreateVolumeInput) (*handlerutil.Out[*volumetypes.Volume], error) {
user, err := handlerutil.RequireUser(ctx)
if err != nil {
return nil, err
@@ -735,7 +658,7 @@ func (h *VolumeHandler) CreateVolume(ctx context.Context, input *CreateVolumeInp
}
response.ActivityID = mo.EmptyableToOption(strings.TrimSpace(activityID)).ToPointer()
- return &CreateVolumeOutput{
+ return &handlerutil.Out[*volumetypes.Volume]{
Body: base.ApiResponse[*volumetypes.Volume]{
Success: true,
Data: response,
@@ -744,17 +667,17 @@ func (h *VolumeHandler) CreateVolume(ctx context.Context, input *CreateVolumeInp
}
// RenameVolume renames an unused Docker volume.
-func (h *VolumeHandler) RenameVolume(ctx context.Context, input *RenameVolumeInput) (*RenameVolumeOutput, error) {
+func (h *VolumeHandler) RenameVolume(ctx context.Context, input *RenameVolumeInput) (*handlerutil.Out[*volumetypes.Volume], error) {
if input.EnvironmentID != "0" {
if h.environmentService == nil {
return nil, huma.Error500InternalServerError("environment service not available")
}
remotePath := fmt.Sprintf("/api/environments/0/volumes/%s/rename", url.PathEscape(input.VolumeName))
- response, err := handlerutil.ProxyRemoteJSON[base.ApiResponse[*volumetypes.Volume]](ctx, h.environmentService.ProxyJSONRequest, input.EnvironmentID, http.MethodPost, remotePath, input.Body)
+ response, err := handlerutil.RemoteJSONProxy(h.environmentService.ProxyJSONRequest).JSON[base.ApiResponse[*volumetypes.Volume]](ctx, input.EnvironmentID, http.MethodPost, remotePath, input.Body)
if err != nil {
return nil, err
}
- return &RenameVolumeOutput{Body: *response}, nil
+ return &handlerutil.Out[*volumetypes.Volume]{Body: *response}, nil
}
user, err := handlerutil.RequireUser(ctx)
@@ -803,11 +726,11 @@ func (h *VolumeHandler) RenameVolume(ctx context.Context, input *RenameVolumeInp
}
response.ActivityID = mo.EmptyableToOption(strings.TrimSpace(activityID)).ToPointer()
- return &RenameVolumeOutput{Body: base.ApiResponse[*volumetypes.Volume]{Success: true, Data: response}}, nil
+ return &handlerutil.Out[*volumetypes.Volume]{Body: base.ApiResponse[*volumetypes.Volume]{Success: true, Data: response}}, nil
}
// RemoveVolume removes a Docker volume.
-func (h *VolumeHandler) RemoveVolume(ctx context.Context, input *RemoveVolumeInput) (*RemoveVolumeOutput, error) {
+func (h *VolumeHandler) RemoveVolume(ctx context.Context, input *RemoveVolumeInput) (*handlerutil.Out[base.MessageResponse], error) {
user, err := handlerutil.RequireUser(ctx)
if err != nil {
return nil, err
@@ -835,7 +758,7 @@ func (h *VolumeHandler) RemoveVolume(ctx context.Context, input *RemoveVolumeInp
return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to delete volume").Error())
}
- return &RemoveVolumeOutput{
+ return &handlerutil.Out[base.MessageResponse]{
Body: base.ApiResponse[base.MessageResponse]{
Success: true,
Data: base.MessageResponse{
@@ -847,7 +770,7 @@ func (h *VolumeHandler) RemoveVolume(ctx context.Context, input *RemoveVolumeInp
}
// PruneVolumes removes all unused Docker volumes.
-func (h *VolumeHandler) PruneVolumes(ctx context.Context, input *PruneVolumesInput) (*PruneVolumesOutput, error) {
+func (h *VolumeHandler) PruneVolumes(ctx context.Context, input *PruneVolumesInput) (*handlerutil.Out[VolumePruneReportData], error) {
var report *volumetypes.PruneReport
runtimeCtx := utils.ActivityRuntimeContext(ctx, h.appCtx)
activityID, err := activitylib.RunHandlerActivity(runtimeCtx, h.activityService, activitylib.HandlerOptions{
@@ -867,7 +790,7 @@ func (h *VolumeHandler) PruneVolumes(ctx context.Context, input *PruneVolumesInp
return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to prune volumes").Error())
}
- return &PruneVolumesOutput{
+ return &handlerutil.Out[VolumePruneReportData]{
Body: base.ApiResponse[VolumePruneReportData]{
Success: true,
Data: VolumePruneReportData{
@@ -880,13 +803,13 @@ func (h *VolumeHandler) PruneVolumes(ctx context.Context, input *PruneVolumesInp
}
// GetVolumeUsage returns containers using a specific volume.
-func (h *VolumeHandler) GetVolumeUsage(ctx context.Context, input *GetVolumeUsageInput) (*GetVolumeUsageOutput, error) {
+func (h *VolumeHandler) GetVolumeUsage(ctx context.Context, input *GetVolumeUsageInput) (*handlerutil.Out[VolumeUsageResponse], error) {
inUse, containers, err := h.volumeService.GetVolumeUsage(ctx, input.VolumeName)
if err != nil {
return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to get volume usage").Error())
}
- return &GetVolumeUsageOutput{
+ return &handlerutil.Out[VolumeUsageResponse]{
Body: base.ApiResponse[VolumeUsageResponse]{
Success: true,
Data: VolumeUsageResponse{
@@ -898,13 +821,13 @@ func (h *VolumeHandler) GetVolumeUsage(ctx context.Context, input *GetVolumeUsag
}
// GetVolumeUsageCounts returns counts of volumes by usage status.
-func (h *VolumeHandler) GetVolumeUsageCounts(ctx context.Context, input *GetVolumeUsageCountsInput) (*GetVolumeUsageCountsOutput, error) {
+func (h *VolumeHandler) GetVolumeUsageCounts(ctx context.Context, input *GetVolumeUsageCountsInput) (*handlerutil.Out[VolumeUsageCountsData], error) {
_, _, counts, err := h.volumeService.ListVolumesPaginated(ctx, pagination.QueryParams{}, input.IncludeInternal)
if err != nil {
return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to get volume counts").Error())
}
- return &GetVolumeUsageCountsOutput{
+ return &handlerutil.Out[VolumeUsageCountsData]{
Body: base.ApiResponse[VolumeUsageCountsData]{
Success: true,
Data: VolumeUsageCountsData{
@@ -918,7 +841,7 @@ func (h *VolumeHandler) GetVolumeUsageCounts(ctx context.Context, input *GetVolu
// GetVolumeSizes returns disk usage sizes for all volumes.
// This is a slow operation as it requires calculating disk usage.
-func (h *VolumeHandler) GetVolumeSizes(ctx context.Context, input *GetVolumeSizesInput) (*GetVolumeSizesOutput, error) {
+func (h *VolumeHandler) GetVolumeSizes(ctx context.Context, input *GetVolumeSizesInput) (*handlerutil.Out[[]VolumeSizeInfo], error) {
sizes, err := h.volumeService.GetVolumeSizes(ctx)
if err != nil {
return nil, huma.Error500InternalServerError(err.Error())
@@ -933,7 +856,7 @@ func (h *VolumeHandler) GetVolumeSizes(ctx context.Context, input *GetVolumeSize
})
}
- return &GetVolumeSizesOutput{
+ return &handlerutil.Out[[]VolumeSizeInfo]{
Body: base.ApiResponse[[]VolumeSizeInfo]{
Success: true,
Data: result,
@@ -981,7 +904,7 @@ func (h *VolumeHandler) ListBackups(ctx context.Context, input *ListBackupsInput
}, nil
}
-func (h *VolumeHandler) CreateBackup(ctx context.Context, input *CreateBackupInput) (*CreateBackupOutput, error) {
+func (h *VolumeHandler) CreateBackup(ctx context.Context, input *CreateBackupInput) (*handlerutil.Out[*VolumeBackup], error) {
user, err := handlerutil.RequireUser(ctx)
if err != nil {
return nil, err
@@ -1022,7 +945,7 @@ func (h *VolumeHandler) CreateBackup(ctx context.Context, input *CreateBackupInp
return nil, huma.Error500InternalServerError(err.Error())
}
backup.ActivityID = mo.EmptyableToOption(strings.TrimSpace(activityID)).ToPointer()
- return &CreateBackupOutput{
+ return &handlerutil.Out[*VolumeBackup]{
Body: base.ApiResponse[*VolumeBackup]{
Success: true,
Data: backup,
@@ -1030,7 +953,7 @@ func (h *VolumeHandler) CreateBackup(ctx context.Context, input *CreateBackupInp
}, nil
}
-func (h *VolumeHandler) RestoreBackup(ctx context.Context, input *RestoreBackupInput) (*RestoreBackupOutput, error) {
+func (h *VolumeHandler) RestoreBackup(ctx context.Context, input *RestoreBackupInput) (*handlerutil.Out[base.MessageResponse], error) {
user, err := handlerutil.RequireUser(ctx)
if err != nil {
return nil, err
@@ -1057,7 +980,7 @@ func (h *VolumeHandler) RestoreBackup(ctx context.Context, input *RestoreBackupI
if err != nil {
return nil, huma.Error500InternalServerError(err.Error())
}
- return &RestoreBackupOutput{
+ return &handlerutil.Out[base.MessageResponse]{
Body: base.ApiResponse[base.MessageResponse]{
Success: true,
Data: base.MessageResponse{Message: "Restore initiated successfully", ActivityID: mo.EmptyableToOption(strings.TrimSpace(activityID)).ToPointer()},
@@ -1065,7 +988,7 @@ func (h *VolumeHandler) RestoreBackup(ctx context.Context, input *RestoreBackupI
}, nil
}
-func (h *VolumeHandler) RestoreBackupFiles(ctx context.Context, input *RestoreBackupFilesInput) (*RestoreBackupFilesOutput, error) {
+func (h *VolumeHandler) RestoreBackupFiles(ctx context.Context, input *RestoreBackupFilesInput) (*handlerutil.Out[base.MessageResponse], error) {
user, err := handlerutil.RequireUser(ctx)
if err != nil {
return nil, err
@@ -1099,7 +1022,7 @@ func (h *VolumeHandler) RestoreBackupFiles(ctx context.Context, input *RestoreBa
return nil, huma.Error500InternalServerError(err.Error())
}
- return &RestoreBackupFilesOutput{
+ return &handlerutil.Out[base.MessageResponse]{
Body: base.ApiResponse[base.MessageResponse]{
Success: true,
Data: base.MessageResponse{Message: "Restore initiated successfully", ActivityID: mo.EmptyableToOption(strings.TrimSpace(activityID)).ToPointer()},
@@ -1107,7 +1030,7 @@ func (h *VolumeHandler) RestoreBackupFiles(ctx context.Context, input *RestoreBa
}, nil
}
-func (h *VolumeHandler) BackupHasPath(ctx context.Context, input *BackupHasPathInput) (*BackupHasPathOutput, error) {
+func (h *VolumeHandler) BackupHasPath(ctx context.Context, input *BackupHasPathInput) (*handlerutil.Out[BackupHasPathResponse], error) {
if input.Path == "" {
return nil, huma.Error400BadRequest("path is required")
}
@@ -1117,7 +1040,7 @@ func (h *VolumeHandler) BackupHasPath(ctx context.Context, input *BackupHasPathI
return nil, huma.Error500InternalServerError(err.Error())
}
- return &BackupHasPathOutput{
+ return &handlerutil.Out[BackupHasPathResponse]{
Body: base.ApiResponse[BackupHasPathResponse]{
Success: true,
Data: BackupHasPathResponse{Exists: exists},
@@ -1125,13 +1048,13 @@ func (h *VolumeHandler) BackupHasPath(ctx context.Context, input *BackupHasPathI
}, nil
}
-func (h *VolumeHandler) ListBackupFiles(ctx context.Context, input *ListBackupFilesInput) (*ListBackupFilesOutput, error) {
+func (h *VolumeHandler) ListBackupFiles(ctx context.Context, input *ListBackupFilesInput) (*handlerutil.Out[[]string], error) {
files, err := h.volumeService.ListBackupFiles(ctx, input.BackupID)
if err != nil {
return nil, huma.Error500InternalServerError(err.Error())
}
- return &ListBackupFilesOutput{
+ return &handlerutil.Out[[]string]{
Body: base.ApiResponse[[]string]{
Success: true,
Data: files,
@@ -1139,7 +1062,7 @@ func (h *VolumeHandler) ListBackupFiles(ctx context.Context, input *ListBackupFi
}, nil
}
-func (h *VolumeHandler) BrowseBackupFiles(ctx context.Context, input *BrowseBackupFilesInput) (*BrowseBackupFilesOutput, error) {
+func (h *VolumeHandler) BrowseBackupFiles(ctx context.Context, input *BrowseBackupFilesInput) (*handlerutil.Page[backuptypes.BackupFileEntry], error) {
params := handlerutil.PaginationParams(input.Start, input.Limit, "", "", input.Search)
items, page, err := h.volumeService.BrowseBackupFiles(ctx, input.BackupID, input.Path, params)
if errors.Is(err, common.ErrBadRequest) {
@@ -1148,12 +1071,12 @@ func (h *VolumeHandler) BrowseBackupFiles(ctx context.Context, input *BrowseBack
if err != nil {
return nil, huma.Error500InternalServerError(err.Error())
}
- return &BrowseBackupFilesOutput{Body: base.Paginated[backuptypes.BackupFileEntry]{
+ return &handlerutil.Page[backuptypes.BackupFileEntry]{Body: base.Paginated[backuptypes.BackupFileEntry]{
Success: true, Data: items, Pagination: handlerutil.PaginationResponse(page),
}}, nil
}
-func (h *VolumeHandler) DeleteBackup(ctx context.Context, input *DeleteBackupInput) (*DeleteBackupOutput, error) {
+func (h *VolumeHandler) DeleteBackup(ctx context.Context, input *DeleteBackupInput) (*handlerutil.Out[base.MessageResponse], error) {
user, _ := common.CurrentUserFromContext(ctx)
runtimeCtx := utils.ActivityRuntimeContext(ctx, h.appCtx)
activityID, err := activitylib.RunHandlerActivity(runtimeCtx, h.activityService, activitylib.HandlerOptions{
@@ -1176,7 +1099,7 @@ func (h *VolumeHandler) DeleteBackup(ctx context.Context, input *DeleteBackupInp
if err != nil {
return nil, huma.Error500InternalServerError(err.Error())
}
- return &DeleteBackupOutput{
+ return &handlerutil.Out[base.MessageResponse]{
Body: base.ApiResponse[base.MessageResponse]{
Success: true,
Data: base.MessageResponse{Message: "Backup deleted successfully", ActivityID: mo.EmptyableToOption(strings.TrimSpace(activityID)).ToPointer()},
@@ -1184,7 +1107,7 @@ func (h *VolumeHandler) DeleteBackup(ctx context.Context, input *DeleteBackupInp
}, nil
}
-func (h *VolumeHandler) UploadBackup(ctx context.Context, input *UploadBackupInput) (*UploadBackupOutput, error) {
+func (h *VolumeHandler) UploadBackup(ctx context.Context, input *UploadBackupInput) (*handlerutil.Out[*VolumeBackup], error) {
if h.volumeService == nil {
return nil, huma.Error500InternalServerError("service not available")
}
@@ -1215,10 +1138,10 @@ func (h *VolumeHandler) UploadBackup(ctx context.Context, input *UploadBackupInp
return nil, huma.Error500InternalServerError(err.Error())
}
backup.ActivityID = mo.EmptyableToOption(strings.TrimSpace(activityID)).ToPointer()
- return &UploadBackupOutput{Body: base.ApiResponse[*VolumeBackup]{Success: true, Data: backup}}, nil
+ return &handlerutil.Out[*VolumeBackup]{Body: base.ApiResponse[*VolumeBackup]{Success: true, Data: backup}}, nil
}
-func (h *VolumeHandler) UploadAndRestore(ctx context.Context, input *UploadAndRestoreInput) (*UploadAndRestoreOutput, error) {
+func (h *VolumeHandler) UploadAndRestore(ctx context.Context, input *UploadAndRestoreInput) (*handlerutil.Out[base.MessageResponse], error) {
user, err := handlerutil.RequireUser(ctx)
if err != nil {
return nil, err
@@ -1254,7 +1177,7 @@ func (h *VolumeHandler) UploadAndRestore(ctx context.Context, input *UploadAndRe
if err != nil {
return nil, huma.Error500InternalServerError(err.Error())
}
- return &UploadAndRestoreOutput{
+ return &handlerutil.Out[base.MessageResponse]{
Body: base.ApiResponse[base.MessageResponse]{
Success: true,
Data: base.MessageResponse{Message: "Backup uploaded and restored successfully", ActivityID: mo.EmptyableToOption(strings.TrimSpace(activityID)).ToPointer()},
diff --git a/backend/internal/volume/helper_container.go b/backend/internal/volume/helper_container.go
index 4ff63053c..afda42d35 100644
--- a/backend/internal/volume/helper_container.go
+++ b/backend/internal/volume/helper_container.go
@@ -5,7 +5,7 @@ import (
"bytes"
"context"
- "encoding/json"
+ "encoding/json/v2"
"io"
"log/slog"
"strings"
diff --git a/backend/internal/volume/listing.go b/backend/internal/volume/listing.go
index f8002f29f..feb29f871 100644
--- a/backend/internal/volume/listing.go
+++ b/backend/internal/volume/listing.go
@@ -438,7 +438,7 @@ func (s *VolumeService) ListVolumesPaginated(ctx context.Context, params paginat
}
config := s.buildVolumePaginationConfigInternal()
- result := pagination.SearchOrderAndPaginate(items, effectiveParams, config)
+ result := config.SearchOrderAndPaginate(items, effectiveParams)
counts := calculateVolumeUsageCountsInternal(items)
paginationResp := pagination.BuildResponse(result.TotalCount, result.TotalAvailable, effectiveParams)
slog.DebugContext(ctx, "volume service: listed volumes",
diff --git a/backend/internal/volume/workspace.go b/backend/internal/volume/workspace.go
index d09d07d7c..4df619c74 100644
--- a/backend/internal/volume/workspace.go
+++ b/backend/internal/volume/workspace.go
@@ -10,7 +10,8 @@ import (
"context"
"crypto/sha256"
"encoding/hex"
- "encoding/json"
+ "encoding/json/jsontext"
+ "encoding/json/v2"
stderrors "errors"
"fmt"
"io"
@@ -127,14 +128,14 @@ func (s *VolumeService) readVolumeWorkspaceFromContainerInternal(ctx context.Con
}
func decodeVolumeWorkspaceWalkInternal(source io.Reader, maxEntries int, maxFileSizeBytes int64) (*workspacetypes.Workspace, error) {
- decoder := json.NewDecoder(source)
+ decoder := jsontext.NewDecoder(source)
files := make([]workspacetypes.FileEntry, 0, min(maxEntries, 256))
classifications := make(map[string]string, min(maxEntries, 256))
trailerSeen := false
truncated := false
for {
var record acfstypes.WalkRecord
- err := decoder.Decode(&record)
+ err := json.UnmarshalDecode(decoder, &record)
if stderrors.Is(err, io.EOF) {
break
}
diff --git a/backend/internal/volume/workspace_handler.go b/backend/internal/volume/workspace_handler.go
index c552a8c08..89fb9c511 100644
--- a/backend/internal/volume/workspace_handler.go
+++ b/backend/internal/volume/workspace_handler.go
@@ -33,30 +33,18 @@ type GetVolumeWorkspaceInput struct {
VolumeName string `path:"volumeName" doc:"Volume name"`
}
-type GetVolumeWorkspaceOutput struct {
- Body base.ApiResponse[workspacetypes.Workspace]
-}
-
type GetVolumeWorkspaceFileInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
VolumeName string `path:"volumeName" doc:"Volume name"`
RelativePath string `query:"relativePath" doc:"Path relative to the volume workspace root"`
}
-type GetVolumeWorkspaceFileOutput struct {
- Body base.ApiResponse[workspacetypes.FileContent]
-}
-
type UpdateVolumeWorkspaceInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
VolumeName string `path:"volumeName" doc:"Volume name"`
RawBody multipart.Form `contentType:"multipart/form-data"`
}
-type UpdateVolumeWorkspaceOutput struct {
- Body base.ApiResponse[workspacetypes.Workspace]
-}
-
func registerVolumeWorkspaceRoutesInternal(api huma.API, h *VolumeHandler) {
basePath := "/environments/{id}/volumes/{volumeName}/workspace"
tag := "Volume Workspace"
@@ -83,20 +71,20 @@ func volumeWorkspaceHTTPErrorInternal(err error) error {
}
}
-func (h *VolumeHandler) GetVolumeWorkspace(ctx context.Context, input *GetVolumeWorkspaceInput) (*GetVolumeWorkspaceOutput, error) {
+func (h *VolumeHandler) GetVolumeWorkspace(ctx context.Context, input *GetVolumeWorkspaceInput) (*handlerutil.Out[workspacetypes.Workspace], error) {
result, err := h.volumeService.GetVolumeWorkspace(ctx, input.VolumeName)
if err != nil {
return nil, volumeWorkspaceHTTPErrorInternal(err)
}
- return &GetVolumeWorkspaceOutput{Body: base.ApiResponse[workspacetypes.Workspace]{Success: true, Data: *result}}, nil
+ return &handlerutil.Out[workspacetypes.Workspace]{Body: base.ApiResponse[workspacetypes.Workspace]{Success: true, Data: *result}}, nil
}
-func (h *VolumeHandler) GetVolumeWorkspaceFile(ctx context.Context, input *GetVolumeWorkspaceFileInput) (*GetVolumeWorkspaceFileOutput, error) {
+func (h *VolumeHandler) GetVolumeWorkspaceFile(ctx context.Context, input *GetVolumeWorkspaceFileInput) (*handlerutil.Out[workspacetypes.FileContent], error) {
result, err := h.volumeService.GetVolumeWorkspaceFile(ctx, input.VolumeName, input.RelativePath)
if err != nil {
return nil, volumeWorkspaceHTTPErrorInternal(err)
}
- return &GetVolumeWorkspaceFileOutput{Body: base.ApiResponse[workspacetypes.FileContent]{Success: true, Data: *result}}, nil
+ return &handlerutil.Out[workspacetypes.FileContent]{Body: base.ApiResponse[workspacetypes.FileContent]{Success: true, Data: *result}}, nil
}
func (h *VolumeHandler) DownloadVolumeWorkspaceFile(ctx context.Context, input *GetVolumeWorkspaceFileInput) (*huma.StreamResponse, error) {
@@ -127,7 +115,7 @@ func requireVolumeWorkspacePermissionsInternal(ctx context.Context, environmentI
return nil
}
-func (h *VolumeHandler) UpdateVolumeWorkspace(ctx context.Context, input *UpdateVolumeWorkspaceInput) (*UpdateVolumeWorkspaceOutput, error) {
+func (h *VolumeHandler) UpdateVolumeWorkspace(ctx context.Context, input *UpdateVolumeWorkspaceInput) (*handlerutil.Out[workspacetypes.Workspace], error) {
manifest, err := handlerutil.ParseMultipartJSONPart[volumetypes.WorkspaceUpdateManifest](input.RawBody, "manifest")
if err != nil {
return nil, err
@@ -162,5 +150,5 @@ func (h *VolumeHandler) UpdateVolumeWorkspace(ctx context.Context, input *Update
return nil, volumeWorkspaceHTTPErrorInternal(err)
}
result.ActivityID = mo.EmptyableToOption(strings.TrimSpace(activityID)).ToPointer()
- return &UpdateVolumeWorkspaceOutput{Body: base.ApiResponse[workspacetypes.Workspace]{Success: true, Data: *result}}, nil
+ return &handlerutil.Out[workspacetypes.Workspace]{Body: base.ApiResponse[workspacetypes.Workspace]{Success: true, Data: *result}}, nil
}
diff --git a/backend/internal/vulnerability/handler.go b/backend/internal/vulnerability/handler.go
index 020d0ba5d..36ba0e5fc 100644
--- a/backend/internal/vulnerability/handler.go
+++ b/backend/internal/vulnerability/handler.go
@@ -28,37 +28,21 @@ type ScanImageInput struct {
ImageID string `path:"imageId" doc:"Image ID to scan"`
}
-type ScanImageOutput struct {
- Body base.ApiResponse[vulnerability.ScanResult]
-}
-
type GetScanResultInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
ImageID string `path:"imageId" doc:"Image ID"`
}
-type GetScanResultOutput struct {
- Body base.ApiResponse[vulnerability.ScanResult]
-}
-
type GetScanSummaryInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
ImageID string `path:"imageId" doc:"Image ID"`
}
-type GetScanSummaryOutput struct {
- Body base.ApiResponse[vulnerability.ScanSummary]
-}
-
type GetScanSummariesInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
Body vulnerability.ScanSummariesRequest `doc:"Batch scan summary request"`
}
-type GetScanSummariesOutput struct {
- Body base.ApiResponse[vulnerability.ScanSummariesResponse]
-}
-
type ListImageVulnerabilitiesInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
ImageID string `path:"imageId" doc:"Image ID"`
@@ -71,18 +55,10 @@ type ListImageVulnerabilitiesInput struct {
Severity string `query:"severity" doc:"Comma-separated severity filter"`
}
-type ListImageVulnerabilitiesOutput struct {
- Body base.Paginated[vulnerability.Vulnerability]
-}
-
type GetEnvironmentSummaryInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
}
-type GetEnvironmentSummaryOutput struct {
- Body base.ApiResponse[vulnerability.EnvironmentVulnerabilitySummary]
-}
-
type ListAllVulnerabilitiesInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
Search string `query:"search" doc:"Search query"`
@@ -96,19 +72,11 @@ type ListAllVulnerabilitiesInput struct {
Ignored bool `query:"ignored" doc:"Show only ignored vulnerabilities instead of active ones"`
}
-type ListAllVulnerabilitiesOutput struct {
- Body base.Paginated[vulnerability.VulnerabilityWithImage]
-}
-
type ListAllVulnerabilityImageOptionsInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
Severity string `query:"severity" doc:"Comma-separated severity filter"`
}
-type ListAllVulnerabilityImageOptionsOutput struct {
- Body base.ApiResponse[[]string]
-}
-
type GetScannerStatusInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
}
@@ -121,10 +89,6 @@ type ScannerStatus struct {
Version string `json:"version,omitempty"`
}
-type GetScannerStatusOutput struct {
- Body base.ApiResponse[ScannerStatus]
-}
-
// RegisterVulnerability registers vulnerability scanning routes using Huma.
func RegisterVulnerability(api huma.API, vulnerabilityService *VulnerabilityService, appCtx handlerutil.ActivityAppContext) {
h := &VulnerabilityHandler{
@@ -254,7 +218,7 @@ func RegisterVulnerability(api huma.API, vulnerabilityService *VulnerabilityServ
}
// ScanImage initiates a vulnerability scan for an image.
-func (h *VulnerabilityHandler) ScanImage(ctx context.Context, input *ScanImageInput) (*ScanImageOutput, error) {
+func (h *VulnerabilityHandler) ScanImage(ctx context.Context, input *ScanImageInput) (*handlerutil.Out[vulnerability.ScanResult], error) {
user, err := handlerutil.RequireUser(ctx)
if err != nil {
return nil, err
@@ -266,7 +230,7 @@ func (h *VulnerabilityHandler) ScanImage(ctx context.Context, input *ScanImageIn
return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to scan image for vulnerabilities").Error())
}
- return &ScanImageOutput{
+ return &handlerutil.Out[vulnerability.ScanResult]{
Body: base.ApiResponse[vulnerability.ScanResult]{
Success: true,
Data: *result,
@@ -275,10 +239,10 @@ func (h *VulnerabilityHandler) ScanImage(ctx context.Context, input *ScanImageIn
}
// GetScanSummaries retrieves scan summaries for a list of image IDs.
-func (h *VulnerabilityHandler) GetScanSummaries(ctx context.Context, input *GetScanSummariesInput) (*GetScanSummariesOutput, error) {
+func (h *VulnerabilityHandler) GetScanSummaries(ctx context.Context, input *GetScanSummariesInput) (*handlerutil.Out[vulnerability.ScanSummariesResponse], error) {
imageIDs := input.Body.ImageIDs
if len(imageIDs) == 0 {
- return &GetScanSummariesOutput{
+ return &handlerutil.Out[vulnerability.ScanSummariesResponse]{
Body: base.ApiResponse[vulnerability.ScanSummariesResponse]{
Success: true,
Data: vulnerability.ScanSummariesResponse{
@@ -293,7 +257,7 @@ func (h *VulnerabilityHandler) GetScanSummaries(ctx context.Context, input *GetS
return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to scan image for vulnerabilities").Error())
}
- return &GetScanSummariesOutput{
+ return &handlerutil.Out[vulnerability.ScanSummariesResponse]{
Body: base.ApiResponse[vulnerability.ScanSummariesResponse]{
Success: true,
Data: vulnerability.ScanSummariesResponse{
@@ -304,7 +268,7 @@ func (h *VulnerabilityHandler) GetScanSummaries(ctx context.Context, input *GetS
}
// GetScanResult retrieves the vulnerability scan result for an image.
-func (h *VulnerabilityHandler) GetScanResult(ctx context.Context, input *GetScanResultInput) (*GetScanResultOutput, error) {
+func (h *VulnerabilityHandler) GetScanResult(ctx context.Context, input *GetScanResultInput) (*handlerutil.Out[vulnerability.ScanResult], error) {
result, err := h.vulnerabilityService.GetScanResult(ctx, input.ImageID)
if err != nil {
return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to retrieve vulnerability scan").Error())
@@ -314,7 +278,7 @@ func (h *VulnerabilityHandler) GetScanResult(ctx context.Context, input *GetScan
return nil, huma.Error404NotFound("Vulnerability scan not found")
}
- return &GetScanResultOutput{
+ return &handlerutil.Out[vulnerability.ScanResult]{
Body: base.ApiResponse[vulnerability.ScanResult]{
Success: true,
Data: *result,
@@ -323,7 +287,7 @@ func (h *VulnerabilityHandler) GetScanResult(ctx context.Context, input *GetScan
}
// GetScanSummary retrieves just the vulnerability summary for an image.
-func (h *VulnerabilityHandler) GetScanSummary(ctx context.Context, input *GetScanSummaryInput) (*GetScanSummaryOutput, error) {
+func (h *VulnerabilityHandler) GetScanSummary(ctx context.Context, input *GetScanSummaryInput) (*handlerutil.Out[vulnerability.ScanSummary], error) {
summary, err := h.vulnerabilityService.GetScanSummary(ctx, input.ImageID)
if err != nil {
return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to retrieve vulnerability scan").Error())
@@ -333,7 +297,7 @@ func (h *VulnerabilityHandler) GetScanSummary(ctx context.Context, input *GetSca
return nil, huma.Error404NotFound("Vulnerability scan not found")
}
- return &GetScanSummaryOutput{
+ return &handlerutil.Out[vulnerability.ScanSummary]{
Body: base.ApiResponse[vulnerability.ScanSummary]{
Success: true,
Data: *summary,
@@ -342,7 +306,7 @@ func (h *VulnerabilityHandler) GetScanSummary(ctx context.Context, input *GetSca
}
// ListImageVulnerabilities returns a paginated list of vulnerabilities for an image.
-func (h *VulnerabilityHandler) ListImageVulnerabilities(ctx context.Context, input *ListImageVulnerabilitiesInput) (*ListImageVulnerabilitiesOutput, error) {
+func (h *VulnerabilityHandler) ListImageVulnerabilities(ctx context.Context, input *ListImageVulnerabilitiesInput) (*handlerutil.Page[vulnerability.Vulnerability], error) {
params := handlerutil.PaginationParams(input.Start, input.Limit, input.Sort, input.Order, input.Search)
if params.Limit == 0 {
params.Limit = 20
@@ -363,7 +327,7 @@ func (h *VulnerabilityHandler) ListImageVulnerabilities(ctx context.Context, inp
items = []vulnerability.Vulnerability{}
}
- return &ListImageVulnerabilitiesOutput{
+ return &handlerutil.Page[vulnerability.Vulnerability]{
Body: base.Paginated[vulnerability.Vulnerability]{
Success: true,
Data: items,
@@ -373,7 +337,7 @@ func (h *VulnerabilityHandler) ListImageVulnerabilities(ctx context.Context, inp
}
// GetEnvironmentSummary returns aggregated vulnerability info for the current environment.
-func (h *VulnerabilityHandler) GetEnvironmentSummary(ctx context.Context, input *GetEnvironmentSummaryInput) (*GetEnvironmentSummaryOutput, error) {
+func (h *VulnerabilityHandler) GetEnvironmentSummary(ctx context.Context, input *GetEnvironmentSummaryInput) (*handlerutil.Out[vulnerability.EnvironmentVulnerabilitySummary], error) {
summary, err := h.vulnerabilityService.GetEnvironmentSummary(ctx)
if err != nil {
return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to retrieve vulnerability scan").Error())
@@ -383,7 +347,7 @@ func (h *VulnerabilityHandler) GetEnvironmentSummary(ctx context.Context, input
summary = &vulnerability.EnvironmentVulnerabilitySummary{}
}
- return &GetEnvironmentSummaryOutput{
+ return &handlerutil.Out[vulnerability.EnvironmentVulnerabilitySummary]{
Body: base.ApiResponse[vulnerability.EnvironmentVulnerabilitySummary]{
Success: true,
Data: *summary,
@@ -392,7 +356,7 @@ func (h *VulnerabilityHandler) GetEnvironmentSummary(ctx context.Context, input
}
// ListAllVulnerabilities returns a paginated list of vulnerabilities across all images.
-func (h *VulnerabilityHandler) ListAllVulnerabilities(ctx context.Context, input *ListAllVulnerabilitiesInput) (*ListAllVulnerabilitiesOutput, error) {
+func (h *VulnerabilityHandler) ListAllVulnerabilities(ctx context.Context, input *ListAllVulnerabilitiesInput) (*handlerutil.Page[vulnerability.VulnerabilityWithImage], error) {
params := handlerutil.PaginationParams(input.Start, input.Limit, input.Sort, input.Order, input.Search)
if params.Limit == 0 {
params.Limit = 20
@@ -416,7 +380,7 @@ func (h *VulnerabilityHandler) ListAllVulnerabilities(ctx context.Context, input
items = []vulnerability.VulnerabilityWithImage{}
}
- return &ListAllVulnerabilitiesOutput{
+ return &handlerutil.Page[vulnerability.VulnerabilityWithImage]{
Body: base.Paginated[vulnerability.VulnerabilityWithImage]{
Success: true,
Data: items,
@@ -426,7 +390,7 @@ func (h *VulnerabilityHandler) ListAllVulnerabilities(ctx context.Context, input
}
// ListAllVulnerabilityImageOptions returns available image options for vulnerability filtering.
-func (h *VulnerabilityHandler) ListAllVulnerabilityImageOptions(ctx context.Context, input *ListAllVulnerabilityImageOptionsInput) (*ListAllVulnerabilityImageOptionsOutput, error) {
+func (h *VulnerabilityHandler) ListAllVulnerabilityImageOptions(ctx context.Context, input *ListAllVulnerabilityImageOptionsInput) (*handlerutil.Out[[]string], error) {
items, err := h.vulnerabilityService.ListAllVulnerabilityImageOptions(ctx, input.Severity)
if err != nil {
return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to retrieve vulnerability scan").Error())
@@ -436,7 +400,7 @@ func (h *VulnerabilityHandler) ListAllVulnerabilityImageOptions(ctx context.Cont
items = []string{}
}
- return &ListAllVulnerabilityImageOptionsOutput{
+ return &handlerutil.Out[[]string]{
Body: base.ApiResponse[[]string]{
Success: true,
Data: items,
@@ -445,11 +409,11 @@ func (h *VulnerabilityHandler) ListAllVulnerabilityImageOptions(ctx context.Cont
}
// GetScannerStatus checks if the vulnerability scanner is available.
-func (h *VulnerabilityHandler) GetScannerStatus(ctx context.Context, input *GetScannerStatusInput) (*GetScannerStatusOutput, error) {
+func (h *VulnerabilityHandler) GetScannerStatus(ctx context.Context, input *GetScannerStatusInput) (*handlerutil.Out[ScannerStatus], error) {
version := h.vulnerabilityService.GetTrivyVersion(ctx)
available := version != ""
- return &GetScannerStatusOutput{
+ return &handlerutil.Out[ScannerStatus]{
Body: base.ApiResponse[ScannerStatus]{
Success: true,
Data: ScannerStatus{
@@ -465,12 +429,8 @@ type IgnoreVulnerabilityInput struct {
Body vulnerability.IgnorePayload
}
-type IgnoreVulnerabilityOutput struct {
- Body base.ApiResponse[vulnerability.IgnoredVulnerability]
-}
-
// IgnoreVulnerability creates an ignore record for a vulnerability.
-func (h *VulnerabilityHandler) IgnoreVulnerability(ctx context.Context, input *IgnoreVulnerabilityInput) (*IgnoreVulnerabilityOutput, error) {
+func (h *VulnerabilityHandler) IgnoreVulnerability(ctx context.Context, input *IgnoreVulnerabilityInput) (*handlerutil.Out[vulnerability.IgnoredVulnerability], error) {
user, err := handlerutil.RequireUser(ctx)
if err != nil {
return nil, err
@@ -487,7 +447,7 @@ func (h *VulnerabilityHandler) IgnoreVulnerability(ctx context.Context, input *I
return nil, huma.Error500InternalServerError(err.Error())
}
- return &IgnoreVulnerabilityOutput{
+ return &handlerutil.Out[vulnerability.IgnoredVulnerability]{
Body: base.ApiResponse[vulnerability.IgnoredVulnerability]{
Success: true,
Data: vulnerability.IgnoredVulnerability{
@@ -510,12 +470,8 @@ type UnignoreVulnerabilityInput struct {
IgnoreID string `path:"ignoreId" doc:"Ignore record ID"`
}
-type UnignoreVulnerabilityOutput struct {
- Body base.ApiResponse[struct{}]
-}
-
// UnignoreVulnerability removes an ignore record for a vulnerability.
-func (h *VulnerabilityHandler) UnignoreVulnerability(ctx context.Context, input *UnignoreVulnerabilityInput) (*UnignoreVulnerabilityOutput, error) {
+func (h *VulnerabilityHandler) UnignoreVulnerability(ctx context.Context, input *UnignoreVulnerabilityInput) (*handlerutil.Out[struct{}], error) {
if err := h.vulnerabilityService.UnignoreVulnerability(ctx, input.EnvironmentID, input.IgnoreID); err != nil {
if err.Error() == "ignore record not found" {
return nil, huma.Error404NotFound(err.Error())
@@ -523,7 +479,7 @@ func (h *VulnerabilityHandler) UnignoreVulnerability(ctx context.Context, input
return nil, huma.Error500InternalServerError(err.Error())
}
- return &UnignoreVulnerabilityOutput{
+ return &handlerutil.Out[struct{}]{
Body: base.ApiResponse[struct{}]{
Success: true,
},
@@ -539,12 +495,8 @@ type ListIgnoredVulnerabilitiesInput struct {
Limit int `query:"limit" doc:"Limit"`
}
-type ListIgnoredVulnerabilitiesOutput struct {
- Body base.Paginated[vulnerability.IgnoredVulnerability]
-}
-
// ListIgnoredVulnerabilities returns a list of ignored vulnerabilities.
-func (h *VulnerabilityHandler) ListIgnoredVulnerabilities(ctx context.Context, input *ListIgnoredVulnerabilitiesInput) (*ListIgnoredVulnerabilitiesOutput, error) {
+func (h *VulnerabilityHandler) ListIgnoredVulnerabilities(ctx context.Context, input *ListIgnoredVulnerabilitiesInput) (*handlerutil.Page[vulnerability.IgnoredVulnerability], error) {
params := handlerutil.PaginationParams(input.Start, input.Limit, input.Sort, input.Order, input.Search)
if params.Limit == 0 {
params.Limit = 20
@@ -559,7 +511,7 @@ func (h *VulnerabilityHandler) ListIgnoredVulnerabilities(ctx context.Context, i
items = []vulnerability.IgnoredVulnerability{}
}
- return &ListIgnoredVulnerabilitiesOutput{
+ return &handlerutil.Page[vulnerability.IgnoredVulnerability]{
Body: base.Paginated[vulnerability.IgnoredVulnerability]{
Success: true,
Data: items,
diff --git a/backend/internal/vulnerability/vulnerability_query.go b/backend/internal/vulnerability/vulnerability_query.go
index f03b6dfcb..32b3982f7 100644
--- a/backend/internal/vulnerability/vulnerability_query.go
+++ b/backend/internal/vulnerability/vulnerability_query.go
@@ -138,7 +138,7 @@ func (s *VulnerabilityService) ListVulnerabilities(ctx context.Context, imageID
},
}
- filtered := pagination.SearchOrderAndPaginate(result.Vulnerabilities, params, config)
+ filtered := config.SearchOrderAndPaginate(result.Vulnerabilities, params)
response := pagination.BuildResponse(filtered.TotalCount, filtered.TotalAvailable, params)
return filtered.Items, response, nil
@@ -368,7 +368,7 @@ func (s *VulnerabilityService) ListAllVulnerabilities(ctx context.Context, envID
ImageName: record.ImageName,
}
totalAvailable++
- if pagination.MatchesSearchAndFilters(item, params, config) {
+ if config.MatchesSearchAndFilters(item, params) {
items = append(items, item)
}
}
@@ -381,7 +381,7 @@ func (s *VulnerabilityService) ListAllVulnerabilities(ctx context.Context, envID
// Search and filters were already applied during decode; only sorting
// and page slicing remain.
- page := pagination.OrderAndPaginate(items, params, config)
+ page := config.OrderAndPaginate(items, params)
response := pagination.BuildResponse(int64(len(items)), int64(totalAvailable), params)
return page, response, nil
diff --git a/backend/internal/webhook/handler.go b/backend/internal/webhook/handler.go
index 79c6518c3..72ff048da 100644
--- a/backend/internal/webhook/handler.go
+++ b/backend/internal/webhook/handler.go
@@ -26,38 +26,22 @@ type ListWebhooksInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
}
-type ListWebhooksOutput struct {
- Body base.ApiResponse[[]webhook.Summary]
-}
-
type CreateWebhookInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
Body *webhook.CreateInput `required:"true"`
}
-type CreateWebhookOutput struct {
- Body base.ApiResponse[webhook.Created]
-}
-
type DeleteWebhookInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
WebhookID string `path:"webhookId" doc:"Webhook ID"`
}
-type DeleteWebhookOutput struct {
- Body base.ApiResponse[any]
-}
-
type UpdateWebhookInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
WebhookID string `path:"webhookId" doc:"Webhook ID"`
Body *webhook.UpdateInput `required:"true"`
}
-type UpdateWebhookOutput struct {
- Body base.ApiResponse[any]
-}
-
// RegisterWebhooks registers the authenticated CRUD routes for webhook management.
func RegisterWebhooks(api huma.API, webhookService *WebhookService) {
h := &WebhookHandler{webhookService: webhookService}
@@ -104,13 +88,13 @@ func RegisterWebhooks(api huma.API, webhookService *WebhookService) {
}
// ListWebhooks returns all webhooks for an environment (tokens are masked).
-func (h *WebhookHandler) ListWebhooks(ctx context.Context, input *ListWebhooksInput) (*ListWebhooksOutput, error) {
+func (h *WebhookHandler) ListWebhooks(ctx context.Context, input *ListWebhooksInput) (*handlerutil.Out[[]webhook.Summary], error) {
webhooks, err := h.webhookService.ListWebhookSummaries(ctx, input.EnvironmentID)
if err != nil {
return nil, huma.Error500InternalServerError("failed to list webhooks")
}
- return &ListWebhooksOutput{
+ return &handlerutil.Out[[]webhook.Summary]{
Body: base.ApiResponse[[]webhook.Summary]{
Success: true,
Data: webhooks,
@@ -119,7 +103,7 @@ func (h *WebhookHandler) ListWebhooks(ctx context.Context, input *ListWebhooksIn
}
// CreateWebhook creates a new webhook and returns the raw token (shown once only).
-func (h *WebhookHandler) CreateWebhook(ctx context.Context, input *CreateWebhookInput) (*CreateWebhookOutput, error) {
+func (h *WebhookHandler) CreateWebhook(ctx context.Context, input *CreateWebhookInput) (*handlerutil.Out[webhook.Created], error) {
if input.Body == nil {
return nil, huma.Error400BadRequest("request body is required")
}
@@ -151,7 +135,7 @@ func (h *WebhookHandler) CreateWebhook(ctx context.Context, input *CreateWebhook
return nil, huma.Error500InternalServerError("failed to create webhook")
}
- return &CreateWebhookOutput{
+ return &handlerutil.Out[webhook.Created]{
Body: base.ApiResponse[webhook.Created]{
Success: true,
Data: webhook.Created{
@@ -168,7 +152,7 @@ func (h *WebhookHandler) CreateWebhook(ctx context.Context, input *CreateWebhook
}
// UpdateWebhook updates a webhook's enabled state.
-func (h *WebhookHandler) UpdateWebhook(ctx context.Context, input *UpdateWebhookInput) (*UpdateWebhookOutput, error) {
+func (h *WebhookHandler) UpdateWebhook(ctx context.Context, input *UpdateWebhookInput) (*handlerutil.Out[any], error) {
if input.Body == nil {
return nil, huma.Error400BadRequest("request body is required")
}
@@ -187,13 +171,13 @@ func (h *WebhookHandler) UpdateWebhook(ctx context.Context, input *UpdateWebhook
}
_ = wh // updated record available if needed in future
- return &UpdateWebhookOutput{
+ return &handlerutil.Out[any]{
Body: base.ApiResponse[any]{Success: true},
}, nil
}
// DeleteWebhook removes a webhook.
-func (h *WebhookHandler) DeleteWebhook(ctx context.Context, input *DeleteWebhookInput) (*DeleteWebhookOutput, error) {
+func (h *WebhookHandler) DeleteWebhook(ctx context.Context, input *DeleteWebhookInput) (*handlerutil.Out[any], error) {
actor := common.User{}
if currentUser, exists := common.CurrentUserFromContext(ctx); exists && currentUser != nil {
actor = *currentUser
@@ -206,7 +190,7 @@ func (h *WebhookHandler) DeleteWebhook(ctx context.Context, input *DeleteWebhook
return nil, huma.Error500InternalServerError("failed to delete webhook")
}
- return &DeleteWebhookOutput{
+ return &handlerutil.Out[any]{
Body: base.ApiResponse[any]{
Success: true,
},
diff --git a/backend/pkg/libarcane/activity/writer.go b/backend/pkg/libarcane/activity/writer.go
index 3c385b465..abfe944b5 100644
--- a/backend/pkg/libarcane/activity/writer.go
+++ b/backend/pkg/libarcane/activity/writer.go
@@ -6,13 +6,13 @@ import (
"bytes"
"context"
"encoding/json/v2"
- "fmt"
"io"
"log/slog"
"net/http"
"strings"
"sync"
+ "github.com/getarcaneapp/arcane/backend/v2/pkg/utils"
activitytypes "github.com/getarcaneapp/arcane/types/v2/activity"
"github.com/samber/mo"
@@ -150,14 +150,14 @@ func (w *Writer) processLineInternal(line string) mo.Option[writerAppendMessage]
if errorValue, ok := payload["error"]; ok && errorValue != nil {
return mo.Some(writerAppendMessage{
level: activitytypes.MessageLevelError,
- message: valueToStringInternal(errorValue),
+ message: utils.ToString(errorValue),
payload: payload,
step: w.defaultStep,
})
}
if logValue, ok := payload["log"]; ok {
- message := valueToStringInternal(logValue)
+ message := utils.ToString(logValue)
if strings.TrimSpace(message) == "" {
return mo.None[writerAppendMessage]()
}
@@ -267,16 +267,3 @@ func doneInternal(ctx context.Context) <-chan struct{} {
}
return ctx.Done()
}
-
-func valueToStringInternal(value any) string {
- switch typed := value.(type) {
- case string:
- return typed
- case fmt.Stringer:
- return typed.String()
- case nil:
- return ""
- default:
- return fmt.Sprint(typed)
- }
-}
diff --git a/backend/pkg/libarcane/edge/registry.go b/backend/pkg/libarcane/edge/registry.go
index 861d0bf96..ee97f2b57 100644
--- a/backend/pkg/libarcane/edge/registry.go
+++ b/backend/pkg/libarcane/edge/registry.go
@@ -152,7 +152,7 @@ func (r *TunnelRegistry) RegisterSession(ctx context.Context, tunnel *AgentTunne
return false, false, "environment ID is required", nil
}
- result, err := actors.ApplyStateMap(ctx, r.tunnels, "register edge tunnel session", func(tunnels map[string]*AgentTunnel) (registerSessionResultInternal, bool, error) {
+ result, err := r.tunnels.ApplyTyped(ctx, "register edge tunnel session", func(tunnels map[string]*AgentTunnel) (registerSessionResultInternal, bool, error) {
var result registerSessionResultInternal
if existing := tunnels[envID]; existing != nil {
if existing == tunnel {
@@ -212,7 +212,7 @@ func (r *TunnelRegistry) UnregisterCurrent(ctx context.Context, envID string, cu
removed bool
activeReplacement bool
}
- result, err := actors.ApplyStateMap(ctx, r.tunnels, "unregister current edge tunnel", func(tunnels map[string]*AgentTunnel) (resultInternal, bool, error) {
+ result, err := r.tunnels.ApplyTyped(ctx, "unregister current edge tunnel", func(tunnels map[string]*AgentTunnel) (resultInternal, bool, error) {
var result resultInternal
existing := tunnels[envID]
if existing != current {
diff --git a/backend/pkg/pagination/db_utils.go b/backend/pkg/pagination/db_utils.go
index 3d5e02b06..b7c182ffd 100644
--- a/backend/pkg/pagination/db_utils.go
+++ b/backend/pkg/pagination/db_utils.go
@@ -43,7 +43,7 @@ func ApplyLikeSearch(q *gorm.DB, search string, condition string) *gorm.DB {
}
// PaginateSortAndMapDB paginates DB records and maps them to API DTOs.
-func PaginateSortAndMapDB[M any, D any](params QueryParams, query *gorm.DB, records *[]M) ([]D, Response, error) {
+func (params QueryParams) PaginateSortAndMapDB[M any, D any](query *gorm.DB, records *[]M) ([]D, Response, error) {
paginationResp, err := PaginateAndSortDB(params, query, records)
if err != nil {
return nil, Response{}, errors.WrapIf(err, "paginate db records")
diff --git a/backend/pkg/pagination/filters.go b/backend/pkg/pagination/filters.go
index eca171f1d..c1fe373bb 100644
--- a/backend/pkg/pagination/filters.go
+++ b/backend/pkg/pagination/filters.go
@@ -22,14 +22,14 @@ type Config[T any] struct {
FilterAccessors []FilterAccessor[T]
}
-func SearchOrderAndPaginate[T any](items []T, params QueryParams, searchConfig Config[T]) FilterResult[T] {
+func (c Config[T]) SearchOrderAndPaginate(items []T, params QueryParams) FilterResult[T] {
totalAvailable := len(items)
- items = searchFn(items, params.SearchQuery, searchConfig.SearchAccessors)
- items = filterFn(items, params.Filters, searchConfig.FilterAccessors)
+ items = searchFn(items, params.SearchQuery, c.SearchAccessors)
+ items = filterFn(items, params.Filters, c.FilterAccessors)
return FilterResult[T]{
- Items: OrderAndPaginate(items, params, searchConfig),
+ Items: c.OrderAndPaginate(items, params),
TotalCount: int64(len(items)),
TotalAvailable: int64(totalAvailable),
}
@@ -39,20 +39,20 @@ func SearchOrderAndPaginate[T any](items []T, params QueryParams, searchConfig C
// the search term or filters — for callers that already filtered while
// building the item list (e.g. dropping non-matches during an incremental
// decode) and only need ordering plus the page cut.
-func OrderAndPaginate[T any](items []T, params QueryParams, config Config[T]) []T {
- items = sortFunction(items, params.SortParams, config.SortBindings)
+func (c Config[T]) OrderAndPaginate(items []T, params QueryParams) []T {
+ items = sortFunction(items, params.SortParams, c.SortBindings)
return paginateItemsFunction(items, params.Params)
}
// MatchesSearchAndFilters reports whether a single item passes params' search
-// term and filters under config — the same predicate SearchOrderAndPaginate
+// term and filters under the config — the same predicate SearchOrderAndPaginate
// applies. It lets callers that decode large payloads incrementally drop
// non-matching items as they go instead of materializing everything first.
-func MatchesSearchAndFilters[T any](item T, params QueryParams, config Config[T]) bool {
+func (c Config[T]) MatchesSearchAndFilters(item T, params QueryParams) bool {
search := strings.ToLower(strings.TrimSpace(params.Search))
if search != "" {
matched := false
- for _, accessor := range config.SearchAccessors {
+ for _, accessor := range c.SearchAccessors {
value, err := accessor(item)
if err == nil && strings.Contains(strings.ToLower(value), search) {
matched = true
@@ -67,7 +67,7 @@ func MatchesSearchAndFilters[T any](item T, params QueryParams, config Config[T]
if len(params.Filters) == 0 {
return true
}
- return itemMatches(item, params.Filters, config.FilterAccessors)
+ return itemMatches(item, params.Filters, c.FilterAccessors)
}
func filterFn[T any](items []T, filters map[string]string, accessors []FilterAccessor[T]) []T {
diff --git a/backend/pkg/pagination/reflect.go b/backend/pkg/pagination/reflect.go
index 351e7da94..61b262b71 100644
--- a/backend/pkg/pagination/reflect.go
+++ b/backend/pkg/pagination/reflect.go
@@ -9,7 +9,7 @@ import (
"gorm.io/gorm/clause"
)
-func PaginateAndSortDB(params QueryParams, query *gorm.DB, result any) (Response, error) {
+func PaginateAndSortDB[M any](params QueryParams, query *gorm.DB, result *[]M) (Response, error) {
sortColumn := params.Sort
sortDirection := string(params.Order)
@@ -17,7 +17,7 @@ func PaginateAndSortDB(params QueryParams, query *gorm.DB, result any) (Response
sortDirection = "asc"
}
- modelType := reflect.TypeOf(result).Elem().Elem()
+ modelType := reflect.TypeFor[M]()
capitalizedSortColumn := stringutils.CapitalizeFirstLetter(sortColumn)
sortField, sortFieldFound := modelType.FieldByName(capitalizedSortColumn)
isSortable, _ := strconv.ParseBool(sortField.Tag.Get("sortable"))
@@ -67,7 +67,7 @@ func PaginateAndSortDB(params QueryParams, query *gorm.DB, result any) (Response
// paginateDBAll returns all results without pagination limits.
// When skipCount is true the COUNT(*) is elided and TotalItems/TotalPages are returned as UnknownTotal.
// Count runs before Find so it sees a clean session (Find sets Statement.Dest in GORM v2).
-func paginateDBAll(query *gorm.DB, result any, skipCount bool) (Response, error) {
+func paginateDBAll[M any](query *gorm.DB, result *[]M, skipCount bool) (Response, error) {
var totalItems int64
if !skipCount {
if err := query.Count(&totalItems).Error; err != nil {
@@ -99,7 +99,7 @@ func paginateDBAll(query *gorm.DB, result any, skipCount bool) (Response, error)
// paginateDB applies offset/limit pagination. When skipCount is true the COUNT(*) is elided
// and TotalItems/TotalPages are returned as UnknownTotal.
// Count runs before Find so it sees a clean session (Find sets Statement.Dest in GORM v2).
-func paginateDB(offset int, pageSize int, query *gorm.DB, result any, skipCount bool) (Response, error) {
+func paginateDB[M any](offset int, pageSize int, query *gorm.DB, result *[]M, skipCount bool) (Response, error) {
if offset < 0 {
offset = 0
}
diff --git a/backend/pkg/pagination/sort_test.go b/backend/pkg/pagination/sort_test.go
index d919512ff..4cb31738e 100644
--- a/backend/pkg/pagination/sort_test.go
+++ b/backend/pkg/pagination/sort_test.go
@@ -143,10 +143,10 @@ func TestSearchOrderAndPaginateStablePageWalkAcrossReorderedInput(t *testing.T)
shuffled := slices.Clone(source)
r.Shuffle(len(shuffled), func(i, j int) { shuffled[i], shuffled[j] = shuffled[j], shuffled[i] })
- result := SearchOrderAndPaginate(shuffled, QueryParams{
+ result := config.SearchOrderAndPaginate(shuffled, QueryParams{
Sort: sort,
Start: start, Limit: limit,
- }, config)
+ })
for _, item := range result.Items {
seen[item.ID]++
}
diff --git a/backend/pkg/remenv/client.go b/backend/pkg/remenv/client.go
index dab222282..44f4af4b0 100644
--- a/backend/pkg/remenv/client.go
+++ b/backend/pkg/remenv/client.go
@@ -110,17 +110,18 @@ func (c *Client) Do(ctx context.Context, req Request) (*Response, error) {
return c.doDirectHTTPInternal(ctx, req)
}
-func (c *Client) DoJSON(ctx context.Context, req Request, out any) error {
+func (c *Client) DoJSON[T any](ctx context.Context, req Request) (T, error) {
+ var zero T
resp, err := c.Do(ctx, req)
if err != nil {
- return err
+ return zero, err
}
if err := resp.RequireSuccess(); err != nil {
- return err
+ return zero, err
}
- return resp.DecodeJSON(out)
+ return resp.DecodeJSON[T]()
}
func (c *Client) doViaTunnelInternal(ctx context.Context, req Request) (*Response, error) {
@@ -188,17 +189,15 @@ func (r *Response) RequireSuccess() error {
}
}
-func (r *Response) DecodeJSON(out any) error {
- if out == nil {
- return nil
- }
+func (r *Response) DecodeJSON[T any]() (T, error) {
+ var out T
if r == nil {
- return &DecodeError{Err: errors.New("response is nil")}
+ return out, &DecodeError{Err: errors.New("response is nil")}
}
- if err := json.Unmarshal(r.Body, out); err != nil {
- return &DecodeError{Err: err}
+ if err := json.Unmarshal(r.Body, &out); err != nil {
+ return out, &DecodeError{Err: err}
}
- return nil
+ return out, nil
}
type TransportError struct {
diff --git a/backend/pkg/remenv/client_test.go b/backend/pkg/remenv/client_test.go
index 8e218ba7c..99429d70b 100644
--- a/backend/pkg/remenv/client_test.go
+++ b/backend/pkg/remenv/client_test.go
@@ -114,22 +114,20 @@ func TestClientDoJSON_ClassifiesStatusAndDecodeErrors(t *testing.T) {
client := NewClient(server.Client(), nil)
- var statusOut map[string]any
- err := client.DoJSON(context.Background(), Request{
+ _, err := client.DoJSON[map[string]any](context.Background(), Request{
Method: http.MethodGet,
URL: server.URL + "/status",
Path: "/status",
- }, &statusOut)
+ })
var statusErr *StatusError
require.ErrorAs(t, err, &statusErr)
require.Equal(t, http.StatusBadGateway, statusErr.StatusCode)
- var decodeOut map[string]any
- err = client.DoJSON(context.Background(), Request{
+ _, err = client.DoJSON[map[string]any](context.Background(), Request{
Method: http.MethodGet,
URL: server.URL + "/decode",
Path: "/decode",
- }, &decodeOut)
+ })
var decodeErr *DecodeError
require.ErrorAs(t, err, &decodeErr)
}
diff --git a/backend/pkg/scheduler/image_update_watcher.go b/backend/pkg/scheduler/image_update_watcher.go
index 41d3cc853..2542c0a5c 100644
--- a/backend/pkg/scheduler/image_update_watcher.go
+++ b/backend/pkg/scheduler/image_update_watcher.go
@@ -254,9 +254,8 @@ func (w *ImageUpdateWatcher) RunNow(ctx context.Context) error {
return errors.New("image update watcher is not running")
}
- admission, err := actors.Request[imageUpdateMessageKindInternal, context.Context, *actors.Promise[error]](
+ admission, err := process.Request[imageUpdateMessageKindInternal, context.Context, *actors.Promise[error]](
ctx,
- process,
actors.Message[imageUpdateMessageKindInternal, context.Context]{Kind: imageUpdateManualScanRequestMessageInternal, Value: ctx},
)
if err != nil {
diff --git a/backend/pkg/utils/backupbrowser/browser.go b/backend/pkg/utils/backupbrowser/browser.go
index 696c6b7d3..898182a51 100644
--- a/backend/pkg/utils/backupbrowser/browser.go
+++ b/backend/pkg/utils/backupbrowser/browser.go
@@ -111,14 +111,15 @@ func compareEntriesInternal(left, right backuptypes.BackupFileEntry) int {
// Browse searches, orders, and paginates backup entries using the standard pagination contract.
func Browse(entries []backuptypes.BackupFileEntry, params pagination.QueryParams) ([]backuptypes.BackupFileEntry, pagination.Response) {
- result := pagination.SearchOrderAndPaginate(entries, params, pagination.Config[backuptypes.BackupFileEntry]{
+ config := pagination.Config[backuptypes.BackupFileEntry]{
SearchAccessors: []pagination.SearchAccessor[backuptypes.BackupFileEntry]{
func(entry backuptypes.BackupFileEntry) (string, error) { return entry.Path, nil },
},
SortBindings: []pagination.SortBinding[backuptypes.BackupFileEntry]{
{Key: "path", Fn: compareEntriesInternal},
},
- })
+ }
+ result := config.SearchOrderAndPaginate(entries, params)
return result.Items, pagination.BuildResponse(result.TotalCount, result.TotalAvailable, params)
}
diff --git a/backend/pkg/utils/fingerprint.go b/backend/pkg/utils/fingerprint.go
index 68c579053..123646f49 100644
--- a/backend/pkg/utils/fingerprint.go
+++ b/backend/pkg/utils/fingerprint.go
@@ -105,14 +105,13 @@ func (f *Fingerprint) Sum() uint64 {
return f.h.Sum64()
}
-// FingerprintOf hashes a slice of items with a per-item writer, including the
-// slice length so resizing or reordering changes the result. The writer receives
-// a pointer so large structs are not copied per item.
-func FingerprintOf[T any](items []T, write func(*Fingerprint, *T)) uint64 {
- f := NewFingerprint()
+// Slice hashes a slice of items with a per-item writer, including the slice
+// length so resizing or reordering changes the result. The writer receives a
+// pointer so large structs are not copied per item.
+func (f *Fingerprint) Slice[T any](items []T, write func(*Fingerprint, *T)) *Fingerprint {
f.Int(int64(len(items)))
for i := range items {
write(f, &items[i])
}
- return f.Sum()
+ return f
}
diff --git a/backend/pkg/utils/handlerutil/handlerutil.go b/backend/pkg/utils/handlerutil/handlerutil.go
index f5563ce6b..99e5aeb38 100644
--- a/backend/pkg/utils/handlerutil/handlerutil.go
+++ b/backend/pkg/utils/handlerutil/handlerutil.go
@@ -19,6 +19,18 @@ import (
"github.com/getarcaneapp/arcane/types/v2/base"
)
+// Out is the huma response envelope for endpoints returning base.ApiResponse[T].
+// It replaces the per-endpoint `type XxxOutput struct { Body base.ApiResponse[T] }`
+// wrappers; outputs carrying extra fields (headers, status) keep their own type.
+type Out[T any] struct {
+ Body base.ApiResponse[T]
+}
+
+// Page is the huma response envelope for endpoints returning base.Paginated[T].
+type Page[T any] struct {
+ Body base.Paginated[T]
+}
+
// ActivityAppContext carries the app lifecycle context through handler registration.
type ActivityAppContext struct {
ctx context.Context
diff --git a/backend/pkg/utils/handlerutil/remote_proxy.go b/backend/pkg/utils/handlerutil/remote_proxy.go
index 11bc6a52a..6279612c6 100644
--- a/backend/pkg/utils/handlerutil/remote_proxy.go
+++ b/backend/pkg/utils/handlerutil/remote_proxy.go
@@ -12,10 +12,9 @@ import (
// RemoteJSONProxy is the remote environment transport operation used by domain handlers.
type RemoteJSONProxy func(context.Context, string, string, string, []byte, any) error
-// ProxyRemoteJSON marshals a request, invokes an environment proxy, and translates transport errors for Huma.
-func ProxyRemoteJSON[T any](
+// JSON marshals a request, invokes the environment proxy, and translates transport errors for Huma.
+func (p RemoteJSONProxy) JSON[T any](
ctx context.Context,
- proxy RemoteJSONProxy,
environmentID string,
method string,
path string,
@@ -27,7 +26,7 @@ func ProxyRemoteJSON[T any](
}
var output T
- if err := proxy(ctx, environmentID, method, path, body, &output); err != nil {
+ if err := p(ctx, environmentID, method, path, body, &output); err != nil {
return nil, TranslateRemoteProxyError(err)
}
diff --git a/backend/pkg/utils/jwtclaims/jwt.go b/backend/pkg/utils/jwtclaims/jwt.go
index cc483162f..d1ae7f5dd 100644
--- a/backend/pkg/utils/jwtclaims/jwt.go
+++ b/backend/pkg/utils/jwtclaims/jwt.go
@@ -8,6 +8,7 @@ import (
"emperror.dev/errors"
+ "github.com/getarcaneapp/arcane/backend/v2/pkg/utils"
"github.com/samber/mo"
"github.com/samber/mo/result"
)
@@ -45,28 +46,32 @@ func GetBoolClaim(m map[string]any, key string) bool {
return false
}
-// GetStringSliceClaim extracts a string slice claim from a map
-func GetStringSliceClaim(m map[string]any, key string) []string {
- return StringSliceFromClaimValue(m[key])
-}
-
-// StringSliceFromClaimValue flattens a claim value into a slice of strings.
-// Accepts string (comma or space separated), []string, []any, or nil.
-func StringSliceFromClaimValue(v any) []string {
+// StringSliceFromValue flattens a claim value into a slice of strings.
+// Accepts string (trimmed, single element), []string, []any (string elements
+// only), or nil. Unlike GetStringSliceClaim it never splits a single string
+// into multiple values, so it is safe for claims whose values may legally
+// contain separators (e.g. aud URIs).
+func StringSliceFromValue(v any) []string {
switch t := v.(type) {
case []string:
- return t
+ return stringSliceFromStringsInternal(t)
case []any:
- out := make([]string, 0, len(t))
- for _, it := range t {
- if s, ok := it.(string); ok && s != "" {
- out = append(out, s)
- }
- }
- if len(out) > 0 {
- return out
- }
+ return stringSliceFromInterfacesInternal(t)
case string:
+ return stringSliceFromStringsInternal([]string{t})
+ }
+ return nil
+}
+
+// GetStringSliceClaim extracts a string slice claim from a map. A single
+// string value is split on commas or spaces (group/role claims are commonly
+// delivered that way).
+func GetStringSliceClaim(m map[string]any, key string) []string {
+ v, ok := m[key]
+ if !ok || v == nil {
+ return nil
+ }
+ if t, ok := v.(string); ok {
s := strings.TrimSpace(t)
if s == "" {
return nil
@@ -86,7 +91,29 @@ func StringSliceFromClaimValue(v any) []string {
}
return strings.Fields(s)
}
- return nil
+ return StringSliceFromValue(v)
+}
+
+func stringSliceFromStringsInternal[S ~string](items []S) []string {
+ out := make([]string, 0, len(items))
+ for _, item := range items {
+ if s := strings.TrimSpace(string(item)); s != "" {
+ out = append(out, s)
+ }
+ }
+ return utils.UniqueNonEmptyStrings(out)
+}
+
+func stringSliceFromInterfacesInternal[T any](items []T) []string {
+ out := make([]string, 0, len(items))
+ for _, item := range items {
+ if s, ok := any(item).(string); ok {
+ if trimmed := strings.TrimSpace(s); trimmed != "" {
+ out = append(out, trimmed)
+ }
+ }
+ }
+ return utils.UniqueNonEmptyStrings(out)
}
// ParseJWTClaims decodes and unmarshals the payload part of a JWT
diff --git a/backend/pkg/utils/mapper/mapper.go b/backend/pkg/utils/mapper/mapper.go
index f542d26e9..6fde831be 100644
--- a/backend/pkg/utils/mapper/mapper.go
+++ b/backend/pkg/utils/mapper/mapper.go
@@ -59,7 +59,7 @@ func MapOne[S any, D any](source S) (D, error) {
return dest, nil
}
-func MapStruct(source any, destination any) error {
+func MapStruct[S any, D any](source S, destination *D) error {
return copier.CopyWithOption(destination, source, copier.Option{
DeepCopy: true,
Converters: typeConverters,
diff --git a/backend/pkg/utils/reflection.go b/backend/pkg/utils/reflection.go
index cbc135db6..ddfd5fefd 100644
--- a/backend/pkg/utils/reflection.go
+++ b/backend/pkg/utils/reflection.go
@@ -38,13 +38,13 @@ func ParseKeywords(keywordsStr string) []string {
return keywords
}
-// ExtractCategoryMetadata extracts category metadata from struct fields with catmeta tags
+// ExtractCategoryMetadata extracts category metadata from T's fields with catmeta tags
// Returns a map of category ID to category metadata in field order
-func ExtractCategoryMetadata(model any, categoryIDsInOrder []string) map[string]map[string]string {
+func ExtractCategoryMetadata[T any]() map[string]map[string]string {
result := make(map[string]map[string]string)
seenCategories := make(map[string]bool)
- rt := reflect.TypeOf(model)
+ rt := reflect.TypeFor[T]()
for field := range rt.Fields() {
catmetaTag := field.Tag.Get("catmeta")
if catmetaTag == "" {
diff --git a/cli/internal/ci/ci_detect.go b/cli/internal/ci/ci_detect.go
index a51e4e9ec..ebef9b313 100644
--- a/cli/internal/ci/ci_detect.go
+++ b/cli/internal/ci/ci_detect.go
@@ -2,7 +2,7 @@ package ci
import (
"context"
- "encoding/json"
+ "encoding/json/v2"
"io"
"net/http"
"net/url"
diff --git a/cli/internal/client/client.go b/cli/internal/client/client.go
index 45e8edafe..720549835 100644
--- a/cli/internal/client/client.go
+++ b/cli/internal/client/client.go
@@ -25,7 +25,8 @@ package client
import (
"bytes"
"context"
- "encoding/json"
+ "encoding/json/jsontext"
+ "encoding/json/v2"
stderrors "errors"
"io"
"net"
@@ -254,7 +255,7 @@ func (c *Client) Request(ctx context.Context, method, path string, body any) (*h
switch v := body.(type) {
case []byte:
bodyBytes = v
- case json.RawMessage:
+ case jsontext.Value:
bodyBytes = v
case io.Reader:
// Streaming bodies cannot be replayed, so skip auto-refresh.
@@ -566,26 +567,48 @@ func (c *Client) DeleteWithBody(ctx context.Context, path string, body any) (*ht
return c.Request(ctx, http.MethodDelete, path, body)
}
-// DoJSON performs a request and decodes a standard API envelope into out.
-func (c *Client) DoJSON(ctx context.Context, method, path string, body any, out any) error {
+// DoJSON performs a request and decodes the response JSON, enforcing a
+// successful HTTP status. Unlike GetJSON/PostJSON it does not require the
+// standard API envelope or its Success flag.
+func (c *Client) DoJSON[T any](ctx context.Context, method, path string, body any) (T, error) {
+ var out T
resp, err := c.Request(ctx, method, path, body)
if err != nil {
- return err
+ return out, err
}
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
b, _ := io.ReadAll(io.LimitReader(resp.Body, maxErrorBody))
- return errors.Errorf("request failed with status %d: %s", resp.StatusCode, strings.TrimSpace(string(b)))
+ return out, errors.Errorf("request failed with status %d: %s", resp.StatusCode, strings.TrimSpace(string(b)))
}
- if out == nil {
- return nil
+ if err := json.UnmarshalRead(resp.Body, &out); err != nil {
+ return out, errors.WrapIf(err, "failed to decode response")
}
- if err := json.NewDecoder(resp.Body).Decode(out); err != nil {
- return errors.WrapIf(err, "failed to decode response")
+ return out, nil
+}
+
+// GetJSON performs a GET and decodes the standard API envelope, enforcing
+// HTTP and API success.
+func (c *Client) GetJSON[T any](ctx context.Context, path string) (*APIResponse[T], error) {
+ resp, err := c.Get(ctx, path)
+ if err != nil {
+ return nil, err
}
- return nil
+ defer func() { _ = resp.Body.Close() }()
+ return decodeResponseStrictInternal[T](resp)
+}
+
+// PostJSON performs a POST with a JSON body and decodes the standard API
+// envelope, enforcing HTTP and API success.
+func (c *Client) PostJSON[T any](ctx context.Context, path string, body any) (*APIResponse[T], error) {
+ resp, err := c.Post(ctx, path, body)
+ if err != nil {
+ return nil, err
+ }
+ defer func() { _ = resp.Body.Close() }()
+ return decodeResponseStrictInternal[T](resp)
}
// DoRaw performs a request and returns the response payload when status is 2xx.
@@ -608,14 +631,33 @@ func (c *Client) DoRaw(ctx context.Context, method, path string, body any) ([]by
return b, nil
}
-// DecodeResponseStrict decodes an API response into the given type and enforces
-// HTTP and API success. It reads the response body, unmarshals it as JSON, and
-// returns the typed result. If the response indicates failure (Success=false) or
-// carries a non-2xx status code, an error is returned with the message from the
-// API. Note: This function closes the response body.
-func DecodeResponseStrict[T any](resp *http.Response) (*APIResponse[T], error) {
+// PutJSON performs a PUT with a JSON body and decodes the standard API
+// envelope, enforcing HTTP and API success.
+func (c *Client) PutJSON[T any](ctx context.Context, path string, body any) (*APIResponse[T], error) {
+ resp, err := c.Put(ctx, path, body)
+ if err != nil {
+ return nil, err
+ }
+ defer func() { _ = resp.Body.Close() }()
+ return decodeResponseStrictInternal[T](resp)
+}
+
+// DeleteJSON performs a DELETE and decodes the standard API envelope,
+// enforcing HTTP and API success.
+func (c *Client) DeleteJSON[T any](ctx context.Context, path string) (*APIResponse[T], error) {
+ resp, err := c.Delete(ctx, path)
+ if err != nil {
+ return nil, err
+ }
defer func() { _ = resp.Body.Close() }()
+ return decodeResponseStrictInternal[T](resp)
+}
+// decodeResponseStrictInternal decodes an API response into the given type and
+// enforces HTTP and API success. If the response indicates failure
+// (Success=false) or carries a non-2xx status code, an error is returned with
+// the message from the API. The caller owns the response body.
+func decodeResponseStrictInternal[T any](resp *http.Response) (*APIResponse[T], error) {
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
body, _ := io.ReadAll(io.LimitReader(resp.Body, maxErrorBody))
return nil, errors.Errorf("request failed with status %d: %s", resp.StatusCode, strings.TrimSpace(string(body)))
diff --git a/cli/internal/client/retry_test.go b/cli/internal/client/retry_test.go
index 83b4d5ff0..464e2a08e 100644
--- a/cli/internal/client/retry_test.go
+++ b/cli/internal/client/retry_test.go
@@ -99,9 +99,8 @@ func TestClient_DoJSON_StrictStatus(t *testing.T) {
require.NoError(t, err,
"New() error: %v", err)
- var out map[string]any
{
- err := c.DoJSON(context.Background(), http.MethodGet, "/api/version", nil, &out)
+ _, err := c.DoJSON[map[string]any](context.Background(), http.MethodGet, "/api/version", nil)
require.Error(t, err,
"expected strict status error")
}
@@ -117,7 +116,7 @@ func TestDecodeResponseStrict_RequiresSuccessEnvelope(t *testing.T) {
resp := rec.Result()
{
- _, err := DecodeResponseStrict[map[string]any](resp)
+ _, err := decodeResponseStrictInternal[map[string]any](resp)
require.Error(t, err,
"expected envelope failure")
}
diff --git a/cli/internal/cmdutil/resolve.go b/cli/internal/cmdutil/resolve.go
new file mode 100644
index 000000000..8d37d70a3
--- /dev/null
+++ b/cli/internal/cmdutil/resolve.go
@@ -0,0 +1,265 @@
+package cmdutil
+
+import (
+ "context"
+ "encoding/json/v2"
+ "fmt"
+ "io"
+ "net/http"
+ "net/url"
+ "strings"
+
+ "emperror.dev/errors"
+ "github.com/getarcaneapp/arcane/cli/v2/internal/client"
+ "github.com/getarcaneapp/arcane/cli/v2/internal/prompt"
+ "github.com/getarcaneapp/arcane/types/v2/base"
+)
+
+// MaxPromptOptions caps how many search matches the resolver offers
+// interactively before asking the user to refine the query instead.
+const MaxPromptOptions = 20
+
+// ResourceRef describes how one resource kind is resolved from a name, ID, or
+// prefix. D is the detail type returned by the GET-by-identifier endpoint and
+// S the summary type returned by the list endpoint.
+type ResourceRef[D any, S any] struct {
+ // Singular and Plural name the resource in prompts and error messages
+ // ("container", "containers").
+ Singular string
+ Plural string
+ // IDHint completes "use <IDHint> or run `<ListCmd>`" guidance
+ // ("the container ID", "the volume name").
+ IDHint string
+ ListCmd string
+
+ // GetPath builds the GET-by-identifier path; ListPath the list endpoint
+ // that Resolve queries with ?search=<identifier>&limit=-1.
+ GetPath func(envID, identifier string) string
+ ListPath func(envID string) string
+ // SearchCandidates replaces the standard list search for resources with
+ // specialized matching rules.
+ SearchCandidates func(context.Context, *client.Client, string) ([]S, error)
+ // SelectCandidate replaces the standard ambiguity handling while keeping
+ // direct lookup and not-found behavior in Resolve.
+ SelectCandidate func([]S, string, bool) (*S, error)
+ // Validate checks a successful direct lookup before Resolve returns it.
+ Validate func(D, string) error
+
+ // Matches reports whether a listed item matches the identifier.
+ Matches func(item S, identifierLower, original string) bool
+ // Label renders one match as an interactive prompt option.
+ Label func(S) string
+ // Promote converts a selected summary into the detail shape.
+ Promote func(S) *D
+
+ // IDOf enables the last-resort ID-prefix scan over the full list for
+ // resources addressed by opaque IDs (containers, images). Leave nil to
+ // skip that fallback.
+ IDOf func(S) string
+
+ // Exact optionally reports an exact identifier match. When set and
+ // exactly one search match is exact, it wins without prompting even if
+ // broader substring matches exist.
+ Exact func(item S, identifierLower, original string) bool
+}
+
+// Resolve finds one resource by exact identifier or search. The bool result
+// reports whether the returned details are complete (fetched from the
+// GET-by-identifier endpoint) rather than promoted from a list row.
+func (ref ResourceRef[D, S]) Resolve(ctx context.Context, c *client.Client, identifier string, allowPrompt bool) (*D, bool, error) {
+ trimmed := strings.TrimSpace(identifier)
+ if trimmed == "" {
+ return nil, false, errors.Errorf("%s identifier is required", ref.Singular)
+ }
+
+ details, found, err := ref.fetchByIdentifierInternal(ctx, c, trimmed)
+ if err != nil {
+ return nil, false, err
+ }
+ if found {
+ return details, true, nil
+ }
+
+ var matches []S
+ if ref.SearchCandidates != nil {
+ matches, err = ref.SearchCandidates(ctx, c, trimmed)
+ } else {
+ matches, err = ref.searchMatchesInternal(ctx, c, trimmed)
+ }
+ if err != nil {
+ return nil, false, err
+ }
+
+ if ref.Exact != nil && len(matches) > 1 {
+ identifierLower := strings.ToLower(trimmed)
+ exact := make([]S, 0, 1)
+ for _, match := range matches {
+ if ref.Exact(match, identifierLower, trimmed) {
+ exact = append(exact, match)
+ }
+ }
+ if len(exact) == 1 {
+ matches = exact
+ }
+ }
+
+ selected, err := ref.selectCandidateInternal(matches, trimmed, allowPrompt)
+ if err != nil {
+ return nil, false, err
+ }
+ if selected != nil {
+ return ref.Promote(*selected), false, nil
+ }
+
+ if ref.IDOf != nil {
+ identifierLower := strings.ToLower(trimmed)
+ if LooksLikeIDPrefix(identifierLower) {
+ fallbackMatches, err := ref.fallbackByIDPrefixInternal(ctx, c, identifierLower)
+ if err != nil {
+ return nil, false, err
+ }
+ selected, err := ref.selectCandidateInternal(fallbackMatches, trimmed, allowPrompt)
+ if err != nil {
+ return nil, false, err
+ }
+ if selected != nil {
+ return ref.Promote(*selected), false, nil
+ }
+ }
+ }
+
+ return nil, false, errors.Errorf("%s %q not found; use %s or run `%s`", ref.Singular, trimmed, ref.IDHint, ref.ListCmd)
+}
+
+func (ref ResourceRef[D, S]) fetchByIdentifierInternal(ctx context.Context, c *client.Client, identifier string) (*D, bool, error) {
+ resp, err := c.Get(ctx, ref.GetPath(c.EnvID(), identifier))
+ if err != nil {
+ return nil, false, errors.WrapIff(err, "failed to resolve %s %q", ref.Singular, identifier)
+ }
+
+ body, err := io.ReadAll(resp.Body)
+ _ = resp.Body.Close()
+ if err != nil {
+ return nil, false, errors.WrapIff(err, "failed to read %s response", ref.Singular)
+ }
+
+ if resp.StatusCode == http.StatusOK {
+ var result base.ApiResponse[D]
+ if err := json.Unmarshal(body, &result); err != nil {
+ return nil, false, errors.WrapIff(err, "failed to parse %s response", ref.Singular)
+ }
+ if ref.Validate != nil {
+ if err := ref.Validate(result.Data, identifier); err != nil {
+ return nil, false, err
+ }
+ }
+ return &result.Data, true, nil
+ }
+
+ if resp.StatusCode != http.StatusNotFound {
+ return nil, false, errors.Errorf("failed to resolve %s %q (status %d): %s", ref.Singular, identifier, resp.StatusCode, strings.TrimSpace(string(body)))
+ }
+
+ return nil, false, nil
+}
+
+func (ref ResourceRef[D, S]) searchMatchesInternal(ctx context.Context, c *client.Client, identifier string) ([]S, error) {
+ searchPath := fmt.Sprintf("%s?search=%s&limit=%d", ref.ListPath(c.EnvID()), url.QueryEscape(identifier), ShowAllLimit)
+ items, err := ref.listItemsInternal(ctx, c, searchPath)
+ if err != nil {
+ return nil, err
+ }
+
+ identifierLower := strings.ToLower(identifier)
+ matches := make([]S, 0)
+ for _, item := range items {
+ if ref.Matches(item, identifierLower, identifier) {
+ matches = append(matches, item)
+ }
+ }
+ return matches, nil
+}
+
+func (ref ResourceRef[D, S]) selectCandidateInternal(matches []S, identifier string, allowPrompt bool) (*S, error) {
+ if ref.SelectCandidate != nil {
+ return ref.SelectCandidate(matches, identifier, allowPrompt)
+ }
+ return ref.selectMatchInternal(matches, identifier, allowPrompt)
+}
+
+func (ref ResourceRef[D, S]) selectMatchInternal(matches []S, identifier string, allowPrompt bool) (*S, error) {
+ if len(matches) == 1 {
+ return &matches[0], nil
+ }
+ if len(matches) == 0 {
+ return nil, nil
+ }
+
+ if !allowPrompt {
+ return nil, errors.Errorf("multiple %s match %q; use %s or run `%s`", ref.Plural, identifier, ref.IDHint, ref.ListCmd)
+ }
+ if len(matches) > MaxPromptOptions {
+ return nil, errors.Errorf("multiple %s match %q (%d results); refine your query or use %s", ref.Plural, identifier, len(matches), ref.IDHint)
+ }
+
+ options := make([]string, 0, len(matches))
+ for _, match := range matches {
+ options = append(options, ref.Label(match))
+ }
+ choice, err := prompt.Select(ref.Singular, options)
+ if err != nil {
+ return nil, err
+ }
+ return &matches[choice], nil
+}
+
+func (ref ResourceRef[D, S]) fallbackByIDPrefixInternal(ctx context.Context, c *client.Client, identifierLower string) ([]S, error) {
+ items, err := ref.listItemsInternal(ctx, c, fmt.Sprintf("%s?limit=%d", ref.ListPath(c.EnvID()), ShowAllLimit))
+ if err != nil {
+ return nil, err
+ }
+ matches := make([]S, 0)
+ for _, item := range items {
+ if strings.HasPrefix(strings.ToLower(ref.IDOf(item)), identifierLower) {
+ matches = append(matches, item)
+ }
+ }
+ return matches, nil
+}
+
+func (ref ResourceRef[D, S]) listItemsInternal(ctx context.Context, c *client.Client, path string) ([]S, error) {
+ resp, err := c.Get(ctx, path)
+ if err != nil {
+ return nil, errors.WrapIff(err, "failed to search %s", ref.Plural)
+ }
+
+ body, err := io.ReadAll(resp.Body)
+ _ = resp.Body.Close()
+ if err != nil {
+ return nil, errors.WrapIff(err, "failed to read %s response", ref.Plural)
+ }
+
+ if resp.StatusCode < 200 || resp.StatusCode >= 300 {
+ return nil, errors.Errorf("failed to search %s (status %d): %s", ref.Plural, resp.StatusCode, strings.TrimSpace(string(body)))
+ }
+
+ var result base.Paginated[S]
+ if err := json.Unmarshal(body, &result); err != nil {
+ return nil, errors.WrapIff(err, "failed to parse %s response", ref.Plural)
+ }
+ return result.Data, nil
+}
+
+// LooksLikeIDPrefix reports whether identifier could be a hex ID prefix worth
+// scanning the full list for.
+func LooksLikeIDPrefix(identifierLower string) bool {
+ if len(identifierLower) < 4 {
+ return false
+ }
+ for _, r := range identifierLower {
+ if (r < '0' || r > '9') && (r < 'a' || r > 'f') {
+ return false
+ }
+ }
+ return true
+}
diff --git a/cli/internal/cmdutil/response.go b/cli/internal/cmdutil/response.go
index c6e075f97..b004c6699 100644
--- a/cli/internal/cmdutil/response.go
+++ b/cli/internal/cmdutil/response.go
@@ -2,7 +2,8 @@ package cmdutil
import (
"bytes"
- "encoding/json"
+ "encoding/json/jsontext"
+ "encoding/json/v2"
"fmt"
"io"
"net/http"
@@ -50,7 +51,7 @@ func DecodeJSON[T any](resp *http.Response, out *T) error {
if out == nil {
return errors.New("nil decode target")
}
- if err := json.NewDecoder(resp.Body).Decode(out); err != nil {
+ if err := json.UnmarshalRead(resp.Body, out); err != nil {
return errors.WrapIf(err, "failed to parse response")
}
return nil
@@ -74,9 +75,9 @@ func ReadJSONBody(resp *http.Response) ([]byte, error) {
// PrintRawJSON pretty-prints a raw JSON document, falling back to the bytes as-is.
func PrintRawJSON(body []byte) error {
- var buf bytes.Buffer
- if json.Indent(&buf, body, "", " ") == nil {
- fmt.Println(buf.String())
+ value := jsontext.Value(bytes.Clone(body))
+ if value.Indent(jsontext.WithIndent(" ")) == nil {
+ fmt.Println(value.String())
return nil
}
// Not valid JSON: echo the server's bytes verbatim rather than swallow them.
@@ -86,7 +87,7 @@ func PrintRawJSON(body []byte) error {
// PrintJSON prints indented JSON to stdout.
func PrintJSON(v any) error {
- b, err := json.MarshalIndent(v, "", " ")
+ b, err := json.Marshal(v, jsontext.WithIndent(" "))
if err != nil {
return errors.WrapIf(err, "failed to marshal JSON")
}
diff --git a/cli/internal/cmdutil/run.go b/cli/internal/cmdutil/run.go
new file mode 100644
index 000000000..a5893cf8c
--- /dev/null
+++ b/cli/internal/cmdutil/run.go
@@ -0,0 +1,109 @@
+package cmdutil
+
+import (
+ "encoding/json/v2"
+ "net/url"
+ "time"
+
+ "emperror.dev/errors"
+ "github.com/getarcaneapp/arcane/cli/v2/internal/client"
+ "github.com/getarcaneapp/arcane/cli/v2/internal/output"
+ "github.com/getarcaneapp/arcane/types/v2/base"
+ "github.com/spf13/cobra"
+)
+
+// ListSpec describes one standard list command: fetch a paginated endpoint,
+// echo the raw body for --json (so unmodeled fields like counts and groups
+// survive, see ReadJSONBody), otherwise render a table.
+type ListSpec[T any] struct {
+ // Resource names the collection in error messages and the trailing
+ // "Showing x of y <resource>" line.
+ Resource string
+ // Endpoint is the list path (environment already applied).
+ Endpoint string
+ // Params configures pagination from the command's flags.
+ Params ListParams
+ // Query holds extra query parameters, applied after pagination.
+ Query url.Values
+ // JSON selects raw JSON passthrough output.
+ JSON bool
+
+ Headers []string
+ Row func(T) []string
+}
+
+// RunList executes one standard list command as described by spec.
+func RunList[T any](cmd *cobra.Command, c *client.Client, spec ListSpec[T]) error {
+ path, err := ApplyPaginationParams(cmd, spec.Endpoint, spec.Params)
+ if err != nil {
+ return errors.WrapIf(err, "failed to build pagination query")
+ }
+ if len(spec.Query) > 0 {
+ path = AppendQuery(path, spec.Query)
+ }
+
+ resp, err := c.Get(cmd.Context(), path)
+ if err != nil {
+ return errors.WrapIff(err, "failed to list %s", spec.Resource)
+ }
+ defer func() { _ = resp.Body.Close() }()
+
+ body, err := ReadJSONBody(resp)
+ if err != nil {
+ return errors.WrapIff(err, "failed to list %s", spec.Resource)
+ }
+
+ if spec.JSON {
+ return PrintRawJSON(body)
+ }
+
+ var result base.Paginated[T]
+ if err := json.Unmarshal(body, &result); err != nil {
+ return errors.WrapIf(err, "failed to parse response")
+ }
+
+ rows := make([][]string, len(result.Data))
+ for i, item := range result.Data {
+ rows[i] = spec.Row(item)
+ }
+
+ output.Table(spec.Headers, rows)
+ output.Showing(len(result.Data), result.Pagination.TotalItems, spec.Resource)
+ return nil
+}
+
+// PostActionSpec describes one resolve→POST→decode→report action command. T
+// is the API envelope's data payload.
+type PostActionSpec struct {
+ // Path is the fully built action path.
+ Path string
+ // Body is the optional JSON request body.
+ Body any
+ // FailureMessage wraps transport and status errors.
+ FailureMessage string
+ // SuccessMessage is the preformatted human-readable success line.
+ SuccessMessage string
+ // Timeout optionally extends the client timeout for slow actions.
+ Timeout time.Duration
+ // JSON prints the decoded response data instead of the success line.
+ JSON bool
+}
+
+// RunPostAction executes one POST action command as described by spec.
+func RunPostAction[T any](cmd *cobra.Command, c *client.Client, spec PostActionSpec) error {
+ if spec.Timeout > 0 {
+ c.SetTimeout(spec.Timeout)
+ }
+
+ result, err := c.PostJSON[T](cmd.Context(), spec.Path, spec.Body)
+ if err != nil {
+ return errors.WrapIff(err, "%s", spec.FailureMessage)
+ }
+
+ if spec.JSON {
+ return PrintJSON(result.Data)
+ }
+
+ output.Success("%s", spec.SuccessMessage)
+ return nil
+}
diff --git a/cli/internal/cmdutil/upload.go b/cli/internal/cmdutil/upload.go
index 8563178f3..0d0cf0473 100644
--- a/cli/internal/cmdutil/upload.go
+++ b/cli/internal/cmdutil/upload.go
@@ -38,14 +38,11 @@ func UploadFileInChunks(ctx context.Context, c *client.Client, kind, filePath st
return "", errors.WrapIf(err, "failed to stat file")
}
- var created struct {
- Success bool `json:"success"`
- Data uploadtypes.Session `json:"data"`
- }
- if err := c.DoJSON(ctx, http.MethodPost, types.UploadSessions(c.EnvID(), kind), uploadtypes.CreateSessionRequest{
+ created, err := c.PostJSON[uploadtypes.Session](ctx, types.UploadSessions(c.EnvID(), kind), uploadtypes.CreateSessionRequest{
Filename: filepath.Base(filePath),
Size: fileInfo.Size(),
- }, &created); err != nil {
+ })
+ if err != nil {
return "", errors.WrapIf(err, "failed to create upload session")
}
session := created.Data
diff --git a/cli/internal/types/endpoints.go b/cli/internal/types/endpoints.go
index 845639b28..5505f5702 100644
--- a/cli/internal/types/endpoints.go
+++ b/cli/internal/types/endpoints.go
@@ -426,9 +426,6 @@ func Variable(id string) string { return pathf("/api/variables/%s", id) }
func VariablesSync() string { return "/api/variables/sync" }
func VariablesSyncStatus() string { return "/api/variables/sync-status" }
-// TemplatesVariables is the historical alias for the global variables listing.
-func TemplatesVariables() string { return "/api/variables" }
-
// System backup endpoints (admin-only)
func Backups() string { return "/api/backups" }
diff --git a/cli/pkg/activities/cmd.go b/cli/pkg/activities/cmd.go
index eec963a2f..230c60bcf 100644
--- a/cli/pkg/activities/cmd.go
+++ b/cli/pkg/activities/cmd.go
@@ -3,7 +3,6 @@
package activities
import (
- "encoding/json"
"fmt"
"net/url"
"strconv"
@@ -15,7 +14,6 @@ import (
"github.com/getarcaneapp/arcane/cli/v2/internal/output"
"github.com/getarcaneapp/arcane/cli/v2/internal/types"
activitytypes "github.com/getarcaneapp/arcane/types/v2/activity"
- "github.com/getarcaneapp/arcane/types/v2/base"
"github.com/spf13/cobra"
)
@@ -49,17 +47,6 @@ var listCmd = &cobra.Command{
return err
}
- path, err := cmdutil.ApplyPaginationParams(cmd, types.Activities(c.EnvID()), cmdutil.ListParams{
- Resource: "activities",
- Limit: limitFlag,
- FallbackDefault: 50,
- Start: startFlag,
- All: allFlag,
- })
- if err != nil {
- return errors.WrapIf(err, "failed to build pagination query")
- }
-
query := url.Values{}
if statusFlag != "" {
query.Set("status", statusFlag)
@@ -70,47 +57,26 @@ var listCmd = &cobra.Command{
if resourceTypeFlag != "" {
query.Set("resourceType", resourceTypeFlag)
}
- if len(query) > 0 {
- path = cmdutil.AppendQuery(path, query)
- }
-
- resp, err := c.Get(cmd.Context(), path)
- if err != nil {
- return errors.WrapIf(err, "failed to list activities")
- }
- defer func() { _ = resp.Body.Close() }()
-
- body, err := cmdutil.ReadJSONBody(resp)
- if err != nil {
- return errors.WrapIf(err, "failed to list activities")
- }
-
- if jsonOutput {
- return cmdutil.PrintRawJSON(body)
- }
-
- var result base.Paginated[activitytypes.Activity]
- if err := json.Unmarshal(body, &result); err != nil {
- return errors.WrapIf(err, "failed to parse response")
- }
-
- headers := []string{"ID", "TYPE", "STATUS", "RESOURCE", "STARTED", "PROGRESS", "MESSAGE"}
- rows := make([][]string, len(result.Data))
- for i, item := range result.Data {
- rows[i] = []string{
- item.ID,
- string(item.Type),
- string(item.Status),
- activityResource(item),
- item.StartedAt.Format(time.RFC3339),
- activityProgress(item),
- activityMessage(item),
- }
- }
- output.Table(headers, rows)
- output.Showing(len(result.Data), result.Pagination.TotalItems, "activities")
- return nil
+ return cmdutil.RunList(cmd, c, cmdutil.ListSpec[activitytypes.Activity]{
+ Resource: "activities",
+ Endpoint: types.Activities(c.EnvID()),
+ Params: cmdutil.ListParams{Resource: "activities", Limit: limitFlag, FallbackDefault: 50, Start: startFlag, All: allFlag},
+ Query: query,
+ JSON: jsonOutput,
+ Headers: []string{"ID", "TYPE", "STATUS", "RESOURCE", "STARTED", "PROGRESS", "MESSAGE"},
+ Row: func(item activitytypes.Activity) []string {
+ return []string{
+ item.ID,
+ string(item.Type),
+ string(item.Status),
+ activityResource(item),
+ item.StartedAt.Format(time.RFC3339),
+ activityProgress(item),
+ activityMessage(item),
+ }
+ },
+ })
},
}
@@ -129,24 +95,13 @@ var getCmd = &cobra.Command{
types.Activity(c.EnvID(), args[0]),
url.Values{"limit": []string{strconv.Itoa(messagesFlag)}},
)
- resp, err := c.Get(cmd.Context(), path)
- if err != nil {
- return errors.WrapIf(err, "failed to get activity")
- }
- defer func() { _ = resp.Body.Close() }()
-
- body, err := cmdutil.ReadJSONBody(resp)
+ result, err := c.GetJSON[activitytypes.Detail](cmd.Context(), path)
if err != nil {
return errors.WrapIf(err, "failed to get activity")
}
if jsonOutput {
- return cmdutil.PrintRawJSON(body)
- }
-
- var result base.ApiResponse[activitytypes.Detail]
- if err := json.Unmarshal(body, &result); err != nil {
- return errors.WrapIf(err, "failed to parse response")
+ return cmdutil.PrintJSON(result.Data)
}
item := result.Data.Activity
@@ -213,16 +168,10 @@ var cancelCmd = &cobra.Command{
return err
}
- resp, err := c.Post(cmd.Context(), types.ActivityCancel(c.EnvID(), args[0]), nil)
+ result, err := c.PostJSON[activitytypes.Activity](cmd.Context(), types.ActivityCancel(c.EnvID(), args[0]), nil)
if err != nil {
return errors.WrapIf(err, "failed to cancel activity")
}
- defer func() { _ = resp.Body.Close() }()
-
- var result base.ApiResponse[activitytypes.Activity]
- if err := cmdutil.DecodeJSON(resp, &result); err != nil {
- return errors.WrapIf(err, "failed to cancel activity")
- }
if jsonOutput {
return cmdutil.PrintJSON(result.Data)
@@ -254,16 +203,10 @@ var clearCmd = &cobra.Command{
return err
}
- resp, err := c.Delete(cmd.Context(), types.ActivitiesHistory(c.EnvID()))
+ result, err := c.DeleteJSON[activitytypes.ClearHistoryResult](cmd.Context(), types.ActivitiesHistory(c.EnvID()))
if err != nil {
return errors.WrapIf(err, "failed to clear activity history")
}
- defer func() { _ = resp.Body.Close() }()
-
- var result base.ApiResponse[activitytypes.ClearHistoryResult]
- if err := cmdutil.DecodeJSON(resp, &result); err != nil {
- return errors.WrapIf(err, "failed to clear activity history")
- }
if jsonOutput {
return cmdutil.PrintJSON(result.Data)
diff --git a/cli/pkg/admin/apikeys/cmd.go b/cli/pkg/admin/apikeys/cmd.go
index b463c7b36..854ecba0a 100644
--- a/cli/pkg/admin/apikeys/cmd.go
+++ b/cli/pkg/admin/apikeys/cmd.go
@@ -95,51 +95,31 @@ var listCmd = &cobra.Command{
return err
}
- path := types.ApiKeys()
- path, err = cmdutil.ApplyPaginationParams(cmd, path, cmdutil.ListParams{Resource: "apikeys", Limit: limitFlag, FallbackDefault: 20, Start: startFlag, All: allFlag})
- if err != nil {
- return errors.WrapIf(err, "failed to build pagination query")
- }
-
- resp, err := c.Get(cmd.Context(), path)
- if err != nil {
- return errors.WrapIf(err, "failed to list API keys")
- }
- defer func() { _ = resp.Body.Close() }()
-
- var result base.Paginated[apikey.ApiKey]
- if err := cmdutil.DecodeJSON(resp, &result); err != nil {
- return errors.WrapIf(err, "failed to list API keys")
- }
-
- if jsonOutput {
- return cmdutil.PrintJSON(result)
- }
-
- headers := []string{"ID", "NAME", "DESCRIPTION", "PERMISSIONS", "CREATED", "LAST USED"}
- rows := make([][]string, len(result.Data))
- for i, key := range result.Data {
- description := ""
- if key.Description != nil {
- description = *key.Description
- }
- lastUsed := "Never"
- if key.LastUsedAt != nil {
- lastUsed = key.LastUsedAt.Format("2006-01-02 15:04")
- }
- rows[i] = []string{
- key.ID,
- key.Name,
- description,
- strconv.Itoa(len(key.Permissions)),
- key.CreatedAt.Format("2006-01-02 15:04"),
- lastUsed,
- }
- }
-
- output.Table(headers, rows)
- output.Showing(len(result.Data), result.Pagination.TotalItems, "API keys")
- return nil
+ return cmdutil.RunList(cmd, c, cmdutil.ListSpec[apikey.ApiKey]{
+ Resource: "API keys",
+ Endpoint: types.ApiKeys(),
+ Params: cmdutil.ListParams{Resource: "apikeys", Limit: limitFlag, FallbackDefault: 20, Start: startFlag, All: allFlag},
+ JSON: jsonOutput,
+ Headers: []string{"ID", "NAME", "DESCRIPTION", "PERMISSIONS", "CREATED", "LAST USED"},
+ Row: func(key apikey.ApiKey) []string {
+ description := ""
+ if key.Description != nil {
+ description = *key.Description
+ }
+ lastUsed := "Never"
+ if key.LastUsedAt != nil {
+ lastUsed = key.LastUsedAt.Format("2006-01-02 15:04")
+ }
+ return []string{
+ key.ID,
+ key.Name,
+ description,
+ strconv.Itoa(len(key.Permissions)),
+ key.CreatedAt.Format("2006-01-02 15:04"),
+ lastUsed,
+ }
+ },
+ })
},
}
@@ -178,16 +158,10 @@ var createCmd = &cobra.Command{
createReq.ExpiresAt = &parsed
}
- resp, err := c.Post(cmd.Context(), types.ApiKeys(), createReq)
+ result, err := c.PostJSON[apikey.ApiKeyCreatedDto](cmd.Context(), types.ApiKeys(), createReq)
if err != nil {
return errors.WrapIf(err, "failed to create API key")
}
- defer func() { _ = resp.Body.Close() }()
-
- var result base.ApiResponse[apikey.ApiKeyCreatedDto]
- if err := cmdutil.DecodeJSON(resp, &result); err != nil {
- return errors.WrapIf(err, "failed to create API key")
- }
if jsonOutput {
return cmdutil.PrintJSON(result.Data)
@@ -227,20 +201,12 @@ var deleteCmd = &cobra.Command{
return err
}
- resp, err := c.Delete(cmd.Context(), types.ApiKey(args[0]))
+ result, err := c.DeleteJSON[base.MessageResponse](cmd.Context(), types.ApiKey(args[0]))
if err != nil {
return errors.WrapIf(err, "failed to delete API key")
}
- defer func() { _ = resp.Body.Close() }()
- if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
- return errors.WrapIf(err, "failed to delete API key")
- }
if jsonOutput {
- var result base.ApiResponse[any]
- if err := cmdutil.DecodeJSON(resp, &result); err != nil {
- return errors.WrapIf(err, "failed to delete API key")
- }
return cmdutil.PrintJSON(result.Data)
}
@@ -260,16 +226,10 @@ var getCmd = &cobra.Command{
return err
}
- resp, err := c.Get(cmd.Context(), types.ApiKey(args[0]))
+ result, err := c.GetJSON[apikey.ApiKey](cmd.Context(), types.ApiKey(args[0]))
if err != nil {
return errors.WrapIf(err, "failed to get API key")
}
- defer func() { _ = resp.Body.Close() }()
-
- var result base.ApiResponse[apikey.ApiKey]
- if err := cmdutil.DecodeJSON(resp, &result); err != nil {
- return errors.WrapIf(err, "failed to get API key")
- }
if jsonOutput {
return cmdutil.PrintJSON(result.Data)
@@ -340,20 +300,12 @@ var updateCmd = &cobra.Command{
req.Permissions = &grants
}
- resp, err := c.Put(cmd.Context(), types.ApiKey(args[0]), req)
+ result, err := c.PutJSON[apikey.ApiKey](cmd.Context(), types.ApiKey(args[0]), req)
if err != nil {
return errors.WrapIf(err, "failed to update API key")
}
- defer func() { _ = resp.Body.Close() }()
- if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
- return errors.WrapIf(err, "failed to update API key")
- }
if jsonOutput {
- var result base.ApiResponse[any]
- if err := cmdutil.DecodeJSON(resp, &result); err != nil {
- return errors.WrapIf(err, "failed to update API key")
- }
return cmdutil.PrintJSON(result.Data)
}
diff --git a/cli/pkg/admin/events/cmd.go b/cli/pkg/admin/events/cmd.go
index 47b51c98f..8634b03b0 100644
--- a/cli/pkg/admin/events/cmd.go
+++ b/cli/pkg/admin/events/cmd.go
@@ -1,7 +1,6 @@
package events
import (
- "encoding/json"
"fmt"
"emperror.dev/errors"
@@ -41,38 +40,25 @@ var listCmd = &cobra.Command{
return err
}
- path := types.Events()
+ endpoint := types.Events()
if envOnlyFlag {
- path = types.EventsEnvironment(c.EnvID())
- }
- path, err = cmdutil.ApplyPaginationParams(cmd, path, cmdutil.ListParams{Resource: "events", Limit: limitFlag, FallbackDefault: 20, Start: startFlag, All: allFlag})
- if err != nil {
- return errors.WrapIf(err, "failed to build pagination query")
- }
-
- resp, err := c.Get(cmd.Context(), path)
- if err != nil {
- return errors.WrapIf(err, "failed to list events")
- }
- defer func() { _ = resp.Body.Close() }()
-
- var result base.Paginated[event.Event]
- if err := cmdutil.DecodeJSON(resp, &result); err != nil {
- return err
+ endpoint = types.EventsEnvironment(c.EnvID())
}
- if jsonOutput {
- resultBytes, err := json.MarshalIndent(result, "", " ")
- if err != nil {
- return errors.WrapIf(err, "failed to marshal JSON")
- }
- fmt.Println(string(resultBytes))
- return nil
- }
+ return cmdutil.RunList(cmd, c, eventListSpecInternal(endpoint))
+ },
+}
- headers := []string{"ID", "TYPE", "RESOURCE", "USER", "TIMESTAMP"}
- rows := make([][]string, len(result.Data))
- for i, evt := range result.Data {
+// eventListSpecInternal builds the shared list spec for the global and
+// per-environment event list commands, which render identically.
+func eventListSpecInternal(endpoint string) cmdutil.ListSpec[event.Event] {
+ return cmdutil.ListSpec[event.Event]{
+ Resource: "events",
+ Endpoint: endpoint,
+ Params: cmdutil.ListParams{Resource: "events", Limit: limitFlag, FallbackDefault: 20, Start: startFlag, All: allFlag},
+ JSON: jsonOutput,
+ Headers: []string{"ID", "TYPE", "RESOURCE", "USER", "TIMESTAMP"},
+ Row: func(evt event.Event) []string {
resource := ""
if evt.ResourceName != nil && evt.ResourceType != nil {
resource = fmt.Sprintf("%s (%s)", *evt.ResourceName, *evt.ResourceType)
@@ -81,19 +67,15 @@ var listCmd = &cobra.Command{
if evt.Username != nil {
username = *evt.Username
}
- rows[i] = []string{
+ return []string{
evt.ID,
evt.Type,
resource,
username,
evt.Timestamp.String(),
}
- }
-
- output.Table(headers, rows)
- output.Showing(len(result.Data), result.Pagination.TotalItems, "events")
- return nil
- },
+ },
+ }
}
var deleteCmd = &cobra.Command{
@@ -119,12 +101,7 @@ var deleteCmd = &cobra.Command{
return err
}
- resp, err := c.Delete(cmd.Context(), types.Event(args[0]))
- if err != nil {
- return errors.WrapIf(err, "failed to delete event")
- }
- defer func() { _ = resp.Body.Close() }()
- if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
+ if _, err := c.DeleteJSON[base.MessageResponse](cmd.Context(), types.Event(args[0])); err != nil {
return errors.WrapIf(err, "failed to delete event")
}
@@ -143,32 +120,21 @@ var statsCmd = &cobra.Command{
return err
}
- resp, err := c.Get(cmd.Context(), types.EventsStats())
- if err != nil {
- return errors.WrapIf(err, "failed to get event stats")
- }
- defer func() { _ = resp.Body.Close() }()
-
// The severity counts DTO lives only in the backend's internal event
// package, so mirror its wire shape here.
- var result base.ApiResponse[struct {
+ result, err := c.GetJSON[struct {
Total int64 `json:"total"`
Info int64 `json:"info"`
Success int64 `json:"success"`
Warning int64 `json:"warning"`
Error int64 `json:"error"`
- }]
- if err := cmdutil.DecodeJSON(resp, &result); err != nil {
- return err
+ }](cmd.Context(), types.EventsStats())
+ if err != nil {
+ return errors.WrapIf(err, "failed to get event stats")
}
if jsonOutput {
- resultBytes, err := json.MarshalIndent(result.Data, "", " ")
- if err != nil {
- return errors.WrapIf(err, "failed to marshal JSON")
- }
- fmt.Println(string(resultBytes))
- return nil
+ return cmdutil.PrintJSON(result.Data)
}
output.Header("Event Stats")
diff --git a/cli/pkg/admin/federatedcredentials/cmd.go b/cli/pkg/admin/federatedcredentials/cmd.go
index 1f9cf48c0..26e610ad1 100644
--- a/cli/pkg/admin/federatedcredentials/cmd.go
+++ b/cli/pkg/admin/federatedcredentials/cmd.go
@@ -67,48 +67,24 @@ var listCmd = &cobra.Command{
return err
}
- path, err := cmdutil.ApplyPaginationParams(cmd, types.FederatedCredentials(), cmdutil.ListParams{
- Resource: "federated-credentials",
- Limit: limitFlag,
- FallbackDefault: 20,
- Start: startFlag,
- All: allFlag,
+ return cmdutil.RunList(cmd, c, cmdutil.ListSpec[federatedtypes.FederatedCredential]{
+ Resource: "federated credentials",
+ Endpoint: types.FederatedCredentials(),
+ Params: cmdutil.ListParams{Resource: "federated-credentials", Limit: limitFlag, FallbackDefault: 20, Start: startFlag, All: allFlag},
+ JSON: jsonOutput,
+ Headers: []string{"ID", "NAME", "ISSUER", "SUBJECT", "ROLE", "ENABLED"},
+ Row: func(cred federatedtypes.FederatedCredential) []string {
+ role := cred.RoleName
+ if role == "" {
+ role = cred.RoleID
+ }
+ enabled := "false"
+ if cred.Enabled {
+ enabled = "true"
+ }
+ return []string{cred.ID, cred.Name, cred.IssuerURL, cred.SubjectMatch, role, enabled}
+ },
})
- if err != nil {
- return errors.WrapIf(err, "failed to build pagination query")
- }
-
- resp, err := c.Get(cmd.Context(), path)
- if err != nil {
- return errors.WrapIf(err, "failed to list federated credentials")
- }
- defer func() { _ = resp.Body.Close() }()
-
- var result base.Paginated[federatedtypes.FederatedCredential]
- if err := cmdutil.DecodeJSON(resp, &result); err != nil {
- return errors.WrapIf(err, "failed to list federated credentials")
- }
-
- if jsonOutput {
- return cmdutil.PrintJSON(result.Data)
- }
-
- headers := []string{"ID", "NAME", "ISSUER", "SUBJECT", "ROLE", "ENABLED"}
- rows := make([][]string, len(result.Data))
- for i, cred := range result.Data {
- role := cred.RoleName
- if role == "" {
- role = cred.RoleID
- }
- enabled := "false"
- if cred.Enabled {
- enabled = "true"
- }
- rows[i] = []string{cred.ID, cred.Name, cred.IssuerURL, cred.SubjectMatch, role, enabled}
- }
- output.Table(headers, rows)
- output.Showing(len(result.Data), result.Pagination.TotalItems, "federated credentials")
- return nil
},
}
@@ -123,16 +99,10 @@ var getCmd = &cobra.Command{
return err
}
- resp, err := c.Get(cmd.Context(), types.FederatedCredential(args[0]))
+ result, err := c.GetJSON[federatedtypes.FederatedCredential](cmd.Context(), types.FederatedCredential(args[0]))
if err != nil {
return errors.WrapIf(err, "failed to get federated credential")
}
- defer func() { _ = resp.Body.Close() }()
-
- var result base.ApiResponse[federatedtypes.FederatedCredential]
- if err := cmdutil.DecodeJSON(resp, &result); err != nil {
- return errors.WrapIf(err, "failed to get federated credential")
- }
if jsonOutput {
return cmdutil.PrintJSON(result.Data)
@@ -182,16 +152,10 @@ var createCmd = &cobra.Command{
req.ExpiresAt = &parsed
}
- resp, err := c.Post(cmd.Context(), types.FederatedCredentials(), req)
+ result, err := c.PostJSON[federatedtypes.FederatedCredential](cmd.Context(), types.FederatedCredentials(), req)
if err != nil {
return errors.WrapIf(err, "failed to create federated credential")
}
- defer func() { _ = resp.Body.Close() }()
-
- var result base.ApiResponse[federatedtypes.FederatedCredential]
- if err := cmdutil.DecodeJSON(resp, &result); err != nil {
- return errors.WrapIf(err, "failed to create federated credential")
- }
if jsonOutput {
return cmdutil.PrintJSON(result.Data)
@@ -266,16 +230,10 @@ var updateCmd = &cobra.Command{
req.ExpiresAt = &parsed
}
- resp, err := c.Put(cmd.Context(), types.FederatedCredential(args[0]), req)
+ result, err := c.PutJSON[federatedtypes.FederatedCredential](cmd.Context(), types.FederatedCredential(args[0]), req)
if err != nil {
return errors.WrapIf(err, "failed to update federated credential")
}
- defer func() { _ = resp.Body.Close() }()
-
- var result base.ApiResponse[federatedtypes.FederatedCredential]
- if err := cmdutil.DecodeJSON(resp, &result); err != nil {
- return errors.WrapIf(err, "failed to update federated credential")
- }
if jsonOutput {
return cmdutil.PrintJSON(result.Data)
@@ -310,12 +268,7 @@ var deleteCmd = &cobra.Command{
return err
}
- resp, err := c.Delete(cmd.Context(), types.FederatedCredential(args[0]))
- if err != nil {
- return errors.WrapIf(err, "failed to delete federated credential")
- }
- defer func() { _ = resp.Body.Close() }()
- if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
+ if _, err := c.DeleteJSON[base.MessageResponse](cmd.Context(), types.FederatedCredential(args[0])); err != nil {
return errors.WrapIf(err, "failed to delete federated credential")
}
diff --git a/cli/pkg/admin/notifications/cmd.go b/cli/pkg/admin/notifications/cmd.go
index 2e409f564..0e25a725c 100644
--- a/cli/pkg/admin/notifications/cmd.go
+++ b/cli/pkg/admin/notifications/cmd.go
@@ -1,8 +1,9 @@
package notifications
import (
- "encoding/json"
+ "encoding/json/v2"
"fmt"
+ "net/http"
"os"
"strconv"
@@ -43,24 +44,13 @@ var settingsGetCmd = &cobra.Command{
return err
}
- resp, err := c.Get(cmd.Context(), types.NotificationsSettings(c.EnvID()))
+ result, err := c.DoJSON[[]notification.Response](cmd.Context(), http.MethodGet, types.NotificationsSettings(c.EnvID()), nil)
if err != nil {
return errors.WrapIf(err, "failed to get settings")
}
- defer func() { _ = resp.Body.Close() }()
-
- var result []notification.Response
- if err := cmdutil.DecodeJSON(resp, &result); err != nil {
- return err
- }
if jsonOutput {
- resultBytes, err := json.MarshalIndent(result, "", " ")
- if err != nil {
- return errors.WrapIf(err, "failed to marshal JSON")
- }
- fmt.Println(string(resultBytes))
- return nil
+ return cmdutil.PrintJSON(result)
}
headers := []string{"ID", "PROVIDER", "ENABLED"}
@@ -101,13 +91,13 @@ var settingsDeleteCmd = &cobra.Command{
return err
}
- resp, err := c.Delete(cmd.Context(), types.NotificationSettingsProvider(c.EnvID(), args[0]))
+ result, err := c.DeleteJSON[base.MessageResponse](cmd.Context(), types.NotificationSettingsProvider(c.EnvID(), args[0]))
if err != nil {
return errors.WrapIf(err, "failed to delete notification settings")
}
- defer func() { _ = resp.Body.Close() }()
- if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
- return errors.WrapIf(err, "failed to delete notification settings")
+
+ if jsonOutput {
+ return cmdutil.PrintJSON(result.Data)
}
output.Success("Notification settings for %s deleted successfully", args[0])
@@ -162,19 +152,10 @@ var settingsSetCmd = &cobra.Command{
return err
}
- resp, err := c.Post(cmd.Context(), types.NotificationsSettings(c.EnvID()), req)
+ result, err := c.DoJSON[notification.Response](cmd.Context(), http.MethodPost, types.NotificationsSettings(c.EnvID()), req)
if err != nil {
return errors.WrapIf(err, "failed to save notification settings")
}
- defer func() { _ = resp.Body.Close() }()
- if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
- return errors.WrapIf(err, "failed to save notification settings")
- }
-
- var result notification.Response
- if err := cmdutil.DecodeJSON(resp, &result); err != nil {
- return err
- }
if jsonOutput {
return cmdutil.PrintJSON(result)
@@ -198,27 +179,12 @@ var testProviderCmd = &cobra.Command{
return err
}
- resp, err := c.Post(cmd.Context(), types.NotificationsTestProvider(c.EnvID(), args[0]), nil)
- if err != nil {
- return errors.WrapIf(err, "failed to test notification provider")
- }
- defer func() { _ = resp.Body.Close() }()
- if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
- return errors.WrapIf(err, "notification test failed")
- }
-
- if jsonOutput {
- var result base.ApiResponse[any]
- if err := json.NewDecoder(resp.Body).Decode(&result); err == nil {
- if resultBytes, err := json.MarshalIndent(result.Data, "", " "); err == nil {
- fmt.Println(string(resultBytes))
- }
- }
- return nil
- }
-
- output.Success("Notification test for %s successful", args[0])
- return nil
+ return cmdutil.RunPostAction[notification.TestResponse](cmd, c, cmdutil.PostActionSpec{
+ Path: types.NotificationsTestProvider(c.EnvID(), args[0]),
+ FailureMessage: "failed to test notification provider",
+ SuccessMessage: fmt.Sprintf("Notification test for %s successful", args[0]),
+ JSON: jsonOutput,
+ })
},
}
diff --git a/cli/pkg/admin/oidcmappings/cmd.go b/cli/pkg/admin/oidcmappings/cmd.go
index 9b3f989ba..1dee97731 100644
--- a/cli/pkg/admin/oidcmappings/cmd.go
+++ b/cli/pkg/admin/oidcmappings/cmd.go
@@ -10,7 +10,6 @@ import (
"github.com/getarcaneapp/arcane/cli/v2/internal/cmdutil"
"github.com/getarcaneapp/arcane/cli/v2/internal/output"
"github.com/getarcaneapp/arcane/cli/v2/internal/types"
- "github.com/getarcaneapp/arcane/types/v2/base"
roletypes "github.com/getarcaneapp/arcane/types/v2/role"
"github.com/spf13/cobra"
)
@@ -53,16 +52,10 @@ var listCmd = &cobra.Command{
if err != nil {
return err
}
- resp, err := c.Get(cmd.Context(), types.OidcRoleMappings())
+ result, err := c.GetJSON[[]roletypes.OidcRoleMapping](cmd.Context(), types.OidcRoleMappings())
if err != nil {
return errors.WrapIf(err, "failed to list OIDC mappings")
}
- defer func() { _ = resp.Body.Close() }()
-
- var result base.ApiResponse[[]roletypes.OidcRoleMapping]
- if err := cmdutil.DecodeJSON(resp, &result); err != nil {
- return errors.WrapIf(err, "failed to list OIDC mappings")
- }
if jsonOutput {
return cmdutil.PrintJSON(result.Data)
@@ -105,15 +98,10 @@ var createCmd = &cobra.Command{
req.EnvironmentID = new(createEnvironment)
}
- resp, err := c.Post(cmd.Context(), types.OidcRoleMappings(), req)
+ result, err := c.PostJSON[roletypes.OidcRoleMapping](cmd.Context(), types.OidcRoleMappings(), req)
if err != nil {
return errors.WrapIf(err, "failed to create OIDC mapping")
}
- defer func() { _ = resp.Body.Close() }()
- var result base.ApiResponse[roletypes.OidcRoleMapping]
- if err := cmdutil.DecodeJSON(resp, &result); err != nil {
- return errors.WrapIf(err, "failed to create OIDC mapping")
- }
if jsonOutput {
return cmdutil.PrintJSON(result.Data)
@@ -223,15 +211,10 @@ func fetchMappingInternal(cmd *cobra.Command, id string) (*roletypes.OidcRoleMap
if err != nil {
return nil, err
}
- resp, err := c.Get(cmd.Context(), types.OidcRoleMappings())
+ result, err := c.GetJSON[[]roletypes.OidcRoleMapping](cmd.Context(), types.OidcRoleMappings())
if err != nil {
return nil, errors.WrapIf(err, "failed to load current mapping")
}
- defer func() { _ = resp.Body.Close() }()
- var result base.ApiResponse[[]roletypes.OidcRoleMapping]
- if err := cmdutil.DecodeJSON(resp, &result); err != nil {
- return nil, errors.WrapIf(err, "failed to load current mapping")
- }
for i := range result.Data {
if result.Data[i].ID == id {
return &result.Data[i], nil
diff --git a/cli/pkg/admin/roles/cmd.go b/cli/pkg/admin/roles/cmd.go
index 9643da986..195a22e4c 100644
--- a/cli/pkg/admin/roles/cmd.go
+++ b/cli/pkg/admin/roles/cmd.go
@@ -15,7 +15,6 @@ import (
"github.com/getarcaneapp/arcane/cli/v2/internal/cmdutil"
"github.com/getarcaneapp/arcane/cli/v2/internal/output"
"github.com/getarcaneapp/arcane/cli/v2/internal/types"
- "github.com/getarcaneapp/arcane/types/v2/base"
roletypes "github.com/getarcaneapp/arcane/types/v2/role"
"github.com/spf13/cobra"
)
@@ -66,45 +65,26 @@ var listCmd = &cobra.Command{
return err
}
- path := types.Roles()
- path, err = cmdutil.ApplyPaginationParams(cmd, path, cmdutil.ListParams{Resource: "roles", Limit: limitFlag, FallbackDefault: 20, Start: startFlag, All: allFlag})
- if err != nil {
- return errors.WrapIf(err, "failed to build pagination query")
- }
-
- resp, err := c.Get(cmd.Context(), path)
- if err != nil {
- return errors.WrapIf(err, "failed to list roles")
- }
- defer func() { _ = resp.Body.Close() }()
-
- var result base.Paginated[roletypes.Role]
- if err := cmdutil.DecodeJSON(resp, &result); err != nil {
- return errors.WrapIf(err, "failed to list roles")
- }
-
- if jsonOutput {
- return cmdutil.PrintJSON(result)
- }
-
- headers := []string{"ID", "NAME", "TYPE", "USERS", "PERMISSIONS"}
- rows := make([][]string, len(result.Data))
- for i, r := range result.Data {
- roleType := "custom"
- if r.BuiltIn {
- roleType = "built-in"
- }
- rows[i] = []string{
- r.ID,
- r.Name,
- roleType,
- strconv.Itoa(r.AssignedUserCount),
- strconv.Itoa(len(r.Permissions)),
- }
- }
- output.Table(headers, rows)
- output.Showing(len(result.Data), result.Pagination.TotalItems, "roles")
- return nil
+ return cmdutil.RunList(cmd, c, cmdutil.ListSpec[roletypes.Role]{
+ Resource: "roles",
+ Endpoint: types.Roles(),
+ Params: cmdutil.ListParams{Resource: "roles", Limit: limitFlag, FallbackDefault: 20, Start: startFlag, All: allFlag},
+ JSON: jsonOutput,
+ Headers: []string{"ID", "NAME", "TYPE", "USERS", "PERMISSIONS"},
+ Row: func(r roletypes.Role) []string {
+ roleType := "custom"
+ if r.BuiltIn {
+ roleType = "built-in"
+ }
+ return []string{
+ r.ID,
+ r.Name,
+ roleType,
+ strconv.Itoa(r.AssignedUserCount),
+ strconv.Itoa(len(r.Permissions)),
+ }
+ },
+ })
},
}
@@ -118,16 +98,10 @@ var getCmd = &cobra.Command{
if err != nil {
return err
}
- resp, err := c.Get(cmd.Context(), types.Role(args[0]))
+ result, err := c.GetJSON[roletypes.Role](cmd.Context(), types.Role(args[0]))
if err != nil {
return errors.WrapIf(err, "failed to get role")
}
- defer func() { _ = resp.Body.Close() }()
-
- var result base.ApiResponse[roletypes.Role]
- if err := cmdutil.DecodeJSON(resp, &result); err != nil {
- return errors.WrapIf(err, "failed to get role")
- }
if jsonOutput {
return cmdutil.PrintJSON(result.Data)
@@ -177,15 +151,10 @@ var createCmd = &cobra.Command{
req.Description = &roleCreateDescription
}
- resp, err := c.Post(cmd.Context(), types.Roles(), req)
+ result, err := c.PostJSON[roletypes.Role](cmd.Context(), types.Roles(), req)
if err != nil {
return errors.WrapIf(err, "failed to create role")
}
- defer func() { _ = resp.Body.Close() }()
- var result base.ApiResponse[roletypes.Role]
- if err := cmdutil.DecodeJSON(resp, &result); err != nil {
- return errors.WrapIf(err, "failed to create role")
- }
if jsonOutput {
return cmdutil.PrintJSON(result.Data)
@@ -291,16 +260,10 @@ var permissionsCmd = &cobra.Command{
if err != nil {
return err
}
- resp, err := c.Get(cmd.Context(), types.RolesAvailablePermissions())
+ result, err := c.GetJSON[roletypes.PermissionsManifest](cmd.Context(), types.RolesAvailablePermissions())
if err != nil {
return errors.WrapIf(err, "failed to load permission manifest")
}
- defer func() { _ = resp.Body.Close() }()
-
- var result base.ApiResponse[roletypes.PermissionsManifest]
- if err := cmdutil.DecodeJSON(resp, &result); err != nil {
- return errors.WrapIf(err, "failed to load permission manifest")
- }
if jsonOutput {
return cmdutil.PrintJSON(result.Data)
@@ -330,16 +293,10 @@ var assignmentsCmd = &cobra.Command{
if err != nil {
return err
}
- resp, err := c.Get(cmd.Context(), types.UserRoleAssignments(args[0]))
+ result, err := c.GetJSON[[]roletypes.RoleAssignment](cmd.Context(), types.UserRoleAssignments(args[0]))
if err != nil {
return errors.WrapIf(err, "failed to list assignments")
}
- defer func() { _ = resp.Body.Close() }()
-
- var result base.ApiResponse[[]roletypes.RoleAssignment]
- if err := cmdutil.DecodeJSON(resp, &result); err != nil {
- return errors.WrapIf(err, "failed to list assignments")
- }
if jsonOutput {
return cmdutil.PrintJSON(result.Data)
@@ -385,15 +342,10 @@ var assignCmd = &cobra.Command{
if err != nil {
return err
}
- resp, err := c.Put(cmd.Context(), types.UserRoleAssignments(args[0]), req)
+ result, err := c.PutJSON[[]roletypes.RoleAssignment](cmd.Context(), types.UserRoleAssignments(args[0]), req)
if err != nil {
return errors.WrapIf(err, "failed to set assignments")
}
- defer func() { _ = resp.Body.Close() }()
- var result base.ApiResponse[[]roletypes.RoleAssignment]
- if err := cmdutil.DecodeJSON(resp, &result); err != nil {
- return errors.WrapIf(err, "failed to set assignments")
- }
if jsonOutput {
return cmdutil.PrintJSON(result.Data)
}
@@ -432,15 +384,10 @@ func fetchRoleInternal(cmd *cobra.Command, id string) (*roletypes.Role, error) {
if err != nil {
return nil, err
}
- resp, err := c.Get(cmd.Context(), types.Role(id))
+ result, err := c.GetJSON[roletypes.Role](cmd.Context(), types.Role(id))
if err != nil {
return nil, errors.WrapIf(err, "failed to load current role")
}
- defer func() { _ = resp.Body.Close() }()
- var result base.ApiResponse[roletypes.Role]
- if err := cmdutil.DecodeJSON(resp, &result); err != nil {
- return nil, errors.WrapIf(err, "failed to load current role")
- }
return &result.Data, nil
}
diff --git a/cli/pkg/admin/users/cmd.go b/cli/pkg/admin/users/cmd.go
index 91de57913..622b2257d 100644
--- a/cli/pkg/admin/users/cmd.go
+++ b/cli/pkg/admin/users/cmd.go
@@ -1,7 +1,6 @@
package users
import (
- "encoding/json"
"fmt"
"os"
"strings"
@@ -12,7 +11,6 @@ import (
"github.com/getarcaneapp/arcane/cli/v2/internal/cmdutil"
"github.com/getarcaneapp/arcane/cli/v2/internal/output"
"github.com/getarcaneapp/arcane/cli/v2/internal/types"
- "github.com/getarcaneapp/arcane/types/v2/base"
"github.com/getarcaneapp/arcane/types/v2/user"
"github.com/spf13/cobra"
)
@@ -102,55 +100,30 @@ var listCmd = &cobra.Command{
return err
}
- path := types.Users()
- path, err = cmdutil.ApplyPaginationParams(cmd, path, cmdutil.ListParams{Resource: "users", Limit: limitFlag, FallbackDefault: 20, Start: startFlag, All: allFlag})
- if err != nil {
- return errors.WrapIf(err, "failed to build pagination query")
- }
-
- resp, err := c.Get(cmd.Context(), path)
- if err != nil {
- return errors.WrapIf(err, "failed to list users")
- }
- defer func() { _ = resp.Body.Close() }()
-
- var result base.Paginated[user.User]
- if err := cmdutil.DecodeJSON(resp, &result); err != nil {
- return err
- }
-
- if jsonOutput {
- resultBytes, err := json.MarshalIndent(result, "", " ")
- if err != nil {
- return errors.WrapIf(err, "failed to marshal JSON")
- }
- fmt.Println(string(resultBytes))
- return nil
- }
-
- headers := []string{"ID", "USERNAME", "DISPLAY NAME", "EMAIL", "ROLE ASSIGNMENTS"}
- rows := make([][]string, len(result.Data))
- for i, usr := range result.Data {
- displayName := ""
- if usr.DisplayName != nil {
- displayName = *usr.DisplayName
- }
- email := ""
- if usr.Email != nil {
- email = *usr.Email
- }
- rows[i] = []string{
- usr.ID,
- usr.Username,
- displayName,
- email,
- summarizeRoleAssignments(usr.RoleAssignments),
- }
- }
-
- output.Table(headers, rows)
- output.Showing(len(result.Data), result.Pagination.TotalItems, "users")
- return nil
+ return cmdutil.RunList(cmd, c, cmdutil.ListSpec[user.User]{
+ Resource: "users",
+ Endpoint: types.Users(),
+ Params: cmdutil.ListParams{Resource: "users", Limit: limitFlag, FallbackDefault: 20, Start: startFlag, All: allFlag},
+ JSON: jsonOutput,
+ Headers: []string{"ID", "USERNAME", "DISPLAY NAME", "EMAIL", "ROLE ASSIGNMENTS"},
+ Row: func(usr user.User) []string {
+ displayName := ""
+ if usr.DisplayName != nil {
+ displayName = *usr.DisplayName
+ }
+ email := ""
+ if usr.Email != nil {
+ email = *usr.Email
+ }
+ return []string{
+ usr.ID,
+ usr.Username,
+ displayName,
+ email,
+ summarizeRoleAssignments(usr.RoleAssignments),
+ }
+ },
+ })
},
}
@@ -188,27 +161,13 @@ var createCmd = &cobra.Command{
req.Email = &userCreateEmail
}
- resp, err := c.Post(cmd.Context(), types.Users(), req)
+ result, err := c.PostJSON[user.User](cmd.Context(), types.Users(), req)
if err != nil {
return errors.WrapIf(err, "failed to create user")
}
- defer func() { _ = resp.Body.Close() }()
- if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
- return errors.WrapIf(err, "failed to create user")
- }
-
- var result base.ApiResponse[user.User]
- if err := cmdutil.DecodeJSON(resp, &result); err != nil {
- return err
- }
if jsonOutput {
- resultBytes, err := json.MarshalIndent(result.Data, "", " ")
- if err != nil {
- return errors.WrapIf(err, "failed to marshal JSON")
- }
- fmt.Println(string(resultBytes))
- return nil
+ return cmdutil.PrintJSON(result.Data)
}
output.Success("User %s created successfully", result.Data.Username)
@@ -230,24 +189,13 @@ var getCmd = &cobra.Command{
return err
}
- resp, err := c.Get(cmd.Context(), types.User(args[0]))
+ result, err := c.GetJSON[user.User](cmd.Context(), types.User(args[0]))
if err != nil {
return errors.WrapIf(err, "failed to get user")
}
- defer func() { _ = resp.Body.Close() }()
-
- var result base.ApiResponse[user.User]
- if err := cmdutil.DecodeJSON(resp, &result); err != nil {
- return err
- }
if jsonOutput {
- resultBytes, err := json.MarshalIndent(result.Data, "", " ")
- if err != nil {
- return errors.WrapIf(err, "failed to marshal JSON")
- }
- fmt.Println(string(resultBytes))
- return nil
+ return cmdutil.PrintJSON(result.Data)
}
output.Header("User Details")
@@ -298,23 +246,13 @@ var updateCmd = &cobra.Command{
req.Email = &userUpdateEmail
}
- resp, err := c.Put(cmd.Context(), types.User(args[0]), req)
+ result, err := c.PutJSON[user.User](cmd.Context(), types.User(args[0]), req)
if err != nil {
return errors.WrapIf(err, "failed to update user")
}
- defer func() { _ = resp.Body.Close() }()
- if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
- return errors.WrapIf(err, "failed to update user")
- }
if jsonOutput {
- var result base.ApiResponse[any]
- if err := json.NewDecoder(resp.Body).Decode(&result); err == nil {
- if resultBytes, err := json.MarshalIndent(result.Data, "", " "); err == nil {
- fmt.Println(string(resultBytes))
- }
- }
- return nil
+ return cmdutil.PrintJSON(result.Data)
}
output.Success("User updated successfully")
diff --git a/cli/pkg/auth/apikeys.go b/cli/pkg/auth/apikeys.go
index c3d778ff8..93084a029 100644
--- a/cli/pkg/auth/apikeys.go
+++ b/cli/pkg/auth/apikeys.go
@@ -10,7 +10,6 @@ import (
"github.com/getarcaneapp/arcane/cli/v2/internal/output"
"github.com/getarcaneapp/arcane/cli/v2/internal/types"
apikeytypes "github.com/getarcaneapp/arcane/types/v2/apikey"
- "github.com/getarcaneapp/arcane/types/v2/base"
"github.com/spf13/cobra"
)
@@ -43,16 +42,10 @@ var apiKeysListCmd = &cobra.Command{
return err
}
- resp, err := c.Get(cmd.Context(), types.AuthMeApiKeys())
+ result, err := c.GetJSON[[]apikeytypes.ApiKey](cmd.Context(), types.AuthMeApiKeys())
if err != nil {
return errors.WrapIf(err, "failed to list API keys")
}
- defer func() { _ = resp.Body.Close() }()
-
- var result base.ApiResponse[[]apikeytypes.ApiKey]
- if err := cmdutil.DecodeJSON(resp, &result); err != nil {
- return errors.WrapIf(err, "failed to list API keys")
- }
if cmdutil.JSONOutputEnabled(cmd) || jsonOutput {
return cmdutil.PrintJSON(result.Data)
@@ -112,16 +105,10 @@ var apiKeysCreateCmd = &cobra.Command{
req.ExpiresAt = &parsed
}
- resp, err := c.Post(cmd.Context(), types.AuthMeApiKeys(), req)
+ result, err := c.PostJSON[apikeytypes.ApiKeyCreatedDto](cmd.Context(), types.AuthMeApiKeys(), req)
if err != nil {
return errors.WrapIf(err, "failed to create API key")
}
- defer func() { _ = resp.Body.Close() }()
-
- var result base.ApiResponse[apikeytypes.ApiKeyCreatedDto]
- if err := cmdutil.DecodeJSON(resp, &result); err != nil {
- return errors.WrapIf(err, "failed to create API key")
- }
if cmdutil.JSONOutputEnabled(cmd) || jsonOutput {
return cmdutil.PrintJSON(result.Data)
diff --git a/cli/pkg/auth/cmd.go b/cli/pkg/auth/cmd.go
index 25add9337..9e8ea09da 100644
--- a/cli/pkg/auth/cmd.go
+++ b/cli/pkg/auth/cmd.go
@@ -1,9 +1,10 @@
package auth
import (
- "encoding/json"
+ "encoding/json/v2"
"fmt"
"io"
+ "net/http"
"os"
"strconv"
"strings"
@@ -18,6 +19,7 @@ import (
"github.com/getarcaneapp/arcane/cli/v2/internal/types"
"github.com/getarcaneapp/arcane/types/v2/auth"
"github.com/getarcaneapp/arcane/types/v2/base"
+ "github.com/getarcaneapp/arcane/types/v2/user"
"github.com/spf13/cobra"
)
@@ -138,18 +140,13 @@ var loginCmd = &cobra.Command{
}
if cmdutil.JSONOutputEnabled(cmd) || jsonOutput {
- resultBytes, err := json.MarshalIndent(map[string]any{
+ return cmdutil.PrintJSON(map[string]any{
"success": tokenResult.Success,
"token": tokenResult.Token,
"refreshToken": tokenResult.RefreshToken,
"expiresAt": tokenResult.ExpiresAt,
"user": tokenResult.User,
- }, "", " ")
- if err != nil {
- return errors.WrapIf(err, "failed to marshal JSON")
- }
- fmt.Println(string(resultBytes))
- return nil
+ })
}
cfg, err := config.Load()
@@ -181,14 +178,10 @@ var logoutCmd = &cobra.Command{
return err
}
- resp, err := c.Post(cmd.Context(), types.AuthLogout(), nil)
+ result, err := c.PostJSON[base.MessageResponse](cmd.Context(), types.AuthLogout(), nil)
if err != nil {
return errors.WrapIf(err, "logout failed")
}
- defer func() { _ = resp.Body.Close() }()
- if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
- return errors.WrapIf(err, "logout failed")
- }
// Clear token from config after successful API logout.
cfg, err := config.Load()
@@ -202,13 +195,7 @@ var logoutCmd = &cobra.Command{
}
if cmdutil.JSONOutputEnabled(cmd) || jsonOutput {
- var result base.ApiResponse[any]
- if err := json.NewDecoder(resp.Body).Decode(&result); err == nil {
- if resultBytes, err := json.MarshalIndent(result.Data, "", " "); err == nil {
- fmt.Println(string(resultBytes))
- }
- }
- return nil
+ return cmdutil.PrintJSON(result.Data)
}
output.Success("Logout successful")
@@ -228,36 +215,17 @@ var meCmd = &cobra.Command{
return err
}
- resp, err := c.Get(cmd.Context(), types.AuthMe())
+ result, err := c.GetJSON[user.User](cmd.Context(), types.AuthMe())
if err != nil {
return errors.WrapIf(err, "failed to get user info")
}
- defer func() { _ = resp.Body.Close() }()
- if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
- return errors.WrapIf(err, "failed to get user info")
- }
-
- var result base.ApiResponse[any]
- if err := cmdutil.DecodeJSON(resp, &result); err != nil {
- return err
- }
if cmdutil.JSONOutputEnabled(cmd) || jsonOutput {
- resultBytes, err := json.MarshalIndent(result.Data, "", " ")
- if err != nil {
- return errors.WrapIf(err, "failed to marshal JSON")
- }
- fmt.Println(string(resultBytes))
- return nil
+ return cmdutil.PrintJSON(result.Data)
}
output.Header("Current User")
- userBytes, err := json.MarshalIndent(result.Data, "", " ")
- if err != nil {
- return errors.WrapIf(err, "failed to marshal user data")
- }
- fmt.Println(string(userBytes))
- return nil
+ return cmdutil.PrintJSON(result.Data)
},
}
@@ -304,23 +272,13 @@ var passwordCmd = &cobra.Command{
return errors.WrapIf(err, "failed to marshal request")
}
- resp, err := c.Post(cmd.Context(), types.AuthPassword(), reqBody)
+ result, err := c.PostJSON[base.MessageResponse](cmd.Context(), types.AuthPassword(), reqBody)
if err != nil {
return errors.WrapIf(err, "password change failed")
}
- defer func() { _ = resp.Body.Close() }()
- if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
- return errors.WrapIf(err, "password change failed")
- }
if cmdutil.JSONOutputEnabled(cmd) || jsonOutput {
- var result base.ApiResponse[any]
- if err := json.NewDecoder(resp.Body).Decode(&result); err == nil {
- if resultBytes, err := json.MarshalIndent(result.Data, "", " "); err == nil {
- fmt.Println(string(resultBytes))
- }
- }
- return nil
+ return cmdutil.PrintJSON(result.Data)
}
output.Success("Password changed successfully")
@@ -360,31 +318,17 @@ var refreshCmd = &cobra.Command{
return errors.WrapIf(err, "failed to marshal request")
}
- resp, err := c.Post(cmd.Context(), types.AuthRefresh(), reqBody)
+ result, err := c.PostJSON[auth.TokenRefreshResponse](cmd.Context(), types.AuthRefresh(), reqBody)
if err != nil {
return errors.WrapIf(err, "token refresh failed")
}
- defer func() { _ = resp.Body.Close() }()
- if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
- return errors.WrapIf(err, "token refresh failed")
- }
-
- var result base.ApiResponse[auth.TokenRefreshResponse]
- if err := cmdutil.DecodeJSON(resp, &result); err != nil {
- return err
- }
if cmdutil.JSONOutputEnabled(cmd) || jsonOutput {
- resultBytes, err := json.MarshalIndent(map[string]any{
+ return cmdutil.PrintJSON(map[string]any{
"token": result.Data.Token,
"refreshToken": result.Data.RefreshToken,
"expiresAt": result.Data.ExpiresAt,
- }, "", " ")
- if err != nil {
- return errors.WrapIf(err, "failed to marshal JSON")
- }
- fmt.Println(string(resultBytes))
- return nil
+ })
}
// Save new JWT token to config
@@ -415,31 +359,20 @@ var oidcStatusCmd = &cobra.Command{
return err
}
- resp, err := c.Get(cmd.Context(), types.OIDCStatus())
- if err != nil {
- return errors.WrapIf(err, "failed to get OIDC status")
- }
- defer func() { _ = resp.Body.Close() }()
- if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
- return errors.WrapIf(err, "failed to get OIDC status")
- }
-
- var result struct {
+ // This endpoint returns its payload directly, not wrapped in an
+ // ApiResponse envelope.
+ type oidcStatusResult struct {
EnvForced bool `json:"envForced"`
EnvConfigured bool `json:"envConfigured"`
MergeAccounts bool `json:"mergeAccounts"`
}
- if err := cmdutil.DecodeJSON(resp, &result); err != nil {
- return err
+ result, err := c.DoJSON[oidcStatusResult](cmd.Context(), http.MethodGet, types.OIDCStatus(), nil)
+ if err != nil {
+ return errors.WrapIf(err, "failed to get OIDC status")
}
if cmdutil.JSONOutputEnabled(cmd) || jsonOutput {
- resultBytes, err := json.MarshalIndent(result, "", " ")
- if err != nil {
- return errors.WrapIf(err, "failed to marshal JSON")
- }
- fmt.Println(string(resultBytes))
- return nil
+ return cmdutil.PrintJSON(result)
}
output.Header("OIDC Status")
diff --git a/cli/pkg/auth/federated.go b/cli/pkg/auth/federated.go
index 7b19ba2b7..9f7502f5f 100644
--- a/cli/pkg/auth/federated.go
+++ b/cli/pkg/auth/federated.go
@@ -1,7 +1,7 @@
package auth
import (
- "encoding/json"
+ "encoding/json/v2"
"fmt"
"io"
"net/http"
@@ -94,7 +94,7 @@ GitHub Actions example:
switch {
case cmdutil.JSONOutputEnabled(cmd):
- resultBytes, err := json.MarshalIndent(map[string]any{
+ return cmdutil.PrintJSON(map[string]any{
"token": tokenResp.AccessToken,
"tokenType": tokenResp.TokenType,
"expiresIn": tokenResp.ExpiresIn,
@@ -102,11 +102,7 @@ GitHub Actions example:
"issuedTokenType": tokenResp.IssuedTokenType,
"source": tokenSource,
"persisted": persist,
- }, "", " ")
- if err != nil {
- return errors.WrapIf(err, "failed to marshal JSON")
- }
- fmt.Println(string(resultBytes))
+ })
case exportOutput:
fmt.Printf("export ARCANE_TOKEN=%s\n", shellQuoteInternal(tokenResp.AccessToken))
fmt.Printf("export ARCANE_TOKEN_EXPIRES_AT=%s\n", shellQuoteInternal(expiresAt.Format(time.RFC3339)))
diff --git a/cli/pkg/backups/cmd.go b/cli/pkg/backups/cmd.go
index 6bcf9808f..3d9cdeab8 100644
--- a/cli/pkg/backups/cmd.go
+++ b/cli/pkg/backups/cmd.go
@@ -1,9 +1,10 @@
package backups
import (
- "encoding/json"
+ "encoding/json/v2"
"fmt"
"io"
+ "net/http"
"os"
"strconv"
@@ -77,58 +78,28 @@ var listCmd = &cobra.Command{
return err
}
- path, err := cmdutil.ApplyPaginationParams(cmd, types.Backups(), cmdutil.ListParams{
- Resource: "backups",
- Limit: limitFlag,
- FallbackDefault: 20,
- Start: startFlag,
- All: allFlag,
+ return cmdutil.RunList(cmd, c, cmdutil.ListSpec[backup.SystemBackupRun]{
+ Resource: "backups",
+ Endpoint: types.Backups(),
+ Params: cmdutil.ListParams{Resource: "backups", Limit: limitFlag, FallbackDefault: 20, Start: startFlag, All: allFlag},
+ JSON: cmdutil.JSONOutputEnabled(cmd),
+ Headers: []string{"ID", "STATUS", "TRIGGER", "DESTINATION", "SIZE", "S3 DESTINATION", "CREATED"},
+ Row: func(run backup.SystemBackupRun) []string {
+ size := ""
+ if run.Size > 0 {
+ size = output.Bytes(run.Size)
+ }
+ return []string{
+ run.ID,
+ run.Status,
+ run.Trigger,
+ string(run.Destination),
+ size,
+ run.S3DestinationName,
+ run.CreatedAt.Format("2006-01-02 15:04"),
+ }
+ },
})
- if err != nil {
- return errors.WrapIf(err, "failed to build pagination query")
- }
-
- resp, err := c.Get(cmd.Context(), path)
- if err != nil {
- return errors.WrapIf(err, "failed to list backups")
- }
- defer func() { _ = resp.Body.Close() }()
-
- body, err := cmdutil.ReadJSONBody(resp)
- if err != nil {
- return errors.WrapIf(err, "failed to list backups")
- }
-
- if cmdutil.JSONOutputEnabled(cmd) {
- return cmdutil.PrintRawJSON(body)
- }
-
- var result base.Paginated[backup.SystemBackupRun]
- if err := json.Unmarshal(body, &result); err != nil {
- return errors.WrapIf(err, "failed to parse response")
- }
-
- headers := []string{"ID", "STATUS", "TRIGGER", "DESTINATION", "SIZE", "S3 DESTINATION", "CREATED"}
- rows := make([][]string, len(result.Data))
- for i, run := range result.Data {
- size := ""
- if run.Size > 0 {
- size = output.Bytes(run.Size)
- }
- rows[i] = []string{
- run.ID,
- run.Status,
- run.Trigger,
- string(run.Destination),
- size,
- run.S3DestinationName,
- run.CreatedAt.Format("2006-01-02 15:04"),
- }
- }
-
- output.Table(headers, rows)
- output.Showing(len(result.Data), result.Pagination.TotalItems, "backups")
- return nil
},
}
@@ -147,7 +118,7 @@ alone stores it in S3, and --local together with --s3-destination stores it in b
s3DestinationID := ""
if createS3Destination != "" {
- resolved, err := resolveS3Destination(cmd.Context(), c, createS3Destination, !cmdutil.JSONOutputEnabled(cmd))
+ resolved, _, err := s3DestinationRef.Resolve(cmd.Context(), c, createS3Destination, !cmdutil.JSONOutputEnabled(cmd) && prompt.IsInteractive())
if err != nil {
return err
}
@@ -182,27 +153,13 @@ alone stores it in S3, and --local together with --s3-destination stores it in b
PolicyID: createPolicyID,
}
- resp, err := c.Post(cmd.Context(), types.Backups(), req)
- if err != nil {
- return errors.WrapIf(err, "failed to create backup")
- }
- defer func() { _ = resp.Body.Close() }()
- if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
- return errors.WrapIf(err, "failed to create backup")
- }
-
- body, err := cmdutil.ReadJSONBody(resp)
+ run, err := c.DoJSON[backup.SystemBackupRun](cmd.Context(), http.MethodPost, types.Backups(), req)
if err != nil {
return errors.WrapIf(err, "failed to create backup")
}
if cmdutil.JSONOutputEnabled(cmd) {
- return cmdutil.PrintRawJSON(body)
- }
-
- var run backup.SystemBackupRun
- if err := json.Unmarshal(body, &run); err != nil {
- return errors.WrapIf(err, "failed to parse response")
+ return cmdutil.PrintJSON(run)
}
output.Success("Backup %s created successfully", run.ID)
@@ -242,21 +199,13 @@ var deleteCmd = &cobra.Command{
return err
}
- resp, err := c.DeleteWithBody(cmd.Context(), types.Backup(args[0]), backup.DeleteSystemBackupRequest{RecoveryKey: deleteRecoveryKey})
+ result, err := c.DoJSON[base.ApiResponse[base.MessageResponse]](cmd.Context(), http.MethodDelete, types.Backup(args[0]), backup.DeleteSystemBackupRequest{RecoveryKey: deleteRecoveryKey})
if err != nil {
return errors.WrapIf(err, "failed to delete backup")
}
- defer func() { _ = resp.Body.Close() }()
- if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
- return errors.WrapIf(err, "failed to delete backup")
- }
if cmdutil.JSONOutputEnabled(cmd) {
- body, err := cmdutil.ReadJSONBody(resp)
- if err != nil {
- return errors.WrapIf(err, "failed to delete backup")
- }
- return cmdutil.PrintRawJSON(body)
+ return cmdutil.PrintJSON(result.Data)
}
output.Success("Backup %s deleted successfully", args[0])
@@ -305,27 +254,13 @@ var restoreCmd = &cobra.Command{
return err
}
- resp, err := c.Post(cmd.Context(), types.BackupRestore(args[0]), backup.RestoreSystemBackupRequest{RecoveryKey: key})
- if err != nil {
- return errors.WrapIf(err, "failed to restore backup")
- }
- defer func() { _ = resp.Body.Close() }()
- if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
- return errors.WrapIf(err, "failed to restore backup")
- }
-
- body, err := cmdutil.ReadJSONBody(resp)
+ result, err := c.PostJSON[base.MessageResponse](cmd.Context(), types.BackupRestore(args[0]), backup.RestoreSystemBackupRequest{RecoveryKey: key})
if err != nil {
return errors.WrapIf(err, "failed to restore backup")
}
if cmdutil.JSONOutputEnabled(cmd) {
- return cmdutil.PrintRawJSON(body)
- }
-
- var result base.ApiResponse[base.MessageResponse]
- if err := json.Unmarshal(body, &result); err != nil {
- return errors.WrapIf(err, "failed to parse response")
+ return cmdutil.PrintJSON(result.Data)
}
output.Success("%s", result.Data.Message)
@@ -345,7 +280,7 @@ var uploadCmd = &cobra.Command{
return err
}
- resolved, err := resolveS3Destination(cmd.Context(), c, uploadS3Destination, !cmdutil.JSONOutputEnabled(cmd))
+ resolved, _, err := s3DestinationRef.Resolve(cmd.Context(), c, uploadS3Destination, !cmdutil.JSONOutputEnabled(cmd) && prompt.IsInteractive())
if err != nil {
return err
}
@@ -355,27 +290,13 @@ var uploadCmd = &cobra.Command{
RecoveryKey: uploadRecoveryKey,
}
- resp, err := c.Post(cmd.Context(), types.BackupUpload(args[0]), req)
- if err != nil {
- return errors.WrapIf(err, "failed to upload backup")
- }
- defer func() { _ = resp.Body.Close() }()
- if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
- return errors.WrapIf(err, "failed to upload backup")
- }
-
- body, err := cmdutil.ReadJSONBody(resp)
+ run, err := c.DoJSON[backup.SystemBackupRun](cmd.Context(), http.MethodPost, types.BackupUpload(args[0]), req)
if err != nil {
return errors.WrapIf(err, "failed to upload backup")
}
if cmdutil.JSONOutputEnabled(cmd) {
- return cmdutil.PrintRawJSON(body)
- }
-
- var run backup.SystemBackupRun
- if err := json.Unmarshal(body, &run); err != nil {
- return errors.WrapIf(err, "failed to parse response")
+ return cmdutil.PrintJSON(run)
}
output.Success("Backup %s uploaded successfully", run.ID)
@@ -399,7 +320,7 @@ var discoverCmd = &cobra.Command{
return err
}
- resolved, err := resolveS3Destination(cmd.Context(), c, discoverS3Destination, !cmdutil.JSONOutputEnabled(cmd))
+ resolved, _, err := s3DestinationRef.Resolve(cmd.Context(), c, discoverS3Destination, !cmdutil.JSONOutputEnabled(cmd) && prompt.IsInteractive())
if err != nil {
return err
}
@@ -409,27 +330,13 @@ var discoverCmd = &cobra.Command{
RecoveryKey: discoverRecoveryKey,
}
- resp, err := c.Post(cmd.Context(), types.BackupsDiscover(), req)
- if err != nil {
- return errors.WrapIf(err, "failed to discover backups")
- }
- defer func() { _ = resp.Body.Close() }()
- if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
- return errors.WrapIf(err, "failed to discover backups")
- }
-
- body, err := cmdutil.ReadJSONBody(resp)
+ result, err := c.PostJSON[int](cmd.Context(), types.BackupsDiscover(), req)
if err != nil {
return errors.WrapIf(err, "failed to discover backups")
}
if cmdutil.JSONOutputEnabled(cmd) {
- return cmdutil.PrintRawJSON(body)
- }
-
- var result base.ApiResponse[int]
- if err := json.Unmarshal(body, &result); err != nil {
- return errors.WrapIf(err, "failed to parse response")
+ return cmdutil.PrintJSON(result.Data)
}
output.Success("Discovered %d backup(s)", result.Data)
@@ -448,24 +355,13 @@ var policiesCmd = &cobra.Command{
return err
}
- resp, err := c.Get(cmd.Context(), types.BackupsPolicies())
- if err != nil {
- return errors.WrapIf(err, "failed to get backup policies")
- }
- defer func() { _ = resp.Body.Close() }()
-
- body, err := cmdutil.ReadJSONBody(resp)
+ result, err := c.DoJSON[backup.SystemBackupPolicyCollection](cmd.Context(), http.MethodGet, types.BackupsPolicies(), nil)
if err != nil {
return errors.WrapIf(err, "failed to get backup policies")
}
if cmdutil.JSONOutputEnabled(cmd) {
- return cmdutil.PrintRawJSON(body)
- }
-
- var result backup.SystemBackupPolicyCollection
- if err := json.Unmarshal(body, &result); err != nil {
- return errors.WrapIf(err, "failed to parse response")
+ return cmdutil.PrintJSON(result)
}
printPolicies(result)
@@ -540,19 +436,10 @@ Alternatively, --file replaces all policies from a raw JSON payload.`,
return errors.WrapIf(err, "failed to parse policies file")
}
} else {
- currentResp, err := c.Get(cmd.Context(), types.BackupsPolicies())
+ current, err := c.DoJSON[backup.SystemBackupPolicyCollection](cmd.Context(), http.MethodGet, types.BackupsPolicies(), nil)
if err != nil {
return errors.WrapIf(err, "failed to get current backup policies")
}
- defer func() { _ = currentResp.Body.Close() }()
- if err := cmdutil.EnsureSuccessStatus(currentResp); err != nil {
- return errors.WrapIf(err, "failed to get current backup policies")
- }
-
- var current backup.SystemBackupPolicyCollection
- if err := cmdutil.DecodeJSON(currentResp, &current); err != nil {
- return err
- }
req.Policies = make([]backup.UpdateSystemBackupPolicy, len(current.Policies))
targetIndex := -1
@@ -607,7 +494,7 @@ Alternatively, --file replaces all policies from a raw JSON payload.`,
target.S3Enabled = policiesUpdateS3
}
if cmd.Flags().Changed("s3-destination") {
- resolved, err := resolveS3Destination(cmd.Context(), c, policiesUpdateS3Destination, !cmdutil.JSONOutputEnabled(cmd))
+ resolved, _, err := s3DestinationRef.Resolve(cmd.Context(), c, policiesUpdateS3Destination, !cmdutil.JSONOutputEnabled(cmd) && prompt.IsInteractive())
if err != nil {
return err
}
@@ -618,27 +505,13 @@ Alternatively, --file replaces all policies from a raw JSON payload.`,
}
}
- resp, err := c.Put(cmd.Context(), types.BackupsPolicies(), req)
- if err != nil {
- return errors.WrapIf(err, "failed to update backup policies")
- }
- defer func() { _ = resp.Body.Close() }()
- if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
- return errors.WrapIf(err, "failed to update backup policies")
- }
-
- body, err := cmdutil.ReadJSONBody(resp)
+ result, err := c.DoJSON[backup.SystemBackupPolicyCollection](cmd.Context(), http.MethodPut, types.BackupsPolicies(), req)
if err != nil {
return errors.WrapIf(err, "failed to update backup policies")
}
if cmdutil.JSONOutputEnabled(cmd) {
- return cmdutil.PrintRawJSON(body)
- }
-
- var result backup.SystemBackupPolicyCollection
- if err := json.Unmarshal(body, &result); err != nil {
- return errors.WrapIf(err, "failed to parse response")
+ return cmdutil.PrintJSON(result)
}
output.Success("Backup policies updated successfully")
@@ -663,32 +536,18 @@ var recoveryKeyGenerateCmd = &cobra.Command{
return err
}
- resp, err := c.Post(cmd.Context(), types.BackupsRecoveryKeyGenerate(), nil)
- if err != nil {
- return errors.WrapIf(err, "failed to generate recovery key")
- }
- defer func() { _ = resp.Body.Close() }()
- if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
- return errors.WrapIf(err, "failed to generate recovery key")
- }
-
- body, err := cmdutil.ReadJSONBody(resp)
+ result, err := c.DoJSON[backup.SystemBackupRecoveryKey](cmd.Context(), http.MethodPost, types.BackupsRecoveryKeyGenerate(), nil)
if err != nil {
return errors.WrapIf(err, "failed to generate recovery key")
}
- var result backup.SystemBackupRecoveryKey
- if err := json.Unmarshal(body, &result); err != nil {
- return errors.WrapIf(err, "failed to parse response")
- }
-
if cmdutil.JSONOutputEnabled(cmd) {
if generateSave {
if err := storeRecoveryKey(cmd, c, result.RecoveryKey); err != nil {
return err
}
}
- return cmdutil.PrintRawJSON(body)
+ return cmdutil.PrintJSON(result)
}
output.Header("Generated Recovery Key")
@@ -742,21 +601,13 @@ var recoveryKeySetCmd = &cobra.Command{
return err
}
- resp, err := c.Put(cmd.Context(), types.BackupsRecoveryKey(), backup.SystemBackupRecoveryKey{RecoveryKey: key})
+ status, err := c.DoJSON[backup.SystemBackupRecoveryKeyStatus](cmd.Context(), http.MethodPut, types.BackupsRecoveryKey(), backup.SystemBackupRecoveryKey{RecoveryKey: key})
if err != nil {
return errors.WrapIf(err, "failed to set recovery key")
}
- defer func() { _ = resp.Body.Close() }()
- if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
- return errors.WrapIf(err, "failed to set recovery key")
- }
if cmdutil.JSONOutputEnabled(cmd) {
- body, err := cmdutil.ReadJSONBody(resp)
- if err != nil {
- return errors.WrapIf(err, "failed to set recovery key")
- }
- return cmdutil.PrintRawJSON(body)
+ return cmdutil.PrintJSON(status)
}
output.Success("Recovery key configured successfully")
@@ -765,12 +616,8 @@ var recoveryKeySetCmd = &cobra.Command{
}
func storeRecoveryKey(cmd *cobra.Command, c *client.Client, key string) error {
- resp, err := c.Put(cmd.Context(), types.BackupsRecoveryKey(), backup.SystemBackupRecoveryKey{RecoveryKey: key})
- if err != nil {
- return errors.WrapIf(err, "failed to store recovery key")
- }
- defer func() { _ = resp.Body.Close() }()
- return errors.WrapIf(cmdutil.EnsureSuccessStatus(resp), "failed to store recovery key")
+ _, err := c.DoJSON[backup.SystemBackupRecoveryKeyStatus](cmd.Context(), http.MethodPut, types.BackupsRecoveryKey(), backup.SystemBackupRecoveryKey{RecoveryKey: key})
+ return errors.WrapIf(err, "failed to store recovery key")
}
func init() {
diff --git a/cli/pkg/backups/resolve.go b/cli/pkg/backups/resolve.go
index dbcdd9f8f..caca9e249 100644
--- a/cli/pkg/backups/resolve.go
+++ b/cli/pkg/backups/resolve.go
@@ -3,85 +3,49 @@ package backups
import (
"context"
"fmt"
+ "net/http"
"strings"
"emperror.dev/errors"
"github.com/getarcaneapp/arcane/cli/v2/internal/client"
"github.com/getarcaneapp/arcane/cli/v2/internal/cmdutil"
- "github.com/getarcaneapp/arcane/cli/v2/internal/prompt"
"github.com/getarcaneapp/arcane/cli/v2/internal/types"
"github.com/getarcaneapp/arcane/types/v2/backup"
)
-const maxPromptOptions = 20
-
-// resolveS3Destination resolves an S3 destination identifier (ID or name) to
-// the saved destination: exact ID first, then exact name (case-insensitive),
-// then substring match. Multiple matches prompt interactively when allowed.
-func resolveS3Destination(ctx context.Context, c *client.Client, identifier string, allowPrompt bool) (*backup.S3Destination, error) {
- trimmed := strings.TrimSpace(identifier)
- if trimmed == "" {
- return nil, errors.New("S3 destination name or ID is required")
- }
-
- resp, err := c.Get(ctx, types.BackupsS3Options())
- if err != nil {
- return nil, errors.WrapIf(err, "failed to list S3 destinations")
- }
- defer func() { _ = resp.Body.Close() }()
- if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
- return nil, errors.WrapIf(err, "failed to list S3 destinations")
- }
-
- var destinations []backup.S3Destination
- if err := cmdutil.DecodeJSON(resp, &destinations); err != nil {
- return nil, err
- }
-
- for i := range destinations {
- if destinations[i].ID == trimmed {
- return &destinations[i], nil
- }
- }
-
- matches := make([]backup.S3Destination, 0)
- for _, dest := range destinations {
- if strings.EqualFold(dest.Name, trimmed) {
- matches = append(matches, dest)
+// s3DestinationRef resolves an S3 destination by ID or name: exact ID via the
+// GET endpoint, then exact name (case-insensitive), then substring match over
+// the saved destinations.
+var s3DestinationRef = cmdutil.ResourceRef[backup.S3Destination, backup.S3Destination]{
+ Singular: "S3 destination",
+ Plural: "S3 destinations",
+ IDHint: "the destination ID",
+ ListCmd: "arcane backups s3 list",
+ GetPath: func(_, identifier string) string { return types.BackupsS3Destination(identifier) },
+ SearchCandidates: func(ctx context.Context, c *client.Client, identifier string) ([]backup.S3Destination, error) {
+ destinations, err := c.DoJSON[[]backup.S3Destination](ctx, http.MethodGet, types.BackupsS3Options(), nil)
+ if err != nil {
+ return nil, errors.WrapIf(err, "failed to list S3 destinations")
}
- }
- if len(matches) == 0 {
- identifierLower := strings.ToLower(trimmed)
+ matches := make([]backup.S3Destination, 0)
for _, dest := range destinations {
- if strings.Contains(strings.ToLower(dest.Name), identifierLower) {
+ if strings.EqualFold(dest.Name, identifier) {
matches = append(matches, dest)
}
}
- }
-
- if len(matches) == 1 {
- return &matches[0], nil
- }
-
- if len(matches) > 1 {
- if allowPrompt && prompt.IsInteractive() && len(matches) <= maxPromptOptions {
- options := make([]string, 0, len(matches))
- for _, match := range matches {
- options = append(options, fmt.Sprintf("%s (%s, bucket %s)", match.Name, match.ID, match.Bucket))
- }
- choice, err := prompt.Select("S3 destination", options)
- if err != nil {
- return nil, err
+ if len(matches) == 0 {
+ identifierLower := strings.ToLower(identifier)
+ for _, dest := range destinations {
+ if strings.Contains(strings.ToLower(dest.Name), identifierLower) {
+ matches = append(matches, dest)
+ }
}
- return &matches[choice], nil
}
- names := make([]string, 0, len(matches))
- for _, match := range matches {
- names = append(names, fmt.Sprintf("%s (%s)", match.Name, match.ID))
- }
- return nil, errors.Errorf("multiple S3 destinations match %q: %s; use the exact name or ID", trimmed, strings.Join(names, ", "))
- }
-
- return nil, errors.Errorf("S3 destination %q not found; run `arcane backups s3 list`", trimmed)
+ return matches, nil
+ },
+ Label: func(dest backup.S3Destination) string {
+ return fmt.Sprintf("%s (%s, bucket %s)", dest.Name, dest.ID, dest.Bucket)
+ },
+ Promote: func(dest backup.S3Destination) *backup.S3Destination { return &dest },
}
diff --git a/cli/pkg/backups/s3.go b/cli/pkg/backups/s3.go
index 6adfe5195..8d29d4c9f 100644
--- a/cli/pkg/backups/s3.go
+++ b/cli/pkg/backups/s3.go
@@ -1,7 +1,6 @@
package backups
import (
- "encoding/json"
"fmt"
"net/http"
"strconv"
@@ -10,6 +9,7 @@ import (
"github.com/getarcaneapp/arcane/cli/v2/internal/cmdutil"
"github.com/getarcaneapp/arcane/cli/v2/internal/output"
+ "github.com/getarcaneapp/arcane/cli/v2/internal/prompt"
"github.com/getarcaneapp/arcane/cli/v2/internal/types"
"github.com/getarcaneapp/arcane/types/v2/backup"
"github.com/getarcaneapp/arcane/types/v2/base"
@@ -46,67 +46,31 @@ var s3ListCmd = &cobra.Command{
return err
}
- path, err := cmdutil.ApplyPaginationParams(cmd, types.BackupsS3(), cmdutil.ListParams{
- Resource: "s3 destinations",
- Limit: limitFlag,
- FallbackDefault: 20,
- Start: startFlag,
- All: allFlag,
+ return cmdutil.RunList(cmd, c, cmdutil.ListSpec[backup.S3Destination]{
+ Resource: "S3 destinations",
+ Endpoint: types.BackupsS3(),
+ Params: cmdutil.ListParams{Resource: "s3 destinations", Limit: limitFlag, FallbackDefault: 20, Start: startFlag, All: allFlag},
+ JSON: cmdutil.JSONOutputEnabled(cmd),
+ Headers: []string{"ID", "NAME", "BUCKET", "REGION", "ENDPOINT", "SSL", "SECRET"},
+ Row: func(dest backup.S3Destination) []string {
+ secret := "Not set"
+ if dest.SecretConfigured {
+ secret = "Set"
+ }
+ return []string{
+ dest.ID,
+ dest.Name,
+ dest.Bucket,
+ dest.Region,
+ dest.Endpoint,
+ strconv.FormatBool(dest.UseSSL),
+ secret,
+ }
+ },
})
- if err != nil {
- return errors.WrapIf(err, "failed to build pagination query")
- }
-
- resp, err := c.Get(cmd.Context(), path)
- if err != nil {
- return errors.WrapIf(err, "failed to list S3 destinations")
- }
- defer func() { _ = resp.Body.Close() }()
-
- body, err := cmdutil.ReadJSONBody(resp)
- if err != nil {
- return errors.WrapIf(err, "failed to list S3 destinations")
- }
-
- if cmdutil.JSONOutputEnabled(cmd) {
- return cmdutil.PrintRawJSON(body)
- }
-
- var result base.Paginated[backup.S3Destination]
- if err := json.Unmarshal(body, &result); err != nil {
- return errors.WrapIf(err, "failed to parse response")
- }
-
- output.Table(s3TableHeaders(), s3TableRows(result.Data))
- output.Showing(len(result.Data), result.Pagination.TotalItems, "S3 destinations")
- return nil
},
}
-func s3TableHeaders() []string {
- return []string{"ID", "NAME", "BUCKET", "REGION", "ENDPOINT", "SSL", "SECRET"}
-}
-
-func s3TableRows(destinations []backup.S3Destination) [][]string {
- rows := make([][]string, len(destinations))
- for i, dest := range destinations {
- secret := "Not set"
- if dest.SecretConfigured {
- secret = "Set"
- }
- rows[i] = []string{
- dest.ID,
- dest.Name,
- dest.Bucket,
- dest.Region,
- dest.Endpoint,
- strconv.FormatBool(dest.UseSSL),
- secret,
- }
- }
- return rows
-}
-
var s3GetCmd = &cobra.Command{
Use: "get <destination>",
Short: "Get S3 destination details by name or ID",
@@ -118,51 +82,26 @@ var s3GetCmd = &cobra.Command{
return err
}
- resolved, err := resolveS3Destination(cmd.Context(), c, args[0], !cmdutil.JSONOutputEnabled(cmd))
+ resolved, _, err := s3DestinationRef.Resolve(cmd.Context(), c, args[0], !cmdutil.JSONOutputEnabled(cmd) && prompt.IsInteractive())
if err != nil {
return err
}
-
- resp, err := c.Get(cmd.Context(), types.BackupsS3Destination(resolved.ID))
- if err != nil {
- return errors.WrapIf(err, "failed to get S3 destination")
- }
- defer func() { _ = resp.Body.Close() }()
-
- body, err := cmdutil.ReadJSONBody(resp)
- if err != nil {
- return errors.WrapIf(err, "failed to get S3 destination")
- }
+ dest := *resolved
if !s3GetInUse {
if cmdutil.JSONOutputEnabled(cmd) {
- return cmdutil.PrintRawJSON(body)
- }
- var dest backup.S3Destination
- if err := json.Unmarshal(body, &dest); err != nil {
- return errors.WrapIf(err, "failed to parse response")
+ return cmdutil.PrintJSON(dest)
}
printS3Destination(dest)
return nil
}
- var dest backup.S3Destination
- if err := json.Unmarshal(body, &dest); err != nil {
- return errors.WrapIf(err, "failed to parse response")
- }
-
- usageResp, err := c.Get(cmd.Context(), types.BackupsS3DestinationInUse(resolved.ID))
+ usage, err := c.DoJSON[struct {
+ InUse bool `json:"inUse"`
+ }](cmd.Context(), http.MethodGet, types.BackupsS3DestinationInUse(resolved.ID), nil)
if err != nil {
return errors.WrapIf(err, "failed to check S3 destination usage")
}
- defer func() { _ = usageResp.Body.Close() }()
-
- var usage struct {
- InUse bool `json:"inUse"`
- }
- if err := cmdutil.DecodeJSON(usageResp, &usage); err != nil {
- return err
- }
if cmdutil.JSONOutputEnabled(cmd) {
return cmdutil.PrintJSON(map[string]any{"destination": dest, "inUse": usage.InUse})
@@ -222,27 +161,13 @@ var s3CreateCmd = &cobra.Command{
return err
}
- resp, err := c.Post(cmd.Context(), types.BackupsS3(), s3DestinationFromFlags())
- if err != nil {
- return errors.WrapIf(err, "failed to create S3 destination")
- }
- defer func() { _ = resp.Body.Close() }()
- if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
- return errors.WrapIf(err, "failed to create S3 destination")
- }
-
- body, err := cmdutil.ReadJSONBody(resp)
+ dest, err := c.DoJSON[backup.S3Destination](cmd.Context(), http.MethodPost, types.BackupsS3(), s3DestinationFromFlags())
if err != nil {
return errors.WrapIf(err, "failed to create S3 destination")
}
if cmdutil.JSONOutputEnabled(cmd) {
- return cmdutil.PrintRawJSON(body)
- }
-
- var dest backup.S3Destination
- if err := json.Unmarshal(body, &dest); err != nil {
- return errors.WrapIf(err, "failed to parse response")
+ return cmdutil.PrintJSON(dest)
}
output.Success("S3 destination %s created successfully", dest.Name)
@@ -262,32 +187,18 @@ var s3UpdateCmd = &cobra.Command{
return err
}
- resolved, err := resolveS3Destination(cmd.Context(), c, args[0], !cmdutil.JSONOutputEnabled(cmd))
+ resolved, _, err := s3DestinationRef.Resolve(cmd.Context(), c, args[0], !cmdutil.JSONOutputEnabled(cmd) && prompt.IsInteractive())
if err != nil {
return err
}
- resp, err := c.Put(cmd.Context(), types.BackupsS3Destination(resolved.ID), s3DestinationFromFlags())
- if err != nil {
- return errors.WrapIf(err, "failed to update S3 destination")
- }
- defer func() { _ = resp.Body.Close() }()
- if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
- return errors.WrapIf(err, "failed to update S3 destination")
- }
-
- body, err := cmdutil.ReadJSONBody(resp)
+ dest, err := c.DoJSON[backup.S3Destination](cmd.Context(), http.MethodPut, types.BackupsS3Destination(resolved.ID), s3DestinationFromFlags())
if err != nil {
return errors.WrapIf(err, "failed to update S3 destination")
}
if cmdutil.JSONOutputEnabled(cmd) {
- return cmdutil.PrintRawJSON(body)
- }
-
- var dest backup.S3Destination
- if err := json.Unmarshal(body, &dest); err != nil {
- return errors.WrapIf(err, "failed to parse response")
+ return cmdutil.PrintJSON(dest)
}
output.Success("S3 destination %s updated successfully", dest.Name)
@@ -308,7 +219,7 @@ var s3DeleteCmd = &cobra.Command{
return err
}
- resolved, err := resolveS3Destination(cmd.Context(), c, args[0], !forceFlag && !cmdutil.JSONOutputEnabled(cmd))
+ resolved, _, err := s3DestinationRef.Resolve(cmd.Context(), c, args[0], !forceFlag && !cmdutil.JSONOutputEnabled(cmd) && prompt.IsInteractive())
if err != nil {
return err
}
@@ -324,21 +235,13 @@ var s3DeleteCmd = &cobra.Command{
}
}
- resp, err := c.Delete(cmd.Context(), types.BackupsS3Destination(resolved.ID))
+ result, err := c.DeleteJSON[base.MessageResponse](cmd.Context(), types.BackupsS3Destination(resolved.ID))
if err != nil {
return errors.WrapIf(err, "failed to delete S3 destination")
}
- defer func() { _ = resp.Body.Close() }()
- if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
- return errors.WrapIf(err, "failed to delete S3 destination")
- }
if cmdutil.JSONOutputEnabled(cmd) {
- body, err := cmdutil.ReadJSONBody(resp)
- if err != nil {
- return errors.WrapIf(err, "failed to delete S3 destination")
- }
- return cmdutil.PrintRawJSON(body)
+ return cmdutil.PrintJSON(result.Data)
}
output.Success("S3 destination %s deleted successfully", resolved.Name)
@@ -367,39 +270,28 @@ passing the connection flags (--name, --bucket, --region, ...) with no argument.
return err
}
- var resp *http.Response
+ testPath := types.BackupsS3Test()
+ var testBody any = s3DestinationFromFlags()
if len(args) == 1 {
if connectionFlagsSet {
return errors.New("pass either a saved destination name or ID, or the connection flags, not both")
}
- resolved, err := resolveS3Destination(cmd.Context(), c, args[0], !cmdutil.JSONOutputEnabled(cmd))
+ resolved, _, err := s3DestinationRef.Resolve(cmd.Context(), c, args[0], !cmdutil.JSONOutputEnabled(cmd) && prompt.IsInteractive())
if err != nil {
return err
}
- resp, err = c.Post(cmd.Context(), types.BackupsS3DestinationTest(resolved.ID), nil)
- if err != nil {
- return errors.WrapIf(err, "failed to test S3 destination")
- }
- } else {
- if s3Bucket == "" {
- return errors.New("either a destination name or ID, or connection flags (--name, --bucket, --region, ...) are required")
- }
- resp, err = c.Post(cmd.Context(), types.BackupsS3Test(), s3DestinationFromFlags())
- if err != nil {
- return errors.WrapIf(err, "failed to test S3 destination")
- }
+ testPath, testBody = types.BackupsS3DestinationTest(resolved.ID), nil
+ } else if s3Bucket == "" {
+ return errors.New("either a destination name or ID, or connection flags (--name, --bucket, --region, ...) are required")
}
- defer func() { _ = resp.Body.Close() }()
- if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
+
+ result, err := c.PostJSON[base.MessageResponse](cmd.Context(), testPath, testBody)
+ if err != nil {
return errors.WrapIf(err, "failed to test S3 destination")
}
if cmdutil.JSONOutputEnabled(cmd) {
- body, err := cmdutil.ReadJSONBody(resp)
- if err != nil {
- return errors.WrapIf(err, "failed to test S3 destination")
- }
- return cmdutil.PrintRawJSON(body)
+ return cmdutil.PrintJSON(result.Data)
}
output.Success("S3 connection test succeeded")
diff --git a/cli/pkg/containers/actions.go b/cli/pkg/containers/actions.go
index 632e94361..75c4d637c 100644
--- a/cli/pkg/containers/actions.go
+++ b/cli/pkg/containers/actions.go
@@ -1,7 +1,7 @@
package containers
import (
- "encoding/json"
+ "encoding/json/v2"
"fmt"
"net/url"
"os"
@@ -10,7 +10,6 @@ import (
"emperror.dev/errors"
- "github.com/getarcaneapp/arcane/cli/v2/internal/client"
"github.com/getarcaneapp/arcane/cli/v2/internal/cmdutil"
"github.com/getarcaneapp/arcane/cli/v2/internal/output"
"github.com/getarcaneapp/arcane/cli/v2/internal/types"
@@ -40,16 +39,24 @@ var containersKillCmd = &cobra.Command{
Args: cobra.ExactArgs(1),
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
- return runContainerPostAction[base.MessageResponse](cmd, args[0], containerPostActionConfig[base.MessageResponse]{
- endpoint: func(envID, containerID string) string {
- path := types.ContainerKill(envID, containerID)
- if signal := strings.TrimSpace(killSignal); signal != "" {
- path += "?signal=" + url.QueryEscape(signal)
- }
- return path
- },
- failureMessage: "failed to kill container",
- successVerb: "killed",
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
+ resolved, _, err := containerRef.Resolve(cmd.Context(), c, args[0], false)
+ if err != nil {
+ return err
+ }
+
+ path := types.ContainerKill(c.EnvID(), resolved.ID)
+ if signal := strings.TrimSpace(killSignal); signal != "" {
+ path += "?signal=" + url.QueryEscape(signal)
+ }
+ return cmdutil.RunPostAction[base.MessageResponse](cmd, c, cmdutil.PostActionSpec{
+ Path: path,
+ FailureMessage: "failed to kill container",
+ SuccessMessage: fmt.Sprintf("Container %s killed successfully", containerDisplayName(resolved)),
+ JSON: jsonOutput,
})
},
}
@@ -60,10 +67,19 @@ var containersPauseCmd = &cobra.Command{
Args: cobra.ExactArgs(1),
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
- return runContainerPostAction[base.MessageResponse](cmd, args[0], containerPostActionConfig[base.MessageResponse]{
- endpoint: types.ContainerPause,
- failureMessage: "failed to pause container",
- successVerb: "paused",
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
+ resolved, _, err := containerRef.Resolve(cmd.Context(), c, args[0], false)
+ if err != nil {
+ return err
+ }
+ return cmdutil.RunPostAction[base.MessageResponse](cmd, c, cmdutil.PostActionSpec{
+ Path: types.ContainerPause(c.EnvID(), resolved.ID),
+ FailureMessage: "failed to pause container",
+ SuccessMessage: fmt.Sprintf("Container %s paused successfully", containerDisplayName(resolved)),
+ JSON: jsonOutput,
})
},
}
@@ -74,10 +90,19 @@ var containersUnpauseCmd = &cobra.Command{
Args: cobra.ExactArgs(1),
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
- return runContainerPostAction[base.MessageResponse](cmd, args[0], containerPostActionConfig[base.MessageResponse]{
- endpoint: types.ContainerUnpause,
- failureMessage: "failed to unpause container",
- successVerb: "unpaused",
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
+ resolved, _, err := containerRef.Resolve(cmd.Context(), c, args[0], false)
+ if err != nil {
+ return err
+ }
+ return cmdutil.RunPostAction[base.MessageResponse](cmd, c, cmdutil.PostActionSpec{
+ Path: types.ContainerUnpause(c.EnvID(), resolved.ID),
+ FailureMessage: "failed to unpause container",
+ SuccessMessage: fmt.Sprintf("Container %s unpaused successfully", containerDisplayName(resolved)),
+ JSON: jsonOutput,
})
},
}
@@ -88,12 +113,12 @@ var containersCommitCmd = &cobra.Command{
Args: cobra.ExactArgs(1),
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
- c, err := client.NewFromConfig()
+ c, err := cmdutil.ClientFromCommand(cmd)
if err != nil {
return err
}
- resolved, _, err := resolveContainer(cmd.Context(), c, args[0], false)
+ resolved, _, err := containerRef.Resolve(cmd.Context(), c, args[0], false)
if err != nil {
return err
}
@@ -109,27 +134,13 @@ var containersCommitCmd = &cobra.Command{
c.SetTimeout(30 * time.Minute)
- resp, err := c.Post(cmd.Context(), types.ContainerCommit(c.EnvID(), resolved.ID), body)
+ result, err := c.PostJSON[container.CommitResult](cmd.Context(), types.ContainerCommit(c.EnvID(), resolved.ID), body)
if err != nil {
return errors.WrapIf(err, "failed to commit container")
}
- defer func() { _ = resp.Body.Close() }()
- if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
- return errors.WrapIf(err, "failed to commit container")
- }
-
- var result base.ApiResponse[container.CommitResult]
- if err := cmdutil.DecodeJSON(resp, &result); err != nil {
- return err
- }
if jsonOutput {
- resultBytes, err := json.MarshalIndent(result.Data, "", " ")
- if err != nil {
- return errors.WrapIf(err, "failed to marshal JSON")
- }
- fmt.Println(string(resultBytes))
- return nil
+ return cmdutil.PrintJSON(result.Data)
}
output.Success("Container %s committed successfully", containerDisplayName(resolved))
@@ -145,37 +156,23 @@ var containersEditCmd = &cobra.Command{
Args: cobra.ExactArgs(1),
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
- c, err := client.NewFromConfig()
+ c, err := cmdutil.ClientFromCommand(cmd)
if err != nil {
return err
}
- resolved, _, err := resolveContainer(cmd.Context(), c, args[0], false)
+ resolved, _, err := containerRef.Resolve(cmd.Context(), c, args[0], false)
if err != nil {
return err
}
if editFile == "" {
- resp, err := c.Get(cmd.Context(), types.ContainerEditConfig(c.EnvID(), resolved.ID))
+ result, err := c.GetJSON[container.EditConfig](cmd.Context(), types.ContainerEditConfig(c.EnvID(), resolved.ID))
if err != nil {
return errors.WrapIf(err, "failed to get container edit config")
}
- defer func() { _ = resp.Body.Close() }()
- if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
- return errors.WrapIf(err, "failed to get container edit config")
- }
-
- var result base.ApiResponse[container.EditConfig]
- if err := cmdutil.DecodeJSON(resp, &result); err != nil {
- return err
- }
- resultBytes, err := json.MarshalIndent(result.Data, "", " ")
- if err != nil {
- return errors.WrapIf(err, "failed to marshal JSON")
- }
- fmt.Println(string(resultBytes))
- return nil
+ return cmdutil.PrintJSON(result.Data)
}
data, err := os.ReadFile(editFile)
@@ -189,27 +186,13 @@ var containersEditCmd = &cobra.Command{
c.SetTimeout(30 * time.Minute)
- resp, err := c.Post(cmd.Context(), types.ContainerEdit(c.EnvID(), resolved.ID), body)
+ result, err := c.PostJSON[container.Details](cmd.Context(), types.ContainerEdit(c.EnvID(), resolved.ID), body)
if err != nil {
return errors.WrapIf(err, "failed to edit container")
}
- defer func() { _ = resp.Body.Close() }()
- if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
- return errors.WrapIf(err, "failed to edit container")
- }
-
- var result base.ApiResponse[container.Details]
- if err := cmdutil.DecodeJSON(resp, &result); err != nil {
- return err
- }
if jsonOutput {
- resultBytes, err := json.MarshalIndent(result.Data, "", " ")
- if err != nil {
- return errors.WrapIf(err, "failed to marshal JSON")
- }
- fmt.Println(string(resultBytes))
- return nil
+ return cmdutil.PrintJSON(result.Data)
}
output.Success("Container %s edited successfully", containerDisplayName(resolved))
@@ -224,12 +207,12 @@ var containersAutoUpdateCmd = &cobra.Command{
Args: cobra.ExactArgs(1),
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
- c, err := client.NewFromConfig()
+ c, err := cmdutil.ClientFromCommand(cmd)
if err != nil {
return err
}
- resolved, _, err := resolveContainer(cmd.Context(), c, args[0], false)
+ resolved, _, err := containerRef.Resolve(cmd.Context(), c, args[0], false)
if err != nil {
return err
}
@@ -238,27 +221,13 @@ var containersAutoUpdateCmd = &cobra.Command{
Enabled bool `json:"enabled"`
}{Enabled: autoUpdateEnabled}
- resp, err := c.Put(cmd.Context(), types.ContainerAutoUpdate(c.EnvID(), resolved.ID), body)
+ result, err := c.PutJSON[base.MessageResponse](cmd.Context(), types.ContainerAutoUpdate(c.EnvID(), resolved.ID), body)
if err != nil {
return errors.WrapIf(err, "failed to set container auto-update")
}
- defer func() { _ = resp.Body.Close() }()
- if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
- return errors.WrapIf(err, "failed to set container auto-update")
- }
-
- var result base.ApiResponse[base.MessageResponse]
- if err := cmdutil.DecodeJSON(resp, &result); err != nil {
- return err
- }
if jsonOutput {
- resultBytes, err := json.MarshalIndent(result.Data, "", " ")
- if err != nil {
- return errors.WrapIf(err, "failed to marshal JSON")
- }
- fmt.Println(string(resultBytes))
- return nil
+ return cmdutil.PrintJSON(result.Data)
}
state := "disabled"
diff --git a/cli/pkg/containers/cmd.go b/cli/pkg/containers/cmd.go
index 5ed04208b..d575ef1fa 100644
--- a/cli/pkg/containers/cmd.go
+++ b/cli/pkg/containers/cmd.go
@@ -1,11 +1,8 @@
package containers
import (
- "context"
- "encoding/json"
+ "encoding/json/v2"
"fmt"
- "io"
- "net/http"
"net/url"
"os"
"strconv"
@@ -55,8 +52,6 @@ var (
containerCreateCmd string
)
-const maxPromptOptions = 20
-
// ContainersCmd is the parent command for container operations
var ContainersCmd = &cobra.Command{
Use: "containers",
@@ -89,40 +84,45 @@ func runContainersList(cmd *cobra.Command, forceHasUpdateFilter bool) error {
return err
}
- path, err := buildContainersListPath(cmd, c, forceHasUpdateFilter)
- if err != nil {
- return err
- }
- resp, err := c.Get(cmd.Context(), path)
- if err != nil {
- return errors.WrapIf(err, "failed to list containers")
+ query := url.Values{}
+ if containersStandalone != "" {
+ query.Set("standalone", containersStandalone)
}
- defer func() { _ = resp.Body.Close() }()
-
- body, err := cmdutil.ReadJSONBody(resp)
- if err != nil {
- return errors.WrapIf(err, "failed to list containers")
+ if containersIncludeInternal {
+ query.Set("includeInternal", "true")
}
-
- if jsonOutput {
- return cmdutil.PrintRawJSON(body)
+ updatesFilter := strings.TrimSpace(containersUpdatesFilter)
+ if forceHasUpdateFilter {
+ updatesFilter = "has_update"
}
-
- var result base.Paginated[container.Summary]
- if err := json.Unmarshal(body, &result); err != nil {
- return errors.WrapIf(err, "failed to parse response")
+ if updatesFilter != "" {
+ query.Set("updates", updatesFilter)
}
- effectiveUpdatesFilter := strings.TrimSpace(containersUpdatesFilter)
- if forceHasUpdateFilter {
- effectiveUpdatesFilter = "has_update"
+ spec := cmdutil.ListSpec[container.Summary]{
+ Resource: "containers",
+ Endpoint: types.Containers(c.EnvID()),
+ Params: cmdutil.ListParams{Resource: "containers", Limit: containersLimit, FallbackDefault: 20, Start: containersStart, All: containersAll},
+ Query: query,
+ JSON: jsonOutput,
+ Headers: []string{"ID", "NAME", "IMAGE", "STATE", "STATUS"},
+ Row: func(item container.Summary) []string {
+ return []string{
+ shortID(item.ID),
+ containerSummaryName(item),
+ item.Image,
+ item.State,
+ item.Status,
+ }
+ },
}
- if effectiveUpdatesFilter != "" {
- output.Header("Container Updates")
- headers := []string{"ID", "NAME", "IMAGE", "STATE", "UPDATES", "LATEST"}
- rows := make([][]string, len(result.Data))
- for i, item := range result.Data {
- rows[i] = []string{
+ if updatesFilter != "" {
+ if !jsonOutput {
+ output.Header("Container Updates")
+ }
+ spec.Headers = []string{"ID", "NAME", "IMAGE", "STATE", "UPDATES", "LATEST"}
+ spec.Row = func(item container.Summary) []string {
+ return []string{
shortID(item.ID),
containerSummaryName(item),
item.Image,
@@ -131,62 +131,8 @@ func runContainersList(cmd *cobra.Command, forceHasUpdateFilter bool) error {
containerUpdateLatest(item),
}
}
- output.Table(headers, rows)
- output.Showing(len(result.Data), result.Pagination.TotalItems, "containers")
- return nil
- }
-
- headers := []string{"ID", "NAME", "IMAGE", "STATE", "STATUS"}
- rows := make([][]string, len(result.Data))
- for i, item := range result.Data {
- rows[i] = []string{
- shortID(item.ID),
- containerSummaryName(item),
- item.Image,
- item.State,
- item.Status,
- }
- }
-
- output.Table(headers, rows)
- output.Showing(len(result.Data), result.Pagination.TotalItems, "containers")
- return nil
-}
-
-func buildContainersListPath(cmd *cobra.Command, c *client.Client, forceHasUpdateFilter bool) (string, error) {
- path, err := cmdutil.ApplyPaginationParams(cmd, types.Containers(c.EnvID()), cmdutil.ListParams{
- Resource: "containers",
- Limit: containersLimit,
- FallbackDefault: 20,
- Start: containersStart,
- All: containersAll,
- })
- if err != nil {
- return "", errors.WrapIf(err, "failed to build pagination query")
- }
-
- parsed, err := url.Parse(path)
- if err != nil {
- return "", errors.WrapIf(err, "failed to parse path")
- }
-
- query := parsed.Query()
- if containersStandalone != "" {
- query.Set("standalone", containersStandalone)
}
- if containersIncludeInternal {
- query.Set("includeInternal", "true")
- }
- updatesFilter := strings.TrimSpace(containersUpdatesFilter)
- if forceHasUpdateFilter {
- updatesFilter = "has_update"
- }
- if updatesFilter != "" {
- query.Set("updates", updatesFilter)
- }
-
- parsed.RawQuery = query.Encode()
- return parsed.String(), nil
+ return cmdutil.RunList(cmd, c, spec)
}
func containerUpdateStatus(item container.Summary) string {
@@ -227,33 +173,21 @@ var containersGetCmd = &cobra.Command{
}
allowPrompt := !jsonOutput && prompt.IsInteractive()
- resolved, complete, err := resolveContainer(cmd.Context(), c, args[0], allowPrompt)
+ resolved, complete, err := containerRef.Resolve(cmd.Context(), c, args[0], allowPrompt)
if err != nil {
return err
}
if !complete {
- path := types.Container(c.EnvID(), resolved.ID)
- resp, err := c.Get(cmd.Context(), path)
+ result, err := c.GetJSON[container.Details](cmd.Context(), types.Container(c.EnvID(), resolved.ID))
if err != nil {
return errors.WrapIf(err, "failed to get container")
}
- defer func() { _ = resp.Body.Close() }()
-
- var result base.ApiResponse[container.Details]
- if err := cmdutil.DecodeJSON(resp, &result); err != nil {
- return err
- }
resolved = &result.Data
}
if jsonOutput {
- resultBytes, err := json.MarshalIndent(resolved, "", " ")
- if err != nil {
- return errors.WrapIf(err, "failed to marshal JSON")
- }
- fmt.Println(string(resultBytes))
- return nil
+ return cmdutil.PrintJSON(resolved)
}
output.Header("Container Details")
@@ -272,10 +206,21 @@ var containersStartCmd = &cobra.Command{
Args: cobra.ExactArgs(1),
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
- return runContainerPostAction[base.MessageResponse](cmd, args[0], containerPostActionConfig[base.MessageResponse]{
- endpoint: types.ContainerStart,
- failureMessage: "failed to start container",
- successVerb: "started",
+ c, err := client.NewFromConfig()
+ if err != nil {
+ return err
+ }
+
+ resolved, _, err := containerRef.Resolve(cmd.Context(), c, args[0], false)
+ if err != nil {
+ return err
+ }
+
+ return cmdutil.RunPostAction[base.MessageResponse](cmd, c, cmdutil.PostActionSpec{
+ Path: types.ContainerStart(c.EnvID(), resolved.ID),
+ FailureMessage: "failed to start container",
+ SuccessMessage: fmt.Sprintf("Container %s started successfully", containerDisplayName(resolved)),
+ JSON: jsonOutput,
})
},
}
@@ -286,10 +231,21 @@ var containersStopCmd = &cobra.Command{
Args: cobra.ExactArgs(1),
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
- return runContainerPostAction[base.MessageResponse](cmd, args[0], containerPostActionConfig[base.MessageResponse]{
- endpoint: types.ContainerStop,
- failureMessage: "failed to stop container",
- successVerb: "stopped",
+ c, err := client.NewFromConfig()
+ if err != nil {
+ return err
+ }
+
+ resolved, _, err := containerRef.Resolve(cmd.Context(), c, args[0], false)
+ if err != nil {
+ return err
+ }
+
+ return cmdutil.RunPostAction[base.MessageResponse](cmd, c, cmdutil.PostActionSpec{
+ Path: types.ContainerStop(c.EnvID(), resolved.ID),
+ FailureMessage: "failed to stop container",
+ SuccessMessage: fmt.Sprintf("Container %s stopped successfully", containerDisplayName(resolved)),
+ JSON: jsonOutput,
})
},
}
@@ -300,10 +256,21 @@ var containersRestartCmd = &cobra.Command{
Args: cobra.ExactArgs(1),
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
- return runContainerPostAction[base.MessageResponse](cmd, args[0], containerPostActionConfig[base.MessageResponse]{
- endpoint: types.ContainerRestart,
- failureMessage: "failed to restart container",
- successVerb: "restarted",
+ c, err := client.NewFromConfig()
+ if err != nil {
+ return err
+ }
+
+ resolved, _, err := containerRef.Resolve(cmd.Context(), c, args[0], false)
+ if err != nil {
+ return err
+ }
+
+ return cmdutil.RunPostAction[base.MessageResponse](cmd, c, cmdutil.PostActionSpec{
+ Path: types.ContainerRestart(c.EnvID(), resolved.ID),
+ FailureMessage: "failed to restart container",
+ SuccessMessage: fmt.Sprintf("Container %s restarted successfully", containerDisplayName(resolved)),
+ JSON: jsonOutput,
})
},
}
@@ -314,13 +281,24 @@ var containersUpdateCmd = &cobra.Command{
Args: cobra.ExactArgs(1),
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := client.NewFromConfig()
+ if err != nil {
+ return err
+ }
+
+ resolved, _, err := containerRef.Resolve(cmd.Context(), c, args[0], false)
+ if err != nil {
+ return err
+ }
+
// This route is served by the updater handler, so it answers with an
// updater.Result rather than a container.ActionResult.
- return runContainerPostAction[updater.Result](cmd, args[0], containerPostActionConfig[updater.Result]{
- endpoint: types.ContainerUpdate,
- failureMessage: "failed to update container",
- successVerb: "updated",
- timeout: 30 * time.Minute,
+ return cmdutil.RunPostAction[updater.Result](cmd, c, cmdutil.PostActionSpec{
+ Path: types.ContainerUpdate(c.EnvID(), resolved.ID),
+ FailureMessage: "failed to update container",
+ SuccessMessage: fmt.Sprintf("Container %s updated successfully", containerDisplayName(resolved)),
+ Timeout: 30 * time.Minute,
+ JSON: jsonOutput,
})
},
}
@@ -331,64 +309,24 @@ var containersRedeployCmd = &cobra.Command{
Args: cobra.ExactArgs(1),
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
- return runContainerPostAction[container.Details](cmd, args[0], containerPostActionConfig[container.Details]{
- endpoint: types.ContainerRedeploy,
- failureMessage: "failed to redeploy container",
- successVerb: "redeployed",
- timeout: 30 * time.Minute,
- })
- },
-}
-
-type containerPostActionConfig[T any] struct {
- endpoint func(string, string) string
- failureMessage string
- successVerb string
- timeout time.Duration
-}
-
-func runContainerPostAction[T any](cmd *cobra.Command, containerRef string, cfg containerPostActionConfig[T]) error {
- c, err := client.NewFromConfig()
- if err != nil {
- return err
- }
-
- resolved, _, err := resolveContainer(cmd.Context(), c, containerRef, false)
- if err != nil {
- return err
- }
-
- if cfg.timeout > 0 {
- c.SetTimeout(cfg.timeout)
- }
-
- path := cfg.endpoint(c.EnvID(), resolved.ID)
- resp, err := c.Post(cmd.Context(), path, nil)
- if err != nil {
- return errors.WrapIff(err, "%s", cfg.failureMessage)
- }
- defer func() { _ = resp.Body.Close() }()
-
- if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
- return errors.WrapIff(err, "%s", cfg.failureMessage)
- }
-
- var result base.ApiResponse[T]
- if err := cmdutil.DecodeJSON(resp, &result); err != nil {
- return err
- }
+ c, err := client.NewFromConfig()
+ if err != nil {
+ return err
+ }
- if jsonOutput {
- resultBytes, err := json.MarshalIndent(result.Data, "", " ")
+ resolved, _, err := containerRef.Resolve(cmd.Context(), c, args[0], false)
if err != nil {
- return errors.WrapIf(err, "failed to marshal JSON")
+ return err
}
- fmt.Println(string(resultBytes))
- return nil
- }
- output.Success("Container %s %s successfully", containerDisplayName(resolved), cfg.successVerb)
- return nil
+ return cmdutil.RunPostAction[container.Details](cmd, c, cmdutil.PostActionSpec{
+ Path: types.ContainerRedeploy(c.EnvID(), resolved.ID),
+ FailureMessage: "failed to redeploy container",
+ SuccessMessage: fmt.Sprintf("Container %s redeployed successfully", containerDisplayName(resolved)),
+ Timeout: 30 * time.Minute,
+ JSON: jsonOutput,
+ })
+ },
}
var containersDeleteCmd = &cobra.Command{
@@ -403,7 +341,7 @@ var containersDeleteCmd = &cobra.Command{
return err
}
- resolved, _, err := resolveContainer(cmd.Context(), c, args[0], false)
+ resolved, _, err := containerRef.Resolve(cmd.Context(), c, args[0], false)
if err != nil {
return err
}
@@ -425,32 +363,13 @@ var containersDeleteCmd = &cobra.Command{
query.Set("force", strconv.FormatBool(forceFlag))
query.Set("volumes", strconv.FormatBool(containersDeleteVolumes))
path := types.Container(c.EnvID(), resolved.ID) + "?" + query.Encode()
- resp, err := c.Delete(cmd.Context(), path)
+ result, err := c.DeleteJSON[base.MessageResponse](cmd.Context(), path)
if err != nil {
return errors.WrapIf(err, "failed to delete container")
}
- defer func() { _ = resp.Body.Close() }()
-
- var result base.ApiResponse[base.MessageResponse]
- if err := cmdutil.DecodeJSON(resp, &result); err != nil {
- return errors.WrapIf(err, "failed to delete container")
- }
-
- if !result.Success {
- msg := result.Data.Message
- if msg == "" {
- msg = "unknown error"
- }
- return errors.Errorf("failed to delete container: %s", msg)
- }
if jsonOutput {
- resultBytes, err := json.MarshalIndent(result.Data, "", " ")
- if err != nil {
- return errors.WrapIf(err, "failed to marshal JSON")
- }
- fmt.Println(string(resultBytes))
- return nil
+ return cmdutil.PrintJSON(result.Data)
}
output.Success("Container %s deleted successfully", displayName)
@@ -468,25 +387,13 @@ var containersCountsCmd = &cobra.Command{
return err
}
- path := types.ContainersCounts(c.EnvID())
- resp, err := c.Get(cmd.Context(), path)
+ result, err := c.GetJSON[container.StatusCounts](cmd.Context(), types.ContainersCounts(c.EnvID()))
if err != nil {
return errors.WrapIf(err, "failed to get container counts")
}
- defer func() { _ = resp.Body.Close() }()
-
- var result base.ApiResponse[container.StatusCounts]
- if err := cmdutil.DecodeJSON(resp, &result); err != nil {
- return err
- }
if jsonOutput {
- resultBytes, err := json.MarshalIndent(result.Data, "", " ")
- if err != nil {
- return errors.WrapIf(err, "failed to marshal JSON")
- }
- fmt.Println(string(resultBytes))
- return nil
+ return cmdutil.PrintJSON(result.Data)
}
output.Header("Container Status Counts")
@@ -593,28 +500,13 @@ var containersCreateCmd = &cobra.Command{
return errors.New("--image is required")
}
- path := types.Containers(c.EnvID())
- resp, err := c.Post(cmd.Context(), path, req)
+ result, err := c.PostJSON[container.Created](cmd.Context(), types.Containers(c.EnvID()), req)
if err != nil {
return errors.WrapIf(err, "failed to create container")
}
- defer func() { _ = resp.Body.Close() }()
- if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
- return errors.WrapIf(err, "failed to create container")
- }
-
- var result base.ApiResponse[container.Created]
- if err := cmdutil.DecodeJSON(resp, &result); err != nil {
- return err
- }
if jsonOutput {
- resultBytes, err := json.MarshalIndent(result.Data, "", " ")
- if err != nil {
- return errors.WrapIf(err, "failed to marshal JSON")
- }
- fmt.Println(string(resultBytes))
- return nil
+ return cmdutil.PrintJSON(result.Data)
}
output.Success("Container %s created successfully", result.Data.Name)
@@ -707,131 +599,17 @@ func containerDisplayName(details *container.Details) string {
return ""
}
-func resolveContainer(ctx context.Context, c *client.Client, identifier string, allowPrompt bool) (*container.Details, bool, error) {
- trimmed := strings.TrimSpace(identifier)
- if trimmed == "" {
- return nil, false, errors.New("container identifier is required")
- }
-
- details, complete, found, err := fetchContainerByIdentifier(ctx, c, trimmed)
- if err != nil {
- return nil, false, err
- }
- if found {
- return details, complete, nil
- }
-
- matches, err := searchContainerMatches(ctx, c, trimmed)
- if err != nil {
- return nil, false, err
- }
-
- selected, err := selectContainerMatch(matches, trimmed, allowPrompt)
- if err != nil {
- return nil, false, err
- }
- if selected != nil {
- return containerDetailsFromSummary(*selected), false, nil
- }
-
- identifierLower := strings.ToLower(trimmed)
- if looksLikeIDPrefix(identifierLower) {
- fallback, ok, err := fallbackContainerByIDPrefix(ctx, c, identifierLower)
- if err != nil {
- return nil, false, err
- }
- if ok {
- return fallback, false, nil
- }
- }
-
- return nil, false, errors.Errorf("container %q not found; use the container ID or run `arcane containers list`", trimmed)
-}
-
-func fetchContainerByIdentifier(ctx context.Context, c *client.Client, identifier string) (*container.Details, bool, bool, error) {
- resp, err := c.Get(ctx, types.Container(c.EnvID(), identifier))
- if err != nil {
- return nil, false, false, errors.WrapIff(err, "failed to resolve container %q", identifier)
- }
-
- body, err := io.ReadAll(resp.Body)
- _ = resp.Body.Close()
- if err != nil {
- return nil, false, false, errors.WrapIf(err, "failed to read container response")
- }
-
- if resp.StatusCode == http.StatusOK {
- var result base.ApiResponse[container.Details]
- if err := json.Unmarshal(body, &result); err != nil {
- return nil, false, false, errors.WrapIf(err, "failed to parse container response")
- }
- return &result.Data, true, true, nil
- }
-
- if resp.StatusCode != http.StatusNotFound {
- return nil, false, false, errors.Errorf("failed to resolve container %q (status %d): %s", identifier, resp.StatusCode, strings.TrimSpace(string(body)))
- }
-
- return nil, false, false, nil
-}
-
-func searchContainerMatches(ctx context.Context, c *client.Client, identifier string) ([]container.Summary, error) {
- searchPath := fmt.Sprintf("%s?search=%s&limit=%d", types.Containers(c.EnvID()), url.QueryEscape(identifier), cmdutil.ShowAllLimit)
- searchResp, err := c.Get(ctx, searchPath)
- if err != nil {
- return nil, errors.WrapIf(err, "failed to search containers")
- }
-
- searchBody, err := io.ReadAll(searchResp.Body)
- _ = searchResp.Body.Close()
- if err != nil {
- return nil, errors.WrapIf(err, "failed to read containers response")
- }
-
- if searchResp.StatusCode < 200 || searchResp.StatusCode >= 300 {
- return nil, errors.Errorf("failed to search containers (status %d): %s", searchResp.StatusCode, strings.TrimSpace(string(searchBody)))
- }
-
- var result base.Paginated[container.Summary]
- if err := json.Unmarshal(searchBody, &result); err != nil {
- return nil, errors.WrapIf(err, "failed to parse containers response")
- }
-
- identifierLower := strings.ToLower(identifier)
- matches := make([]container.Summary, 0)
- for _, item := range result.Data {
- if containerMatches(item, identifierLower, identifier) {
- matches = append(matches, item)
- }
- }
-
- return matches, nil
-}
-
-func selectContainerMatch(matches []container.Summary, identifier string, allowPrompt bool) (*container.Summary, error) {
- if len(matches) == 1 {
- return &matches[0], nil
- }
- if len(matches) == 0 {
- return nil, nil
- }
-
- if !allowPrompt {
- return nil, errors.Errorf("multiple containers match %q; use the container ID or run `arcane containers list`", identifier)
- }
- if len(matches) > maxPromptOptions {
- return nil, errors.Errorf("multiple containers match %q (%d results); refine your query or use the container ID", identifier, len(matches))
- }
-
- options := make([]string, 0, len(matches))
- for _, match := range matches {
- options = append(options, formatContainerOption(match))
- }
- choice, err := prompt.Select("container", options)
- if err != nil {
- return nil, err
- }
- return &matches[choice], nil
+var containerRef = cmdutil.ResourceRef[container.Details, container.Summary]{
+ Singular: "container",
+ Plural: "containers",
+ IDHint: "the container ID",
+ ListCmd: "arcane containers list",
+ GetPath: types.Container,
+ ListPath: types.Containers,
+ Matches: containerMatches,
+ Label: formatContainerOption,
+ Promote: containerDetailsFromSummary,
+ IDOf: func(item container.Summary) string { return item.ID },
}
func containerSummaryName(summary container.Summary) string {
@@ -845,34 +623,6 @@ func containerDetailsFromSummary(summary container.Summary) *container.Details {
return &container.Details{ID: summary.ID, Name: containerSummaryName(summary)}
}
-func fallbackContainerByIDPrefix(ctx context.Context, c *client.Client, identifierLower string) (*container.Details, bool, error) {
- fallbackPath := fmt.Sprintf("%s?limit=%d", types.Containers(c.EnvID()), cmdutil.ShowAllLimit)
- fallbackResp, err := c.Get(ctx, fallbackPath)
- if err != nil {
- return nil, false, errors.WrapIf(err, "failed to search containers")
- }
- fallbackBody, err := io.ReadAll(fallbackResp.Body)
- _ = fallbackResp.Body.Close()
- if err != nil {
- return nil, false, errors.WrapIf(err, "failed to read containers response")
- }
- if fallbackResp.StatusCode < 200 || fallbackResp.StatusCode >= 300 {
- return nil, false, nil
- }
-
- var fallbackResult base.Paginated[container.Summary]
- if err := json.Unmarshal(fallbackBody, &fallbackResult); err != nil {
- return nil, false, errors.WrapIf(err, "failed to parse containers response")
- }
- for _, item := range fallbackResult.Data {
- if strings.HasPrefix(strings.ToLower(item.ID), identifierLower) {
- return containerDetailsFromSummary(item), true, nil
- }
- }
-
- return nil, false, nil
-}
-
func containerMatches(item container.Summary, identifierLower, original string) bool {
idLower := strings.ToLower(item.ID)
if idLower == identifierLower || (len(identifierLower) >= 4 && strings.HasPrefix(idLower, identifierLower)) {
@@ -914,15 +664,3 @@ func formatContainerOption(item container.Summary) string {
}
return fmt.Sprintf("%s (%s, %s)", name, shortID(item.ID), image+" / "+state)
}
-
-func looksLikeIDPrefix(value string) bool {
- if len(value) < 4 {
- return false
- }
- for _, r := range value {
- if (r < '0' || r > '9') && (r < 'a' || r > 'f') {
- return false
- }
- }
- return true
-}
diff --git a/cli/pkg/doctor/cmd.go b/cli/pkg/doctor/cmd.go
index cadd6d67d..a2e215cc0 100644
--- a/cli/pkg/doctor/cmd.go
+++ b/cli/pkg/doctor/cmd.go
@@ -1,12 +1,11 @@
package doctor
import (
- "encoding/json"
- "fmt"
"strings"
"emperror.dev/errors"
+ "github.com/getarcaneapp/arcane/cli/v2/internal/cmdutil"
"github.com/getarcaneapp/arcane/cli/v2/internal/config"
"github.com/getarcaneapp/arcane/cli/v2/internal/output"
runtimectx "github.com/getarcaneapp/arcane/cli/v2/internal/runtime"
@@ -105,11 +104,9 @@ var DoctorCmd = &cobra.Command{
}
if jsonOutput || app.IsJSON() {
- b, err := json.MarshalIndent(rep, "", " ")
- if err != nil {
+ if err := cmdutil.PrintJSON(rep); err != nil {
return errors.WrapIf(err, "failed to marshal doctor output")
}
- fmt.Println(string(b))
} else {
output.Header("Arcane CLI Diagnostics")
rows := make([][]string, 0, len(rep.Checks))
diff --git a/cli/pkg/environments/cmd.go b/cli/pkg/environments/cmd.go
index fff036427..2e2f567f4 100644
--- a/cli/pkg/environments/cmd.go
+++ b/cli/pkg/environments/cmd.go
@@ -1,8 +1,8 @@
package environments
import (
- "encoding/json"
"fmt"
+ "net/http"
"sort"
"strconv"
"strings"
@@ -71,51 +71,26 @@ var listCmd = &cobra.Command{
return err
}
- path := types.Environments()
- path, err = cmdutil.ApplyPaginationParams(cmd, path, cmdutil.ListParams{Resource: "environments", Limit: limitFlag, FallbackDefault: 20, Start: startFlag, All: allFlag})
- if err != nil {
- return errors.WrapIf(err, "failed to build pagination query")
- }
-
- resp, err := c.Get(cmd.Context(), path)
- if err != nil {
- return errors.WrapIf(err, "failed to list environments")
- }
- defer func() { _ = resp.Body.Close() }()
-
- var result base.Paginated[environment.Environment]
- if err := cmdutil.DecodeJSON(resp, &result); err != nil {
- return err
- }
-
- if jsonOutput {
- resultBytes, err := json.MarshalIndent(result, "", " ")
- if err != nil {
- return errors.WrapIf(err, "failed to marshal JSON")
- }
- fmt.Println(string(resultBytes))
- return nil
- }
-
- headers := []string{"ID", "NAME", "API URL", "STATUS", "ENABLED"}
- rows := make([][]string, len(result.Data))
- for i, env := range result.Data {
- enabled := "false"
- if env.Enabled {
- enabled = "true"
- }
- rows[i] = []string{
- env.ID,
- env.Name,
- env.ApiUrl,
- env.Status,
- enabled,
- }
- }
-
- output.Table(headers, rows)
- output.Showing(len(result.Data), result.Pagination.TotalItems, "environments")
- return nil
+ return cmdutil.RunList(cmd, c, cmdutil.ListSpec[environment.Environment]{
+ Resource: "environments",
+ Endpoint: types.Environments(),
+ Params: cmdutil.ListParams{Resource: "environments", Limit: limitFlag, FallbackDefault: 20, Start: startFlag, All: allFlag},
+ JSON: jsonOutput,
+ Headers: []string{"ID", "NAME", "API URL", "STATUS", "ENABLED"},
+ Row: func(env environment.Environment) []string {
+ enabled := "false"
+ if env.Enabled {
+ enabled = "true"
+ }
+ return []string{
+ env.ID,
+ env.Name,
+ env.ApiUrl,
+ env.Status,
+ enabled,
+ }
+ },
+ })
},
}
@@ -142,12 +117,7 @@ var deleteCmd = &cobra.Command{
return err
}
- resp, err := c.Delete(cmd.Context(), types.Environment(args[0]))
- if err != nil {
- return errors.WrapIf(err, "failed to delete environment")
- }
- defer func() { _ = resp.Body.Close() }()
- if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
+ if _, err := c.DeleteJSON[base.MessageResponse](cmd.Context(), types.Environment(args[0])); err != nil {
return errors.WrapIf(err, "failed to delete environment")
}
@@ -167,24 +137,13 @@ var getCmd = &cobra.Command{
return err
}
- resp, err := c.Get(cmd.Context(), types.Environment(args[0]))
+ result, err := c.GetJSON[environment.Environment](cmd.Context(), types.Environment(args[0]))
if err != nil {
return errors.WrapIf(err, "failed to get environment")
}
- defer func() { _ = resp.Body.Close() }()
-
- var result base.ApiResponse[environment.Environment]
- if err := cmdutil.DecodeJSON(resp, &result); err != nil {
- return err
- }
if jsonOutput {
- resultBytes, err := json.MarshalIndent(buildEnvironmentPayloadInternal(result.Data), "", " ")
- if err != nil {
- return errors.WrapIf(err, "failed to marshal JSON")
- }
- fmt.Println(string(resultBytes))
- return nil
+ return cmdutil.PrintJSON(buildEnvironmentPayloadInternal(result.Data))
}
output.Header("Environment Details")
@@ -208,27 +167,12 @@ var testCmd = &cobra.Command{
return err
}
- resp, err := c.Post(cmd.Context(), types.EnvironmentTest(args[0]), nil)
- if err != nil {
- return errors.WrapIf(err, "failed to test environment")
- }
- defer func() { _ = resp.Body.Close() }()
- if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
- return errors.WrapIf(err, "failed to test environment")
- }
-
- if jsonOutput {
- var result base.ApiResponse[any]
- if err := json.NewDecoder(resp.Body).Decode(&result); err == nil {
- if resultBytes, err := json.MarshalIndent(result.Data, "", " "); err == nil {
- fmt.Println(string(resultBytes))
- }
- }
- return nil
- }
-
- output.Success("Environment connection test successful")
- return nil
+ return cmdutil.RunPostAction[environment.Test](cmd, c, cmdutil.PostActionSpec{
+ Path: types.EnvironmentTest(args[0]),
+ FailureMessage: "failed to test environment",
+ SuccessMessage: "Environment connection test successful",
+ JSON: jsonOutput,
+ })
},
}
@@ -253,16 +197,10 @@ var switchCmd = &cobra.Command{
}
path := fmt.Sprintf("%s?limit=%d", types.Environments(), cmdutil.ShowAllLimit)
- resp, err := c.Get(cmd.Context(), path)
+ result, err := c.DoJSON[base.Paginated[environment.Environment]](cmd.Context(), http.MethodGet, path, nil)
if err != nil {
return errors.WrapIf(err, "failed to list environments")
}
- defer func() { _ = resp.Body.Close() }()
-
- var result base.Paginated[environment.Environment]
- if err := cmdutil.DecodeJSON(resp, &result); err != nil {
- return err
- }
if len(result.Data) == 0 {
return errors.New("no environments available")
@@ -373,27 +311,13 @@ var updateCmd = &cobra.Command{
req.Enabled = new(false)
}
- resp, err := c.Put(cmd.Context(), types.Environment(args[0]), req)
+ result, err := c.PutJSON[environment.Environment](cmd.Context(), types.Environment(args[0]), req)
if err != nil {
return errors.WrapIf(err, "failed to update environment")
}
- defer func() { _ = resp.Body.Close() }()
- if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
- return errors.WrapIf(err, "failed to update environment")
- }
-
- var result base.ApiResponse[environment.Environment]
- if err := cmdutil.DecodeJSON(resp, &result); err != nil {
- return err
- }
if jsonOutput {
- resultBytes, err := json.MarshalIndent(buildEnvironmentPayloadInternal(result.Data), "", " ")
- if err != nil {
- return errors.WrapIf(err, "failed to marshal JSON")
- }
- fmt.Println(string(resultBytes))
- return nil
+ return cmdutil.PrintJSON(buildEnvironmentPayloadInternal(result.Data))
}
output.Success("Environment updated successfully")
@@ -432,27 +356,13 @@ var createCmd = &cobra.Command{
req.Enabled = new(!envCreateDisabled)
}
- resp, err := c.Post(cmd.Context(), types.Environments(), req)
+ result, err := c.PostJSON[environment.Environment](cmd.Context(), types.Environments(), req)
if err != nil {
return errors.WrapIf(err, "failed to create environment")
}
- defer func() { _ = resp.Body.Close() }()
- if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
- return errors.WrapIf(err, "failed to create environment")
- }
-
- var result base.ApiResponse[environment.Environment]
- if err := cmdutil.DecodeJSON(resp, &result); err != nil {
- return err
- }
if jsonOutput {
- resultBytes, err := json.MarshalIndent(buildEnvironmentPayloadInternal(result.Data), "", " ")
- if err != nil {
- return errors.WrapIf(err, "failed to marshal JSON")
- }
- fmt.Println(string(resultBytes))
- return nil
+ return cmdutil.PrintJSON(buildEnvironmentPayloadInternal(result.Data))
}
output.Success("Environment created successfully")
@@ -479,27 +389,13 @@ var versionCmd = &cobra.Command{
return err
}
- resp, err := c.Get(cmd.Context(), types.EnvironmentVersion(args[0]))
+ result, err := c.GetJSON[version.Info](cmd.Context(), types.EnvironmentVersion(args[0]))
if err != nil {
return errors.WrapIf(err, "failed to get environment version")
}
- defer func() { _ = resp.Body.Close() }()
- if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
- return errors.WrapIf(err, "failed to get environment version")
- }
-
- var result base.ApiResponse[version.Info]
- if err := cmdutil.DecodeJSON(resp, &result); err != nil {
- return err
- }
if jsonOutput {
- resultBytes, err := json.MarshalIndent(result.Data, "", " ")
- if err != nil {
- return errors.WrapIf(err, "failed to marshal JSON")
- }
- fmt.Println(string(resultBytes))
- return nil
+ return cmdutil.PrintJSON(result.Data)
}
output.Header("Environment Version")
diff --git a/cli/pkg/gitops/cmd.go b/cli/pkg/gitops/cmd.go
index c0008f03d..79ec309a9 100644
--- a/cli/pkg/gitops/cmd.go
+++ b/cli/pkg/gitops/cmd.go
@@ -1,11 +1,7 @@
package gitops
import (
- "context"
- "encoding/json"
"fmt"
- "io"
- "net/http"
"net/url"
"strings"
@@ -16,7 +12,6 @@ import (
"github.com/getarcaneapp/arcane/cli/v2/internal/output"
"github.com/getarcaneapp/arcane/cli/v2/internal/prompt"
"github.com/getarcaneapp/arcane/cli/v2/internal/types"
- "github.com/getarcaneapp/arcane/types/v2/base"
"github.com/getarcaneapp/arcane/types/v2/gitops"
"github.com/spf13/cobra"
)
@@ -40,8 +35,6 @@ var (
gitopsUpdateInterval int
)
-const maxPromptOptions = 20
-
// GitopsCmd is the parent command for gitops sync operations
var GitopsCmd = &cobra.Command{
Use: "gitops",
@@ -60,60 +53,35 @@ var listCmd = &cobra.Command{
return err
}
- path := types.GitOpsSyncs(c.EnvID())
- path, err = cmdutil.ApplyPaginationParams(cmd, path, cmdutil.ListParams{Resource: "gitops-syncs", Limit: limitFlag, FallbackDefault: 20, Start: startFlag, All: allFlag})
- if err != nil {
- return errors.WrapIf(err, "failed to build pagination query")
- }
-
- resp, err := c.Get(cmd.Context(), path)
- if err != nil {
- return errors.WrapIf(err, "failed to list gitops syncs")
- }
- defer func() { _ = resp.Body.Close() }()
-
- var result base.Paginated[gitops.GitOpsSync]
- if err := cmdutil.DecodeJSON(resp, &result); err != nil {
- return err
- }
-
- if jsonOutput {
- resultBytes, err := json.MarshalIndent(result, "", " ")
- if err != nil {
- return errors.WrapIf(err, "failed to marshal JSON")
- }
- fmt.Println(string(resultBytes))
- return nil
- }
-
- headers := []string{"ID", "NAME", "BRANCH", "AUTO-SYNC", "LAST STATUS", "LAST SYNC"}
- rows := make([][]string, len(result.Data))
- for i, sync := range result.Data {
- autoSync := "false"
- if sync.AutoSync {
- autoSync = "true"
- }
- lastStatus := "-"
- if sync.LastSyncStatus != nil {
- lastStatus = *sync.LastSyncStatus
- }
- lastSync := "-"
- if sync.LastSyncAt != nil {
- lastSync = sync.LastSyncAt.Format("2006-01-02 15:04:05")
- }
- rows[i] = []string{
- sync.ID,
- sync.Name,
- sync.Branch,
- autoSync,
- lastStatus,
- lastSync,
- }
- }
-
- output.Table(headers, rows)
- output.Showing(len(result.Data), result.Pagination.TotalItems, "gitops syncs")
- return nil
+ return cmdutil.RunList(cmd, c, cmdutil.ListSpec[gitops.GitOpsSync]{
+ Resource: "gitops syncs",
+ Endpoint: types.GitOpsSyncs(c.EnvID()),
+ Params: cmdutil.ListParams{Resource: "gitops-syncs", Limit: limitFlag, FallbackDefault: 20, Start: startFlag, All: allFlag},
+ JSON: jsonOutput,
+ Headers: []string{"ID", "NAME", "BRANCH", "AUTO-SYNC", "LAST STATUS", "LAST SYNC"},
+ Row: func(sync gitops.GitOpsSync) []string {
+ autoSync := "false"
+ if sync.AutoSync {
+ autoSync = "true"
+ }
+ lastStatus := "-"
+ if sync.LastSyncStatus != nil {
+ lastStatus = *sync.LastSyncStatus
+ }
+ lastSync := "-"
+ if sync.LastSyncAt != nil {
+ lastSync = sync.LastSyncAt.Format("2006-01-02 15:04:05")
+ }
+ return []string{
+ sync.ID,
+ sync.Name,
+ sync.Branch,
+ autoSync,
+ lastStatus,
+ lastSync,
+ }
+ },
+ })
},
}
@@ -147,28 +115,13 @@ var createCmd = &cobra.Command{
req.SyncInterval = &interval
}
- resp, err := c.Post(cmd.Context(), types.GitOpsSyncs(c.EnvID()), req)
+ result, err := c.PostJSON[gitops.GitOpsSync](cmd.Context(), types.GitOpsSyncs(c.EnvID()), req)
if err != nil {
return errors.WrapIf(err, "failed to create gitops sync")
}
- defer func() { _ = resp.Body.Close() }()
-
- if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
- return errors.WrapIf(err, "failed to create gitops sync")
- }
-
- var result base.ApiResponse[gitops.GitOpsSync]
- if err := cmdutil.DecodeJSON(resp, &result); err != nil {
- return err
- }
if jsonOutput {
- resultBytes, err := json.MarshalIndent(result.Data, "", " ")
- if err != nil {
- return errors.WrapIf(err, "failed to marshal JSON")
- }
- fmt.Println(string(resultBytes))
- return nil
+ return cmdutil.PrintJSON(result.Data)
}
output.Success("GitOps sync %s created successfully (ID: %s)", result.Data.Name, result.Data.ID)
@@ -188,32 +141,21 @@ var getCmd = &cobra.Command{
}
allowPrompt := !jsonOutput && prompt.IsInteractive()
- resolved, complete, err := resolveGitOpsSync(cmd.Context(), c, args[0], allowPrompt)
+ resolved, complete, err := gitopsSyncRef.Resolve(cmd.Context(), c, args[0], allowPrompt)
if err != nil {
return err
}
if !complete {
- resp, err := c.Get(cmd.Context(), types.GitOpsSync(c.EnvID(), resolved.ID))
+ result, err := c.GetJSON[gitops.GitOpsSync](cmd.Context(), types.GitOpsSync(c.EnvID(), resolved.ID))
if err != nil {
return errors.WrapIf(err, "failed to get gitops sync")
}
- defer func() { _ = resp.Body.Close() }()
-
- var result base.ApiResponse[gitops.GitOpsSync]
- if err := cmdutil.DecodeJSON(resp, &result); err != nil {
- return err
- }
resolved = &result.Data
}
if jsonOutput {
- resultBytes, err := json.MarshalIndent(resolved, "", " ")
- if err != nil {
- return errors.WrapIf(err, "failed to marshal JSON")
- }
- fmt.Println(string(resultBytes))
- return nil
+ return cmdutil.PrintJSON(resolved)
}
output.Header("GitOps Sync Details")
@@ -248,7 +190,7 @@ var updateCmd = &cobra.Command{
return err
}
- resolved, _, err := resolveGitOpsSync(cmd.Context(), c, args[0], false)
+ resolved, _, err := gitopsSyncRef.Resolve(cmd.Context(), c, args[0], false)
if err != nil {
return err
}
@@ -303,7 +245,7 @@ var deleteCmd = &cobra.Command{
return err
}
- resolved, _, err := resolveGitOpsSync(cmd.Context(), c, args[0], false)
+ resolved, _, err := gitopsSyncRef.Resolve(cmd.Context(), c, args[0], false)
if err != nil {
return err
}
@@ -348,29 +290,18 @@ var statusCmd = &cobra.Command{
return err
}
- resolved, _, err := resolveGitOpsSync(cmd.Context(), c, args[0], false)
+ resolved, _, err := gitopsSyncRef.Resolve(cmd.Context(), c, args[0], false)
if err != nil {
return err
}
- resp, err := c.Get(cmd.Context(), types.GitOpsSyncStatus(c.EnvID(), resolved.ID))
+ result, err := c.GetJSON[gitops.SyncStatus](cmd.Context(), types.GitOpsSyncStatus(c.EnvID(), resolved.ID))
if err != nil {
return errors.WrapIf(err, "failed to get gitops sync status")
}
- defer func() { _ = resp.Body.Close() }()
-
- var result base.ApiResponse[gitops.SyncStatus]
- if err := cmdutil.DecodeJSON(resp, &result); err != nil {
- return err
- }
if jsonOutput {
- resultBytes, err := json.MarshalIndent(result.Data, "", " ")
- if err != nil {
- return errors.WrapIf(err, "failed to marshal JSON")
- }
- fmt.Println(string(resultBytes))
- return nil
+ return cmdutil.PrintJSON(result.Data)
}
output.Header("GitOps Sync Status")
@@ -406,29 +337,18 @@ var syncCmd = &cobra.Command{
return err
}
- resolved, _, err := resolveGitOpsSync(cmd.Context(), c, args[0], false)
+ resolved, _, err := gitopsSyncRef.Resolve(cmd.Context(), c, args[0], false)
if err != nil {
return err
}
- resp, err := c.Post(cmd.Context(), types.GitOpsSyncTrigger(c.EnvID(), resolved.ID), nil)
+ result, err := c.PostJSON[gitops.SyncResult](cmd.Context(), types.GitOpsSyncTrigger(c.EnvID(), resolved.ID), nil)
if err != nil {
return errors.WrapIf(err, "failed to trigger gitops sync")
}
- defer func() { _ = resp.Body.Close() }()
-
- var result base.ApiResponse[gitops.SyncResult]
- if err := cmdutil.DecodeJSON(resp, &result); err != nil {
- return err
- }
if jsonOutput {
- resultBytes, err := json.MarshalIndent(result.Data, "", " ")
- if err != nil {
- return errors.WrapIf(err, "failed to marshal JSON")
- }
- fmt.Println(string(resultBytes))
- return nil
+ return cmdutil.PrintJSON(result.Data)
}
if result.Data.Success {
@@ -455,7 +375,7 @@ var filesCmd = &cobra.Command{
return err
}
- resolved, _, err := resolveGitOpsSync(cmd.Context(), c, args[0], false)
+ resolved, _, err := gitopsSyncRef.Resolve(cmd.Context(), c, args[0], false)
if err != nil {
return err
}
@@ -465,25 +385,14 @@ var filesCmd = &cobra.Command{
filesPath = cmdutil.AppendQuery(filesPath, url.Values{"path": []string{gitopsFilesPath}})
}
- resp, err := c.Get(cmd.Context(), filesPath)
+ result, err := c.GetJSON[gitops.BrowseResponse](cmd.Context(), filesPath)
if err != nil {
return errors.WrapIf(err, "failed to get gitops sync files")
}
- defer func() { _ = resp.Body.Close() }()
-
- var result base.ApiResponse[gitops.BrowseResponse]
- if err := cmdutil.DecodeJSON(resp, &result); err != nil {
- return err
- }
files := result.Data.Files
if jsonOutput {
- resultBytes, err := json.MarshalIndent(files, "", " ")
- if err != nil {
- return errors.WrapIf(err, "failed to marshal JSON")
- }
- fmt.Println(string(resultBytes))
- return nil
+ return cmdutil.PrintJSON(files)
}
headers := []string{"NAME", "TYPE", "PATH", "SIZE"}
@@ -522,28 +431,13 @@ var importCmd = &cobra.Command{
// The endpoint accepts a batch, so a single sync still has to be wrapped
// in an array.
- resp, err := c.Post(cmd.Context(), types.GitOpsSyncsImport(c.EnvID()), []gitops.ImportGitOpsSyncRequest{req})
+ result, err := c.PostJSON[gitops.ImportGitOpsSyncResponse](cmd.Context(), types.GitOpsSyncsImport(c.EnvID()), []gitops.ImportGitOpsSyncRequest{req})
if err != nil {
return errors.WrapIf(err, "failed to import gitops sync")
}
- defer func() { _ = resp.Body.Close() }()
-
- if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
- return errors.WrapIf(err, "failed to import gitops sync")
- }
-
- var result base.ApiResponse[gitops.ImportGitOpsSyncResponse]
- if err := cmdutil.DecodeJSON(resp, &result); err != nil {
- return err
- }
if jsonOutput {
- resultBytes, err := json.MarshalIndent(result.Data, "", " ")
- if err != nil {
- return errors.WrapIf(err, "failed to marshal JSON")
- }
- fmt.Println(string(resultBytes))
- return nil
+ return cmdutil.PrintJSON(result.Data)
}
output.Success("Import completed: %d succeeded, %d failed", result.Data.SuccessCount, result.Data.FailedCount)
@@ -629,93 +523,22 @@ func init() {
_ = importCmd.MarkFlagRequired("compose-path")
}
-func resolveGitOpsSync(ctx context.Context, c *client.Client, identifier string, allowPrompt bool) (*gitops.GitOpsSync, bool, error) {
- trimmed := strings.TrimSpace(identifier)
- if trimmed == "" {
- return nil, false, errors.New("gitops sync identifier is required")
- }
-
- resp, err := c.Get(ctx, types.GitOpsSync(c.EnvID(), trimmed))
- if err != nil {
- return nil, false, errors.WrapIff(err, "failed to resolve gitops sync %q", trimmed)
- }
-
- bodyBytes, err := io.ReadAll(resp.Body)
- _ = resp.Body.Close()
- if err != nil {
- return nil, false, errors.WrapIf(err, "failed to read gitops sync response")
- }
-
- if resp.StatusCode == http.StatusOK {
- var result base.ApiResponse[gitops.GitOpsSync]
- if err := json.Unmarshal(bodyBytes, &result); err != nil {
- return nil, false, errors.WrapIf(err, "failed to parse gitops sync response")
- }
- return &result.Data, true, nil
- }
-
- if resp.StatusCode != http.StatusNotFound {
- return nil, false, errors.Errorf("failed to resolve gitops sync %q (status %d): %s", trimmed, resp.StatusCode, strings.TrimSpace(string(bodyBytes)))
- }
-
- identifierLower := strings.ToLower(trimmed)
-
- searchPath := fmt.Sprintf("%s?search=%s&limit=%d", types.GitOpsSyncs(c.EnvID()), url.QueryEscape(trimmed), cmdutil.ShowAllLimit)
- searchResp, err := c.Get(ctx, searchPath)
- if err != nil {
- return nil, false, errors.WrapIf(err, "failed to search gitops syncs")
- }
-
- searchBody, err := io.ReadAll(searchResp.Body)
- _ = searchResp.Body.Close()
- if err != nil {
- return nil, false, errors.WrapIf(err, "failed to read gitops syncs response")
- }
-
- if searchResp.StatusCode < 200 || searchResp.StatusCode >= 300 {
- return nil, false, errors.Errorf("failed to search gitops syncs (status %d): %s", searchResp.StatusCode, strings.TrimSpace(string(searchBody)))
- }
-
- var result base.Paginated[gitops.GitOpsSync]
- if err := json.Unmarshal(searchBody, &result); err != nil {
- return nil, false, errors.WrapIf(err, "failed to parse gitops syncs response")
- }
-
- matches := make([]gitops.GitOpsSync, 0)
- for _, sync := range result.Data {
- if gitOpsSyncMatches(sync, identifierLower, trimmed) {
- matches = append(matches, sync)
- }
- }
-
- if len(matches) == 1 {
- return &matches[0], false, nil
- }
-
- if len(matches) > 1 {
- if !allowPrompt {
- return nil, false, errors.Errorf("multiple gitops syncs match %q; use the sync ID or run `arcane gitops list`", trimmed)
- }
- if len(matches) > maxPromptOptions {
- return nil, false, errors.Errorf("multiple gitops syncs match %q (%d results); refine your query or use the sync ID", trimmed, len(matches))
- }
-
- options := make([]string, 0, len(matches))
- for _, match := range matches {
- lastStatus := "-"
- if match.LastSyncStatus != nil {
- lastStatus = *match.LastSyncStatus
- }
- options = append(options, fmt.Sprintf("%s (%s, %s)", match.Name, match.ID, lastStatus))
- }
- choice, err := prompt.Select("gitops sync", options)
- if err != nil {
- return nil, false, err
- }
- return &matches[choice], false, nil
- }
-
- return nil, false, errors.Errorf("gitops sync %q not found; use the sync ID or run `arcane gitops list`", trimmed)
+var gitopsSyncRef = cmdutil.ResourceRef[gitops.GitOpsSync, gitops.GitOpsSync]{
+ Singular: "gitops sync",
+ Plural: "gitops syncs",
+ IDHint: "the sync ID",
+ ListCmd: "arcane gitops list",
+ GetPath: types.GitOpsSync,
+ ListPath: types.GitOpsSyncs,
+ Matches: gitOpsSyncMatches,
+ Label: func(match gitops.GitOpsSync) string {
+ lastStatus := "-"
+ if match.LastSyncStatus != nil {
+ lastStatus = *match.LastSyncStatus
+ }
+ return fmt.Sprintf("%s (%s, %s)", match.Name, match.ID, lastStatus)
+ },
+ Promote: func(match gitops.GitOpsSync) *gitops.GitOpsSync { return &match },
}
func gitOpsSyncMatches(item gitops.GitOpsSync, identifierLower, original string) bool {
diff --git a/cli/pkg/images/cmd.go b/cli/pkg/images/cmd.go
index 5cc452381..ab1d1f26b 100644
--- a/cli/pkg/images/cmd.go
+++ b/cli/pkg/images/cmd.go
@@ -32,7 +32,8 @@ package images
import (
"context"
- "encoding/json"
+ "encoding/json/jsontext"
+ "encoding/json/v2"
"fmt"
"io"
"net/http"
@@ -50,7 +51,6 @@ import (
"github.com/getarcaneapp/arcane/cli/v2/internal/prompt"
"github.com/getarcaneapp/arcane/cli/v2/internal/types"
"github.com/getarcaneapp/arcane/cli/v2/pkg/images/updates"
- "github.com/getarcaneapp/arcane/types/v2/base"
"github.com/getarcaneapp/arcane/types/v2/image"
uploadtypes "github.com/getarcaneapp/arcane/types/v2/upload"
"github.com/spf13/cobra"
@@ -69,8 +69,6 @@ var (
imagesUpdatesFilter string
)
-const maxPromptOptions = 20
-
// ImagesCmd is the parent command for image operations
var ImagesCmd = &cobra.Command{
Use: "images",
@@ -84,7 +82,6 @@ var imagesListCmd = &cobra.Command{
Short: "List images",
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
- log := logger.GetLogger()
c, err := cmdutil.ClientFromCommand(cmd)
if err != nil {
return err
@@ -93,91 +90,53 @@ var imagesListCmd = &cobra.Command{
return errors.New("--inuse and --unused cannot be used together")
}
- path := types.Images(c.EnvID())
-
- // Parse the path to handle query params
- u, err := url.Parse(path)
- if err != nil {
- return errors.WrapIf(err, "failed to parse endpoint path")
- }
- q := u.Query()
-
+ query := url.Values{}
if imagesSort != "" {
- q.Set("sort", imagesSort)
+ query.Set("sort", imagesSort)
}
if imagesOrder != "" {
- q.Set("order", imagesOrder)
+ query.Set("order", imagesOrder)
}
if imagesSearch != "" {
- q.Set("search", imagesSearch)
+ query.Set("search", imagesSearch)
}
// Filter server-side so that pagination and the reported totals apply to
// the matching set rather than to whichever page happened to be fetched.
if imagesInUseOnly {
- q.Set("inUse", "true")
+ query.Set("inUse", "true")
}
if imagesUnusedOnly {
- q.Set("inUse", "false")
+ query.Set("inUse", "false")
}
if imagesUpdatesFilter != "" {
- q.Set("updates", imagesUpdatesFilter)
- }
-
- u.RawQuery = q.Encode()
- path, err = cmdutil.ApplyPaginationParams(cmd, u.String(), cmdutil.ListParams{
- Resource: "images",
- Limit: imagesLimit,
- FallbackDefault: 0,
- Start: imagesStart,
- All: imagesAll,
+ query.Set("updates", imagesUpdatesFilter)
+ }
+
+ return cmdutil.RunList(cmd, c, cmdutil.ListSpec[image.Summary]{
+ Resource: "images",
+ Endpoint: types.Images(c.EnvID()),
+ Params: cmdutil.ListParams{
+ Resource: "images",
+ Limit: imagesLimit,
+ FallbackDefault: 0,
+ Start: imagesStart,
+ All: imagesAll,
+ },
+ Query: query,
+ JSON: cmdutil.JSONOutputEnabled(cmd),
+ Headers: []string{"ID", "REPOSITORY:TAG", "SIZE", "IN USE"},
+ Row: func(img image.Summary) []string {
+ tag := "<none>"
+ if len(img.RepoTags) > 0 {
+ tag = img.RepoTags[0]
+ }
+ inUse := "No"
+ if img.InUse {
+ inUse = "Yes"
+ }
+ return []string{img.ID, tag, output.Bytes(img.Size), inUse}
+ },
})
- if err != nil {
- return errors.WrapIf(err, "failed to build pagination query")
- }
-
- log.Debugf("Listing images from: %s", path)
-
- resp, err := c.Get(cmd.Context(), path)
- if err != nil {
- return errors.WrapIf(err, "failed to list images")
- }
- defer func() { _ = resp.Body.Close() }()
-
- body, err := cmdutil.ReadJSONBody(resp)
- if err != nil {
- return errors.WrapIf(err, "failed to list images")
- }
-
- log.Debugf("Response body: %s", string(body))
-
- if cmdutil.JSONOutputEnabled(cmd) {
- return cmdutil.PrintRawJSON(body)
- }
-
- var result base.Paginated[image.Summary]
- if err := json.Unmarshal(body, &result); err != nil {
- return errors.WrapIf(err, "failed to parse response")
- }
-
- headers := []string{"ID", "REPOSITORY:TAG", "SIZE", "IN USE"}
- var rows [][]string
-
- for _, img := range result.Data {
- tag := "<none>"
- if len(img.RepoTags) > 0 {
- tag = img.RepoTags[0]
- }
- inUse := "No"
- if img.InUse {
- inUse = "Yes"
- }
- rows = append(rows, []string{img.ID, tag, output.Bytes(img.Size), inUse})
- }
-
- output.Table(headers, rows)
- output.Showing(len(result.Data), result.Pagination.TotalItems, "images")
-
- return nil
},
}
@@ -196,11 +155,11 @@ var imagesGetCmd = &cobra.Command{
jsonOutput := cmdutil.JSONOutputEnabled(cmd)
allowPrompt := !jsonOutput && prompt.IsInteractive()
- imageID, err := resolveImageID(cmd.Context(), c, args[0], allowPrompt)
+ resolved, _, err := ImageRef.Resolve(cmd.Context(), c, args[0], allowPrompt)
if err != nil {
return err
}
- path := types.Image(c.EnvID(), imageID)
+ path := types.Image(c.EnvID(), resolved.ID)
log.Debugf("Getting image details from: %s", path)
@@ -292,11 +251,11 @@ var imagesRemoveCmd = &cobra.Command{
return err
}
- imageID, err := resolveImageID(cmd.Context(), c, args[0], false)
+ resolved, _, err := ImageRef.Resolve(cmd.Context(), c, args[0], false)
if err != nil {
return err
}
- path := types.Image(c.EnvID(), imageID)
+ path := types.Image(c.EnvID(), resolved.ID)
if removeForce {
u, err := url.Parse(path)
@@ -395,7 +354,7 @@ var imagesPullCmd = &cobra.Command{
output.Info("Pulling image: %s", imageName)
- decoder := json.NewDecoder(resp.Body)
+ decoder := jsontext.NewDecoder(resp.Body)
var progressUI *output.Progress
var currentID string
@@ -411,8 +370,8 @@ var imagesPullCmd = &cobra.Command{
} `json:"progressDetail"`
}
- if err := decoder.Decode(&event); err != nil {
- if err == io.EOF {
+ if err := json.UnmarshalDecode(decoder, &event); err != nil {
+ if errors.Is(err, io.EOF) {
break
}
return errors.WrapIf(err, "failed to decode stream")
@@ -615,7 +574,6 @@ var imagesUploadCmd = &cobra.Command{
c.SetTimeout(30 * time.Minute)
filePath := args[0]
-
output.Info("Uploading image: %s", filePath)
jsonOutput := cmdutil.JSONOutputEnabled(cmd)
@@ -684,21 +642,43 @@ func init() {
ImagesCmd.AddCommand(imagesUploadCmd)
}
-func resolveImageID(ctx context.Context, c *client.Client, identifier string, allowPrompt bool) (string, error) {
- trimmed := strings.TrimSpace(identifier)
- if trimmed == "" {
- return "", errors.New("image identifier is required")
- }
-
- resolvedID, found, err := resolveImageByID(ctx, c, trimmed)
- if err != nil {
- return "", err
- }
- if found {
- return resolvedID, nil
- }
+var ImageRef = cmdutil.ResourceRef[image.DetailSummary, image.Summary]{
+ Singular: "image",
+ Plural: "images",
+ IDHint: "the image ID",
+ ListCmd: "arcane images list",
+ GetPath: types.Image,
+ ListPath: types.Images,
+ SearchCandidates: searchImageCandidatesInternal,
+ Matches: imageMatches,
+ Label: func(match image.Summary) string {
+ label := match.ID
+ if len(match.RepoTags) > 0 {
+ label = match.RepoTags[0]
+ } else if match.Repo != "" && match.Tag != "" {
+ label = match.Repo + ":" + match.Tag
+ }
+ return fmt.Sprintf("%s (%s)", label, match.ID)
+ },
+ Promote: func(match image.Summary) *image.DetailSummary {
+ return &image.DetailSummary{
+ ID: match.ID,
+ RepoTags: match.RepoTags,
+ RepoDigests: match.RepoDigests,
+ Size: match.Size,
+ }
+ },
+ IDOf: func(match image.Summary) string { return match.ID },
+ Validate: func(details image.DetailSummary, identifier string) error {
+ if details.ID == "" {
+ return errors.Errorf("image lookup for %q returned empty ID", identifier)
+ }
+ return nil
+ },
+}
- terms := buildImageSearchTerms(trimmed)
+func searchImageCandidatesInternal(ctx context.Context, c *client.Client, identifier string) ([]image.Summary, error) {
+ terms := imageSearchTermsInternal(identifier)
seenTerms := make(map[string]struct{}, len(terms))
for _, term := range terms {
term = strings.TrimSpace(term)
@@ -710,114 +690,47 @@ func resolveImageID(ctx context.Context, c *client.Client, identifier string, al
}
seenTerms[term] = struct{}{}
- matches, err := searchImageMatches(ctx, c, term, trimmed)
- if err != nil {
- return "", err
- }
-
- selectedID, resolved, err := selectImageMatchID(matches, trimmed, allowPrompt)
+ searchPath := fmt.Sprintf("%s?search=%s&limit=%d", types.Images(c.EnvID()), url.QueryEscape(term), cmdutil.ShowAllLimit)
+ result, err := c.GetJSON[[]image.Summary](ctx, searchPath)
if err != nil {
- return "", err
- }
- if resolved {
- return selectedID, nil
+ return nil, errors.WrapIf(err, "failed to search images")
}
- }
-
- return "", errors.Errorf("image %q not found; use the image ID or run `arcane images list`", trimmed)
-}
-
-func resolveImageByID(ctx context.Context, c *client.Client, identifier string) (string, bool, error) {
- resp, err := c.Get(ctx, types.Image(c.EnvID(), identifier))
- if err != nil {
- return "", false, errors.WrapIff(err, "failed to resolve image %q", identifier)
- }
-
- body, err := io.ReadAll(resp.Body)
- _ = resp.Body.Close()
- if err != nil {
- return "", false, errors.WrapIf(err, "failed to read image response")
- }
- if resp.StatusCode == http.StatusOK {
- var result struct {
- Success bool `json:"success"`
- Data image.DetailSummary `json:"data"`
- }
- if err := json.Unmarshal(body, &result); err != nil {
- return "", false, errors.WrapIf(err, "failed to parse image response")
+ identifierLower := strings.ToLower(identifier)
+ matches := make([]image.Summary, 0)
+ for _, item := range result.Data {
+ if imageMatches(item, identifierLower, identifier) {
+ matches = append(matches, item)
+ }
}
- if result.Data.ID == "" {
- return "", false, errors.Errorf("image lookup for %q returned empty ID", identifier)
+ if len(matches) > 0 {
+ return matches, nil
}
- return result.Data.ID, true, nil
- }
-
- if resp.StatusCode != http.StatusNotFound {
- return "", false, errors.Errorf("failed to resolve image %q (status %d): %s", identifier, resp.StatusCode, strings.TrimSpace(string(body)))
}
- return "", false, nil
+ return nil, nil
}
-func buildImageSearchTerms(trimmed string) []string {
- terms := []string{trimmed}
- identifierLower := strings.ToLower(trimmed)
- if strings.Contains(trimmed, "@") {
- if repo, _, ok := strings.Cut(trimmed, "@"); ok && repo != "" {
- terms = append(terms, repo)
+func imageSearchTermsInternal(identifier string) []string {
+ terms := []string{identifier}
+ identifierLower := strings.ToLower(identifier)
+ if strings.Contains(identifier, "@") {
+ if repository, _, ok := strings.Cut(identifier, "@"); ok && repository != "" {
+ terms = append(terms, repository)
}
return terms
}
- if strings.Contains(trimmed, ":") && !strings.HasPrefix(identifierLower, "sha256:") {
- if repo, _, ok := strings.Cut(trimmed, ":"); ok && repo != "" {
- terms = append(terms, repo)
+ if strings.Contains(identifier, ":") && !strings.HasPrefix(identifierLower, "sha256:") {
+ if repository, _, ok := strings.Cut(identifier, ":"); ok && repository != "" {
+ terms = append(terms, repository)
}
}
return terms
}
-func searchImageMatches(ctx context.Context, c *client.Client, term, trimmed string) ([]image.Summary, error) {
- searchPath := fmt.Sprintf("%s?search=%s&limit=%d", types.Images(c.EnvID()), url.QueryEscape(term), cmdutil.ShowAllLimit)
- searchResp, err := c.Get(ctx, searchPath)
- if err != nil {
- return nil, errors.WrapIf(err, "failed to search images")
- }
-
- searchBody, err := io.ReadAll(searchResp.Body)
- _ = searchResp.Body.Close()
- if err != nil {
- return nil, errors.WrapIf(err, "failed to read images response")
- }
-
- if searchResp.StatusCode < 200 || searchResp.StatusCode >= 300 {
- return nil, errors.Errorf("failed to search images (status %d): %s", searchResp.StatusCode, strings.TrimSpace(string(searchBody)))
- }
-
- var result struct {
- Success bool `json:"success"`
- Data []image.Summary `json:"data"`
- }
- if err := json.Unmarshal(searchBody, &result); err != nil {
- return nil, errors.WrapIf(err, "failed to parse images response")
- }
-
- return filterImageMatches(result.Data, trimmed), nil
-}
-
-func filterImageMatches(items []image.Summary, trimmed string) []image.Summary {
- identifierLower := strings.ToLower(trimmed)
- hasSeparator := strings.Contains(trimmed, ":") || strings.Contains(trimmed, "@")
- matches := make([]image.Summary, 0)
- for _, item := range items {
- if imageMatches(item, trimmed, identifierLower, hasSeparator) {
- matches = append(matches, item)
- }
- }
- return matches
-}
+func imageMatches(item image.Summary, identifierLower, original string) bool {
+ hasSeparator := strings.Contains(original, ":") || strings.Contains(original, "@")
-func imageMatches(item image.Summary, trimmed, identifierLower string, hasSeparator bool) bool {
idLower := strings.ToLower(item.ID)
if idLower == identifierLower || (len(identifierLower) >= 4 && strings.HasPrefix(idLower, identifierLower)) {
return true
@@ -829,7 +742,7 @@ func imageMatches(item image.Summary, trimmed, identifierLower string, hasSepara
for _, tag := range item.RepoTags {
tagLower := strings.ToLower(tag)
- if (!hasSeparator && strings.Contains(tagLower, identifierLower)) || strings.EqualFold(tag, trimmed) {
+ if (!hasSeparator && strings.Contains(tagLower, identifierLower)) || strings.EqualFold(tag, original) {
return true
}
}
@@ -837,53 +750,17 @@ func imageMatches(item image.Summary, trimmed, identifierLower string, hasSepara
if item.Repo != "" && item.Tag != "" {
combined := item.Repo + ":" + item.Tag
combinedLower := strings.ToLower(combined)
- if strings.EqualFold(combined, trimmed) || (hasSeparator && strings.Contains(combinedLower, identifierLower)) {
+ if strings.EqualFold(combined, original) || (hasSeparator && strings.Contains(combinedLower, identifierLower)) {
return true
}
}
for _, digest := range item.RepoDigests {
digestLower := strings.ToLower(digest)
- if strings.EqualFold(digest, trimmed) || strings.Contains(digestLower, identifierLower) {
+ if strings.EqualFold(digest, original) || strings.Contains(digestLower, identifierLower) {
return true
}
}
return false
}
-
-func selectImageMatchID(matches []image.Summary, trimmed string, allowPrompt bool) (string, bool, error) {
- if len(matches) == 1 {
- return matches[0].ID, true, nil
- }
- if len(matches) == 0 {
- return "", false, nil
- }
-
- if !allowPrompt {
- return "", false, errors.Errorf("multiple images match %q; use the image ID or run `arcane images list`", trimmed)
- }
- if len(matches) > maxPromptOptions {
- return "", false, errors.Errorf("multiple images match %q (%d results); refine your query or use the image ID", trimmed, len(matches))
- }
-
- options := make([]string, 0, len(matches))
- for _, match := range matches {
- options = append(options, formatImageMatchOption(match))
- }
- choice, err := prompt.Select("image", options)
- if err != nil {
- return "", false, err
- }
- return matches[choice].ID, true, nil
-}
-
-func formatImageMatchOption(match image.Summary) string {
- label := match.ID
- if len(match.RepoTags) > 0 {
- label = match.RepoTags[0]
- } else if match.Repo != "" && match.Tag != "" {
- label = match.Repo + ":" + match.Tag
- }
- return fmt.Sprintf("%s (%s)", label, match.ID)
-}
diff --git a/cli/pkg/images/extra.go b/cli/pkg/images/extra.go
index 5f0fb807e..3c89f5dd8 100644
--- a/cli/pkg/images/extra.go
+++ b/cli/pkg/images/extra.go
@@ -2,7 +2,7 @@ package images
import (
"bufio"
- "encoding/json"
+ "encoding/json/v2"
"fmt"
"io"
"net/http"
@@ -40,27 +40,13 @@ var imagesSearchCmd = &cobra.Command{
log.Debugf("Searching images from: %s", path)
- resp, err := c.Get(cmd.Context(), path)
- if err != nil {
- return errors.WrapIf(err, "failed to search images")
- }
- defer func() { _ = resp.Body.Close() }()
-
- body, err := cmdutil.ReadJSONBody(resp)
+ result, err := c.GetJSON[[]image.SearchResult](cmd.Context(), path)
if err != nil {
return errors.WrapIf(err, "failed to search images")
}
if cmdutil.JSONOutputEnabled(cmd) {
- return cmdutil.PrintRawJSON(body)
- }
-
- var result struct {
- Success bool `json:"success"`
- Data []image.SearchResult `json:"data"`
- }
- if err := json.Unmarshal(body, &result); err != nil {
- return errors.WrapIf(err, "failed to parse response")
+ return cmdutil.PrintJSON(result.Data)
}
headers := []string{"NAME", "DESCRIPTION", "STARS", "OFFICIAL"}
@@ -95,10 +81,11 @@ var imagesHistoryCmd = &cobra.Command{
jsonOutput := cmdutil.JSONOutputEnabled(cmd)
allowPrompt := !jsonOutput && prompt.IsInteractive()
- imageID, err := resolveImageID(cmd.Context(), c, args[0], allowPrompt)
+ resolved, _, err := ImageRef.Resolve(cmd.Context(), c, args[0], allowPrompt)
if err != nil {
return err
}
+ imageID := resolved.ID
path := types.ImageHistory(c.EnvID(), imageID)
log.Debugf("Getting image history from: %s", path)
@@ -157,10 +144,11 @@ var imagesTagCmd = &cobra.Command{
jsonOutput := cmdutil.JSONOutputEnabled(cmd)
allowPrompt := !jsonOutput && prompt.IsInteractive()
- imageID, err := resolveImageID(cmd.Context(), c, args[0], allowPrompt)
+ resolved, _, err := ImageRef.Resolve(cmd.Context(), c, args[0], allowPrompt)
if err != nil {
return err
}
+ imageID := resolved.ID
repository, tag := splitImageRef(args[1])
if repository == "" {
@@ -217,10 +205,11 @@ var imagesExportCmd = &cobra.Command{
allowPrompt := prompt.IsInteractive()
- imageID, err := resolveImageID(cmd.Context(), c, args[0], allowPrompt)
+ resolved, _, err := ImageRef.Resolve(cmd.Context(), c, args[0], allowPrompt)
if err != nil {
return err
}
+ imageID := resolved.ID
outputFile := exportFileName(args[0])
if len(args) == 2 {
@@ -509,74 +498,36 @@ var imagesBuildsCmd = &cobra.Command{
Short: "List image build history",
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
- log := logger.GetLogger()
c, err := cmdutil.ClientFromCommand(cmd)
if err != nil {
return err
}
- u, err := url.Parse(types.ImageBuilds(c.EnvID()))
- if err != nil {
- return errors.WrapIf(err, "failed to parse endpoint path")
- }
- q := u.Query()
+ query := url.Values{}
if buildsStatus != "" {
- q.Set("status", buildsStatus)
+ query.Set("status", buildsStatus)
}
if buildsProvider != "" {
- q.Set("provider", buildsProvider)
- }
- u.RawQuery = q.Encode()
-
- path, err := cmdutil.ApplyPaginationParams(cmd, u.String(), cmdutil.ListParams{
- Resource: "builds",
- Limit: buildsLimit,
- FallbackDefault: 0,
- Start: buildsStart,
- All: buildsAll,
+ query.Set("provider", buildsProvider)
+ }
+
+ return cmdutil.RunList(cmd, c, cmdutil.ListSpec[image.BuildRecord]{
+ Resource: "builds",
+ Endpoint: types.ImageBuilds(c.EnvID()),
+ Params: cmdutil.ListParams{Resource: "builds", Limit: buildsLimit, FallbackDefault: 0, Start: buildsStart, All: buildsAll},
+ Query: query,
+ JSON: cmdutil.JSONOutputEnabled(cmd),
+ Headers: []string{"ID", "IMAGE", "STATUS", "STARTED", "DURATION"},
+ Row: func(record image.BuildRecord) []string {
+ return []string{
+ record.ID,
+ buildImageLabel(record),
+ output.TintStatus(record.Status),
+ record.CreatedAt.Format(time.RFC3339),
+ buildDurationLabel(record.DurationMs),
+ }
+ },
})
- if err != nil {
- return errors.WrapIf(err, "failed to build pagination query")
- }
-
- log.Debugf("Listing image builds from: %s", path)
-
- resp, err := c.Get(cmd.Context(), path)
- if err != nil {
- return errors.WrapIf(err, "failed to list image builds")
- }
- defer func() { _ = resp.Body.Close() }()
-
- body, err := cmdutil.ReadJSONBody(resp)
- if err != nil {
- return errors.WrapIf(err, "failed to list image builds")
- }
-
- if cmdutil.JSONOutputEnabled(cmd) {
- return cmdutil.PrintRawJSON(body)
- }
-
- var result base.Paginated[image.BuildRecord]
- if err := json.Unmarshal(body, &result); err != nil {
- return errors.WrapIf(err, "failed to parse response")
- }
-
- headers := []string{"ID", "IMAGE", "STATUS", "STARTED", "DURATION"}
- var rows [][]string
- for _, record := range result.Data {
- rows = append(rows, []string{
- record.ID,
- buildImageLabel(record),
- output.TintStatus(record.Status),
- record.CreatedAt.Format(time.RFC3339),
- buildDurationLabel(record.DurationMs),
- })
- }
-
- output.Table(headers, rows)
- output.Showing(len(result.Data), result.Pagination.TotalItems, "builds")
-
- return nil
},
}
diff --git a/cli/pkg/images/updates/cmd.go b/cli/pkg/images/updates/cmd.go
index 848cf79fc..17fb506c8 100644
--- a/cli/pkg/images/updates/cmd.go
+++ b/cli/pkg/images/updates/cmd.go
@@ -1,14 +1,13 @@
package updates
import (
- "encoding/json"
"fmt"
- "net/http"
"sort"
"strconv"
"emperror.dev/errors"
"github.com/getarcaneapp/arcane/cli/v2/internal/client"
+ "github.com/getarcaneapp/arcane/cli/v2/internal/cmdutil"
"github.com/getarcaneapp/arcane/cli/v2/internal/output"
"github.com/getarcaneapp/arcane/cli/v2/internal/types"
"github.com/getarcaneapp/arcane/types/v2/imageupdate"
@@ -41,12 +40,12 @@ var checkCmd = &cobra.Command{
if len(args) > 0 {
return errors.New("--all cannot be combined with image references")
}
- // The handler declares a non-pointer Body, so an empty body is a 400.
- resp, err := c.Post(cmd.Context(), types.ImageUpdatesCheckAll(c.EnvID()), imageupdate.CheckAllImagesRequest{})
+
+ result, err := c.PostJSON[imageupdate.BatchResponse](cmd.Context(), types.ImageUpdatesCheckAll(c.EnvID()), imageupdate.CheckAllImagesRequest{})
if err != nil {
return errors.WrapIf(err, "failed to check all updates")
}
- return printBatchResults(resp, "failed to check all updates")
+ return printBatchResultsInternal(result.Data)
}
if len(args) == 0 {
@@ -54,30 +53,20 @@ var checkCmd = &cobra.Command{
}
if len(args) > 1 {
- resp, err := c.Post(cmd.Context(), types.ImageUpdatesCheckBatch(c.EnvID()), imageupdate.BatchImageUpdateRequest{ImageRefs: args})
+ result, err := c.PostJSON[imageupdate.BatchResponse](cmd.Context(), types.ImageUpdatesCheckBatch(c.EnvID()), imageupdate.BatchImageUpdateRequest{ImageRefs: args})
if err != nil {
return errors.WrapIf(err, "failed to check updates")
}
- return printBatchResults(resp, "failed to check updates")
- }
-
- resp, err := c.Get(cmd.Context(), types.ImageUpdatesCheck(c.EnvID(), args[0]))
- if err != nil {
- return errors.WrapIf(err, "failed to check updates")
+ return printBatchResultsInternal(result.Data)
}
- result, err := client.DecodeResponseStrict[imageupdate.Response](resp)
+ result, err := c.GetJSON[imageupdate.Response](cmd.Context(), types.ImageUpdatesCheck(c.EnvID(), args[0]))
if err != nil {
return errors.WrapIf(err, "failed to check updates")
}
if jsonOutput {
- resultBytes, err := json.MarshalIndent(result.Data, "", " ")
- if err != nil {
- return errors.WrapIf(err, "failed to marshal JSON")
- }
- fmt.Println(string(resultBytes))
- return nil
+ return cmdutil.PrintJSON(result.Data)
}
output.Header("Image Update Status")
@@ -106,23 +95,13 @@ var checkAllCmd = &cobra.Command{
}
// The handler declares a non-pointer Body, so an empty body is a 400.
- resp, err := c.Post(cmd.Context(), types.ImageUpdatesCheckAll(c.EnvID()), imageupdate.CheckAllImagesRequest{})
- if err != nil {
- return errors.WrapIf(err, "failed to check all updates")
- }
-
- result, err := client.DecodeResponseStrict[imageupdate.BatchResponse](resp)
+ result, err := c.PostJSON[imageupdate.BatchResponse](cmd.Context(), types.ImageUpdatesCheckAll(c.EnvID()), imageupdate.CheckAllImagesRequest{})
if err != nil {
return errors.WrapIf(err, "failed to check all updates")
}
if jsonOutput {
- resultBytes, err := json.MarshalIndent(result.Data, "", " ")
- if err != nil {
- return errors.WrapIf(err, "failed to marshal JSON")
- }
- fmt.Println(string(resultBytes))
- return nil
+ return cmdutil.PrintJSON(result.Data)
}
output.Header("Check All Results")
@@ -151,23 +130,13 @@ var checkImageCmd = &cobra.Command{
return err
}
- resp, err := c.Get(cmd.Context(), types.ImageUpdatesCheckById(c.EnvID(), args[0]))
- if err != nil {
- return errors.WrapIf(err, "failed to check image update")
- }
-
- result, err := client.DecodeResponseStrict[imageupdate.Response](resp)
+ result, err := c.GetJSON[imageupdate.Response](cmd.Context(), types.ImageUpdatesCheckById(c.EnvID(), args[0]))
if err != nil {
return errors.WrapIf(err, "failed to check image update")
}
if jsonOutput {
- resultBytes, err := json.MarshalIndent(result.Data, "", " ")
- if err != nil {
- return errors.WrapIf(err, "failed to marshal JSON")
- }
- fmt.Println(string(resultBytes))
- return nil
+ return cmdutil.PrintJSON(result.Data)
}
output.Header("Image Update Status")
@@ -193,23 +162,13 @@ var summaryCmd = &cobra.Command{
return err
}
- resp, err := c.Get(cmd.Context(), types.ImageUpdatesSummary(c.EnvID()))
- if err != nil {
- return errors.WrapIf(err, "failed to get summary")
- }
-
- result, err := client.DecodeResponseStrict[imageupdate.Summary](resp)
+ result, err := c.GetJSON[imageupdate.Summary](cmd.Context(), types.ImageUpdatesSummary(c.EnvID()))
if err != nil {
return errors.WrapIf(err, "failed to get summary")
}
if jsonOutput {
- resultBytes, err := json.MarshalIndent(result.Data, "", " ")
- if err != nil {
- return errors.WrapIf(err, "failed to marshal JSON")
- }
- fmt.Println(string(resultBytes))
- return nil
+ return cmdutil.PrintJSON(result.Data)
}
output.Header("Image Updates Summary")
@@ -221,25 +180,15 @@ var summaryCmd = &cobra.Command{
},
}
-// printBatchResults decodes a batch update-check response and prints every
-// requested reference, including up-to-date and failed checks.
-func printBatchResults(resp *http.Response, wrapMsg string) error {
- result, err := client.DecodeResponseStrict[imageupdate.BatchResponse](resp)
- if err != nil {
- return errors.WrapIf(err, wrapMsg)
- }
-
+// printBatchResultsInternal prints every requested reference, including
+// up-to-date and failed checks.
+func printBatchResultsInternal(result imageupdate.BatchResponse) error {
if jsonOutput {
- resultBytes, err := json.MarshalIndent(result.Data, "", " ")
- if err != nil {
- return errors.WrapIf(err, "failed to marshal JSON")
- }
- fmt.Println(string(resultBytes))
- return nil
+ return cmdutil.PrintJSON(result)
}
- refs := make([]string, 0, len(result.Data))
- for imageRef := range result.Data {
+ refs := make([]string, 0, len(result))
+ for imageRef := range result {
refs = append(refs, imageRef)
}
sort.Strings(refs)
@@ -248,7 +197,7 @@ func printBatchResults(resp *http.Response, wrapMsg string) error {
rows := make([][]string, 0, len(refs))
updatesAvailable := 0
for _, imageRef := range refs {
- update := result.Data[imageRef]
+ update := result[imageRef]
if update == nil {
rows = append(rows, []string{imageRef, "unknown", "", "", ""})
continue
@@ -266,7 +215,7 @@ func printBatchResults(resp *http.Response, wrapMsg string) error {
}
output.Table(headers, rows)
- fmt.Printf("\nTotal: %d images checked, %d updates available\n", len(result.Data), updatesAvailable)
+ fmt.Printf("\nTotal: %d images checked, %d updates available\n", len(result), updatesAvailable)
return nil
}
diff --git a/cli/pkg/jobs/cmd.go b/cli/pkg/jobs/cmd.go
index e9e2bdb2f..9a2266928 100644
--- a/cli/pkg/jobs/cmd.go
+++ b/cli/pkg/jobs/cmd.go
@@ -1,8 +1,8 @@
package jobs
import (
- "encoding/json"
"fmt"
+ "net/http"
"strconv"
"time"
@@ -12,7 +12,6 @@ import (
"github.com/getarcaneapp/arcane/cli/v2/internal/cmdutil"
"github.com/getarcaneapp/arcane/cli/v2/internal/output"
"github.com/getarcaneapp/arcane/cli/v2/internal/types"
- "github.com/getarcaneapp/arcane/types/v2/base"
"github.com/getarcaneapp/arcane/types/v2/jobschedule"
"github.com/spf13/cobra"
)
@@ -36,27 +35,13 @@ var getCmd = &cobra.Command{
return err
}
- resp, err := c.Get(cmd.Context(), types.JobSchedules(c.EnvID()))
+ cfg, err := c.DoJSON[jobschedule.Config](cmd.Context(), http.MethodGet, types.JobSchedules(c.EnvID()), nil)
if err != nil {
return errors.WrapIf(err, "failed to get job schedules")
}
- defer func() { _ = resp.Body.Close() }()
- if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
- return errors.WrapIf(err, "failed to get job schedules")
- }
-
- var cfg jobschedule.Config
- if err := cmdutil.DecodeJSON(resp, &cfg); err != nil {
- return err
- }
if jsonOutput {
- b, err := json.MarshalIndent(cfg, "", " ")
- if err != nil {
- return errors.WrapIf(err, "failed to marshal JSON")
- }
- fmt.Println(string(b))
- return nil
+ return cmdutil.PrintJSON(cfg)
}
output.Header("Job Schedules")
@@ -98,24 +83,13 @@ var updateCmd = &cobra.Command{
return errors.New("no updates provided (set at least one interval flag)")
}
- resp, err := c.Put(cmd.Context(), types.JobSchedules(c.EnvID()), req)
+ result, err := c.PutJSON[jobschedule.Config](cmd.Context(), types.JobSchedules(c.EnvID()), req)
if err != nil {
return errors.WrapIf(err, "failed to update job schedules")
}
- defer func() { _ = resp.Body.Close() }()
-
- var result base.ApiResponse[jobschedule.Config]
- if err := cmdutil.DecodeJSON(resp, &result); err != nil {
- return err
- }
if jsonOutput {
- b, err := json.MarshalIndent(result.Data, "", " ")
- if err != nil {
- return errors.WrapIf(err, "failed to marshal JSON")
- }
- fmt.Println(string(b))
- return nil
+ return cmdutil.PrintJSON(result.Data)
}
output.Success("Job schedules updated")
@@ -137,19 +111,10 @@ var listCmd = &cobra.Command{
return err
}
- resp, err := c.Get(cmd.Context(), types.Jobs(c.EnvID()))
+ result, err := c.DoJSON[jobschedule.JobListResponse](cmd.Context(), http.MethodGet, types.Jobs(c.EnvID()), nil)
if err != nil {
return errors.WrapIf(err, "failed to list jobs")
}
- defer func() { _ = resp.Body.Close() }()
- if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
- return errors.WrapIf(err, "failed to list jobs")
- }
-
- var result jobschedule.JobListResponse
- if err := cmdutil.DecodeJSON(resp, &result); err != nil {
- return err
- }
if jsonOutput {
return cmdutil.PrintJSON(result)
@@ -189,19 +154,10 @@ var runCmd = &cobra.Command{
return err
}
- resp, err := c.Post(cmd.Context(), types.JobRun(c.EnvID(), args[0]), nil)
+ result, err := c.DoJSON[jobschedule.JobRunResponse](cmd.Context(), http.MethodPost, types.JobRun(c.EnvID(), args[0]), nil)
if err != nil {
return errors.WrapIf(err, "failed to run job")
}
- defer func() { _ = resp.Body.Close() }()
- if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
- return errors.WrapIf(err, "failed to run job")
- }
-
- var result jobschedule.JobRunResponse
- if err := cmdutil.DecodeJSON(resp, &result); err != nil {
- return err
- }
if jsonOutput {
return cmdutil.PrintJSON(result)
diff --git a/cli/pkg/networks/cmd.go b/cli/pkg/networks/cmd.go
index e83c6153e..8dfbd4625 100644
--- a/cli/pkg/networks/cmd.go
+++ b/cli/pkg/networks/cmd.go
@@ -1,11 +1,7 @@
package networks
import (
- "context"
- "encoding/json"
"fmt"
- "io"
- "net/http"
"net/url"
"strings"
@@ -52,8 +48,6 @@ var (
disconnectForce bool
)
-const maxPromptOptions = 20
-
// NetworksCmd is the parent command for network operations
var NetworksCmd = &cobra.Command{
Use: "networks",
@@ -75,66 +69,44 @@ var listCmd = &cobra.Command{
return err
}
- path, err := cmdutil.ApplyPaginationParams(cmd, types.Networks(c.EnvID()), cmdutil.ListParams{
- Resource: "networks",
- Limit: limitFlag,
- FallbackDefault: 20,
- Start: startFlag,
- All: allFlag,
- })
- if err != nil {
- return errors.WrapIf(err, "failed to build pagination query")
- }
-
// Filter server-side so that pagination and the reported totals apply to
// the matching set rather than to whichever page happened to be fetched.
+ query := url.Values{}
if inUseOnlyFlag {
- path = cmdutil.AppendQuery(path, url.Values{"inUse": []string{"true"}})
+ query.Set("inUse", "true")
}
if unusedOnlyFlag {
- path = cmdutil.AppendQuery(path, url.Values{"inUse": []string{"false"}})
- }
-
- resp, err := c.Get(cmd.Context(), path)
- if err != nil {
- return errors.WrapIf(err, "failed to list networks")
- }
- defer func() { _ = resp.Body.Close() }()
-
- body, err := cmdutil.ReadJSONBody(resp)
- if err != nil {
- return errors.WrapIf(err, "failed to list networks")
- }
-
- if jsonOutput {
- return cmdutil.PrintRawJSON(body)
- }
-
- var result base.Paginated[network.Summary]
- if err := json.Unmarshal(body, &result); err != nil {
- return errors.WrapIf(err, "failed to parse response")
- }
-
- headers := []string{"ID", "NAME", "DRIVER", "SCOPE", "CREATED", "IN USE"}
- rows := make([][]string, len(result.Data))
- for i, net := range result.Data {
- inUse := "No"
- if net.InUse {
- inUse = "Yes"
- }
- rows[i] = []string{
- shortID(net.ID),
- net.Name,
- net.Driver,
- net.Scope,
- net.Created.Format("2006-01-02 15:04"),
- inUse,
- }
- }
-
- output.Table(headers, rows)
- output.Showing(len(result.Data), result.Pagination.TotalItems, "networks")
- return nil
+ query.Set("inUse", "false")
+ }
+
+ return cmdutil.RunList(cmd, c, cmdutil.ListSpec[network.Summary]{
+ Resource: "networks",
+ Endpoint: types.Networks(c.EnvID()),
+ Params: cmdutil.ListParams{
+ Resource: "networks",
+ Limit: limitFlag,
+ FallbackDefault: 20,
+ Start: startFlag,
+ All: allFlag,
+ },
+ Query: query,
+ JSON: jsonOutput,
+ Headers: []string{"ID", "NAME", "DRIVER", "SCOPE", "CREATED", "IN USE"},
+ Row: func(net network.Summary) []string {
+ inUse := "No"
+ if net.InUse {
+ inUse = "Yes"
+ }
+ return []string{
+ shortID(net.ID),
+ net.Name,
+ net.Driver,
+ net.Scope,
+ net.Created.Format("2006-01-02 15:04"),
+ inUse,
+ }
+ },
+ })
},
}
@@ -150,46 +122,33 @@ var getCmd = &cobra.Command{
}
allowPrompt := !jsonOutput && prompt.IsInteractive()
- resolvedID, resolvedName, err := resolveNetworkID(cmd.Context(), c, args[0], allowPrompt)
+ resolved, complete, err := networkRef.Resolve(cmd.Context(), c, args[0], allowPrompt)
if err != nil {
return err
}
- resp, err := c.Get(cmd.Context(), types.Network(c.EnvID(), resolvedID))
- if err != nil {
- return errors.WrapIf(err, "failed to get network")
- }
- defer func() { _ = resp.Body.Close() }()
-
- var result base.ApiResponse[network.Inspect]
- if err := cmdutil.DecodeJSON(resp, &result); err != nil {
- return err
- }
-
- if jsonOutput {
- resultBytes, err := json.MarshalIndent(result.Data, "", " ")
+ if !complete {
+ result, err := c.GetJSON[network.Inspect](cmd.Context(), types.Network(c.EnvID(), resolved.ID))
if err != nil {
- return errors.WrapIf(err, "failed to marshal JSON")
+ return errors.WrapIf(err, "failed to get network")
}
- fmt.Println(string(resultBytes))
- return nil
+ resolved = &result.Data
}
- display := resolvedName
- if display == "" {
- display = result.Data.Name
+ if jsonOutput {
+ return cmdutil.PrintJSON(resolved)
}
output.Header("Network Details")
- output.KeyValue("ID", result.Data.ID)
- output.KeyValue("Name", display)
- output.KeyValue("Driver", result.Data.Driver)
- output.KeyValue("Scope", result.Data.Scope)
- output.KeyValue("Created", result.Data.Created.Format("2006-01-02 15:04"))
- output.KeyValue("Internal", result.Data.Internal)
- output.KeyValue("Attachable", result.Data.Attachable)
- output.KeyValue("Ingress", result.Data.Ingress)
- output.KeyValue("Containers", len(result.Data.ContainersList))
+ output.KeyValue("ID", resolved.ID)
+ output.KeyValue("Name", resolved.Name)
+ output.KeyValue("Driver", resolved.Driver)
+ output.KeyValue("Scope", resolved.Scope)
+ output.KeyValue("Created", resolved.Created.Format("2006-01-02 15:04"))
+ output.KeyValue("Internal", resolved.Internal)
+ output.KeyValue("Attachable", resolved.Attachable)
+ output.KeyValue("Ingress", resolved.Ingress)
+ output.KeyValue("Containers", len(resolved.ContainersList))
return nil
},
}
@@ -206,14 +165,14 @@ var deleteCmd = &cobra.Command{
return err
}
- resolvedID, resolvedName, err := resolveNetworkID(cmd.Context(), c, args[0], false)
+ resolved, _, err := networkRef.Resolve(cmd.Context(), c, args[0], false)
if err != nil {
return err
}
- display := resolvedName
+ display := resolved.Name
if display == "" {
- display = shortID(resolvedID)
+ display = shortID(resolved.ID)
}
if !forceFlag {
@@ -227,26 +186,13 @@ var deleteCmd = &cobra.Command{
}
}
- resp, err := c.Delete(cmd.Context(), types.Network(c.EnvID(), resolvedID))
+ result, err := c.DeleteJSON[base.MessageResponse](cmd.Context(), types.Network(c.EnvID(), resolved.ID))
if err != nil {
return errors.WrapIf(err, "failed to delete network")
}
- defer func() { _ = resp.Body.Close() }()
- if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
- return errors.WrapIf(err, "failed to delete network")
- }
if jsonOutput {
- var result base.ApiResponse[any]
- if err := cmdutil.DecodeJSON(resp, &result); err != nil {
- return err
- }
- resultBytes, err := json.MarshalIndent(result.Data, "", " ")
- if err != nil {
- return errors.WrapIf(err, "failed to marshal JSON")
- }
- fmt.Println(string(resultBytes))
- return nil
+ return cmdutil.PrintJSON(result.Data)
}
output.Success("Network %s deleted successfully", display)
@@ -264,24 +210,13 @@ var countsCmd = &cobra.Command{
return err
}
- resp, err := c.Get(cmd.Context(), types.NetworksCounts(c.EnvID()))
+ result, err := c.GetJSON[network.UsageCounts](cmd.Context(), types.NetworksCounts(c.EnvID()))
if err != nil {
return errors.WrapIf(err, "failed to get network counts")
}
- defer func() { _ = resp.Body.Close() }()
-
- var result base.ApiResponse[network.UsageCounts]
- if err := cmdutil.DecodeJSON(resp, &result); err != nil {
- return err
- }
if jsonOutput {
- resultBytes, err := json.MarshalIndent(result.Data, "", " ")
- if err != nil {
- return errors.WrapIf(err, "failed to marshal JSON")
- }
- fmt.Println(string(resultBytes))
- return nil
+ return cmdutil.PrintJSON(result.Data)
}
output.Header("Network Usage Counts")
@@ -313,27 +248,13 @@ var pruneCmd = &cobra.Command{
return err
}
- resp, err := c.Post(cmd.Context(), types.NetworksPrune(c.EnvID()), nil)
+ result, err := c.PostJSON[network.PruneReport](cmd.Context(), types.NetworksPrune(c.EnvID()), nil)
if err != nil {
return errors.WrapIf(err, "failed to prune networks")
}
- defer func() { _ = resp.Body.Close() }()
- if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
- return errors.WrapIf(err, "failed to prune networks")
- }
-
- var result base.ApiResponse[network.PruneReport]
- if err := cmdutil.DecodeJSON(resp, &result); err != nil {
- return err
- }
if jsonOutput {
- resultBytes, err := json.MarshalIndent(result.Data, "", " ")
- if err != nil {
- return errors.WrapIf(err, "failed to marshal JSON")
- }
- fmt.Println(string(resultBytes))
- return nil
+ return cmdutil.PrintJSON(result.Data)
}
output.Success("Networks pruned successfully")
@@ -393,19 +314,10 @@ var createCmd = &cobra.Command{
}
}
- resp, err := c.Post(cmd.Context(), types.Networks(c.EnvID()), req)
+ result, err := c.PostJSON[network.CreateResponse](cmd.Context(), types.Networks(c.EnvID()), req)
if err != nil {
return errors.WrapIf(err, "failed to create network")
}
- defer func() { _ = resp.Body.Close() }()
- if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
- return errors.WrapIf(err, "failed to create network")
- }
-
- var result base.ApiResponse[network.CreateResponse]
- if err := cmdutil.DecodeJSON(resp, &result); err != nil {
- return err
- }
if jsonOutput {
return cmdutil.PrintJSON(result.Data)
@@ -426,13 +338,13 @@ var connectCmd = &cobra.Command{
Args: cobra.ExactArgs(2),
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
- c, err := client.NewFromConfig()
+ c, err := cmdutil.ClientFromCommand(cmd)
if err != nil {
return err
}
allowPrompt := !jsonOutput && prompt.IsInteractive()
- resolvedID, resolvedName, err := resolveNetworkID(cmd.Context(), c, args[0], allowPrompt)
+ resolved, _, err := networkRef.Resolve(cmd.Context(), c, args[0], allowPrompt)
if err != nil {
return err
}
@@ -444,27 +356,18 @@ var connectCmd = &cobra.Command{
IPv6Address: connectIPv6,
}
- resp, err := c.Post(cmd.Context(), types.NetworkConnect(c.EnvID(), resolvedID), req)
+ result, err := c.PostJSON[base.MessageResponse](cmd.Context(), types.NetworkConnect(c.EnvID(), resolved.ID), req)
if err != nil {
return errors.WrapIf(err, "failed to connect container to network")
}
- defer func() { _ = resp.Body.Close() }()
- if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
- return errors.WrapIf(err, "failed to connect container to network")
- }
-
- var result base.ApiResponse[base.MessageResponse]
- if err := cmdutil.DecodeJSON(resp, &result); err != nil {
- return err
- }
if jsonOutput {
return cmdutil.PrintJSON(result.Data)
}
- display := resolvedName
+ display := resolved.Name
if display == "" {
- display = shortID(resolvedID)
+ display = shortID(resolved.ID)
}
output.Success("Container %s connected to network %s", args[1], display)
return nil
@@ -477,13 +380,13 @@ var disconnectCmd = &cobra.Command{
Args: cobra.ExactArgs(2),
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
- c, err := client.NewFromConfig()
+ c, err := cmdutil.ClientFromCommand(cmd)
if err != nil {
return err
}
allowPrompt := !jsonOutput && prompt.IsInteractive()
- resolvedID, resolvedName, err := resolveNetworkID(cmd.Context(), c, args[0], allowPrompt)
+ resolved, _, err := networkRef.Resolve(cmd.Context(), c, args[0], allowPrompt)
if err != nil {
return err
}
@@ -493,27 +396,18 @@ var disconnectCmd = &cobra.Command{
Force: disconnectForce,
}
- resp, err := c.Post(cmd.Context(), types.NetworkDisconnect(c.EnvID(), resolvedID), req)
+ result, err := c.PostJSON[base.MessageResponse](cmd.Context(), types.NetworkDisconnect(c.EnvID(), resolved.ID), req)
if err != nil {
return errors.WrapIf(err, "failed to disconnect container from network")
}
- defer func() { _ = resp.Body.Close() }()
- if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
- return errors.WrapIf(err, "failed to disconnect container from network")
- }
-
- var result base.ApiResponse[base.MessageResponse]
- if err := cmdutil.DecodeJSON(resp, &result); err != nil {
- return err
- }
if jsonOutput {
return cmdutil.PrintJSON(result.Data)
}
- display := resolvedName
+ display := resolved.Name
if display == "" {
- display = shortID(resolvedID)
+ display = shortID(resolved.ID)
}
output.Success("Container %s disconnected from network %s", args[1], display)
return nil
@@ -525,21 +419,15 @@ var topologyCmd = &cobra.Command{
Short: "Show the network topology",
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
- c, err := client.NewFromConfig()
+ c, err := cmdutil.ClientFromCommand(cmd)
if err != nil {
return err
}
- resp, err := c.Get(cmd.Context(), types.NetworksTopology(c.EnvID()))
+ result, err := c.GetJSON[network.Topology](cmd.Context(), types.NetworksTopology(c.EnvID()))
if err != nil {
return errors.WrapIf(err, "failed to get network topology")
}
- defer func() { _ = resp.Body.Close() }()
-
- var result base.ApiResponse[network.Topology]
- if err := cmdutil.DecodeJSON(resp, &result); err != nil {
- return err
- }
if jsonOutput {
return cmdutil.PrintJSON(result.Data)
@@ -657,88 +545,28 @@ func shortID(id string) string {
return id
}
-func resolveNetworkID(ctx context.Context, c *client.Client, identifier string, allowPrompt bool) (string, string, error) {
- trimmed := strings.TrimSpace(identifier)
- if trimmed == "" {
- return "", "", errors.New("network identifier is required")
- }
-
- resp, err := c.Get(ctx, types.Network(c.EnvID(), trimmed))
- if err != nil {
- return "", "", errors.WrapIff(err, "failed to resolve network %q", trimmed)
- }
-
- body, err := io.ReadAll(resp.Body)
- _ = resp.Body.Close()
- if err != nil {
- return "", "", errors.WrapIf(err, "failed to read network response")
- }
-
- if resp.StatusCode == http.StatusOK {
- var result base.ApiResponse[network.Inspect]
- if err := json.Unmarshal(body, &result); err != nil {
- return "", "", errors.WrapIf(err, "failed to parse network response")
- }
- return result.Data.ID, result.Data.Name, nil
- }
-
- if resp.StatusCode != http.StatusNotFound {
- return "", "", errors.Errorf("failed to resolve network %q (status %d): %s", trimmed, resp.StatusCode, strings.TrimSpace(string(body)))
- }
-
- searchPath := fmt.Sprintf("%s?search=%s&limit=%d", types.Networks(c.EnvID()), url.QueryEscape(trimmed), cmdutil.ShowAllLimit)
- searchResp, err := c.Get(ctx, searchPath)
- if err != nil {
- return "", "", errors.WrapIf(err, "failed to search networks")
- }
-
- searchBody, err := io.ReadAll(searchResp.Body)
- _ = searchResp.Body.Close()
- if err != nil {
- return "", "", errors.WrapIf(err, "failed to read networks response")
- }
-
- if searchResp.StatusCode < 200 || searchResp.StatusCode >= 300 {
- return "", "", errors.Errorf("failed to search networks (status %d): %s", searchResp.StatusCode, strings.TrimSpace(string(searchBody)))
- }
-
- var result base.Paginated[network.Summary]
- if err := json.Unmarshal(searchBody, &result); err != nil {
- return "", "", errors.WrapIf(err, "failed to parse networks response")
- }
-
- identifierLower := strings.ToLower(trimmed)
- matches := make([]network.Summary, 0)
- for _, item := range result.Data {
- if networkMatches(item, identifierLower, trimmed) {
- matches = append(matches, item)
- }
- }
-
- if len(matches) == 1 {
- return matches[0].ID, matches[0].Name, nil
- }
-
- if len(matches) > 1 {
- if !allowPrompt {
- return "", "", errors.Errorf("multiple networks match %q; use the network ID or run `arcane networks list`", trimmed)
- }
- if len(matches) > maxPromptOptions {
- return "", "", errors.Errorf("multiple networks match %q (%d results); refine your query or use the network ID", trimmed, len(matches))
- }
-
- options := make([]string, 0, len(matches))
- for _, match := range matches {
- options = append(options, fmt.Sprintf("%s (%s)", match.Name, shortID(match.ID)))
- }
- choice, err := prompt.Select("network", options)
- if err != nil {
- return "", "", err
+var networkRef = cmdutil.ResourceRef[network.Inspect, network.Summary]{
+ Singular: "network",
+ Plural: "networks",
+ IDHint: "the network ID",
+ ListCmd: "arcane networks list",
+ GetPath: types.Network,
+ ListPath: types.Networks,
+ Matches: networkMatches,
+ Label: func(match network.Summary) string {
+ return fmt.Sprintf("%s (%s)", match.Name, shortID(match.ID))
+ },
+ Promote: func(match network.Summary) *network.Inspect {
+ return &network.Inspect{
+ ID: match.ID,
+ Name: match.Name,
+ Driver: match.Driver,
+ Scope: match.Scope,
+ Created: match.Created,
+ Options: match.Options,
+ Labels: match.Labels,
}
- return matches[choice].ID, matches[choice].Name, nil
- }
-
- return "", "", errors.Errorf("network %q not found; use the network ID or run `arcane networks list`", trimmed)
+ },
}
func networkMatches(item network.Summary, identifierLower, original string) bool {
diff --git a/cli/pkg/projects/actions.go b/cli/pkg/projects/actions.go
index 1d7a827ec..92faee07c 100644
--- a/cli/pkg/projects/actions.go
+++ b/cli/pkg/projects/actions.go
@@ -1,7 +1,6 @@
package projects
import (
- "encoding/json"
"fmt"
"io"
"net/http"
@@ -13,7 +12,6 @@ import (
"emperror.dev/errors"
- "github.com/getarcaneapp/arcane/cli/v2/internal/client"
"github.com/getarcaneapp/arcane/cli/v2/internal/cmdutil"
"github.com/getarcaneapp/arcane/cli/v2/internal/output"
"github.com/getarcaneapp/arcane/cli/v2/internal/types"
@@ -39,32 +37,18 @@ var tagsCmd = &cobra.Command{
Short: "List project tags for the environment",
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
- c, err := client.NewFromConfig()
+ c, err := cmdutil.ClientFromCommand(cmd)
if err != nil {
return err
}
- resp, err := c.Get(cmd.Context(), types.ProjectsTags(c.EnvID()))
+ result, err := c.GetJSON[[]project.TagOption](cmd.Context(), types.ProjectsTags(c.EnvID()))
if err != nil {
return errors.WrapIf(err, "failed to list project tags")
}
- defer func() { _ = resp.Body.Close() }()
- if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
- return errors.WrapIf(err, "failed to list project tags")
- }
-
- var result base.ApiResponse[[]project.TagOption]
- if err := cmdutil.DecodeJSON(resp, &result); err != nil {
- return err
- }
if jsonOutput {
- resultBytes, err := json.MarshalIndent(result.Data, "", " ")
- if err != nil {
- return errors.WrapIf(err, "failed to marshal JSON")
- }
- fmt.Println(string(resultBytes))
- return nil
+ return cmdutil.PrintJSON(result.Data)
}
output.Header("Project Tags")
@@ -91,12 +75,12 @@ var tagCmd = &cobra.Command{
return errors.New("--color can only be used with --add")
}
- c, err := client.NewFromConfig()
+ c, err := cmdutil.ClientFromCommand(cmd)
if err != nil {
return err
}
- resolved, _, err := resolveProject(cmd.Context(), c, args[0], false)
+ resolved, _, err := projectRef.Resolve(cmd.Context(), c, args[0], false)
if err != nil {
return err
}
@@ -110,27 +94,13 @@ var tagCmd = &cobra.Command{
body.Name = tagRemove
}
- resp, err := c.Request(cmd.Context(), http.MethodPatch, types.ProjectTags(c.EnvID(), resolved.ID), body)
+ result, err := c.DoJSON[base.ApiResponse[project.UpdateTagResponse]](cmd.Context(), http.MethodPatch, types.ProjectTags(c.EnvID(), resolved.ID), body)
if err != nil {
return errors.WrapIf(err, "failed to update project tag")
}
- defer func() { _ = resp.Body.Close() }()
- if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
- return errors.WrapIf(err, "failed to update project tag")
- }
-
- var result base.ApiResponse[project.UpdateTagResponse]
- if err := cmdutil.DecodeJSON(resp, &result); err != nil {
- return err
- }
if jsonOutput {
- resultBytes, err := json.MarshalIndent(result.Data, "", " ")
- if err != nil {
- return errors.WrapIf(err, "failed to marshal JSON")
- }
- fmt.Println(string(resultBytes))
- return nil
+ return cmdutil.PrintJSON(result.Data)
}
names := make([]string, len(result.Data.Tags))
@@ -149,10 +119,19 @@ var archiveCmd = &cobra.Command{
Args: cobra.ExactArgs(1),
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
- return runProjectPostAction(cmd, args[0], projectPostActionConfig{
- endpoint: types.ProjectArchive,
- failureMessage: "failed to archive project",
- successMessage: "Project %s archived successfully",
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
+ resolved, _, err := projectRef.Resolve(cmd.Context(), c, args[0], false)
+ if err != nil {
+ return err
+ }
+ return cmdutil.RunPostAction[base.MessageResponse](cmd, c, cmdutil.PostActionSpec{
+ Path: types.ProjectArchive(c.EnvID(), resolved.ID),
+ FailureMessage: "failed to archive project",
+ SuccessMessage: fmt.Sprintf("Project %s archived successfully", resolved.Name),
+ JSON: jsonOutput,
})
},
}
@@ -163,10 +142,19 @@ var unarchiveCmd = &cobra.Command{
Args: cobra.ExactArgs(1),
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
- return runProjectPostAction(cmd, args[0], projectPostActionConfig{
- endpoint: types.ProjectUnarchive,
- failureMessage: "failed to unarchive project",
- successMessage: "Project %s unarchived successfully",
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
+ resolved, _, err := projectRef.Resolve(cmd.Context(), c, args[0], false)
+ if err != nil {
+ return err
+ }
+ return cmdutil.RunPostAction[base.MessageResponse](cmd, c, cmdutil.PostActionSpec{
+ Path: types.ProjectUnarchive(c.EnvID(), resolved.ID),
+ FailureMessage: "failed to unarchive project",
+ SuccessMessage: fmt.Sprintf("Project %s unarchived successfully", resolved.Name),
+ JSON: jsonOutput,
})
},
}
@@ -177,12 +165,12 @@ var buildCmd = &cobra.Command{
Args: cobra.ExactArgs(1),
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
- c, err := client.NewFromConfig()
+ c, err := cmdutil.ClientFromCommand(cmd)
if err != nil {
return err
}
- resolved, _, err := resolveProject(cmd.Context(), c, args[0], false)
+ resolved, _, err := projectRef.Resolve(cmd.Context(), c, args[0], false)
if err != nil {
return err
}
@@ -226,12 +214,12 @@ var updateServicesCmd = &cobra.Command{
Args: cobra.MinimumNArgs(1),
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
- c, err := client.NewFromConfig()
+ c, err := cmdutil.ClientFromCommand(cmd)
if err != nil {
return err
}
- resolved, _, err := resolveProject(cmd.Context(), c, args[0], false)
+ resolved, _, err := projectRef.Resolve(cmd.Context(), c, args[0], false)
if err != nil {
return err
}
@@ -242,27 +230,13 @@ var updateServicesCmd = &cobra.Command{
Services []string `json:"services,omitempty"`
}{Services: args[1:]}
- resp, err := c.Post(cmd.Context(), types.ProjectUpdateServices(c.EnvID(), resolved.ID), body)
+ result, err := c.PostJSON[base.MessageResponse](cmd.Context(), types.ProjectUpdateServices(c.EnvID(), resolved.ID), body)
if err != nil {
return errors.WrapIf(err, "failed to update project services")
}
- defer func() { _ = resp.Body.Close() }()
- if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
- return errors.WrapIf(err, "failed to update project services")
- }
-
- var result base.ApiResponse[base.MessageResponse]
- if err := cmdutil.DecodeJSON(resp, &result); err != nil {
- return err
- }
if jsonOutput {
- resultBytes, err := json.MarshalIndent(result.Data, "", " ")
- if err != nil {
- return errors.WrapIf(err, "failed to marshal JSON")
- }
- fmt.Println(string(resultBytes))
- return nil
+ return cmdutil.PrintJSON(result.Data)
}
output.Success("Services updated successfully for project %s", resolved.Name)
@@ -281,38 +255,24 @@ var workspaceCatCmd = &cobra.Command{
Args: cobra.ExactArgs(2),
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
- c, err := client.NewFromConfig()
+ c, err := cmdutil.ClientFromCommand(cmd)
if err != nil {
return err
}
- resolved, _, err := resolveProject(cmd.Context(), c, args[0], false)
+ resolved, _, err := projectRef.Resolve(cmd.Context(), c, args[0], false)
if err != nil {
return err
}
reqPath := types.ProjectWorkspaceFile(c.EnvID(), resolved.ID) + "?relativePath=" + url.QueryEscape(args[1])
- resp, err := c.Get(cmd.Context(), reqPath)
+ result, err := c.GetJSON[workspacetypes.FileContent](cmd.Context(), reqPath)
if err != nil {
return errors.WrapIf(err, "failed to get workspace file")
}
- defer func() { _ = resp.Body.Close() }()
- if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
- return errors.WrapIf(err, "failed to get workspace file")
- }
-
- var result base.ApiResponse[workspacetypes.FileContent]
- if err := cmdutil.DecodeJSON(resp, &result); err != nil {
- return err
- }
if jsonOutput {
- resultBytes, err := json.MarshalIndent(result.Data, "", " ")
- if err != nil {
- return errors.WrapIf(err, "failed to marshal JSON")
- }
- fmt.Println(string(resultBytes))
- return nil
+ return cmdutil.PrintJSON(result.Data)
}
if result.Data.Content == "" && result.Data.ReadOnlyReason != "" {
@@ -329,12 +289,12 @@ var workspaceDownloadCmd = &cobra.Command{
Args: cobra.RangeArgs(2, 3),
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
- c, err := client.NewFromConfig()
+ c, err := cmdutil.ClientFromCommand(cmd)
if err != nil {
return err
}
- resolved, _, err := resolveProject(cmd.Context(), c, args[0], false)
+ resolved, _, err := projectRef.Resolve(cmd.Context(), c, args[0], false)
if err != nil {
return err
}
diff --git a/cli/pkg/projects/cmd.go b/cli/pkg/projects/cmd.go
index ee3da97ac..1653eadbb 100644
--- a/cli/pkg/projects/cmd.go
+++ b/cli/pkg/projects/cmd.go
@@ -3,8 +3,7 @@ package projects
import (
"bufio"
"bytes"
- "context"
- "encoding/json"
+ "encoding/json/v2"
"fmt"
"io"
"mime/multipart"
@@ -50,8 +49,6 @@ var (
includesFile string
)
-const maxPromptOptions = 20
-
// ProjectsCmd is the parent command for project operations
var ProjectsCmd = &cobra.Command{
Use: "projects",
@@ -84,46 +81,57 @@ func runProjectsList(cmd *cobra.Command, forceHasUpdateFilter bool) error {
return err
}
- path, err := buildProjectsListPath(cmd, c, forceHasUpdateFilter)
- if err != nil {
- return err
- }
- resp, err := c.Get(cmd.Context(), path)
- if err != nil {
- return errors.WrapIf(err, "failed to list projects")
+ query := url.Values{}
+ updatesFilter := strings.TrimSpace(projectsUpdatesFilter)
+ if forceHasUpdateFilter {
+ updatesFilter = "has_update"
}
- defer func() { _ = resp.Body.Close() }()
-
- body, err := cmdutil.ReadJSONBody(resp)
- if err != nil {
- return errors.WrapIf(err, "failed to list projects")
+ if updatesFilter != "" {
+ query.Set("updates", updatesFilter)
}
-
- if jsonOutput {
- return cmdutil.PrintRawJSON(body)
+ if projectsStatusFilter != "" {
+ query.Set("status", projectsStatusFilter)
}
-
- var result base.Paginated[project.Details]
- if err := json.Unmarshal(body, &result); err != nil {
- return errors.WrapIf(err, "failed to parse response")
+ // The server excludes archived projects unless asked, so --all has to opt
+ // into them explicitly to actually mean "everything".
+ switch {
+ case projectsArchivedFilter != "":
+ query.Set("archived", projectsArchivedFilter)
+ case allFlag:
+ query.Set("archived", "all")
}
- effectiveUpdatesFilter := strings.TrimSpace(projectsUpdatesFilter)
- if forceHasUpdateFilter {
- effectiveUpdatesFilter = "has_update"
+ spec := cmdutil.ListSpec[project.Details]{
+ Resource: "projects",
+ Endpoint: types.Projects(c.EnvID()),
+ Params: cmdutil.ListParams{Resource: "projects", Limit: limitFlag, FallbackDefault: 20, Start: startFlag, All: allFlag},
+ Query: query,
+ JSON: jsonOutput,
+ Headers: []string{"ID", "NAME", "STATUS", "SERVICES", "RUNNING", "CREATED"},
+ Row: func(proj project.Details) []string {
+ return []string{
+ proj.ID,
+ proj.Name,
+ proj.Status,
+ strconv.Itoa(proj.ServiceCount),
+ strconv.Itoa(proj.RunningCount),
+ proj.CreatedAt,
+ }
+ },
}
- if effectiveUpdatesFilter != "" {
- output.Header("Project Updates")
- headers := []string{"ID", "NAME", "STATUS", "UPDATES", "IMAGES", "UPDATED"}
- rows := make([][]string, len(result.Data))
- for i, proj := range result.Data {
+ if updatesFilter != "" {
+ if !jsonOutput {
+ output.Header("Project Updates")
+ }
+ spec.Headers = []string{"ID", "NAME", "STATUS", "UPDATES", "IMAGES", "UPDATED"}
+ spec.Row = func(proj project.Details) []string {
imageCount := 0
updatedCount := 0
if proj.UpdateInfo != nil {
imageCount = proj.UpdateInfo.ImageCount
updatedCount = proj.UpdateInfo.ImagesWithUpdates
}
- rows[i] = []string{
+ return []string{
proj.ID,
proj.Name,
proj.Status,
@@ -132,68 +140,8 @@ func runProjectsList(cmd *cobra.Command, forceHasUpdateFilter bool) error {
strconv.Itoa(updatedCount),
}
}
- output.Table(headers, rows)
- output.Showing(len(result.Data), result.Pagination.TotalItems, "projects")
- return nil
- }
-
- headers := []string{"ID", "NAME", "STATUS", "SERVICES", "RUNNING", "CREATED"}
- rows := make([][]string, len(result.Data))
- for i, proj := range result.Data {
- rows[i] = []string{
- proj.ID,
- proj.Name,
- proj.Status,
- strconv.Itoa(proj.ServiceCount),
- strconv.Itoa(proj.RunningCount),
- proj.CreatedAt,
- }
}
-
- output.Table(headers, rows)
- output.Showing(len(result.Data), result.Pagination.TotalItems, "projects")
- return nil
-}
-
-func buildProjectsListPath(cmd *cobra.Command, c *client.Client, forceHasUpdateFilter bool) (string, error) {
- path, err := cmdutil.ApplyPaginationParams(cmd, types.Projects(c.EnvID()), cmdutil.ListParams{
- Resource: "projects",
- Limit: limitFlag,
- FallbackDefault: 20,
- Start: startFlag,
- All: allFlag,
- })
- if err != nil {
- return "", errors.WrapIf(err, "failed to build pagination query")
- }
-
- parsed, err := url.Parse(path)
- if err != nil {
- return "", errors.WrapIf(err, "failed to parse path")
- }
-
- query := parsed.Query()
- updatesFilter := strings.TrimSpace(projectsUpdatesFilter)
- if forceHasUpdateFilter {
- updatesFilter = "has_update"
- }
- if updatesFilter != "" {
- query.Set("updates", updatesFilter)
- }
- if projectsStatusFilter != "" {
- query.Set("status", projectsStatusFilter)
- }
- // The server excludes archived projects unless asked, so --all has to opt
- // into them explicitly to actually mean "everything".
- switch {
- case projectsArchivedFilter != "":
- query.Set("archived", projectsArchivedFilter)
- case allFlag:
- query.Set("archived", "all")
- }
-
- parsed.RawQuery = query.Encode()
- return parsed.String(), nil
+ return cmdutil.RunList(cmd, c, spec)
}
func projectUpdateStatus(item project.Details) string {
@@ -215,7 +163,7 @@ var destroyCmd = &cobra.Command{
return err
}
- resolved, _, err := resolveProject(cmd.Context(), c, args[0], false)
+ resolved, _, err := projectRef.Resolve(cmd.Context(), c, args[0], false)
if err != nil {
return err
}
@@ -264,32 +212,21 @@ var getCmd = &cobra.Command{
}
allowPrompt := !jsonOutput && prompt.IsInteractive()
- resolved, complete, err := resolveProject(cmd.Context(), c, args[0], allowPrompt)
+ resolved, complete, err := projectRef.Resolve(cmd.Context(), c, args[0], allowPrompt)
if err != nil {
return err
}
if !complete {
- resp, err := c.Get(cmd.Context(), types.Project(c.EnvID(), resolved.ID))
+ result, err := c.GetJSON[project.Details](cmd.Context(), types.Project(c.EnvID(), resolved.ID))
if err != nil {
return errors.WrapIf(err, "failed to get project")
}
- defer func() { _ = resp.Body.Close() }()
-
- var result base.ApiResponse[project.Details]
- if err := cmdutil.DecodeJSON(resp, &result); err != nil {
- return err
- }
resolved = &result.Data
}
if jsonOutput {
- resultBytes, err := json.MarshalIndent(resolved, "", " ")
- if err != nil {
- return errors.WrapIf(err, "failed to marshal JSON")
- }
- fmt.Println(string(resultBytes))
- return nil
+ return cmdutil.PrintJSON(resolved)
}
output.Header("Project Details")
@@ -308,12 +245,10 @@ var upCmd = &cobra.Command{
Args: cobra.ExactArgs(1),
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
- return runProjectPostAction(cmd, args[0], projectPostActionConfig{
+ return runProjectStreamAction(cmd, args[0], projectStreamActionConfig{
endpoint: types.ProjectUp,
failureMessage: "failed to start project",
successMessage: "Project %s started successfully",
- timeout: 30 * time.Minute,
- stream: true,
})
},
}
@@ -324,10 +259,20 @@ var downCmd = &cobra.Command{
Args: cobra.ExactArgs(1),
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
- return runProjectPostAction(cmd, args[0], projectPostActionConfig{
- endpoint: types.ProjectDown,
- failureMessage: "failed to stop project",
- successMessage: "Project %s stopped successfully",
+ c, err := client.NewFromConfig()
+ if err != nil {
+ return err
+ }
+
+ resolved, _, err := projectRef.Resolve(cmd.Context(), c, args[0], false)
+ if err != nil {
+ return err
+ }
+
+ return cmdutil.RunPostAction[base.MessageResponse](cmd, c, cmdutil.PostActionSpec{
+ Path: types.ProjectDown(c.EnvID(), resolved.ID),
+ FailureMessage: "failed to stop project",
+ SuccessMessage: fmt.Sprintf("Project %s stopped successfully", resolved.Name),
})
},
}
@@ -338,10 +283,20 @@ var restartCmd = &cobra.Command{
Args: cobra.ExactArgs(1),
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
- return runProjectPostAction(cmd, args[0], projectPostActionConfig{
- endpoint: types.ProjectRestart,
- failureMessage: "failed to restart project",
- successMessage: "Project %s restarted successfully",
+ c, err := client.NewFromConfig()
+ if err != nil {
+ return err
+ }
+
+ resolved, _, err := projectRef.Resolve(cmd.Context(), c, args[0], false)
+ if err != nil {
+ return err
+ }
+
+ return cmdutil.RunPostAction[base.MessageResponse](cmd, c, cmdutil.PostActionSpec{
+ Path: types.ProjectRestart(c.EnvID(), resolved.ID),
+ FailureMessage: "failed to restart project",
+ SuccessMessage: fmt.Sprintf("Project %s restarted successfully", resolved.Name),
})
},
}
@@ -352,12 +307,10 @@ var redeployCmd = &cobra.Command{
Args: cobra.ExactArgs(1),
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
- return runProjectPostAction(cmd, args[0], projectPostActionConfig{
+ return runProjectStreamAction(cmd, args[0], projectStreamActionConfig{
endpoint: types.ProjectRedeploy,
failureMessage: "failed to redeploy project",
successMessage: "Project %s redeployed successfully",
- timeout: 30 * time.Minute,
- stream: true,
})
},
}
@@ -368,41 +321,36 @@ var pullCmd = &cobra.Command{
Args: cobra.ExactArgs(1),
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
- return runProjectPostAction(cmd, args[0], projectPostActionConfig{
+ return runProjectStreamAction(cmd, args[0], projectStreamActionConfig{
endpoint: types.ProjectPull,
failureMessage: "failed to pull images",
successMessage: "Images pulled successfully for project %s",
- timeout: 30 * time.Minute,
- stream: true,
})
},
}
-type projectPostActionConfig struct {
+// projectStreamActionConfig describes a project action whose endpoint responds
+// with an NDJSON operation stream: {"log":"<raw docker CLI line>"} frames are
+// printed as-is and a terminal {"error":"..."} frame fails the command.
+type projectStreamActionConfig struct {
endpoint func(string, string) string
failureMessage string
successMessage string
- timeout time.Duration
- // stream marks endpoints that respond with an NDJSON operation stream:
- // {"log":"<raw docker CLI line>"} frames are printed as-is and a terminal
- // {"error":"..."} frame fails the command.
- stream bool
}
-func runProjectPostAction(cmd *cobra.Command, projectRef string, cfg projectPostActionConfig) error {
+func runProjectStreamAction(cmd *cobra.Command, identifier string, cfg projectStreamActionConfig) error {
c, err := client.NewFromConfig()
if err != nil {
return err
}
- resolved, _, err := resolveProject(cmd.Context(), c, projectRef, false)
+ resolved, _, err := projectRef.Resolve(cmd.Context(), c, identifier, false)
if err != nil {
return err
}
- if cfg.timeout > 0 {
- c.SetTimeout(cfg.timeout)
- }
+ // Streamed actions can take a long time as they may pull images.
+ c.SetTimeout(30 * time.Minute)
resp, err := c.Post(cmd.Context(), cfg.endpoint(c.EnvID(), resolved.ID), nil)
if err != nil {
@@ -413,10 +361,8 @@ func runProjectPostAction(cmd *cobra.Command, projectRef string, cfg projectPost
return errors.WrapIff(err, "%s", cfg.failureMessage)
}
- if cfg.stream {
- if err := printOperationStreamInternal(resp.Body); err != nil {
- return errors.WrapIff(err, "%s", cfg.failureMessage)
- }
+ if err := printOperationStreamInternal(resp.Body); err != nil {
+ return errors.WrapIff(err, "%s", cfg.failureMessage)
}
output.Success(cfg.successMessage, resolved.Name)
@@ -524,12 +470,7 @@ var createCmd = &cobra.Command{
}
if jsonOutput {
- resultBytes, err := json.MarshalIndent(result.Data, "", " ")
- if err != nil {
- return errors.WrapIf(err, "failed to marshal JSON")
- }
- fmt.Println(string(resultBytes))
- return nil
+ return cmdutil.PrintJSON(result.Data)
}
output.Success("Project %s created successfully", result.Data.Name)
@@ -553,7 +494,7 @@ var updateCmd = &cobra.Command{
return err
}
- resolved, _, err := resolveProject(cmd.Context(), c, args[0], false)
+ resolved, _, err := projectRef.Resolve(cmd.Context(), c, args[0], false)
if err != nil {
return err
}
@@ -580,26 +521,13 @@ var updateCmd = &cobra.Command{
body.EnvContent = new(string(envBytes))
}
- resp, err := c.Put(cmd.Context(), types.Project(c.EnvID(), resolved.ID), body)
+ result, err := c.PutJSON[project.Details](cmd.Context(), types.Project(c.EnvID(), resolved.ID), body)
if err != nil {
return errors.WrapIf(err, "failed to update project")
}
- defer func() { _ = resp.Body.Close() }()
- if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
- return errors.WrapIf(err, "failed to update project")
- }
if jsonOutput {
- var result base.ApiResponse[project.Details]
- if err := cmdutil.DecodeJSON(resp, &result); err != nil {
- return err
- }
- resultBytes, err := json.MarshalIndent(result.Data, "", " ")
- if err != nil {
- return errors.WrapIf(err, "failed to marshal JSON")
- }
- fmt.Println(string(resultBytes))
- return nil
+ return cmdutil.PrintJSON(result.Data)
}
output.Success("Project %s updated successfully", resolved.Name)
@@ -619,7 +547,7 @@ var updateIncludesCmd = &cobra.Command{
return err
}
- resolved, _, err := resolveProject(cmd.Context(), c, args[0], false)
+ resolved, _, err := projectRef.Resolve(cmd.Context(), c, args[0], false)
if err != nil {
return err
}
@@ -629,18 +557,10 @@ var updateIncludesCmd = &cobra.Command{
return errors.WrapIf(err, "failed to read include file")
}
- workspaceResponse, err := c.Get(cmd.Context(), types.ProjectWorkspace(c.EnvID(), resolved.ID))
+ current, err := c.GetJSON[workspacetypes.Workspace](cmd.Context(), types.ProjectWorkspace(c.EnvID(), resolved.ID))
if err != nil {
return errors.WrapIf(err, "failed to get project workspace")
}
- defer func() { _ = workspaceResponse.Body.Close() }()
- if err := cmdutil.EnsureSuccessStatus(workspaceResponse); err != nil {
- return errors.WrapIf(err, "failed to get project workspace")
- }
- var current base.ApiResponse[workspacetypes.Workspace]
- if err := cmdutil.DecodeJSON(workspaceResponse, &current); err != nil {
- return err
- }
relativePath := filepath.ToSlash(filepath.Base(includesFile))
operation := project.FileOpCreateFile
@@ -689,12 +609,7 @@ var updateIncludesCmd = &cobra.Command{
if err := cmdutil.DecodeJSON(resp, &result); err != nil {
return err
}
- resultBytes, err := json.MarshalIndent(result.Data, "", " ")
- if err != nil {
- return errors.WrapIf(err, "failed to marshal JSON")
- }
- fmt.Println(string(resultBytes))
- return nil
+ return cmdutil.PrintJSON(result.Data)
}
output.Success("Include file %s updated successfully for project %s", filepath.Base(includesFile), resolved.Name)
@@ -712,24 +627,13 @@ var countsCmd = &cobra.Command{
return err
}
- resp, err := c.Get(cmd.Context(), types.ProjectsCounts(c.EnvID()))
+ result, err := c.GetJSON[map[string]any](cmd.Context(), types.ProjectsCounts(c.EnvID()))
if err != nil {
return errors.WrapIf(err, "failed to get project counts")
}
- defer func() { _ = resp.Body.Close() }()
-
- var result base.ApiResponse[map[string]any]
- if err := cmdutil.DecodeJSON(resp, &result); err != nil {
- return err
- }
if jsonOutput {
- resultBytes, err := json.MarshalIndent(result.Data, "", " ")
- if err != nil {
- return errors.WrapIf(err, "failed to marshal JSON")
- }
- fmt.Println(string(resultBytes))
- return nil
+ return cmdutil.PrintJSON(result.Data)
}
output.Header("Project Counts")
@@ -800,89 +704,18 @@ func init() {
_ = updateIncludesCmd.MarkFlagRequired("file")
}
-func resolveProject(ctx context.Context, c *client.Client, identifier string, allowPrompt bool) (*project.Details, bool, error) {
- trimmed := strings.TrimSpace(identifier)
- if trimmed == "" {
- return nil, false, errors.New("project identifier is required")
- }
-
- resp, err := c.Get(ctx, types.Project(c.EnvID(), trimmed))
- if err != nil {
- return nil, false, errors.WrapIff(err, "failed to resolve project %q", trimmed)
- }
-
- bodyBytes, err := io.ReadAll(resp.Body)
- _ = resp.Body.Close()
- if err != nil {
- return nil, false, errors.WrapIf(err, "failed to read project response")
- }
-
- if resp.StatusCode == http.StatusOK {
- var result base.ApiResponse[project.Details]
- if err := json.Unmarshal(bodyBytes, &result); err != nil {
- return nil, false, errors.WrapIf(err, "failed to parse project response")
- }
- return &result.Data, true, nil
- }
-
- if resp.StatusCode != http.StatusNotFound {
- return nil, false, errors.Errorf("failed to resolve project %q (status %d): %s", trimmed, resp.StatusCode, strings.TrimSpace(string(bodyBytes)))
- }
-
- identifierLower := strings.ToLower(trimmed)
-
- searchPath := fmt.Sprintf("%s?search=%s&limit=%d", types.Projects(c.EnvID()), url.QueryEscape(trimmed), cmdutil.ShowAllLimit)
- searchResp, err := c.Get(ctx, searchPath)
- if err != nil {
- return nil, false, errors.WrapIf(err, "failed to search projects")
- }
-
- searchBody, err := io.ReadAll(searchResp.Body)
- _ = searchResp.Body.Close()
- if err != nil {
- return nil, false, errors.WrapIf(err, "failed to read projects response")
- }
-
- if searchResp.StatusCode < 200 || searchResp.StatusCode >= 300 {
- return nil, false, errors.Errorf("failed to search projects (status %d): %s", searchResp.StatusCode, strings.TrimSpace(string(searchBody)))
- }
-
- var result base.Paginated[project.Details]
- if err := json.Unmarshal(searchBody, &result); err != nil {
- return nil, false, errors.WrapIf(err, "failed to parse projects response")
- }
-
- matches := make([]project.Details, 0)
- for _, proj := range result.Data {
- if projectMatches(proj, identifierLower, trimmed) {
- matches = append(matches, proj)
- }
- }
-
- if len(matches) == 1 {
- return &matches[0], false, nil
- }
-
- if len(matches) > 1 {
- if !allowPrompt {
- return nil, false, errors.Errorf("multiple projects match %q; use the project ID or run `arcane projects list`", trimmed)
- }
- if len(matches) > maxPromptOptions {
- return nil, false, errors.Errorf("multiple projects match %q (%d results); refine your query or use the project ID", trimmed, len(matches))
- }
-
- options := make([]string, 0, len(matches))
- for _, match := range matches {
- options = append(options, fmt.Sprintf("%s (%s, %s)", match.Name, match.ID, match.Status))
- }
- choice, err := prompt.Select("project", options)
- if err != nil {
- return nil, false, err
- }
- return &matches[choice], false, nil
- }
-
- return nil, false, errors.Errorf("project %q not found; use the project ID or run `arcane projects list`", trimmed)
+var projectRef = cmdutil.ResourceRef[project.Details, project.Details]{
+ Singular: "project",
+ Plural: "projects",
+ IDHint: "the project ID",
+ ListCmd: "arcane projects list",
+ GetPath: types.Project,
+ ListPath: types.Projects,
+ Matches: projectMatches,
+ Label: func(match project.Details) string {
+ return fmt.Sprintf("%s (%s, %s)", match.Name, match.ID, match.Status)
+ },
+ Promote: func(match project.Details) *project.Details { return &match },
}
func projectMatches(item project.Details, identifierLower, original string) bool {
diff --git a/cli/pkg/registries/cmd.go b/cli/pkg/registries/cmd.go
index a83638dd0..c83943e2f 100644
--- a/cli/pkg/registries/cmd.go
+++ b/cli/pkg/registries/cmd.go
@@ -1,7 +1,6 @@
package registries
import (
- "encoding/json"
"fmt"
"strconv"
@@ -58,55 +57,36 @@ var listCmd = &cobra.Command{
return err
}
- path := types.ContainerRegistries()
- path, err = cmdutil.ApplyPaginationParams(cmd, path, cmdutil.ListParams{Resource: "registries", Limit: limitFlag, FallbackDefault: 20, Start: startFlag, All: allFlag})
- if err != nil {
- return errors.WrapIf(err, "failed to build pagination query")
- }
-
- resp, err := c.Get(cmd.Context(), path)
- if err != nil {
- return errors.WrapIf(err, "failed to list registries")
- }
- defer func() { _ = resp.Body.Close() }()
-
- var result base.Paginated[containerregistry.ContainerRegistry]
- if err := cmdutil.DecodeJSON(resp, &result); err != nil {
- return err
- }
-
- if jsonOutput {
- resultBytes, err := json.MarshalIndent(result, "", " ")
- if err != nil {
- return errors.WrapIf(err, "failed to marshal JSON")
- }
- fmt.Println(string(resultBytes))
- return nil
- }
-
- headers := []string{"ID", "URL", "USERNAME", "ENABLED", "INSECURE"}
- rows := make([][]string, len(result.Data))
- for i, reg := range result.Data {
- enabled := "false"
- if reg.Enabled {
- enabled = "true"
- }
- insecure := "false"
- if reg.Insecure {
- insecure = "true"
- }
- rows[i] = []string{
- reg.ID,
- reg.URL,
- reg.Username,
- enabled,
- insecure,
- }
- }
-
- output.Table(headers, rows)
- output.Showing(len(result.Data), result.Pagination.TotalItems, "registries")
- return nil
+ return cmdutil.RunList(cmd, c, cmdutil.ListSpec[containerregistry.ContainerRegistry]{
+ Resource: "registries",
+ Endpoint: types.ContainerRegistries(),
+ Params: cmdutil.ListParams{
+ Resource: "registries",
+ Limit: limitFlag,
+ FallbackDefault: 20,
+ Start: startFlag,
+ All: allFlag,
+ },
+ JSON: jsonOutput,
+ Headers: []string{"ID", "URL", "USERNAME", "ENABLED", "INSECURE"},
+ Row: func(reg containerregistry.ContainerRegistry) []string {
+ enabled := "false"
+ if reg.Enabled {
+ enabled = "true"
+ }
+ insecure := "false"
+ if reg.Insecure {
+ insecure = "true"
+ }
+ return []string{
+ reg.ID,
+ reg.URL,
+ reg.Username,
+ enabled,
+ insecure,
+ }
+ },
+ })
},
}
@@ -121,27 +101,12 @@ var testCmd = &cobra.Command{
return err
}
- resp, err := c.Post(cmd.Context(), types.ContainerRegistryTest(args[0]), nil)
- if err != nil {
- return errors.WrapIf(err, "failed to test registry")
- }
- defer func() { _ = resp.Body.Close() }()
- if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
- return errors.WrapIf(err, "failed to test registry")
- }
-
- if jsonOutput {
- var result base.ApiResponse[any]
- if err := json.NewDecoder(resp.Body).Decode(&result); err == nil {
- if resultBytes, err := json.MarshalIndent(result.Data, "", " "); err == nil {
- fmt.Println(string(resultBytes))
- }
- }
- return nil
- }
-
- output.Success("Registry connection test successful")
- return nil
+ return cmdutil.RunPostAction[base.MessageResponse](cmd, c, cmdutil.PostActionSpec{
+ Path: types.ContainerRegistryTest(args[0]),
+ FailureMessage: "failed to test registry",
+ SuccessMessage: "Registry connection test successful",
+ JSON: jsonOutput,
+ })
},
}
@@ -156,24 +121,13 @@ var getCmd = &cobra.Command{
return err
}
- resp, err := c.Get(cmd.Context(), types.ContainerRegistry(args[0]))
+ result, err := c.GetJSON[containerregistry.ContainerRegistry](cmd.Context(), types.ContainerRegistry(args[0]))
if err != nil {
return errors.WrapIf(err, "failed to get registry")
}
- defer func() { _ = resp.Body.Close() }()
-
- var result base.ApiResponse[containerregistry.ContainerRegistry]
- if err := cmdutil.DecodeJSON(resp, &result); err != nil {
- return err
- }
if jsonOutput {
- resultBytes, err := json.MarshalIndent(result.Data, "", " ")
- if err != nil {
- return errors.WrapIf(err, "failed to marshal JSON")
- }
- fmt.Println(string(resultBytes))
- return nil
+ return cmdutil.PrintJSON(result.Data)
}
output.Header("Registry Details")
@@ -215,27 +169,13 @@ var createCmd = &cobra.Command{
"awsRegion": registryCreateAWSRegion,
}
- resp, err := c.Post(cmd.Context(), types.ContainerRegistries(), req)
+ result, err := c.PostJSON[containerregistry.ContainerRegistry](cmd.Context(), types.ContainerRegistries(), req)
if err != nil {
return errors.WrapIf(err, "failed to create registry")
}
- defer func() { _ = resp.Body.Close() }()
- if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
- return errors.WrapIf(err, "failed to create registry")
- }
-
- var result base.ApiResponse[containerregistry.ContainerRegistry]
- if err := cmdutil.DecodeJSON(resp, &result); err != nil {
- return err
- }
if jsonOutput {
- resultBytes, err := json.MarshalIndent(result.Data, "", " ")
- if err != nil {
- return errors.WrapIf(err, "failed to marshal JSON")
- }
- fmt.Println(string(resultBytes))
- return nil
+ return cmdutil.PrintJSON(result.Data)
}
output.Success("Registry created successfully")
@@ -306,23 +246,13 @@ var updateCmd = &cobra.Command{
return errors.New("no updates provided; use --url, --username, --password, --enabled, or --disabled")
}
- resp, err := c.Put(cmd.Context(), types.ContainerRegistry(args[0]), req)
+ result, err := c.PutJSON[containerregistry.ContainerRegistry](cmd.Context(), types.ContainerRegistry(args[0]), req)
if err != nil {
return errors.WrapIf(err, "failed to update registry")
}
- defer func() { _ = resp.Body.Close() }()
- if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
- return errors.WrapIf(err, "failed to update registry")
- }
if jsonOutput {
- var result base.ApiResponse[any]
- if err := json.NewDecoder(resp.Body).Decode(&result); err == nil {
- if resultBytes, err := json.MarshalIndent(result.Data, "", " "); err == nil {
- fmt.Println(string(resultBytes))
- }
- }
- return nil
+ return cmdutil.PrintJSON(result.Data)
}
output.Success("Registry updated successfully")
@@ -378,24 +308,13 @@ var usageCmd = &cobra.Command{
return err
}
- resp, err := c.Get(cmd.Context(), types.ContainerRegistriesPullUsage())
+ result, err := c.GetJSON[containerregistry.PullUsageResponse](cmd.Context(), types.ContainerRegistriesPullUsage())
if err != nil {
return errors.WrapIf(err, "failed to get registry pull usage")
}
- defer func() { _ = resp.Body.Close() }()
-
- var result base.ApiResponse[containerregistry.PullUsageResponse]
- if err := cmdutil.DecodeJSON(resp, &result); err != nil {
- return err
- }
if jsonOutput {
- resultBytes, err := json.MarshalIndent(result.Data, "", " ")
- if err != nil {
- return errors.WrapIf(err, "failed to marshal JSON")
- }
- fmt.Println(string(resultBytes))
- return nil
+ return cmdutil.PrintJSON(result.Data)
}
if len(result.Data.Registries) == 0 {
diff --git a/cli/pkg/repos/cmd.go b/cli/pkg/repos/cmd.go
index f036cf8a4..325438988 100644
--- a/cli/pkg/repos/cmd.go
+++ b/cli/pkg/repos/cmd.go
@@ -1,11 +1,7 @@
package repos
import (
- "context"
- "encoding/json"
"fmt"
- "io"
- "net/http"
"net/url"
"os"
"strconv"
@@ -31,8 +27,6 @@ var (
jsonOutput bool
)
-const maxPromptOptions = 20
-
// ReposCmd is the parent command for git repository operations.
var ReposCmd = &cobra.Command{
Use: "repos",
@@ -83,52 +77,27 @@ var listCmd = &cobra.Command{
return err
}
- path := types.GitRepositories()
- path, err = cmdutil.ApplyPaginationParams(cmd, path, cmdutil.ListParams{Resource: "repos", Limit: limitFlag, FallbackDefault: 20, Start: startFlag, All: allFlag})
- if err != nil {
- return errors.WrapIf(err, "failed to build pagination query")
- }
-
- resp, err := c.Get(cmd.Context(), path)
- if err != nil {
- return errors.WrapIf(err, "failed to list repositories")
- }
- defer func() { _ = resp.Body.Close() }()
-
- var result base.Paginated[gitops.GitRepository]
- if err := cmdutil.DecodeJSON(resp, &result); err != nil {
- return err
- }
-
- if jsonOutput {
- resultBytes, err := json.MarshalIndent(result, "", " ")
- if err != nil {
- return errors.WrapIf(err, "failed to marshal JSON")
- }
- fmt.Println(string(resultBytes))
- return nil
- }
-
- headers := []string{"ID", "NAME", "URL", "AUTH TYPE", "ENABLED", "CREATED"}
- rows := make([][]string, len(result.Data))
- for i, repo := range result.Data {
- enabled := "false"
- if repo.Enabled {
- enabled = "true"
- }
- rows[i] = []string{
- repo.ID,
- repo.Name,
- repo.URL,
- repo.AuthType,
- enabled,
- repo.CreatedAt.Format("2006-01-02 15:04:05"),
- }
- }
-
- output.Table(headers, rows)
- output.Showing(len(result.Data), result.Pagination.TotalItems, "repositories")
- return nil
+ return cmdutil.RunList(cmd, c, cmdutil.ListSpec[gitops.GitRepository]{
+ Resource: "repositories",
+ Endpoint: types.GitRepositories(),
+ Params: cmdutil.ListParams{Resource: "repos", Limit: limitFlag, FallbackDefault: 20, Start: startFlag, All: allFlag},
+ JSON: jsonOutput,
+ Headers: []string{"ID", "NAME", "URL", "AUTH TYPE", "ENABLED", "CREATED"},
+ Row: func(repo gitops.GitRepository) []string {
+ enabled := "false"
+ if repo.Enabled {
+ enabled = "true"
+ }
+ return []string{
+ repo.ID,
+ repo.Name,
+ repo.URL,
+ repo.AuthType,
+ enabled,
+ repo.CreatedAt.Format("2006-01-02 15:04:05"),
+ }
+ },
+ })
},
}
@@ -171,27 +140,13 @@ var createCmd = &cobra.Command{
req.Enabled = &repoCreateEnabled
}
- resp, err := c.Post(cmd.Context(), types.GitRepositories(), req)
+ result, err := c.PostJSON[gitops.GitRepository](cmd.Context(), types.GitRepositories(), req)
if err != nil {
return errors.WrapIf(err, "failed to create repository")
}
- defer func() { _ = resp.Body.Close() }()
- if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
- return errors.WrapIf(err, "failed to create repository")
- }
-
- var result base.ApiResponse[gitops.GitRepository]
- if err := cmdutil.DecodeJSON(resp, &result); err != nil {
- return err
- }
if jsonOutput {
- resultBytes, err := json.MarshalIndent(result.Data, "", " ")
- if err != nil {
- return errors.WrapIf(err, "failed to marshal JSON")
- }
- fmt.Println(string(resultBytes))
- return nil
+ return cmdutil.PrintJSON(result.Data)
}
output.Success("Repository created successfully")
@@ -215,18 +170,13 @@ var getCmd = &cobra.Command{
return err
}
- resolved, err := resolveGitRepository(cmd.Context(), c, args[0])
+ resolved, _, err := repoRef.Resolve(cmd.Context(), c, args[0], prompt.IsInteractive())
if err != nil {
return err
}
if jsonOutput {
- resultBytes, err := json.MarshalIndent(resolved, "", " ")
- if err != nil {
- return errors.WrapIf(err, "failed to marshal JSON")
- }
- fmt.Println(string(resultBytes))
- return nil
+ return cmdutil.PrintJSON(resolved)
}
output.Header("Repository Details")
@@ -261,7 +211,7 @@ var updateCmd = &cobra.Command{
return err
}
- resolved, err := resolveGitRepository(cmd.Context(), c, args[0])
+ resolved, _, err := repoRef.Resolve(cmd.Context(), c, args[0], prompt.IsInteractive())
if err != nil {
return err
}
@@ -300,31 +250,13 @@ var updateCmd = &cobra.Command{
req.Enabled = &repoUpdateEnabled
}
- resp, err := c.Put(cmd.Context(), types.GitRepository(resolved.ID), req)
+ result, err := c.PutJSON[gitops.GitRepository](cmd.Context(), types.GitRepository(resolved.ID), req)
if err != nil {
return errors.WrapIf(err, "failed to update repository")
}
- defer func() { _ = resp.Body.Close() }()
- if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
- return errors.WrapIf(err, "failed to update repository")
- }
-
- var result base.ApiResponse[gitops.GitRepository]
- if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
- if jsonOutput {
- return errors.WrapIf(err, "failed to parse response")
- }
- output.Success("Repository updated successfully")
- return nil
- }
if jsonOutput {
- resultBytes, err := json.MarshalIndent(result.Data, "", " ")
- if err != nil {
- return errors.WrapIf(err, "failed to marshal JSON")
- }
- fmt.Println(string(resultBytes))
- return nil
+ return cmdutil.PrintJSON(result.Data)
}
output.Success("Repository updated successfully")
@@ -349,7 +281,7 @@ var deleteCmd = &cobra.Command{
return err
}
- resolved, err := resolveGitRepository(cmd.Context(), c, args[0])
+ resolved, _, err := repoRef.Resolve(cmd.Context(), c, args[0], prompt.IsInteractive())
if err != nil {
return err
}
@@ -390,32 +322,17 @@ var testCmd = &cobra.Command{
return err
}
- resolved, err := resolveGitRepository(cmd.Context(), c, args[0])
+ resolved, _, err := repoRef.Resolve(cmd.Context(), c, args[0], prompt.IsInteractive())
if err != nil {
return err
}
- resp, err := c.Post(cmd.Context(), types.GitRepositoryTest(resolved.ID), nil)
- if err != nil {
- return errors.WrapIf(err, "failed to test repository")
- }
- defer func() { _ = resp.Body.Close() }()
- if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
- return errors.WrapIf(err, "repository connection test failed")
- }
-
- if jsonOutput {
- var result base.ApiResponse[any]
- if err := json.NewDecoder(resp.Body).Decode(&result); err == nil {
- if resultBytes, err := json.MarshalIndent(result.Data, "", " "); err == nil {
- fmt.Println(string(resultBytes))
- }
- }
- return nil
- }
-
- output.Success("Repository connection test successful")
- return nil
+ return cmdutil.RunPostAction[base.MessageResponse](cmd, c, cmdutil.PostActionSpec{
+ Path: types.GitRepositoryTest(resolved.ID),
+ FailureMessage: "repository connection test failed",
+ SuccessMessage: "Repository connection test successful",
+ JSON: jsonOutput,
+ })
},
}
@@ -430,29 +347,18 @@ var branchesCmd = &cobra.Command{
return err
}
- resolved, err := resolveGitRepository(cmd.Context(), c, args[0])
+ resolved, _, err := repoRef.Resolve(cmd.Context(), c, args[0], prompt.IsInteractive())
if err != nil {
return err
}
- resp, err := c.Get(cmd.Context(), types.GitRepositoryBranches(resolved.ID))
+ result, err := c.GetJSON[gitops.BranchesResponse](cmd.Context(), types.GitRepositoryBranches(resolved.ID))
if err != nil {
return errors.WrapIf(err, "failed to list branches")
}
- defer func() { _ = resp.Body.Close() }()
-
- var result base.ApiResponse[gitops.BranchesResponse]
- if err := cmdutil.DecodeJSON(resp, &result); err != nil {
- return err
- }
if jsonOutput {
- resultBytes, err := json.MarshalIndent(result.Data, "", " ")
- if err != nil {
- return errors.WrapIf(err, "failed to marshal JSON")
- }
- fmt.Println(string(resultBytes))
- return nil
+ return cmdutil.PrintJSON(result.Data)
}
headers := []string{"BRANCH", "DEFAULT"}
@@ -485,7 +391,7 @@ var filesCmd = &cobra.Command{
return err
}
- resolved, err := resolveGitRepository(cmd.Context(), c, args[0])
+ resolved, _, err := repoRef.Resolve(cmd.Context(), c, args[0], prompt.IsInteractive())
if err != nil {
return err
}
@@ -502,25 +408,14 @@ var filesCmd = &cobra.Command{
path = path + "?" + params.Encode()
}
- resp, err := c.Get(cmd.Context(), path)
+ result, err := c.GetJSON[gitops.BrowseResponse](cmd.Context(), path)
if err != nil {
return errors.WrapIf(err, "failed to list files")
}
- defer func() { _ = resp.Body.Close() }()
-
- var result base.ApiResponse[gitops.BrowseResponse]
- if err := cmdutil.DecodeJSON(resp, &result); err != nil {
- return err
- }
files := result.Data.Files
if jsonOutput {
- resultBytes, err := json.MarshalIndent(files, "", " ")
- if err != nil {
- return errors.WrapIf(err, "failed to marshal JSON")
- }
- fmt.Println(string(resultBytes))
- return nil
+ return cmdutil.PrintJSON(files)
}
headers := []string{"NAME", "TYPE", "PATH", "SIZE"}
@@ -544,73 +439,31 @@ var filesCmd = &cobra.Command{
},
}
-// resolveGitRepository attempts to resolve a repository by ID or name.
-// It first tries a direct GET by ID. If that returns 404, it falls back to
-// searching the list endpoint by name or ID prefix.
-func resolveGitRepository(ctx context.Context, c *client.Client, identifier string) (*gitops.GitRepository, error) {
- trimmed := strings.TrimSpace(identifier)
- if trimmed == "" {
- return nil, errors.New("repository identifier is required")
- }
-
- // Try direct GET by ID.
- resp, err := c.Get(ctx, types.GitRepository(trimmed))
- if err == nil {
- defer func() { _ = resp.Body.Close() }()
- if resp.StatusCode == http.StatusOK {
- var result base.ApiResponse[gitops.GitRepository]
- if err := json.NewDecoder(resp.Body).Decode(&result); err == nil {
- return &result.Data, nil
- }
- }
- // Drain body on non-OK response.
- _, _ = io.Copy(io.Discard, resp.Body)
- }
-
- // Fallback: search via list endpoint.
- listPath := cmdutil.AppendQuery(types.GitRepositories(), url.Values{"limit": []string{strconv.Itoa(cmdutil.ShowAllLimit)}})
- listResp, err := c.Get(ctx, listPath)
- if err != nil {
- return nil, errors.WrapIf(err, "failed to search repositories")
- }
- defer func() { _ = listResp.Body.Close() }()
-
- var listResult base.Paginated[gitops.GitRepository]
- if err := cmdutil.DecodeJSON(listResp, &listResult); err != nil {
- return nil, errors.WrapIf(err, "failed to search repositories")
- }
+var repoRef = cmdutil.ResourceRef[gitops.GitRepository, gitops.GitRepository]{
+ Singular: "repository",
+ Plural: "repositories",
+ IDHint: "the repository ID",
+ ListCmd: "arcane repos list",
+ GetPath: func(_ string, identifier string) string { return types.GitRepository(identifier) },
+ ListPath: func(string) string { return types.GitRepositories() },
+ Matches: repoMatches,
+ Label: func(match gitops.GitRepository) string {
+ return fmt.Sprintf("%s (%s)", match.Name, match.ID)
+ },
+ Promote: func(match gitops.GitRepository) *gitops.GitRepository { return &match },
+ Exact: func(item gitops.GitRepository, _ string, original string) bool {
+ return strings.EqualFold(item.Name, original) || strings.EqualFold(item.ID, original)
+ },
+}
- lowerIdentifier := strings.ToLower(trimmed)
- var matches []gitops.GitRepository
- for _, repo := range listResult.Data {
- if strings.EqualFold(repo.Name, trimmed) || strings.EqualFold(repo.ID, trimmed) {
- return &repo, nil
- }
- if strings.HasPrefix(strings.ToLower(repo.ID), lowerIdentifier) ||
- strings.Contains(strings.ToLower(repo.Name), lowerIdentifier) {
- matches = append(matches, repo)
- }
+func repoMatches(item gitops.GitRepository, identifierLower, original string) bool {
+ if strings.EqualFold(item.Name, original) || strings.EqualFold(item.ID, original) {
+ return true
}
-
- switch len(matches) {
- case 0:
- return nil, errors.Errorf("repository %q not found", trimmed)
- case 1:
- return &matches[0], nil
- default:
- if !prompt.IsInteractive() || len(matches) > maxPromptOptions {
- return nil, errors.Errorf("ambiguous repository %q: %d matches found, please be more specific", trimmed, len(matches))
- }
- options := make([]string, len(matches))
- for i, m := range matches {
- options[i] = fmt.Sprintf("%s (%s)", m.Name, m.ID)
- }
- choice, err := prompt.Select("repository", options)
- if err != nil {
- return nil, err
- }
- return &matches[choice], nil
+ if strings.HasPrefix(strings.ToLower(item.ID), identifierLower) {
+ return true
}
+ return strings.Contains(strings.ToLower(item.Name), identifierLower)
}
func init() {
diff --git a/cli/pkg/selfupdate/cmd.go b/cli/pkg/selfupdate/cmd.go
index 289513906..08a234cda 100644
--- a/cli/pkg/selfupdate/cmd.go
+++ b/cli/pkg/selfupdate/cmd.go
@@ -6,7 +6,7 @@ import (
"context"
"crypto/sha256"
"encoding/hex"
- "encoding/json"
+ "encoding/json/v2"
"fmt"
"io"
"net/http"
@@ -20,6 +20,7 @@ import (
"emperror.dev/errors"
+ "github.com/getarcaneapp/arcane/cli/v2/internal/cmdutil"
"github.com/getarcaneapp/arcane/cli/v2/internal/config"
"github.com/getarcaneapp/arcane/cli/v2/internal/output"
"github.com/spf13/cobra"
@@ -143,12 +144,7 @@ func runCLIUpdateInternal(ctx context.Context, overrideChannel string) error {
}
if jsonOutput {
- resultBytes, err := json.MarshalIndent(plan, "", " ")
- if err != nil {
- return errors.WrapIf(err, "failed to marshal JSON")
- }
- fmt.Println(string(resultBytes))
- return nil
+ return cmdutil.PrintJSON(plan)
}
output.Header("Arcane CLI Update")
@@ -395,7 +391,7 @@ func fetchLatestGitHubReleaseInternal(ctx context.Context) (string, error) {
}
var latest githubLatestRelease
- if err := json.NewDecoder(resp.Body).Decode(&latest); err != nil {
+ if err := json.UnmarshalRead(resp.Body, &latest); err != nil {
return "", errors.WrapIf(err, "failed to fetch latest GitHub release")
}
return strings.TrimSpace(latest.TagName), nil
diff --git a/cli/pkg/settings/cmd.go b/cli/pkg/settings/cmd.go
index 0edef72cc..d12cc51a0 100644
--- a/cli/pkg/settings/cmd.go
+++ b/cli/pkg/settings/cmd.go
@@ -1,8 +1,9 @@
package settings
import (
- "encoding/json"
+ "encoding/json/v2"
"fmt"
+ "net/http"
"os"
"emperror.dev/errors"
@@ -59,23 +60,13 @@ var updateCmd = &cobra.Command{
return errors.WrapIf(err, "failed to parse settings file")
}
- resp, err := c.Put(cmd.Context(), types.Settings(c.EnvID()), req)
+ result, err := c.PutJSON[[]settings.SettingDto](cmd.Context(), types.Settings(c.EnvID()), req)
if err != nil {
return errors.WrapIf(err, "failed to update settings")
}
- defer func() { _ = resp.Body.Close() }()
- if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
- return errors.WrapIf(err, "failed to update settings")
- }
if jsonOutput {
- var result any
- if err := json.NewDecoder(resp.Body).Decode(&result); err == nil {
- if resultBytes, err := json.MarshalIndent(result, "", " "); err == nil {
- fmt.Println(string(resultBytes))
- }
- }
- return nil
+ return cmdutil.PrintJSON(result.Data)
}
output.Success("Settings updated successfully")
@@ -108,24 +99,13 @@ func runSettingsList(cmd *cobra.Command, cfg settingsListConfig) error {
return err
}
- resp, err := c.Get(cmd.Context(), cfg.endpoint(c.EnvID()))
+ result, err := c.DoJSON[[]settings.PublicSetting](cmd.Context(), http.MethodGet, cfg.endpoint(c.EnvID()), nil)
if err != nil {
return errors.WrapIff(err, "%s", cfg.failureMessage)
}
- defer func() { _ = resp.Body.Close() }()
-
- var result []settings.PublicSetting
- if err := cmdutil.DecodeJSON(resp, &result); err != nil {
- return err
- }
if jsonOutput {
- resultBytes, err := json.MarshalIndent(result, "", " ")
- if err != nil {
- return errors.WrapIf(err, "failed to marshal JSON")
- }
- fmt.Println(string(resultBytes))
- return nil
+ return cmdutil.PrintJSON(result)
}
headers := []string{"KEY", "TYPE", "VALUE"}
diff --git a/cli/pkg/system/cmd.go b/cli/pkg/system/cmd.go
index e8415ee92..4d685b696 100644
--- a/cli/pkg/system/cmd.go
+++ b/cli/pkg/system/cmd.go
@@ -1,8 +1,8 @@
package system
import (
- "encoding/json"
"fmt"
+ "net/http"
"strconv"
"time"
@@ -11,7 +11,7 @@ import (
"github.com/getarcaneapp/arcane/cli/v2/internal/cmdutil"
"github.com/getarcaneapp/arcane/cli/v2/internal/output"
"github.com/getarcaneapp/arcane/cli/v2/internal/types"
- "github.com/getarcaneapp/arcane/types/v2/base"
+ "github.com/getarcaneapp/arcane/types/v2/container"
"github.com/getarcaneapp/arcane/types/v2/dockerinfo"
"github.com/getarcaneapp/arcane/types/v2/system"
"github.com/spf13/cobra"
@@ -42,28 +42,13 @@ var pruneCmd = &cobra.Command{
Networks: &system.PruneNetworksOptions{Mode: system.PruneNetworkModeUnused},
}
- resp, err := c.Post(cmd.Context(), types.SystemPrune(c.EnvID()), req)
+ result, err := c.PostJSON[system.PruneAllResult](cmd.Context(), types.SystemPrune(c.EnvID()), req)
if err != nil {
return errors.WrapIf(err, "failed to prune")
}
- defer func() { _ = resp.Body.Close() }()
-
- if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
- return errors.WrapIf(err, "failed to prune")
- }
-
- var result base.ApiResponse[system.PruneAllResult]
- if err := cmdutil.DecodeJSON(resp, &result); err != nil {
- return err
- }
if jsonOutput {
- resultBytes, err := json.MarshalIndent(result.Data, "", " ")
- if err != nil {
- return errors.WrapIf(err, "failed to marshal JSON")
- }
- fmt.Println(string(resultBytes))
- return nil
+ return cmdutil.PrintJSON(result.Data)
}
output.Header("System Prune Results")
@@ -83,16 +68,10 @@ var dockerInfoCmd = &cobra.Command{
return err
}
- resp, err := c.Get(cmd.Context(), types.SystemDockerInfo(c.EnvID()))
- if err != nil {
- return errors.WrapIf(err, "failed to get docker info")
- }
- defer func() { _ = resp.Body.Close() }()
-
// This endpoint returns dockerinfo.Info directly, not wrapped in an
// ApiResponse envelope.
- var result dockerinfo.Info
- if err := cmdutil.DecodeJSON(resp, &result); err != nil {
+ result, err := c.DoJSON[dockerinfo.Info](cmd.Context(), http.MethodGet, types.SystemDockerInfo(c.EnvID()), nil)
+ if err != nil {
return errors.WrapIf(err, "failed to get docker info")
}
@@ -127,34 +106,18 @@ var containersStartCmd = &cobra.Command{
}
path := types.SystemContainersStartAll(c.EnvID())
+ successMessage := "Started all containers"
if startStoppedOnlyFlag {
path = types.SystemStartStopped(c.EnvID())
- }
- resp, err := c.Post(cmd.Context(), path, nil)
- if err != nil {
- return errors.WrapIf(err, "failed to start containers")
- }
- defer func() { _ = resp.Body.Close() }()
- if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
- return errors.WrapIf(err, "failed to start containers")
+ successMessage = "Started all stopped containers"
}
- if jsonOutput {
- var result base.ApiResponse[any]
- if err := json.NewDecoder(resp.Body).Decode(&result); err == nil {
- if resultBytes, err := json.MarshalIndent(result.Data, "", " "); err == nil {
- fmt.Println(string(resultBytes))
- }
- }
- return nil
- }
-
- if startStoppedOnlyFlag {
- output.Success("Started all stopped containers")
- } else {
- output.Success("Started all containers")
- }
- return nil
+ return cmdutil.RunPostAction[container.ActionResult](cmd, c, cmdutil.PostActionSpec{
+ Path: path,
+ FailureMessage: "failed to start containers",
+ SuccessMessage: successMessage,
+ JSON: jsonOutput,
+ })
},
}
@@ -168,18 +131,12 @@ var containersStopCmd = &cobra.Command{
return err
}
- resp, err := c.Post(cmd.Context(), types.SystemContainersStopAll(c.EnvID()), nil)
- if err != nil {
- return errors.WrapIf(err, "failed to stop all containers")
- }
- defer func() { _ = resp.Body.Close() }()
-
- if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
- return errors.WrapIf(err, "failed to stop all containers")
- }
-
- output.Success("Stopped all containers")
- return nil
+ return cmdutil.RunPostAction[container.ActionResult](cmd, c, cmdutil.PostActionSpec{
+ Path: types.SystemContainersStopAll(c.EnvID()),
+ FailureMessage: "failed to stop all containers",
+ SuccessMessage: "Stopped all containers",
+ JSON: jsonOutput,
+ })
},
}
@@ -194,38 +151,26 @@ var convertCmd = &cobra.Command{
return err
}
- req := map[string]string{"dockerRunCommand": args[0]}
- resp, err := c.Post(cmd.Context(), types.SystemConvert(c.EnvID()), req)
- if err != nil {
- return errors.WrapIf(err, "failed to convert command")
- }
- defer func() { _ = resp.Body.Close() }()
- if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
- return errors.WrapIf(err, "failed to convert command")
- }
-
- var result struct {
+ // This endpoint returns its payload directly, not wrapped in an
+ // ApiResponse envelope.
+ type convertResult struct {
Success bool `json:"success"`
DockerCompose string `json:"dockerCompose"`
EnvVars string `json:"envVars"`
ServiceName string `json:"serviceName"`
}
- if err := cmdutil.DecodeJSON(resp, &result); err != nil {
- return err
+ req := map[string]string{"dockerRunCommand": args[0]}
+ result, err := c.DoJSON[convertResult](cmd.Context(), http.MethodPost, types.SystemConvert(c.EnvID()), req)
+ if err != nil {
+ return errors.WrapIf(err, "failed to convert command")
}
if jsonOutput {
- out := map[string]string{
+ return cmdutil.PrintJSON(map[string]string{
"dockerCompose": result.DockerCompose,
"envVars": result.EnvVars,
"serviceName": result.ServiceName,
- }
- resultBytes, err := json.MarshalIndent(out, "", " ")
- if err != nil {
- return errors.WrapIf(err, "failed to marshal JSON")
- }
- fmt.Println(string(resultBytes))
- return nil
+ })
}
output.Header("Conversion Result")
@@ -280,27 +225,14 @@ var upgradeCmd = &cobra.Command{
return err
}
- resp, err := c.Post(cmd.Context(), types.SystemUpgrade(c.EnvID()), nil)
- if err != nil {
- return errors.WrapIf(err, "failed to upgrade system")
- }
- defer func() { _ = resp.Body.Close() }()
- if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
- return errors.WrapIf(err, "failed to upgrade system")
- }
-
- if jsonOutput {
- var result base.ApiResponse[any]
- if err := json.NewDecoder(resp.Body).Decode(&result); err == nil {
- if resultBytes, err := json.MarshalIndent(result.Data, "", " "); err == nil {
- fmt.Println(string(resultBytes))
- }
- }
- return nil
- }
-
- output.Success("System upgrade initiated")
- return nil
+ // The upgrade payload type is backend-internal, so the envelope stays
+ // untyped to keep --json output complete.
+ return cmdutil.RunPostAction[any](cmd, c, cmdutil.PostActionSpec{
+ Path: types.SystemUpgrade(c.EnvID()),
+ FailureMessage: "failed to upgrade system",
+ SuccessMessage: "System upgrade initiated",
+ JSON: jsonOutput,
+ })
},
}
@@ -312,32 +244,20 @@ func runUpgradeCheckInternal(cmd *cobra.Command) error {
return err
}
- resp, err := c.Get(cmd.Context(), types.SystemUpgradeCheck(c.EnvID()))
- if err != nil {
- return errors.WrapIf(err, "failed to check for upgrades")
- }
- defer func() { _ = resp.Body.Close() }()
-
- if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
- return errors.WrapIf(err, "failed to check for upgrades")
- }
-
- var result struct {
+ // This endpoint returns its payload directly, not wrapped in an
+ // ApiResponse envelope.
+ type upgradeCheckResult struct {
CanUpgrade bool `json:"canUpgrade"`
Error bool `json:"error"`
Message string `json:"message"`
}
- if err := cmdutil.DecodeJSON(resp, &result); err != nil {
- return err
+ result, err := c.DoJSON[upgradeCheckResult](cmd.Context(), http.MethodGet, types.SystemUpgradeCheck(c.EnvID()), nil)
+ if err != nil {
+ return errors.WrapIf(err, "failed to check for upgrades")
}
if jsonOutput {
- resultBytes, err := json.MarshalIndent(result, "", " ")
- if err != nil {
- return errors.WrapIf(err, "failed to marshal JSON")
- }
- fmt.Println(string(resultBytes))
- return nil
+ return cmdutil.PrintJSON(result)
}
output.Header("Upgrade Check")
@@ -370,7 +290,7 @@ type environmentUpdateJob struct {
CompletedAt *time.Time `json:"completedAt,omitempty"`
}
-func printUpdateAllJob(job environmentUpdateJob) {
+func printUpdateAllJobInternal(job environmentUpdateJob) {
output.KeyValue("Status", job.Status)
if job.Username != "" {
output.KeyValue("Triggered By", job.Username)
@@ -420,26 +340,17 @@ func runUpgradeAllInternal(cmd *cobra.Command) error {
}
if upgradeAllStatusFlag {
- resp, err := c.Get(cmd.Context(), types.SystemUpgradeAllStatus(c.EnvID()))
+ result, err := c.GetJSON[environmentUpdateJob](cmd.Context(), types.SystemUpgradeAllStatus(c.EnvID()))
if err != nil {
return errors.WrapIf(err, "failed to get update-all status")
}
- defer func() { _ = resp.Body.Close() }()
- if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
- return errors.WrapIf(err, "failed to get update-all status")
- }
-
- var result base.ApiResponse[environmentUpdateJob]
- if err := cmdutil.DecodeJSON(resp, &result); err != nil {
- return err
- }
if jsonOutput {
return cmdutil.PrintJSON(result.Data)
}
output.Header("Update-All Status")
- printUpdateAllJob(result.Data)
+ printUpdateAllJobInternal(result.Data)
return nil
}
@@ -454,26 +365,17 @@ func runUpgradeAllInternal(cmd *cobra.Command) error {
}
}
- resp, err := c.Post(cmd.Context(), types.SystemUpgradeAll(c.EnvID()), nil)
+ result, err := c.PostJSON[environmentUpdateJob](cmd.Context(), types.SystemUpgradeAll(c.EnvID()), nil)
if err != nil {
return errors.WrapIf(err, "failed to trigger update-all")
}
- defer func() { _ = resp.Body.Close() }()
- if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
- return errors.WrapIf(err, "failed to trigger update-all")
- }
-
- var result base.ApiResponse[environmentUpdateJob]
- if err := cmdutil.DecodeJSON(resp, &result); err != nil {
- return err
- }
if jsonOutput {
return cmdutil.PrintJSON(result.Data)
}
output.Success("Update-all started")
- printUpdateAllJob(result.Data)
+ printUpdateAllJobInternal(result.Data)
return nil
}
diff --git a/cli/pkg/templates/cmd.go b/cli/pkg/templates/cmd.go
index e09f3141e..bc62f4158 100644
--- a/cli/pkg/templates/cmd.go
+++ b/cli/pkg/templates/cmd.go
@@ -2,13 +2,11 @@ package templates
import (
"context"
- "encoding/json"
"fmt"
- "io"
- "net/http"
"net/url"
"os"
"path/filepath"
+ "slices"
"sort"
"strconv"
"strings"
@@ -26,8 +24,6 @@ import (
"github.com/spf13/cobra"
)
-const maxTemplatePromptOptions = 20
-
var (
limitFlag int
startFlag int
@@ -72,67 +68,8 @@ var listCmd = &cobra.Command{
return err
}
- var (
- templates []template.Template
- totalItems int64
- jsonPayload any
- path string
- )
-
- if templateListAll {
- if cmd.Flags().Changed("limit") || cmd.Flags().Changed("start") {
- return errors.New("--all cannot be combined with explicit pagination flags")
- }
- path = types.TemplatesAll()
- resp, err := c.Get(cmd.Context(), path)
- if err != nil {
- return errors.WrapIf(err, "failed to list templates")
- }
- defer func() { _ = resp.Body.Close() }()
-
- var result base.ApiResponse[[]template.Template]
- if err := cmdutil.DecodeJSON(resp, &result); err != nil {
- return err
- }
-
- templates = result.Data
- totalItems = int64(len(result.Data))
- jsonPayload = result.Data
- } else {
- path = types.Templates()
- path, err = cmdutil.ApplyPaginationParams(cmd, path, cmdutil.ListParams{Resource: "templates", Limit: limitFlag, FallbackDefault: 20, Start: startFlag})
- if err != nil {
- return errors.WrapIf(err, "failed to build pagination query")
- }
-
- resp, err := c.Get(cmd.Context(), path)
- if err != nil {
- return errors.WrapIf(err, "failed to list templates")
- }
- defer func() { _ = resp.Body.Close() }()
-
- var result base.Paginated[template.Template]
- if err := cmdutil.DecodeJSON(resp, &result); err != nil {
- return err
- }
-
- templates = result.Data
- totalItems = result.Pagination.TotalItems
- jsonPayload = result
- }
-
- if jsonOutput {
- resultBytes, err := json.MarshalIndent(jsonPayload, "", " ")
- if err != nil {
- return errors.WrapIf(err, "failed to marshal JSON")
- }
- fmt.Println(string(resultBytes))
- return nil
- }
-
headers := []string{"NAME", "CUSTOM", "REMOTE", "DESCRIPTION"}
- rows := make([][]string, len(templates))
- for i, tpl := range templates {
+ row := func(tpl template.Template) []string {
custom := "no"
if tpl.IsCustom {
custom = "yes"
@@ -141,7 +78,7 @@ var listCmd = &cobra.Command{
if tpl.IsRemote {
remote = "yes"
}
- rows[i] = []string{
+ return []string{
tpl.Name,
custom,
remote,
@@ -149,9 +86,37 @@ var listCmd = &cobra.Command{
}
}
- output.Table(headers, rows)
- output.Showing(len(templates), totalItems, "templates")
- return nil
+ if templateListAll {
+ if cmd.Flags().Changed("limit") || cmd.Flags().Changed("start") {
+ return errors.New("--all cannot be combined with explicit pagination flags")
+ }
+
+ result, err := c.GetJSON[[]template.Template](cmd.Context(), types.TemplatesAll())
+ if err != nil {
+ return errors.WrapIf(err, "failed to list templates")
+ }
+
+ if jsonOutput {
+ return cmdutil.PrintJSON(result.Data)
+ }
+
+ rows := make([][]string, len(result.Data))
+ for i, tpl := range result.Data {
+ rows[i] = row(tpl)
+ }
+ output.Table(headers, rows)
+ output.Showing(len(result.Data), int64(len(result.Data)), "templates")
+ return nil
+ }
+
+ return cmdutil.RunList(cmd, c, cmdutil.ListSpec[template.Template]{
+ Resource: "templates",
+ Endpoint: types.Templates(),
+ Params: cmdutil.ListParams{Resource: "templates", Limit: limitFlag, FallbackDefault: 20, Start: startFlag},
+ JSON: jsonOutput,
+ Headers: headers,
+ Row: row,
+ })
},
}
@@ -165,24 +130,13 @@ var defaultCmd = &cobra.Command{
return err
}
- resp, err := c.Get(cmd.Context(), types.TemplatesDefault())
+ result, err := c.GetJSON[template.DefaultTemplatesResponse](cmd.Context(), types.TemplatesDefault())
if err != nil {
return errors.WrapIf(err, "failed to get default templates")
}
- defer func() { _ = resp.Body.Close() }()
-
- var result base.ApiResponse[template.DefaultTemplatesResponse]
- if err := cmdutil.DecodeJSON(resp, &result); err != nil {
- return err
- }
if jsonOutput {
- resultBytes, err := json.MarshalIndent(result.Data, "", " ")
- if err != nil {
- return errors.WrapIf(err, "failed to marshal JSON")
- }
- fmt.Println(string(resultBytes))
- return nil
+ return cmdutil.PrintJSON(result.Data)
}
output.Header("Default Templates")
@@ -203,24 +157,13 @@ var contentCmd = &cobra.Command{
return err
}
- resp, err := c.Get(cmd.Context(), types.TemplateContent(args[0]))
+ result, err := c.GetJSON[template.TemplateContent](cmd.Context(), types.TemplateContent(args[0]))
if err != nil {
return errors.WrapIf(err, "failed to get template content")
}
- defer func() { _ = resp.Body.Close() }()
-
- var result base.ApiResponse[template.TemplateContent]
- if err := cmdutil.DecodeJSON(resp, &result); err != nil {
- return err
- }
if jsonOutput {
- resultBytes, err := json.MarshalIndent(result.Data, "", " ")
- if err != nil {
- return errors.WrapIf(err, "failed to marshal JSON")
- }
- fmt.Println(string(resultBytes))
- return nil
+ return cmdutil.PrintJSON(result.Data)
}
output.Header("Template Content")
@@ -249,24 +192,13 @@ var registriesCmd = &cobra.Command{
return err
}
- resp, err := c.Get(cmd.Context(), types.TemplatesRegistries())
+ result, err := c.GetJSON[[]template.TemplateRegistry](cmd.Context(), types.TemplatesRegistries())
if err != nil {
return errors.WrapIf(err, "failed to list registries")
}
- defer func() { _ = resp.Body.Close() }()
-
- var result base.ApiResponse[[]template.TemplateRegistry]
- if err := cmdutil.DecodeJSON(resp, &result); err != nil {
- return err
- }
if jsonOutput {
- resultBytes, err := json.MarshalIndent(result.Data, "", " ")
- if err != nil {
- return errors.WrapIf(err, "failed to marshal JSON")
- }
- fmt.Println(string(resultBytes))
- return nil
+ return cmdutil.PrintJSON(result.Data)
}
headers := []string{"ID", "NAME", "URL", "ENABLED"}
@@ -290,7 +222,7 @@ var registriesCmd = &cobra.Command{
},
}
-func runTemplateDelete(cmd *cobra.Command, label, path string) error {
+func runTemplateDeleteInternal(cmd *cobra.Command, label, path string) error {
if !forceFlag {
confirmed, err := cmdutil.Confirm(cmd, fmt.Sprintf("Are you sure you want to delete %s?", label))
if err != nil {
@@ -307,13 +239,12 @@ func runTemplateDelete(cmd *cobra.Command, label, path string) error {
return err
}
- resp, err := c.Delete(cmd.Context(), path)
+ result, err := c.DeleteJSON[base.MessageResponse](cmd.Context(), path)
if err != nil {
return errors.WrapIff(err, "failed to delete %s", label)
}
- defer func() { _ = resp.Body.Close() }()
- if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
- return errors.WrapIff(err, "failed to delete %s", label)
+ if jsonOutput {
+ return cmdutil.PrintJSON(result.Data)
}
output.Success("Deleted %s successfully", label)
@@ -327,7 +258,7 @@ var deleteCmd = &cobra.Command{
Args: cobra.ExactArgs(1),
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
- return runTemplateDelete(cmd, "template "+args[0], types.Template(args[0]))
+ return runTemplateDeleteInternal(cmd, "template "+args[0], types.Template(args[0]))
},
}
@@ -338,7 +269,7 @@ var deleteRegistryCmd = &cobra.Command{
Args: cobra.ExactArgs(1),
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
- return runTemplateDelete(cmd, "template registry "+args[0], types.TemplateRegistry(args[0]))
+ return runTemplateDeleteInternal(cmd, "template registry "+args[0], types.TemplateRegistry(args[0]))
},
}
@@ -353,18 +284,14 @@ var getCmd = &cobra.Command{
return err
}
- resolved, err := resolveTemplate(cmd.Context(), c, args[0])
+ allowPrompt := !jsonOutput && prompt.IsInteractive()
+ resolved, _, err := templateRef.Resolve(cmd.Context(), c, args[0], allowPrompt)
if err != nil {
return err
}
if jsonOutput {
- resultBytes, err := json.MarshalIndent(resolved, "", " ")
- if err != nil {
- return errors.WrapIf(err, "failed to marshal JSON")
- }
- fmt.Println(string(resultBytes))
- return nil
+ return cmdutil.PrintJSON(resolved)
}
tpl := *resolved
@@ -386,110 +313,73 @@ var getCmd = &cobra.Command{
},
}
-// resolveTemplate attempts to resolve a template by ID or name.
-// It first tries direct GET by ID and falls back to searching all templates by name/ID.
-func resolveTemplate(ctx context.Context, c *client.Client, identifier string) (*template.Template, error) {
- trimmed := strings.TrimSpace(identifier)
- if trimmed == "" {
- return nil, errors.New("template identifier is required")
- }
-
- resp, err := c.Get(ctx, types.Template(trimmed))
- if err != nil {
- return nil, errors.WrapIf(err, "failed to get template")
- }
- defer func() { _ = resp.Body.Close() }()
-
- if resp.StatusCode == http.StatusOK {
- var result base.ApiResponse[template.Template]
- if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
- return nil, errors.WrapIf(err, "failed to parse response")
- }
- return &result.Data, nil
- }
-
- if resp.StatusCode != http.StatusNotFound {
- body, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))
- return nil, errors.Errorf("failed to get template: request failed with status %d: %s", resp.StatusCode, strings.TrimSpace(string(body)))
- }
+var templateRef = cmdutil.ResourceRef[template.Template, template.Template]{
+ Singular: "template",
+ Plural: "templates",
+ IDHint: "the template ID",
+ ListCmd: "arcane templates list",
+ GetPath: func(_, identifier string) string { return types.Template(identifier) },
+ SearchCandidates: searchTemplateCandidatesInternal,
+ SelectCandidate: selectTemplateCandidateInternal,
+ Promote: func(match template.Template) *template.Template { return &match },
+}
- listResp, err := c.Get(ctx, types.TemplatesAll())
+func searchTemplateCandidatesInternal(ctx context.Context, c *client.Client, identifier string) ([]template.Template, error) {
+ result, err := c.GetJSON[[]template.Template](ctx, types.TemplatesAll())
if err != nil {
return nil, errors.WrapIf(err, "failed to search templates")
}
- defer func() { _ = listResp.Body.Close() }()
-
- if listResp.StatusCode < http.StatusOK || listResp.StatusCode >= http.StatusMultipleChoices {
- body, _ := io.ReadAll(io.LimitReader(listResp.Body, 4096))
- return nil, errors.Errorf("failed to search templates: request failed with status %d: %s", listResp.StatusCode, strings.TrimSpace(string(body)))
- }
- var listResult base.ApiResponse[[]template.Template]
- if err := json.NewDecoder(listResp.Body).Decode(&listResult); err != nil {
- return nil, errors.WrapIf(err, "failed to parse template list")
- }
-
- lowerIdentifier := strings.ToLower(trimmed)
+ identifierLower := strings.ToLower(identifier)
exactNameMatches := make([]template.Template, 0)
partialMatches := make([]template.Template, 0)
-
- for _, tpl := range listResult.Data {
- if strings.EqualFold(tpl.ID, trimmed) {
- return &tpl, nil
+ for _, candidate := range result.Data {
+ if strings.EqualFold(candidate.ID, identifier) {
+ return []template.Template{candidate}, nil
}
- if strings.EqualFold(tpl.Name, trimmed) {
- exactNameMatches = append(exactNameMatches, tpl)
+ if strings.EqualFold(candidate.Name, identifier) {
+ exactNameMatches = append(exactNameMatches, candidate)
continue
}
-
- if strings.Contains(strings.ToLower(tpl.Name), lowerIdentifier) || strings.HasPrefix(strings.ToLower(tpl.ID), lowerIdentifier) {
- partialMatches = append(partialMatches, tpl)
+ if strings.Contains(strings.ToLower(candidate.Name), identifierLower) ||
+ strings.HasPrefix(strings.ToLower(candidate.ID), identifierLower) {
+ partialMatches = append(partialMatches, candidate)
}
}
- if len(exactNameMatches) == 1 {
- return &exactNameMatches[0], nil
- }
- if len(exactNameMatches) > 1 {
- return selectTemplateMatch(trimmed, exactNameMatches)
+ if len(exactNameMatches) > 0 {
+ return exactNameMatches, nil
}
-
if len(partialMatches) == 1 {
- return &partialMatches[0], nil
+ return partialMatches, nil
}
if len(partialMatches) > 1 {
- ranked := rankFuzzyTemplateMatches(trimmed, partialMatches)
- if isConfidentBestFuzzyMatch(ranked) {
- return &ranked[0].template, nil
+ ranked := rankFuzzyTemplateMatchesInternal(identifier, partialMatches)
+ if isConfidentBestFuzzyMatchInternal(ranked) {
+ return []template.Template{ranked[0].template}, nil
}
- return selectTemplateMatch(trimmed, topTemplatesFromRankedMatches(ranked, maxTemplatePromptOptions))
+ return topTemplatesFromRankedMatchesInternal(ranked, cmdutil.MaxPromptOptions), nil
}
- ranked := rankFuzzyTemplateMatches(trimmed, listResult.Data)
- if isConfidentBestFuzzyMatch(ranked) {
- return &ranked[0].template, nil
- }
- if len(ranked) > 0 {
- return selectTemplateMatch(trimmed, topTemplatesFromRankedMatches(ranked, maxTemplatePromptOptions))
+ ranked := rankFuzzyTemplateMatchesInternal(identifier, result.Data)
+ if isConfidentBestFuzzyMatchInternal(ranked) {
+ return []template.Template{ranked[0].template}, nil
}
-
- return nil, errors.Errorf("template %q not found", trimmed)
+ return topTemplatesFromRankedMatchesInternal(ranked, cmdutil.MaxPromptOptions), nil
}
-func selectTemplateMatch(identifier string, matches []template.Template) (*template.Template, error) {
+func selectTemplateCandidateInternal(matches []template.Template, identifier string, allowPrompt bool) (*template.Template, error) {
if len(matches) == 0 {
- return nil, errors.Errorf("template %q not found", identifier)
+ return nil, nil
}
if len(matches) == 1 {
return &matches[0], nil
}
-
- if !prompt.IsInteractive() || len(matches) > maxTemplatePromptOptions {
- return nil, errors.Errorf("ambiguous template %q: %s", identifier, formatTemplateCandidates(matches))
+ if !allowPrompt || len(matches) > cmdutil.MaxPromptOptions {
+ return nil, errors.Errorf("ambiguous template %q: %s", identifier, formatTemplateCandidatesInternal(matches))
}
- ordered := make([]template.Template, len(matches))
- copy(ordered, matches)
+ ordered := slices.Clone(matches)
sort.SliceStable(ordered, func(i, j int) bool {
left := strings.ToLower(strings.TrimSpace(ordered[i].Name))
right := strings.ToLower(strings.TrimSpace(ordered[j].Name))
@@ -500,62 +390,61 @@ func selectTemplateMatch(identifier string, matches []template.Template) (*templ
})
options := make([]string, len(ordered))
- for i, tpl := range ordered {
- source := "local"
- if tpl.IsRemote {
- source = "remote"
- }
- custom := "builtin"
- if tpl.IsCustom {
- custom = "custom"
- }
- options[i] = fmt.Sprintf("%s (id: %s, %s, %s)", tpl.Name, tpl.ID, source, custom)
+ for i, candidate := range ordered {
+ options[i] = templateOptionLabelInternal(candidate)
}
-
choice, err := prompt.Select("template", options)
if err != nil {
return nil, err
}
+ return &ordered[choice], nil
+}
- return new(ordered[choice]), nil
+func templateOptionLabelInternal(candidate template.Template) string {
+ source := "local"
+ if candidate.IsRemote {
+ source = "remote"
+ }
+ custom := "builtin"
+ if candidate.IsCustom {
+ custom = "custom"
+ }
+ return fmt.Sprintf("%s (id: %s, %s, %s)", candidate.Name, candidate.ID, source, custom)
}
-type rankedTemplateMatch struct {
+type rankedTemplateMatchInternal struct {
template template.Template
score int
}
-func rankFuzzyTemplateMatches(query string, candidates []template.Template) []rankedTemplateMatch {
- normalizedQuery := normalizeSearchToken(query)
+func rankFuzzyTemplateMatchesInternal(query string, candidates []template.Template) []rankedTemplateMatchInternal {
+ normalizedQuery := normalizeSearchTokenInternal(query)
if normalizedQuery == "" {
return nil
}
- ranked := make([]rankedTemplateMatch, 0, len(candidates))
+ ranked := make([]rankedTemplateMatchInternal, 0, len(candidates))
for _, candidate := range candidates {
- nameScore, nameOk := fuzzyScore(normalizedQuery, normalizeSearchToken(candidate.Name))
- idScore, idOk := fuzzyScore(normalizedQuery, normalizeSearchToken(candidate.ID))
-
+ nameScore, nameMatches := fuzzyScoreInternal(normalizedQuery, normalizeSearchTokenInternal(candidate.Name))
+ idScore, idMatches := fuzzyScoreInternal(normalizedQuery, normalizeSearchTokenInternal(candidate.ID))
score := 0
matched := false
switch {
- case nameOk && idOk:
- if nameScore <= idScore {
- score = nameScore
- } else {
+ case nameMatches && idMatches:
+ score = nameScore
+ if idScore < nameScore {
score = idScore + 10
}
matched = true
- case nameOk:
+ case nameMatches:
score = nameScore
matched = true
- case idOk:
+ case idMatches:
score = idScore + 10
matched = true
}
-
if matched {
- ranked = append(ranked, rankedTemplateMatch{template: candidate, score: score})
+ ranked = append(ranked, rankedTemplateMatchInternal{template: candidate, score: score})
}
}
@@ -568,133 +457,116 @@ func rankFuzzyTemplateMatches(query string, candidates []template.Template) []ra
}
return ranked[i].template.ID < ranked[j].template.ID
})
-
return ranked
}
-func normalizeSearchToken(value string) string {
+func normalizeSearchTokenInternal(value string) string {
var builder strings.Builder
builder.Grow(len(value))
-
for _, r := range strings.ToLower(strings.TrimSpace(value)) {
if unicode.IsLetter(r) || unicode.IsDigit(r) {
builder.WriteRune(r)
}
}
-
return builder.String()
}
-func fuzzyScore(query, target string) (int, bool) {
+func fuzzyScoreInternal(query, target string) (int, bool) {
if query == "" || target == "" {
return 0, false
}
if query == target {
return 0, true
}
-
if strings.Contains(target, query) {
- return 10 + absInt(len(target)-len(query)), true
+ return 10 + absIntInternal(len(target)-len(query)), true
}
-
- if gap, ok := subsequenceGapPenalty(query, target); ok {
+ if gap, ok := subsequenceGapPenaltyInternal(query, target); ok {
return 40 + gap, true
}
- distance := levenshteinDistance(query, target)
- maxDistance := maxInt(2, len(query)/3)
- if distance <= maxDistance {
- return 80 + (distance * 8) + absInt(len(target)-len(query)), true
+ distance := levenshteinDistanceInternal(query, target)
+ if distance <= max(2, len(query)/3) {
+ return 80 + (distance * 8) + absIntInternal(len(target)-len(query)), true
}
-
return 0, false
}
-func subsequenceGapPenalty(query, target string) (int, bool) {
- q := []rune(query)
- t := []rune(target)
- if len(q) == 0 {
+func subsequenceGapPenaltyInternal(query, target string) (int, bool) {
+ queryRunes := []rune(query)
+ targetRunes := []rune(target)
+ if len(queryRunes) == 0 {
return 0, false
}
- qIdx := 0
+ queryIndex := 0
start := -1
- for idx, r := range t {
- if r != q[qIdx] {
+ for index, r := range targetRunes {
+ if r != queryRunes[queryIndex] {
continue
}
if start == -1 {
- start = idx
+ start = index
}
- qIdx++
- if qIdx == len(q) {
- span := (idx - start) + 1
- gaps := span - len(q)
- return gaps + absInt(len(t)-len(q)), true
+ queryIndex++
+ if queryIndex == len(queryRunes) {
+ span := (index - start) + 1
+ gaps := span - len(queryRunes)
+ return gaps + absIntInternal(len(targetRunes)-len(queryRunes)), true
}
}
-
return 0, false
}
-func levenshteinDistance(a, b string) int {
- ra := []rune(a)
- rb := []rune(b)
-
- if len(ra) == 0 {
- return len(rb)
+func levenshteinDistanceInternal(left, right string) int {
+ leftRunes := []rune(left)
+ rightRunes := []rune(right)
+ if len(leftRunes) == 0 {
+ return len(rightRunes)
}
- if len(rb) == 0 {
- return len(ra)
+ if len(rightRunes) == 0 {
+ return len(leftRunes)
}
- prev := make([]int, len(rb)+1)
- for j := 0; j <= len(rb); j++ {
- prev[j] = j
+ previous := make([]int, len(rightRunes)+1)
+ for index := range previous {
+ previous[index] = index
}
-
- for i := 1; i <= len(ra); i++ {
- curr := make([]int, len(rb)+1)
- curr[0] = i
- for j := 1; j <= len(rb); j++ {
+ for leftIndex := 1; leftIndex <= len(leftRunes); leftIndex++ {
+ current := make([]int, len(rightRunes)+1)
+ current[0] = leftIndex
+ for rightIndex := 1; rightIndex <= len(rightRunes); rightIndex++ {
cost := 0
- if ra[i-1] != rb[j-1] {
+ if leftRunes[leftIndex-1] != rightRunes[rightIndex-1] {
cost = 1
}
- curr[j] = minInt(
- curr[j-1]+1,
- prev[j]+1,
- prev[j-1]+cost,
+ current[rightIndex] = min(
+ current[rightIndex-1]+1,
+ previous[rightIndex]+1,
+ previous[rightIndex-1]+cost,
)
}
- prev = curr
+ previous = current
}
-
- return prev[len(rb)]
+ return previous[len(rightRunes)]
}
-func isConfidentBestFuzzyMatch(matches []rankedTemplateMatch) bool {
+func isConfidentBestFuzzyMatchInternal(matches []rankedTemplateMatchInternal) bool {
if len(matches) == 0 {
return false
}
-
best := matches[0].score
if len(matches) == 1 {
return best <= 110
}
-
- second := matches[1].score
- return best <= 110 && (second-best) >= 8
+ return best <= 110 && matches[1].score-best >= 8
}
-func topTemplatesFromRankedMatches(matches []rankedTemplateMatch, limit int) []template.Template {
+func topTemplatesFromRankedMatchesInternal(matches []rankedTemplateMatchInternal, limit int) []template.Template {
if limit <= 0 || len(matches) == 0 {
return nil
}
- if len(matches) < limit {
- limit = len(matches)
- }
-
+ limit = min(limit, len(matches))
result := make([]template.Template, 0, limit)
for i := range limit {
result = append(result, matches[i].template)
@@ -702,51 +574,26 @@ func topTemplatesFromRankedMatches(matches []rankedTemplateMatch, limit int) []t
return result
}
-func minInt(values ...int) int {
- if len(values) == 0 {
- return 0
- }
- result := values[0]
- for _, value := range values[1:] {
- if value < result {
- result = value
- }
- }
- return result
-}
-
-func maxInt(a, b int) int {
- if a > b {
- return a
- }
- return b
-}
-
-func absInt(value int) int {
+func absIntInternal(value int) int {
if value < 0 {
return -value
}
return value
}
-func formatTemplateCandidates(matches []template.Template) string {
- const previewLimit = 5
-
+func formatTemplateCandidatesInternal(matches []template.Template) string {
if len(matches) == 0 {
return "no matches"
}
-
+ const previewLimit = 5
limit := min(len(matches), previewLimit)
-
parts := make([]string, 0, limit+1)
for i := range limit {
parts = append(parts, fmt.Sprintf("%s (%s)", matches[i].Name, matches[i].ID))
}
-
if len(matches) > limit {
parts = append(parts, fmt.Sprintf("and %d more", len(matches)-limit))
}
-
return strings.Join(parts, ", ")
}
@@ -779,24 +626,13 @@ var createCmd = &cobra.Command{
return err
}
- resp, err := c.Post(cmd.Context(), types.Templates(), req)
+ result, err := c.PostJSON[template.Template](cmd.Context(), types.Templates(), req)
if err != nil {
return errors.WrapIf(err, "failed to create template")
}
- defer func() { _ = resp.Body.Close() }()
-
- var result base.ApiResponse[template.Template]
- if err := cmdutil.DecodeJSON(resp, &result); err != nil {
- return err
- }
if jsonOutput {
- resultBytes, err := json.MarshalIndent(result.Data, "", " ")
- if err != nil {
- return errors.WrapIf(err, "failed to marshal JSON")
- }
- fmt.Println(string(resultBytes))
- return nil
+ return cmdutil.PrintJSON(result.Data)
}
output.Success("Template created successfully")
@@ -856,16 +692,10 @@ var updateCmd = &cobra.Command{
req.EnvContent = string(envContent)
}
- resp, err := c.Put(cmd.Context(), types.Template(args[0]), req)
+ result, err := c.PutJSON[template.Template](cmd.Context(), types.Template(args[0]), req)
if err != nil {
return errors.WrapIf(err, "failed to update template")
}
- defer func() { _ = resp.Body.Close() }()
-
- var result base.ApiResponse[template.Template]
- if err := cmdutil.DecodeJSON(resp, &result); err != nil {
- return errors.WrapIf(err, "failed to update template")
- }
if jsonOutput {
return cmdutil.PrintJSON(result.Data)
@@ -889,19 +719,10 @@ var downloadCmd = &cobra.Command{
return err
}
- resp, err := c.Post(cmd.Context(), types.TemplateDownload(args[0]), nil)
+ result, err := c.PostJSON[template.Template](cmd.Context(), types.TemplateDownload(args[0]), nil)
if err != nil {
return errors.WrapIf(err, "failed to download template")
}
- defer func() { _ = resp.Body.Close() }()
- if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
- return errors.WrapIf(err, "failed to download template")
- }
-
- var result base.ApiResponse[template.Template]
- if err := cmdutil.DecodeJSON(resp, &result); err != nil {
- return err
- }
if templateDownloadOutput != "" {
dir := filepath.Dir(templateDownloadOutput)
@@ -947,25 +768,13 @@ var defaultsSaveCmd = &cobra.Command{
return err
}
- resp, err := c.Post(cmd.Context(), types.TemplatesDefault(), req)
- if err != nil {
- return errors.WrapIf(err, "failed to save default templates")
- }
- defer func() { _ = resp.Body.Close() }()
- if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
- return errors.WrapIf(err, "failed to save default templates")
- }
-
- if jsonOutput {
- var result base.ApiResponse[base.MessageResponse]
- if err := cmdutil.DecodeJSON(resp, &result); err != nil {
- return err
- }
- return cmdutil.PrintJSON(result.Data)
- }
-
- output.Success("Default templates saved successfully")
- return nil
+ return cmdutil.RunPostAction[base.MessageResponse](cmd, c, cmdutil.PostActionSpec{
+ Path: types.TemplatesDefault(),
+ Body: req,
+ FailureMessage: "failed to save default templates",
+ SuccessMessage: "Default templates saved successfully",
+ JSON: jsonOutput,
+ })
},
}
@@ -1014,15 +823,9 @@ var registriesUpdateCmd = &cobra.Command{
req.Enabled = false
}
- resp, err := c.Put(cmd.Context(), types.TemplateRegistry(args[0]), req)
- if err != nil {
- return errors.WrapIf(err, "failed to update registry")
- }
- defer func() { _ = resp.Body.Close() }()
-
// The handler answers with a plain message, not the updated registry.
- var result base.ApiResponse[base.MessageResponse]
- if err := cmdutil.DecodeJSON(resp, &result); err != nil {
+ result, err := c.PutJSON[base.MessageResponse](cmd.Context(), types.TemplateRegistry(args[0]), req)
+ if err != nil {
return errors.WrapIf(err, "failed to update registry")
}
@@ -1039,32 +842,20 @@ var registriesUpdateCmd = &cobra.Command{
// fetchTemplateInternal loads a single template, including its content.
func fetchTemplateInternal(cmd *cobra.Command, c *client.Client, id string) (template.Template, error) {
- resp, err := c.Get(cmd.Context(), types.Template(id))
+ result, err := c.GetJSON[template.Template](cmd.Context(), types.Template(id))
if err != nil {
return template.Template{}, errors.WrapIf(err, "failed to load template")
}
- defer func() { _ = resp.Body.Close() }()
-
- var result base.ApiResponse[template.Template]
- if err := cmdutil.DecodeJSON(resp, &result); err != nil {
- return template.Template{}, errors.WrapIf(err, "failed to load template")
- }
return result.Data, nil
}
// fetchTemplateRegistryInternal looks a registry up by ID. The API exposes no
// get-by-id route for template registries, so this filters the list.
func fetchTemplateRegistryInternal(cmd *cobra.Command, c *client.Client, id string) (template.TemplateRegistry, error) {
- resp, err := c.Get(cmd.Context(), types.TemplatesRegistries())
+ listed, err := c.GetJSON[[]template.TemplateRegistry](cmd.Context(), types.TemplatesRegistries())
if err != nil {
return template.TemplateRegistry{}, errors.WrapIf(err, "failed to load registry")
}
- defer func() { _ = resp.Body.Close() }()
-
- var listed base.ApiResponse[[]template.TemplateRegistry]
- if err := cmdutil.DecodeJSON(resp, &listed); err != nil {
- return template.TemplateRegistry{}, errors.WrapIf(err, "failed to load registry")
- }
for _, registry := range listed.Data {
if registry.ID == id {
@@ -1085,26 +876,13 @@ var fetchCmd = &cobra.Command{
}
path := cmdutil.AppendQuery(types.TemplateFetch(), url.Values{"url": []string{templateFetchURL}})
- resp, err := c.Get(cmd.Context(), path)
+ result, err := c.GetJSON[template.RemoteRegistry](cmd.Context(), path)
if err != nil {
return errors.WrapIf(err, "failed to fetch templates")
}
- defer func() { _ = resp.Body.Close() }()
- if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
- return errors.WrapIf(err, "failed to fetch templates")
- }
if jsonOutput {
- var result base.ApiResponse[any]
- if err := cmdutil.DecodeJSON(resp, &result); err != nil {
- return err
- }
- resultBytes, err := json.MarshalIndent(result.Data, "", " ")
- if err != nil {
- return errors.WrapIf(err, "failed to marshal JSON")
- }
- fmt.Println(string(resultBytes))
- return nil
+ return cmdutil.PrintJSON(result.Data)
}
output.Success("Remote templates fetched successfully")
diff --git a/cli/pkg/updater/cmd.go b/cli/pkg/updater/cmd.go
index f0e5281c7..38eaf7d6e 100644
--- a/cli/pkg/updater/cmd.go
+++ b/cli/pkg/updater/cmd.go
@@ -1,7 +1,6 @@
package updater
import (
- "encoding/json"
"fmt"
"net/url"
"strconv"
@@ -12,7 +11,6 @@ import (
"github.com/getarcaneapp/arcane/cli/v2/internal/cmdutil"
"github.com/getarcaneapp/arcane/cli/v2/internal/output"
"github.com/getarcaneapp/arcane/cli/v2/internal/types"
- "github.com/getarcaneapp/arcane/types/v2/base"
"github.com/getarcaneapp/arcane/types/v2/updater"
"github.com/spf13/cobra"
)
@@ -39,24 +37,13 @@ var statusCmd = &cobra.Command{
return err
}
- resp, err := c.Get(cmd.Context(), types.UpdaterStatus(c.EnvID()))
+ result, err := c.GetJSON[updater.Status](cmd.Context(), types.UpdaterStatus(c.EnvID()))
if err != nil {
return errors.WrapIf(err, "failed to get updater status")
}
- defer func() { _ = resp.Body.Close() }()
-
- var result base.ApiResponse[updater.Status]
- if err := cmdutil.DecodeJSON(resp, &result); err != nil {
- return err
- }
if jsonOutput {
- resultBytes, err := json.MarshalIndent(result.Data, "", " ")
- if err != nil {
- return errors.WrapIf(err, "failed to marshal JSON")
- }
- fmt.Println(string(resultBytes))
- return nil
+ return cmdutil.PrintJSON(result.Data)
}
output.Header("Updater Status")
@@ -79,24 +66,13 @@ var runCmd = &cobra.Command{
// Updater run can take a long time as it pulls images and restarts containers
c.SetTimeout(30 * time.Minute)
- resp, err := c.Post(cmd.Context(), types.UpdaterRun(c.EnvID()), nil)
+ result, err := c.PostJSON[updater.Result](cmd.Context(), types.UpdaterRun(c.EnvID()), nil)
if err != nil {
return errors.WrapIf(err, "failed to run updater")
}
- defer func() { _ = resp.Body.Close() }()
-
- var result base.ApiResponse[updater.Result]
- if err := cmdutil.DecodeJSON(resp, &result); err != nil {
- return err
- }
if jsonOutput {
- resultBytes, err := json.MarshalIndent(result.Data, "", " ")
- if err != nil {
- return errors.WrapIf(err, "failed to marshal JSON")
- }
- fmt.Println(string(resultBytes))
- return nil
+ return cmdutil.PrintJSON(result.Data)
}
output.Header("Updater Results")
@@ -141,16 +117,10 @@ var historyCmd = &cobra.Command{
path = cmdutil.AppendQuery(path, url.Values{"limit": []string{strconv.Itoa(historyLimit)}})
}
- resp, err := c.Get(cmd.Context(), path)
+ result, err := c.GetJSON[[]autoUpdateRecord](cmd.Context(), path)
if err != nil {
return errors.WrapIf(err, "failed to get updater history")
}
- defer func() { _ = resp.Body.Close() }()
-
- var result base.ApiResponse[[]autoUpdateRecord]
- if err := cmdutil.DecodeJSON(resp, &result); err != nil {
- return errors.WrapIf(err, "failed to get updater history")
- }
if jsonOutput {
return cmdutil.PrintJSON(result.Data)
diff --git a/cli/pkg/variables/cmd.go b/cli/pkg/variables/cmd.go
index 8987119ca..2535311da 100644
--- a/cli/pkg/variables/cmd.go
+++ b/cli/pkg/variables/cmd.go
@@ -2,17 +2,16 @@ package variables
import (
"fmt"
- "net/http"
"strconv"
"strings"
"time"
"emperror.dev/errors"
+ "github.com/getarcaneapp/arcane/cli/v2/internal/client"
"github.com/getarcaneapp/arcane/cli/v2/internal/cmdutil"
"github.com/getarcaneapp/arcane/cli/v2/internal/output"
"github.com/getarcaneapp/arcane/cli/v2/internal/types"
- "github.com/getarcaneapp/arcane/types/v2/base"
"github.com/getarcaneapp/arcane/types/v2/env"
"github.com/spf13/cobra"
)
@@ -101,19 +100,10 @@ var listCmd = &cobra.Command{
return err
}
- resp, err := c.Get(cmd.Context(), types.Variables())
+ result, err := c.GetJSON[[]env.GlobalVariable](cmd.Context(), types.Variables())
if err != nil {
return errors.WrapIf(err, "failed to list variables")
}
- defer func() { _ = resp.Body.Close() }()
- if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
- return errors.WrapIf(err, "failed to list variables")
- }
-
- var result base.ApiResponse[[]env.GlobalVariable]
- if err := cmdutil.DecodeJSON(resp, &result); err != nil {
- return errors.WrapIf(err, "failed to list variables")
- }
if jsonOutput {
return cmdutil.PrintJSON(result.Data)
@@ -159,19 +149,10 @@ var createCmd = &cobra.Command{
EnvironmentIDs: createEnvIDs,
}
- resp, err := c.Post(cmd.Context(), types.Variables(), req)
+ result, err := c.PostJSON[env.GlobalVariableMutationResponse](cmd.Context(), types.Variables(), req)
if err != nil {
return errors.WrapIf(err, "failed to create variable")
}
- defer func() { _ = resp.Body.Close() }()
- if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
- return errors.WrapIf(err, "failed to create variable")
- }
-
- var result base.ApiResponse[env.GlobalVariableMutationResponse]
- if err := cmdutil.DecodeJSON(resp, &result); err != nil {
- return err
- }
return printMutationResult(result.Data, fmt.Sprintf("Variable %s created successfully", createKey))
},
@@ -209,19 +190,10 @@ var updateCmd = &cobra.Command{
return errors.New("no updates provided (set at least one flag)")
}
- resp, err := c.Put(cmd.Context(), types.Variable(args[0]), req)
+ result, err := c.PutJSON[env.GlobalVariableMutationResponse](cmd.Context(), types.Variable(args[0]), req)
if err != nil {
return errors.WrapIf(err, "failed to update variable")
}
- defer func() { _ = resp.Body.Close() }()
- if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
- return errors.WrapIf(err, "failed to update variable")
- }
-
- var result base.ApiResponse[env.GlobalVariableMutationResponse]
- if err := cmdutil.DecodeJSON(resp, &result); err != nil {
- return err
- }
return printMutationResult(result.Data, "Variable updated successfully")
},
@@ -250,19 +222,10 @@ var deleteCmd = &cobra.Command{
return err
}
- resp, err := c.Delete(cmd.Context(), types.Variable(args[0]))
+ result, err := c.DeleteJSON[env.GlobalVariableMutationResponse](cmd.Context(), types.Variable(args[0]))
if err != nil {
return errors.WrapIf(err, "failed to delete variable")
}
- defer func() { _ = resp.Body.Close() }()
- if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
- return errors.WrapIf(err, "failed to delete variable")
- }
-
- var result base.ApiResponse[env.GlobalVariableMutationResponse]
- if err := cmdutil.DecodeJSON(resp, &result); err != nil {
- return err
- }
return printMutationResult(result.Data, "Variable deleted successfully")
},
@@ -278,26 +241,17 @@ var syncCmd = &cobra.Command{
return err
}
- var response *http.Response
+ var result *client.APIResponse[[]env.EnvironmentSyncStatus]
failureMessage := "failed to sync variables"
if syncStatusFlag {
failureMessage = "failed to get variable sync status"
- response, err = c.Get(cmd.Context(), types.VariablesSyncStatus())
+ result, err = c.GetJSON[[]env.EnvironmentSyncStatus](cmd.Context(), types.VariablesSyncStatus())
} else {
- response, err = c.Post(cmd.Context(), types.VariablesSync(), nil)
+ result, err = c.PostJSON[[]env.EnvironmentSyncStatus](cmd.Context(), types.VariablesSync(), nil)
}
if err != nil {
return errors.WrapIff(err, "%s", failureMessage)
}
- defer func() { _ = response.Body.Close() }()
- if err := cmdutil.EnsureSuccessStatus(response); err != nil {
- return errors.WrapIff(err, "%s", failureMessage)
- }
-
- var result base.ApiResponse[[]env.EnvironmentSyncStatus]
- if err := cmdutil.DecodeJSON(response, &result); err != nil {
- return err
- }
if jsonOutput {
return cmdutil.PrintJSON(result.Data)
diff --git a/cli/pkg/version/cmd.go b/cli/pkg/version/cmd.go
index 7d98b55c4..c558cb4bc 100644
--- a/cli/pkg/version/cmd.go
+++ b/cli/pkg/version/cmd.go
@@ -1,8 +1,7 @@
package version
import (
- "encoding/json"
- "fmt"
+ "net/http"
"emperror.dev/errors"
"github.com/getarcaneapp/arcane/cli/v2/internal/client"
@@ -31,36 +30,15 @@ var VersionCmd = &cobra.Command{
// neither displayVersion nor revision. /api/app-version returns the full
// version.Info, including the update-check fields printed below.
logger.GetLogger().Debug("Sending request", "endpoint", clitypes.AppVersionEndpoint)
- resp, err := c.Get(cmd.Context(), clitypes.AppVersionEndpoint)
+ result, err := c.DoJSON[version.Info](cmd.Context(), http.MethodGet, clitypes.AppVersionEndpoint, nil)
if err != nil {
return errors.WrapIf(err, "failed to get version")
}
- defer func() { _ = resp.Body.Close() }()
-
- logger.GetLogger().Debug("Response received", "status", resp.Status)
-
- body, err := cmdutil.ReadJSONBody(resp)
- if err != nil {
- return errors.WrapIf(err, "failed to get version")
- }
-
- logger.GetLogger().Debug("Raw response", "body", string(body))
-
- var result version.Info
-
- if err := json.Unmarshal(body, &result); err != nil {
- return errors.WrapIf(err, "failed to parse response")
- }
logger.GetLogger().Debug("Parsed version data", "result", result)
if cmdutil.JSONOutputEnabled(cmd) {
- resultBytes, err := json.MarshalIndent(result, "", " ")
- if err != nil {
- return errors.WrapIf(err, "failed to marshal JSON")
- }
- fmt.Println(string(resultBytes))
- return nil
+ return cmdutil.PrintJSON(result)
}
output.Header("Arcane Environment Details: \n")
diff --git a/cli/pkg/volumes/backup.go b/cli/pkg/volumes/backup.go
index 1803826f4..4e2222997 100644
--- a/cli/pkg/volumes/backup.go
+++ b/cli/pkg/volumes/backup.go
@@ -1,7 +1,7 @@
package volumes
import (
- "encoding/json"
+ "encoding/json/v2"
"fmt"
"io"
"mime"
@@ -56,13 +56,13 @@ var renameCmd = &cobra.Command{
Args: cobra.ExactArgs(2),
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
- c, err := client.NewFromConfig()
+ c, err := cmdutil.ClientFromCommand(cmd)
if err != nil {
return err
}
allowPrompt := !forceFlag && !jsonOutput && prompt.IsInteractive()
- resolved, err := resolveVolume(cmd.Context(), c, args[0], allowPrompt)
+ resolved, _, err := volumeRef.Resolve(cmd.Context(), c, args[0], allowPrompt)
if err != nil {
return err
}
@@ -78,19 +78,10 @@ var renameCmd = &cobra.Command{
}
}
- resp, err := c.Post(cmd.Context(), types.VolumeRename(c.EnvID(), resolved.Name), volume.Rename{Name: args[1]})
+ result, err := c.PostJSON[volume.Volume](cmd.Context(), types.VolumeRename(c.EnvID(), resolved.Name), volume.Rename{Name: args[1]})
if err != nil {
return errors.WrapIf(err, "failed to rename volume")
}
- defer func() { _ = resp.Body.Close() }()
- if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
- return errors.WrapIf(err, "failed to rename volume")
- }
-
- var result base.ApiResponse[volume.Volume]
- if err := cmdutil.DecodeJSON(resp, &result); err != nil {
- return err
- }
if jsonOutput {
return cmdutil.PrintJSON(result.Data)
@@ -107,30 +98,21 @@ var backupsPolicyCmd = &cobra.Command{
Args: cobra.ExactArgs(1),
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
- c, err := client.NewFromConfig()
+ c, err := cmdutil.ClientFromCommand(cmd)
if err != nil {
return err
}
allowPrompt := !jsonOutput && prompt.IsInteractive()
- resolved, err := resolveVolume(cmd.Context(), c, args[0], allowPrompt)
+ resolved, _, err := volumeRef.Resolve(cmd.Context(), c, args[0], allowPrompt)
if err != nil {
return err
}
- resp, err := c.Get(cmd.Context(), types.VolumeBackupPolicy(c.EnvID(), resolved.Name))
+ result, err := c.GetJSON[volume.BackupPolicyCollection](cmd.Context(), types.VolumeBackupPolicy(c.EnvID(), resolved.Name))
if err != nil {
return errors.WrapIf(err, "failed to get backup policies")
}
- defer func() { _ = resp.Body.Close() }()
- if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
- return errors.WrapIf(err, "failed to get backup policies")
- }
-
- var result base.ApiResponse[volume.BackupPolicyCollection]
- if err := cmdutil.DecodeJSON(resp, &result); err != nil {
- return err
- }
if jsonOutput {
return cmdutil.PrintJSON(result.Data)
@@ -147,13 +129,13 @@ var backupsPolicyUpdateCmd = &cobra.Command{
Args: cobra.ExactArgs(1),
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
- c, err := client.NewFromConfig()
+ c, err := cmdutil.ClientFromCommand(cmd)
if err != nil {
return err
}
allowPrompt := !jsonOutput && prompt.IsInteractive()
- resolved, err := resolveVolume(cmd.Context(), c, args[0], allowPrompt)
+ resolved, _, err := volumeRef.Resolve(cmd.Context(), c, args[0], allowPrompt)
if err != nil {
return err
}
@@ -174,19 +156,10 @@ var backupsPolicyUpdateCmd = &cobra.Command{
}
}
- resp, err := c.Put(cmd.Context(), types.VolumeBackupPolicy(c.EnvID(), resolved.Name), payload)
+ result, err := c.PutJSON[volume.BackupPolicyCollection](cmd.Context(), types.VolumeBackupPolicy(c.EnvID(), resolved.Name), payload)
if err != nil {
return errors.WrapIf(err, "failed to update backup policies")
}
- defer func() { _ = resp.Body.Close() }()
- if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
- return errors.WrapIf(err, "failed to update backup policies")
- }
-
- var result base.ApiResponse[volume.BackupPolicyCollection]
- if err := cmdutil.DecodeJSON(resp, &result); err != nil {
- return err
- }
if jsonOutput {
return cmdutil.PrintJSON(result.Data)
@@ -204,19 +177,10 @@ var backupsPolicyUpdateCmd = &cobra.Command{
func buildPolicyUpdate(cmd *cobra.Command, c *client.Client, volumeName string) (volume.UpdateBackupPolicies, error) {
var payload volume.UpdateBackupPolicies
- resp, err := c.Get(cmd.Context(), types.VolumeBackupPolicy(c.EnvID(), volumeName))
+ current, err := c.GetJSON[volume.BackupPolicyCollection](cmd.Context(), types.VolumeBackupPolicy(c.EnvID(), volumeName))
if err != nil {
return payload, errors.WrapIf(err, "failed to get current backup policies")
}
- defer func() { _ = resp.Body.Close() }()
- if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
- return payload, errors.WrapIf(err, "failed to get current backup policies")
- }
-
- var current base.ApiResponse[volume.BackupPolicyCollection]
- if err := cmdutil.DecodeJSON(resp, &current); err != nil {
- return payload, err
- }
payload.Policies = make([]volume.UpdateBackupPolicy, len(current.Data.Policies))
targetIndex := -1
@@ -331,13 +295,13 @@ var backupsListCmd = &cobra.Command{
}
func runListBackups(cmd *cobra.Command, args []string) error {
- c, err := client.NewFromConfig()
+ c, err := cmdutil.ClientFromCommand(cmd)
if err != nil {
return err
}
allowPrompt := !jsonOutput && prompt.IsInteractive()
- resolved, err := resolveVolume(cmd.Context(), c, args[0], allowPrompt)
+ resolved, _, err := volumeRef.Resolve(cmd.Context(), c, args[0], allowPrompt)
if err != nil {
return err
}
@@ -353,24 +317,13 @@ func runListBackups(cmd *cobra.Command, args []string) error {
return errors.WrapIf(err, "failed to build pagination query")
}
- resp, err := c.Get(cmd.Context(), path)
- if err != nil {
- return errors.WrapIf(err, "failed to list backups")
- }
- defer func() { _ = resp.Body.Close() }()
-
- body, err := cmdutil.ReadJSONBody(resp)
+ result, err := c.DoJSON[backupsListResponse](cmd.Context(), http.MethodGet, path, nil)
if err != nil {
return errors.WrapIf(err, "failed to list backups")
}
if jsonOutput {
- return cmdutil.PrintRawJSON(body)
- }
-
- var result backupsListResponse
- if err := json.Unmarshal(body, &result); err != nil {
- return errors.WrapIf(err, "failed to parse response")
+ return cmdutil.PrintJSON(result)
}
headers := []string{"ID", "SIZE", "CREATED", "STATUS", "TRIGGER", "DESTINATION", "FORMAT"}
@@ -401,13 +354,13 @@ var backupsCreateCmd = &cobra.Command{
Args: cobra.ExactArgs(1),
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
- c, err := client.NewFromConfig()
+ c, err := cmdutil.ClientFromCommand(cmd)
if err != nil {
return err
}
allowPrompt := !jsonOutput && prompt.IsInteractive()
- resolved, err := resolveVolume(cmd.Context(), c, args[0], allowPrompt)
+ resolved, _, err := volumeRef.Resolve(cmd.Context(), c, args[0], allowPrompt)
if err != nil {
return err
}
@@ -418,19 +371,10 @@ var backupsCreateCmd = &cobra.Command{
S3DestinationID: backupCreateS3Destination,
}
- resp, err := c.Post(cmd.Context(), types.VolumeBackups(c.EnvID(), resolved.Name), req)
+ result, err := c.PostJSON[volume.BackupEntry](cmd.Context(), types.VolumeBackups(c.EnvID(), resolved.Name), req)
if err != nil {
return errors.WrapIf(err, "failed to create backup")
}
- defer func() { _ = resp.Body.Close() }()
- if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
- return errors.WrapIf(err, "failed to create backup")
- }
-
- var result base.ApiResponse[volume.BackupEntry]
- if err := cmdutil.DecodeJSON(resp, &result); err != nil {
- return err
- }
if jsonOutput {
return cmdutil.PrintJSON(result.Data)
@@ -468,13 +412,13 @@ and restored instead (no backup ID).`,
return errors.New("--path cannot be used with --file")
}
- c, err := client.NewFromConfig()
+ c, err := cmdutil.ClientFromCommand(cmd)
if err != nil {
return err
}
allowPrompt := !forceFlag && prompt.IsInteractive()
- resolved, err := resolveVolume(cmd.Context(), c, args[0], allowPrompt)
+ resolved, _, err := volumeRef.Resolve(cmd.Context(), c, args[0], allowPrompt)
if err != nil {
return err
}
@@ -499,21 +443,13 @@ and restored instead (no backup ID).`,
}
}
- resp, err := c.Post(cmd.Context(), types.VolumeBackupRestore(c.EnvID(), resolved.Name, backupID), nil)
+ result, err := c.PostJSON[base.MessageResponse](cmd.Context(), types.VolumeBackupRestore(c.EnvID(), resolved.Name, backupID), nil)
if err != nil {
return errors.WrapIf(err, "failed to restore backup")
}
- defer func() { _ = resp.Body.Close() }()
- if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
- return errors.WrapIf(err, "failed to restore backup")
- }
if jsonOutput {
- body, err := cmdutil.ReadJSONBody(resp)
- if err != nil {
- return err
- }
- return cmdutil.PrintRawJSON(body)
+ return cmdutil.PrintJSON(result.Data)
}
output.Success("Restore of volume %s from backup %s initiated", resolved.Name, backupID)
@@ -537,21 +473,13 @@ func runRestorePaths(cmd *cobra.Command, c *client.Client, volumeName, backupID
Paths []string `json:"paths"`
}{Paths: restorePaths}
- resp, err := c.Post(cmd.Context(), types.VolumeBackupRestoreFiles(c.EnvID(), volumeName, backupID), body)
+ result, err := c.PostJSON[base.MessageResponse](cmd.Context(), types.VolumeBackupRestoreFiles(c.EnvID(), volumeName, backupID), body)
if err != nil {
return errors.WrapIf(err, "failed to restore backup files")
}
- defer func() { _ = resp.Body.Close() }()
- if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
- return errors.WrapIf(err, "failed to restore backup files")
- }
if jsonOutput {
- respBody, err := cmdutil.ReadJSONBody(resp)
- if err != nil {
- return err
- }
- return cmdutil.PrintRawJSON(respBody)
+ return cmdutil.PrintJSON(result.Data)
}
output.Success("Restore of %d path(s) into volume %s initiated", len(restorePaths), volumeName)
@@ -611,17 +539,12 @@ var backupsDeleteCmd = &cobra.Command{
}
}
- c, err := client.NewFromConfig()
+ c, err := cmdutil.ClientFromCommand(cmd)
if err != nil {
return err
}
- resp, err := c.Delete(cmd.Context(), types.VolumeBackup(c.EnvID(), args[0]))
- if err != nil {
- return errors.WrapIf(err, "failed to delete backup")
- }
- defer func() { _ = resp.Body.Close() }()
- if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
+ if _, err := c.DeleteJSON[base.MessageResponse](cmd.Context(), types.VolumeBackup(c.EnvID(), args[0])); err != nil {
return errors.WrapIf(err, "failed to delete backup")
}
@@ -636,7 +559,7 @@ var backupsUploadCmd = &cobra.Command{
Args: cobra.ExactArgs(1),
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
- c, err := client.NewFromConfig()
+ c, err := cmdutil.ClientFromCommand(cmd)
if err != nil {
return err
}
@@ -645,19 +568,10 @@ var backupsUploadCmd = &cobra.Command{
c.SetTimeout(30 * time.Minute)
req := volume.UploadBackupRequest{S3DestinationID: backupUploadS3Destination}
- resp, err := c.Post(cmd.Context(), types.VolumeBackupUpload(c.EnvID(), args[0]), req)
+ result, err := c.PostJSON[volume.BackupEntry](cmd.Context(), types.VolumeBackupUpload(c.EnvID(), args[0]), req)
if err != nil {
return errors.WrapIf(err, "failed to upload backup")
}
- defer func() { _ = resp.Body.Close() }()
- if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
- return errors.WrapIf(err, "failed to upload backup")
- }
-
- var result base.ApiResponse[volume.BackupEntry]
- if err := cmdutil.DecodeJSON(resp, &result); err != nil {
- return err
- }
if jsonOutput {
return cmdutil.PrintJSON(result.Data)
@@ -674,7 +588,7 @@ var backupsDownloadCmd = &cobra.Command{
Args: cobra.RangeArgs(1, 2),
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
- c, err := client.NewFromConfig()
+ c, err := cmdutil.ClientFromCommand(cmd)
if err != nil {
return err
}
@@ -740,24 +654,15 @@ var backupsFilesCmd = &cobra.Command{
Args: cobra.ExactArgs(1),
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
- c, err := client.NewFromConfig()
+ c, err := cmdutil.ClientFromCommand(cmd)
if err != nil {
return err
}
- resp, err := c.Get(cmd.Context(), types.VolumeBackupFiles(c.EnvID(), args[0]))
+ result, err := c.GetJSON[[]string](cmd.Context(), types.VolumeBackupFiles(c.EnvID(), args[0]))
if err != nil {
return errors.WrapIf(err, "failed to list backup files")
}
- defer func() { _ = resp.Body.Close() }()
- if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
- return errors.WrapIf(err, "failed to list backup files")
- }
-
- var result base.ApiResponse[[]string]
- if err := cmdutil.DecodeJSON(resp, &result); err != nil {
- return err
- }
if jsonOutput {
return cmdutil.PrintJSON(result.Data)
diff --git a/cli/pkg/volumes/cmd.go b/cli/pkg/volumes/cmd.go
index 3b697625f..c585d22ec 100644
--- a/cli/pkg/volumes/cmd.go
+++ b/cli/pkg/volumes/cmd.go
@@ -1,11 +1,7 @@
package volumes
import (
- "context"
- "encoding/json"
"fmt"
- "io"
- "net/http"
"net/url"
"strconv"
"strings"
@@ -17,7 +13,6 @@ import (
"github.com/getarcaneapp/arcane/cli/v2/internal/output"
"github.com/getarcaneapp/arcane/cli/v2/internal/prompt"
"github.com/getarcaneapp/arcane/cli/v2/internal/types"
- "github.com/getarcaneapp/arcane/types/v2/base"
"github.com/getarcaneapp/arcane/types/v2/volume"
"github.com/spf13/cobra"
)
@@ -40,8 +35,6 @@ var (
volumeCreateLabels []string
)
-const maxPromptOptions = 20
-
// VolumesCmd is the parent command for volume operations
var VolumesCmd = &cobra.Command{
Use: "volumes",
@@ -63,17 +56,6 @@ var listCmd = &cobra.Command{
return err
}
- path, err := cmdutil.ApplyPaginationParams(cmd, types.Volumes(c.EnvID()), cmdutil.ListParams{
- Resource: "volumes",
- Limit: limitFlag,
- FallbackDefault: 20,
- Start: startFlag,
- All: allFlag,
- })
- if err != nil {
- return errors.WrapIf(err, "failed to build pagination query")
- }
-
// Filter server-side so that pagination and the reported totals apply to
// the matching set rather than to whichever page happened to be fetched.
query := url.Values{}
@@ -86,49 +68,34 @@ var listCmd = &cobra.Command{
if includeInternalFlag {
query.Set("includeInternal", "true")
}
- if len(query) > 0 {
- path = cmdutil.AppendQuery(path, query)
- }
-
- resp, err := c.Get(cmd.Context(), path)
- if err != nil {
- return errors.WrapIf(err, "failed to list volumes")
- }
- defer func() { _ = resp.Body.Close() }()
-
- body, err := cmdutil.ReadJSONBody(resp)
- if err != nil {
- return errors.WrapIf(err, "failed to list volumes")
- }
-
- if jsonOutput {
- return cmdutil.PrintRawJSON(body)
- }
-
- var result base.Paginated[volume.Volume]
- if err := json.Unmarshal(body, &result); err != nil {
- return errors.WrapIf(err, "failed to parse response")
- }
-
- headers := []string{"NAME", "DRIVER", "MOUNTPOINT", "CREATED", "IN USE"}
- rows := make([][]string, len(result.Data))
- for i, vol := range result.Data {
- inUse := "No"
- if vol.InUse {
- inUse = "Yes"
- }
- rows[i] = []string{
- vol.Name,
- vol.Driver,
- vol.Mountpoint,
- vol.CreatedAt,
- inUse,
- }
- }
- output.Table(headers, rows)
- output.Showing(len(result.Data), result.Pagination.TotalItems, "volumes")
- return nil
+ return cmdutil.RunList(cmd, c, cmdutil.ListSpec[volume.Volume]{
+ Resource: "volumes",
+ Endpoint: types.Volumes(c.EnvID()),
+ Params: cmdutil.ListParams{
+ Resource: "volumes",
+ Limit: limitFlag,
+ FallbackDefault: 20,
+ Start: startFlag,
+ All: allFlag,
+ },
+ Query: query,
+ JSON: jsonOutput,
+ Headers: []string{"NAME", "DRIVER", "MOUNTPOINT", "CREATED", "IN USE"},
+ Row: func(vol volume.Volume) []string {
+ inUse := "No"
+ if vol.InUse {
+ inUse = "Yes"
+ }
+ return []string{
+ vol.Name,
+ vol.Driver,
+ vol.Mountpoint,
+ vol.CreatedAt,
+ inUse,
+ }
+ },
+ })
},
}
@@ -144,18 +111,13 @@ var getCmd = &cobra.Command{
}
allowPrompt := !jsonOutput && prompt.IsInteractive()
- resolved, err := resolveVolume(cmd.Context(), c, args[0], allowPrompt)
+ resolved, _, err := volumeRef.Resolve(cmd.Context(), c, args[0], allowPrompt)
if err != nil {
return err
}
if jsonOutput {
- resultBytes, err := json.MarshalIndent(resolved, "", " ")
- if err != nil {
- return errors.WrapIf(err, "failed to marshal JSON")
- }
- fmt.Println(string(resultBytes))
- return nil
+ return cmdutil.PrintJSON(resolved)
}
output.Header("Volume Details")
@@ -185,7 +147,7 @@ var deleteCmd = &cobra.Command{
}
allowPrompt := !forceFlag && prompt.IsInteractive()
- resolved, err := resolveVolume(cmd.Context(), c, args[0], allowPrompt)
+ resolved, _, err := volumeRef.Resolve(cmd.Context(), c, args[0], allowPrompt)
if err != nil {
return err
}
@@ -254,31 +216,12 @@ var pruneCmd = &cobra.Command{
return err
}
- resp, err := c.Post(cmd.Context(), types.VolumesPrune(c.EnvID()), nil)
- if err != nil {
- return errors.WrapIf(err, "failed to prune volumes")
- }
- defer func() { _ = resp.Body.Close() }()
- if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
- return errors.WrapIf(err, "failed to prune volumes")
- }
-
- var result base.ApiResponse[any]
- if err := cmdutil.DecodeJSON(resp, &result); err != nil {
- return err
- }
-
- if jsonOutput {
- resultBytes, err := json.MarshalIndent(result.Data, "", " ")
- if err != nil {
- return errors.WrapIf(err, "failed to marshal JSON")
- }
- fmt.Println(string(resultBytes))
- return nil
- }
-
- output.Success("Volumes pruned successfully")
- return nil
+ return cmdutil.RunPostAction[any](cmd, c, cmdutil.PostActionSpec{
+ Path: types.VolumesPrune(c.EnvID()),
+ FailureMessage: "failed to prune volumes",
+ SuccessMessage: "Volumes pruned successfully",
+ JSON: jsonOutput,
+ })
},
}
@@ -309,33 +252,15 @@ func runVolumeDataCommand(cmd *cobra.Command, cfg volumeDataCommandConfig) error
return err
}
- resp, err := c.Get(cmd.Context(), cfg.endpoint(c.EnvID()))
+ result, err := c.GetJSON[any](cmd.Context(), cfg.endpoint(c.EnvID()))
if err != nil {
return errors.WrapIff(err, "%s", cfg.failureMessage)
}
- defer func() { _ = resp.Body.Close() }()
- var result base.ApiResponse[any]
- if err := cmdutil.DecodeJSON(resp, &result); err != nil {
- return err
+ if !jsonOutput {
+ output.Header("%s", cfg.header)
}
-
- resultBytes, err := json.MarshalIndent(result.Data, "", " ")
- if err != nil {
- if jsonOutput {
- return errors.WrapIf(err, "failed to marshal JSON")
- }
- return errors.WrapIff(err, "%s", cfg.marshalMessage)
- }
-
- if jsonOutput {
- fmt.Println(string(resultBytes))
- return nil
- }
-
- output.Header("%s", cfg.header)
- fmt.Println(string(resultBytes))
- return nil
+ return errors.WrapIff(cmdutil.PrintJSON(result.Data), "%s", cfg.marshalMessage)
}
var usageCmd = &cobra.Command{
@@ -350,38 +275,22 @@ var usageCmd = &cobra.Command{
}
allowPrompt := !jsonOutput && prompt.IsInteractive()
- resolved, err := resolveVolume(cmd.Context(), c, args[0], allowPrompt)
+ resolved, _, err := volumeRef.Resolve(cmd.Context(), c, args[0], allowPrompt)
if err != nil {
return err
}
- resp, err := c.Get(cmd.Context(), types.VolumeUsage(c.EnvID(), resolved.Name))
+ result, err := c.GetJSON[any](cmd.Context(), types.VolumeUsage(c.EnvID(), resolved.Name))
if err != nil {
return errors.WrapIf(err, "failed to get volume usage")
}
- defer func() { _ = resp.Body.Close() }()
-
- var result base.ApiResponse[any]
- if err := cmdutil.DecodeJSON(resp, &result); err != nil {
- return err
- }
if jsonOutput {
- resultBytes, err := json.MarshalIndent(result.Data, "", " ")
- if err != nil {
- return errors.WrapIf(err, "failed to marshal JSON")
- }
- fmt.Println(string(resultBytes))
- return nil
+ return cmdutil.PrintJSON(result.Data)
}
output.Header("Volume Usage: %s", resolved.Name)
- resultBytes, err := json.MarshalIndent(result.Data, "", " ")
- if err != nil {
- return errors.WrapIf(err, "failed to marshal volume usage")
- }
- fmt.Println(string(resultBytes))
- return nil
+ return cmdutil.PrintJSON(result.Data)
},
}
@@ -420,28 +329,13 @@ var createCmd = &cobra.Command{
}
}
- path := types.Volumes(c.EnvID())
- resp, err := c.Post(cmd.Context(), path, req)
+ result, err := c.PostJSON[volume.Volume](cmd.Context(), types.Volumes(c.EnvID()), req)
if err != nil {
return errors.WrapIf(err, "failed to create volume")
}
- defer func() { _ = resp.Body.Close() }()
- if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
- return errors.WrapIf(err, "failed to create volume")
- }
-
- var result base.ApiResponse[volume.Volume]
- if err := cmdutil.DecodeJSON(resp, &result); err != nil {
- return err
- }
if jsonOutput {
- resultBytes, err := json.MarshalIndent(result.Data, "", " ")
- if err != nil {
- return errors.WrapIf(err, "failed to marshal JSON")
- }
- fmt.Println(string(resultBytes))
- return nil
+ return cmdutil.PrintJSON(result.Data)
}
output.Success("Volume %s created successfully", result.Data.Name)
@@ -496,92 +390,21 @@ func init() {
_ = createCmd.MarkFlagRequired("name")
}
-func resolveVolume(ctx context.Context, c *client.Client, identifier string, allowPrompt bool) (*volume.Volume, error) {
- trimmed := strings.TrimSpace(identifier)
- if trimmed == "" {
- return nil, errors.New("volume identifier is required")
- }
-
- resp, err := c.Get(ctx, types.Volume(c.EnvID(), trimmed))
- if err != nil {
- return nil, errors.WrapIff(err, "failed to resolve volume %q", trimmed)
- }
-
- body, err := io.ReadAll(resp.Body)
- _ = resp.Body.Close()
- if err != nil {
- return nil, errors.WrapIf(err, "failed to read volume response")
- }
-
- if resp.StatusCode == http.StatusOK {
- var result base.ApiResponse[volume.Volume]
- if err := json.Unmarshal(body, &result); err != nil {
- return nil, errors.WrapIf(err, "failed to parse volume response")
- }
- return &result.Data, nil
- }
-
- if resp.StatusCode != http.StatusNotFound {
- return nil, errors.Errorf("failed to resolve volume %q (status %d): %s", trimmed, resp.StatusCode, strings.TrimSpace(string(body)))
- }
-
- searchPath := fmt.Sprintf("%s?search=%s&limit=%d", types.Volumes(c.EnvID()), url.QueryEscape(trimmed), cmdutil.ShowAllLimit)
- searchResp, err := c.Get(ctx, searchPath)
- if err != nil {
- return nil, errors.WrapIf(err, "failed to search volumes")
- }
-
- searchBody, err := io.ReadAll(searchResp.Body)
- _ = searchResp.Body.Close()
- if err != nil {
- return nil, errors.WrapIf(err, "failed to read volumes response")
- }
-
- if searchResp.StatusCode < 200 || searchResp.StatusCode >= 300 {
- return nil, errors.Errorf("failed to search volumes (status %d): %s", searchResp.StatusCode, strings.TrimSpace(string(searchBody)))
- }
-
- var result base.Paginated[volume.Volume]
- if err := json.Unmarshal(searchBody, &result); err != nil {
- return nil, errors.WrapIf(err, "failed to parse volumes response")
- }
-
- identifierLower := strings.ToLower(trimmed)
- matches := make([]volume.Volume, 0)
- for _, item := range result.Data {
- if volumeMatches(item, identifierLower, trimmed) {
- matches = append(matches, item)
- }
- }
-
- if len(matches) == 1 {
- return &matches[0], nil
- }
-
- if len(matches) > 1 {
- if !allowPrompt {
- return nil, errors.Errorf("multiple volumes match %q; use the volume name or run `arcane volumes list`", trimmed)
- }
- if len(matches) > maxPromptOptions {
- return nil, errors.Errorf("multiple volumes match %q (%d results); refine your query or use the volume name", trimmed, len(matches))
- }
-
- options := make([]string, 0, len(matches))
- for _, match := range matches {
- label := match.Name
- if match.Driver != "" {
- label = fmt.Sprintf("%s (%s)", match.Name, match.Driver)
- }
- options = append(options, label)
- }
- choice, err := prompt.Select("volume", options)
- if err != nil {
- return nil, err
- }
- return &matches[choice], nil
- }
-
- return nil, errors.Errorf("volume %q not found; use the volume name or run `arcane volumes list`", trimmed)
+var volumeRef = cmdutil.ResourceRef[volume.Volume, volume.Volume]{
+ Singular: "volume",
+ Plural: "volumes",
+ IDHint: "the volume name",
+ ListCmd: "arcane volumes list",
+ GetPath: types.Volume,
+ ListPath: types.Volumes,
+ Matches: volumeMatches,
+ Label: func(match volume.Volume) string {
+ if match.Driver != "" {
+ return fmt.Sprintf("%s (%s)", match.Name, match.Driver)
+ }
+ return match.Name
+ },
+ Promote: func(match volume.Volume) *volume.Volume { return &match },
}
func volumeMatches(item volume.Volume, identifierLower, original string) bool {
diff --git a/cli/pkg/volumes/workspace.go b/cli/pkg/volumes/workspace.go
index 334b4d792..63e521287 100644
--- a/cli/pkg/volumes/workspace.go
+++ b/cli/pkg/volumes/workspace.go
@@ -2,7 +2,7 @@ package volumes
import (
"bytes"
- "encoding/json"
+ "encoding/json/v2"
"fmt"
"mime/multipart"
"net/http"
@@ -15,7 +15,6 @@ import (
"emperror.dev/errors"
- "github.com/getarcaneapp/arcane/cli/v2/internal/client"
"github.com/getarcaneapp/arcane/cli/v2/internal/cmdutil"
"github.com/getarcaneapp/arcane/cli/v2/internal/output"
"github.com/getarcaneapp/arcane/cli/v2/internal/prompt"
@@ -32,13 +31,13 @@ var workspaceCmd = &cobra.Command{
Args: cobra.RangeArgs(1, 2),
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
- c, err := client.NewFromConfig()
+ c, err := cmdutil.ClientFromCommand(cmd)
if err != nil {
return err
}
allowPrompt := !jsonOutput && prompt.IsInteractive()
- resolved, err := resolveVolume(cmd.Context(), c, args[0], allowPrompt)
+ resolved, _, err := volumeRef.Resolve(cmd.Context(), c, args[0], allowPrompt)
if err != nil {
return err
}
@@ -110,13 +109,13 @@ var workspaceCatCmd = &cobra.Command{
Args: cobra.ExactArgs(2),
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
- c, err := client.NewFromConfig()
+ c, err := cmdutil.ClientFromCommand(cmd)
if err != nil {
return err
}
allowPrompt := !jsonOutput && prompt.IsInteractive()
- resolved, err := resolveVolume(cmd.Context(), c, args[0], allowPrompt)
+ resolved, _, err := volumeRef.Resolve(cmd.Context(), c, args[0], allowPrompt)
if err != nil {
return err
}
@@ -158,13 +157,13 @@ var workspaceDownloadCmd = &cobra.Command{
Args: cobra.RangeArgs(2, 3),
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
- c, err := client.NewFromConfig()
+ c, err := cmdutil.ClientFromCommand(cmd)
if err != nil {
return err
}
allowPrompt := prompt.IsInteractive()
- resolved, err := resolveVolume(cmd.Context(), c, args[0], allowPrompt)
+ resolved, _, err := volumeRef.Resolve(cmd.Context(), c, args[0], allowPrompt)
if err != nil {
return err
}
@@ -208,13 +207,13 @@ var workspacePutCmd = &cobra.Command{
Args: cobra.ExactArgs(3),
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
- c, err := client.NewFromConfig()
+ c, err := cmdutil.ClientFromCommand(cmd)
if err != nil {
return err
}
allowPrompt := !forceFlag && prompt.IsInteractive()
- resolved, err := resolveVolume(cmd.Context(), c, args[0], allowPrompt)
+ resolved, _, err := volumeRef.Resolve(cmd.Context(), c, args[0], allowPrompt)
if err != nil {
return err
}
diff --git a/cli/pkg/vulnerabilities/cmd.go b/cli/pkg/vulnerabilities/cmd.go
index cb1bf01b2..9516379e2 100644
--- a/cli/pkg/vulnerabilities/cmd.go
+++ b/cli/pkg/vulnerabilities/cmd.go
@@ -9,10 +9,7 @@ package vulnerabilities
import (
"context"
- "encoding/json"
"fmt"
- "io"
- "net/http"
"net/url"
"strings"
"time"
@@ -23,8 +20,7 @@ import (
"github.com/getarcaneapp/arcane/cli/v2/internal/cmdutil"
"github.com/getarcaneapp/arcane/cli/v2/internal/output"
"github.com/getarcaneapp/arcane/cli/v2/internal/types"
- "github.com/getarcaneapp/arcane/types/v2/base"
- "github.com/getarcaneapp/arcane/types/v2/image"
+ "github.com/getarcaneapp/arcane/cli/v2/pkg/images"
"github.com/getarcaneapp/arcane/types/v2/vulnerability"
"github.com/spf13/cobra"
)
@@ -62,21 +58,12 @@ var statusCmd = &cobra.Command{
return err
}
- resp, err := c.Get(cmd.Context(), types.VulnerabilitiesScannerStatus(c.EnvID()))
- if err != nil {
- return errors.WrapIf(err, "failed to get scanner status")
- }
- defer func() { _ = resp.Body.Close() }()
- if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
- return errors.WrapIf(err, "failed to get scanner status")
- }
-
- var result base.ApiResponse[struct {
+ result, err := c.GetJSON[struct {
Available bool `json:"available"`
Version string `json:"version,omitempty"`
- }]
- if err := cmdutil.DecodeJSON(resp, &result); err != nil {
- return err
+ }](cmd.Context(), types.VulnerabilitiesScannerStatus(c.EnvID()))
+ if err != nil {
+ return errors.WrapIf(err, "failed to get scanner status")
}
if jsonOutput {
@@ -102,19 +89,10 @@ var summaryCmd = &cobra.Command{
return err
}
- resp, err := c.Get(cmd.Context(), types.VulnerabilitiesSummary(c.EnvID()))
+ result, err := c.GetJSON[vulnerability.EnvironmentVulnerabilitySummary](cmd.Context(), types.VulnerabilitiesSummary(c.EnvID()))
if err != nil {
return errors.WrapIf(err, "failed to get vulnerability summary")
}
- defer func() { _ = resp.Body.Close() }()
- if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
- return errors.WrapIf(err, "failed to get vulnerability summary")
- }
-
- var result base.ApiResponse[vulnerability.EnvironmentVulnerabilitySummary]
- if err := cmdutil.DecodeJSON(resp, &result); err != nil {
- return err
- }
if jsonOutput {
return cmdutil.PrintJSON(result.Data)
@@ -139,17 +117,6 @@ var listCmd = &cobra.Command{
return err
}
- path, err := cmdutil.ApplyPaginationParams(cmd, types.VulnerabilitiesAll(c.EnvID()), cmdutil.ListParams{
- Resource: "vulnerabilities",
- Limit: limitFlag,
- FallbackDefault: 20,
- Start: startFlag,
- All: allFlag,
- })
- if err != nil {
- return errors.WrapIf(err, "failed to build pagination query")
- }
-
query := url.Values{}
if severityFlag != "" {
query.Set("severity", strings.ToUpper(severityFlag))
@@ -157,46 +124,25 @@ var listCmd = &cobra.Command{
if imageFlag != "" {
query.Set("imageName", imageFlag)
}
- if len(query) > 0 {
- path = cmdutil.AppendQuery(path, query)
- }
-
- resp, err := c.Get(cmd.Context(), path)
- if err != nil {
- return errors.WrapIf(err, "failed to list vulnerabilities")
- }
- defer func() { _ = resp.Body.Close() }()
-
- body, err := cmdutil.ReadJSONBody(resp)
- if err != nil {
- return errors.WrapIf(err, "failed to list vulnerabilities")
- }
-
- if jsonOutput {
- return cmdutil.PrintRawJSON(body)
- }
-
- var result base.Paginated[vulnerability.VulnerabilityWithImage]
- if err := json.Unmarshal(body, &result); err != nil {
- return errors.WrapIf(err, "failed to parse response")
- }
-
- headers := []string{"CVE ID", "SEVERITY", "IMAGE", "PACKAGE", "VERSION", "FIXED IN"}
- rows := make([][]string, len(result.Data))
- for i, item := range result.Data {
- rows[i] = []string{
- item.VulnerabilityID,
- string(item.Severity),
- item.ImageName,
- item.PkgName,
- item.InstalledVersion,
- orDash(item.FixedVersion),
- }
- }
- output.Table(headers, rows)
- output.Showing(len(result.Data), result.Pagination.TotalItems, "vulnerabilities")
- return nil
+ return cmdutil.RunList(cmd, c, cmdutil.ListSpec[vulnerability.VulnerabilityWithImage]{
+ Resource: "vulnerabilities",
+ Endpoint: types.VulnerabilitiesAll(c.EnvID()),
+ Params: cmdutil.ListParams{Resource: "vulnerabilities", Limit: limitFlag, FallbackDefault: 20, Start: startFlag, All: allFlag},
+ Query: query,
+ JSON: jsonOutput,
+ Headers: []string{"CVE ID", "SEVERITY", "IMAGE", "PACKAGE", "VERSION", "FIXED IN"},
+ Row: func(item vulnerability.VulnerabilityWithImage) []string {
+ return []string{
+ item.VulnerabilityID,
+ string(item.Severity),
+ item.ImageName,
+ item.PkgName,
+ item.InstalledVersion,
+ orDash(item.FixedVersion),
+ }
+ },
+ })
},
}
@@ -219,19 +165,10 @@ var scanCmd = &cobra.Command{
// Scans can take a long time on large images.
c.SetTimeout(30 * time.Minute)
- resp, err := c.Post(cmd.Context(), types.ImageVulnerabilitiesScan(c.EnvID(), imageID), nil)
+ result, err := c.PostJSON[vulnerability.ScanResult](cmd.Context(), types.ImageVulnerabilitiesScan(c.EnvID(), imageID), nil)
if err != nil {
return errors.WrapIf(err, "failed to scan image")
}
- defer func() { _ = resp.Body.Close() }()
- if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
- return errors.WrapIf(err, "failed to scan image")
- }
-
- var result base.ApiResponse[vulnerability.ScanResult]
- if err := cmdutil.DecodeJSON(resp, &result); err != nil {
- return err
- }
if jsonOutput {
return cmdutil.PrintJSON(result.Data)
@@ -274,73 +211,36 @@ var imageCmd = &cobra.Command{
return runImageSummary(cmd, c, imageID)
}
- path, err := cmdutil.ApplyPaginationParams(cmd, types.ImageVulnerabilitiesList(c.EnvID(), imageID), cmdutil.ListParams{
- Resource: "vulnerabilities",
- Limit: limitFlag,
- FallbackDefault: 20,
- Start: startFlag,
- All: allFlag,
- })
- if err != nil {
- return errors.WrapIf(err, "failed to build pagination query")
- }
-
+ query := url.Values{}
if severityFlag != "" {
- path = cmdutil.AppendQuery(path, url.Values{"severity": []string{strings.ToUpper(severityFlag)}})
- }
-
- resp, err := c.Get(cmd.Context(), path)
- if err != nil {
- return errors.WrapIf(err, "failed to list image vulnerabilities")
- }
- defer func() { _ = resp.Body.Close() }()
-
- body, err := cmdutil.ReadJSONBody(resp)
- if err != nil {
- return errors.WrapIf(err, "failed to list image vulnerabilities")
- }
-
- if jsonOutput {
- return cmdutil.PrintRawJSON(body)
- }
-
- var result base.Paginated[vulnerability.Vulnerability]
- if err := json.Unmarshal(body, &result); err != nil {
- return errors.WrapIf(err, "failed to parse response")
- }
-
- headers := []string{"CVE ID", "SEVERITY", "PACKAGE", "VERSION", "FIXED IN"}
- rows := make([][]string, len(result.Data))
- for i, item := range result.Data {
- rows[i] = []string{
- item.VulnerabilityID,
- string(item.Severity),
- item.PkgName,
- item.InstalledVersion,
- orDash(item.FixedVersion),
- }
+ query.Set("severity", strings.ToUpper(severityFlag))
}
- output.Table(headers, rows)
- output.Showing(len(result.Data), result.Pagination.TotalItems, "vulnerabilities")
- return nil
+ return cmdutil.RunList(cmd, c, cmdutil.ListSpec[vulnerability.Vulnerability]{
+ Resource: "vulnerabilities",
+ Endpoint: types.ImageVulnerabilitiesList(c.EnvID(), imageID),
+ Params: cmdutil.ListParams{Resource: "vulnerabilities", Limit: limitFlag, FallbackDefault: 20, Start: startFlag, All: allFlag},
+ Query: query,
+ JSON: jsonOutput,
+ Headers: []string{"CVE ID", "SEVERITY", "PACKAGE", "VERSION", "FIXED IN"},
+ Row: func(item vulnerability.Vulnerability) []string {
+ return []string{
+ item.VulnerabilityID,
+ string(item.Severity),
+ item.PkgName,
+ item.InstalledVersion,
+ orDash(item.FixedVersion),
+ }
+ },
+ })
},
}
func runImageSummary(cmd *cobra.Command, c *client.Client, imageID string) error {
- resp, err := c.Get(cmd.Context(), types.ImageVulnerabilitiesSummary(c.EnvID(), imageID))
+ result, err := c.GetJSON[vulnerability.ScanSummary](cmd.Context(), types.ImageVulnerabilitiesSummary(c.EnvID(), imageID))
if err != nil {
return errors.WrapIf(err, "failed to get image vulnerability summary")
}
- defer func() { _ = resp.Body.Close() }()
- if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
- return errors.WrapIf(err, "failed to get image vulnerability summary")
- }
-
- var result base.ApiResponse[vulnerability.ScanSummary]
- if err := cmdutil.DecodeJSON(resp, &result); err != nil {
- return err
- }
if jsonOutput {
return cmdutil.PrintJSON(result.Data)
@@ -386,19 +286,10 @@ var ignoreCmd = &cobra.Command{
payload.Reason = &ignoreReasonFlag
}
- resp, err := c.Post(cmd.Context(), types.VulnerabilitiesIgnore(c.EnvID()), payload)
+ result, err := c.PostJSON[vulnerability.IgnoredVulnerability](cmd.Context(), types.VulnerabilitiesIgnore(c.EnvID()), payload)
if err != nil {
return errors.WrapIf(err, "failed to ignore vulnerability")
}
- defer func() { _ = resp.Body.Close() }()
- if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
- return errors.WrapIf(err, "failed to ignore vulnerability")
- }
-
- var result base.ApiResponse[vulnerability.IgnoredVulnerability]
- if err := cmdutil.DecodeJSON(resp, &result); err != nil {
- return err
- }
if jsonOutput {
return cmdutil.PrintJSON(result.Data)
@@ -420,57 +311,27 @@ var ignoredCmd = &cobra.Command{
return err
}
- path, err := cmdutil.ApplyPaginationParams(cmd, types.VulnerabilitiesIgnored(c.EnvID()), cmdutil.ListParams{
- Resource: "vulnerabilities",
- Limit: limitFlag,
- FallbackDefault: 20,
- Start: startFlag,
- All: allFlag,
+ return cmdutil.RunList(cmd, c, cmdutil.ListSpec[vulnerability.IgnoredVulnerability]{
+ Resource: "ignored vulnerabilities",
+ Endpoint: types.VulnerabilitiesIgnored(c.EnvID()),
+ Params: cmdutil.ListParams{Resource: "vulnerabilities", Limit: limitFlag, FallbackDefault: 20, Start: startFlag, All: allFlag},
+ JSON: jsonOutput,
+ Headers: []string{"ID", "CVE ID", "IMAGE ID", "PACKAGE", "REASON", "CREATED"},
+ Row: func(item vulnerability.IgnoredVulnerability) []string {
+ reason := ""
+ if item.Reason != nil {
+ reason = *item.Reason
+ }
+ return []string{
+ item.ID,
+ item.VulnerabilityID,
+ shortImageID(item.ImageID),
+ item.PkgName,
+ orDash(reason),
+ item.CreatedAt.Format(time.RFC3339),
+ }
+ },
})
- if err != nil {
- return errors.WrapIf(err, "failed to build pagination query")
- }
-
- resp, err := c.Get(cmd.Context(), path)
- if err != nil {
- return errors.WrapIf(err, "failed to list ignored vulnerabilities")
- }
- defer func() { _ = resp.Body.Close() }()
-
- body, err := cmdutil.ReadJSONBody(resp)
- if err != nil {
- return errors.WrapIf(err, "failed to list ignored vulnerabilities")
- }
-
- if jsonOutput {
- return cmdutil.PrintRawJSON(body)
- }
-
- var result base.Paginated[vulnerability.IgnoredVulnerability]
- if err := json.Unmarshal(body, &result); err != nil {
- return errors.WrapIf(err, "failed to parse response")
- }
-
- headers := []string{"ID", "CVE ID", "IMAGE ID", "PACKAGE", "REASON", "CREATED"}
- rows := make([][]string, len(result.Data))
- for i, item := range result.Data {
- reason := ""
- if item.Reason != nil {
- reason = *item.Reason
- }
- rows[i] = []string{
- item.ID,
- item.VulnerabilityID,
- shortImageID(item.ImageID),
- item.PkgName,
- orDash(reason),
- item.CreatedAt.Format(time.RFC3339),
- }
- }
-
- output.Table(headers, rows)
- output.Showing(len(result.Data), result.Pagination.TotalItems, "ignored vulnerabilities")
- return nil
},
}
@@ -496,12 +357,7 @@ var unignoreCmd = &cobra.Command{
return err
}
- resp, err := c.Delete(cmd.Context(), types.VulnerabilityIgnore(c.EnvID(), args[0]))
- if err != nil {
- return errors.WrapIf(err, "failed to remove ignore record")
- }
- defer func() { _ = resp.Body.Close() }()
- if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
+ if _, err := c.DeleteJSON[struct{}](cmd.Context(), types.VulnerabilityIgnore(c.EnvID(), args[0])); err != nil {
return errors.WrapIf(err, "failed to remove ignore record")
}
@@ -584,88 +440,11 @@ func shortImageID(id string) string {
}
// resolveImageID resolves an image name, tag, or (partial) ID to a full image
-// ID. It first tries a direct lookup and falls back to a server-side search.
+// ID via the shared images resolver.
func resolveImageID(ctx context.Context, c *client.Client, identifier string) (string, error) {
- trimmed := strings.TrimSpace(identifier)
- if trimmed == "" {
- return "", errors.New("image identifier is required")
- }
-
- resp, err := c.Get(ctx, types.Image(c.EnvID(), trimmed))
- if err != nil {
- return "", errors.WrapIff(err, "failed to resolve image %q", trimmed)
- }
-
- body, err := io.ReadAll(resp.Body)
- _ = resp.Body.Close()
- if err != nil {
- return "", errors.WrapIf(err, "failed to read image response")
- }
-
- if resp.StatusCode == http.StatusOK {
- var result base.ApiResponse[image.DetailSummary]
- if err := json.Unmarshal(body, &result); err != nil {
- return "", errors.WrapIf(err, "failed to parse image response")
- }
- if result.Data.ID == "" {
- return "", errors.Errorf("image lookup for %q returned empty ID", trimmed)
- }
- return result.Data.ID, nil
- }
-
- if resp.StatusCode != http.StatusNotFound {
- return "", errors.Errorf("failed to resolve image %q (status %d): %s", trimmed, resp.StatusCode, strings.TrimSpace(string(body)))
- }
-
- searchPath := fmt.Sprintf("%s?search=%s&limit=%d", types.Images(c.EnvID()), url.QueryEscape(trimmed), cmdutil.ShowAllLimit)
- searchResp, err := c.Get(ctx, searchPath)
+ resolved, _, err := images.ImageRef.Resolve(ctx, c, identifier, false)
if err != nil {
- return "", errors.WrapIf(err, "failed to search images")
- }
-
- searchBody, err := cmdutil.ReadJSONBody(searchResp)
- _ = searchResp.Body.Close()
- if err != nil {
- return "", errors.WrapIf(err, "failed to search images")
- }
-
- var result base.Paginated[image.Summary]
- if err := json.Unmarshal(searchBody, &result); err != nil {
- return "", errors.WrapIf(err, "failed to parse images response")
- }
-
- identifierLower := strings.ToLower(trimmed)
- matches := make([]image.Summary, 0)
- for _, item := range result.Data {
- if imageMatches(item, trimmed, identifierLower) {
- matches = append(matches, item)
- }
- }
-
- switch len(matches) {
- case 1:
- return matches[0].ID, nil
- case 0:
- return "", errors.Errorf("image %q not found; use the image ID or run `arcane images list`", trimmed)
- default:
- return "", errors.Errorf("multiple images match %q; use the image ID or run `arcane images list`", trimmed)
- }
-}
-
-func imageMatches(item image.Summary, trimmed, identifierLower string) bool {
- idLower := strings.ToLower(item.ID)
- if idLower == identifierLower || (len(identifierLower) >= 4 && strings.HasPrefix(idLower, identifierLower)) {
- return true
- }
- for _, tag := range item.RepoTags {
- if strings.EqualFold(tag, trimmed) || strings.Contains(strings.ToLower(tag), identifierLower) {
- return true
- }
- }
- for _, digest := range item.RepoDigests {
- if strings.EqualFold(digest, trimmed) || strings.Contains(strings.ToLower(digest), identifierLower) {
- return true
- }
+ return "", err
}
- return false
+ return resolved.ID, nil
}
diff --git a/cli/pkg/webhooks/cmd.go b/cli/pkg/webhooks/cmd.go
index cba546a8f..0d574b3b8 100644
--- a/cli/pkg/webhooks/cmd.go
+++ b/cli/pkg/webhooks/cmd.go
@@ -3,7 +3,6 @@
package webhooks
import (
- "encoding/json"
"fmt"
"net/http"
"time"
@@ -46,24 +45,13 @@ var listCmd = &cobra.Command{
return err
}
- resp, err := c.Get(cmd.Context(), types.Webhooks(c.EnvID()))
- if err != nil {
- return errors.WrapIf(err, "failed to list webhooks")
- }
- defer func() { _ = resp.Body.Close() }()
-
- body, err := cmdutil.ReadJSONBody(resp)
+ result, err := c.GetJSON[[]webhook.Summary](cmd.Context(), types.Webhooks(c.EnvID()))
if err != nil {
return errors.WrapIf(err, "failed to list webhooks")
}
if jsonOutput {
- return cmdutil.PrintRawJSON(body)
- }
-
- var result base.ApiResponse[[]webhook.Summary]
- if err := json.Unmarshal(body, &result); err != nil {
- return errors.WrapIf(err, "failed to parse response")
+ return cmdutil.PrintJSON(result.Data)
}
headers := []string{"ID", "NAME", "ACTION", "TARGET", "TOKEN", "ENABLED", "LAST TRIGGERED"}
@@ -111,16 +99,10 @@ var createCmd = &cobra.Command{
TargetID: createTargetID,
}
- resp, err := c.Post(cmd.Context(), types.Webhooks(c.EnvID()), req)
+ result, err := c.PostJSON[webhook.Created](cmd.Context(), types.Webhooks(c.EnvID()), req)
if err != nil {
return errors.WrapIf(err, "failed to create webhook")
}
- defer func() { _ = resp.Body.Close() }()
-
- var result base.ApiResponse[webhook.Created]
- if err := cmdutil.DecodeJSON(resp, &result); err != nil {
- return errors.WrapIf(err, "failed to create webhook")
- }
if jsonOutput {
return cmdutil.PrintJSON(result.Data)
@@ -157,12 +139,7 @@ var updateCmd = &cobra.Command{
}
req := webhook.UpdateInput{Enabled: updateEnabled}
- resp, err := c.Request(cmd.Context(), http.MethodPatch, types.Webhook(c.EnvID(), args[0]), req)
- if err != nil {
- return errors.WrapIf(err, "failed to update webhook")
- }
- defer func() { _ = resp.Body.Close() }()
- if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
+ if _, err := c.DoJSON[base.ApiResponse[any]](cmd.Context(), http.MethodPatch, types.Webhook(c.EnvID(), args[0]), req); err != nil {
return errors.WrapIf(err, "failed to update webhook")
}
@@ -202,12 +179,7 @@ var deleteCmd = &cobra.Command{
return err
}
- resp, err := c.Delete(cmd.Context(), types.Webhook(c.EnvID(), args[0]))
- if err != nil {
- return errors.WrapIf(err, "failed to delete webhook")
- }
- defer func() { _ = resp.Body.Close() }()
- if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
+ if _, err := c.DeleteJSON[any](cmd.Context(), types.Webhook(c.EnvID(), args[0])); err != nil {
return errors.WrapIf(err, "failed to delete webhook")
}
@@ -228,13 +200,7 @@ var triggerCmd = &cobra.Command{
return err
}
- resp, err := c.Post(cmd.Context(), types.WebhookTrigger(args[0]), nil)
- if err != nil {
- return errors.WrapIf(err, "failed to trigger webhook")
- }
- defer func() { _ = resp.Body.Close() }()
-
- body, err := cmdutil.ReadJSONBody(resp)
+ body, err := c.DoRaw(cmd.Context(), http.MethodPost, types.WebhookTrigger(args[0]), nil)
if err != nil {
return errors.WrapIf(err, "failed to trigger webhook")
}
diff --git a/go.work.sum b/go.work.sum
index 57cde482d..cc02aac4e 100644
--- a/go.work.sum
+++ b/go.work.sum
@@ -1427,6 +1427,8 @@ github.com/google/go-containerregistry v0.20.6/go.mod h1:T0x8MuoAoKX/873bkeSfLD2
github.com/google/go-containerregistry v0.20.7/go.mod h1:Lx5LCZQjLH1QBaMPeGwsME9biPeo1lPx6lbGj/UmzgM=
github.com/google/go-containerregistry v0.21.6/go.mod h1:U7MMSBIJynke2MVQrQk19NP9k/uQsGz/h0amIFSHMbo=
github.com/google/go-containerregistry v0.21.7/go.mod h1:kjSbt7/zMsKLWfnHrIvKvhXHUw91jbe9DNjPPJ32gXE=
+github.com/google/go-containerregistry v0.21.9 h1:F+D4uZ3iA3DLMJLfhaqMdHJbzeqm/216WGQq2dokuLs=
+github.com/google/go-containerregistry v0.21.9/go.mod h1:dP5XNKcL7kMFF/TB3LfvWmVhAcv7iqkHb3oDK8aauTo=
github.com/google/go-dap v0.12.0 h1:rVcjv3SyMIrpaOoTAdFDyHs99CwVOItIJGKLQFQhNeM=
github.com/google/go-dap v0.12.0/go.mod h1:tNjCASCm5cqePi/RVXXWEVqtnNLV1KTWtYOqu6rZNzc=
github.com/google/go-dap v0.12.1-0.20250904181021-d7a2259b058b h1:m+yLjBIoXaMKk6pwd1IJYYgM76+mwcy7J9+cuY7LqmQ=
@@ -2526,10 +2528,15 @@ go.etcd.io/raft/v3 v3.6.0/go.mod h1:nLvLevg6+xrVtHUmVaTcTz603gQPHfh7kUAwV6YpfGo=
go.getarcane.app/acfs v0.2.0 h1:m7yXsLIB4MfsAE/AFP54RgtMXUr+AFEVCNiF5784XYI=
go.getarcane.app/acfs v0.2.0/go.mod h1:sU3t21KctTsQM3OW10+RNB0Z6lR+YfaSr5Nxubq3cpI=
go.getarcane.app/acfs v0.4.1/go.mod h1:sU3t21KctTsQM3OW10+RNB0Z6lR+YfaSr5Nxubq3cpI=
+go.getarcane.app/acfs v0.4.2/go.mod h1:58JU/5d9TIawZrRvtND1jBmcDy6DrUP0FLhXklmrRjY=
go.getarcane.app/builds v0.3.1 h1:jymgkbcJ98o+XM9P0Ympn7m3WowWhG3vbiVwxIhhwns=
go.getarcane.app/builds v0.3.1/go.mod h1:MJXC3VNSspckX6NBu+l7kBaCckuNsXIw4B8WAuxXo94=
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/docker/convert v0.2.0 h1:Mj72F0SkgPxrlDujjHZTnSdzqwyx7PqZwskiIwm1qts=
+go.getarcane.app/docker/convert v0.2.0/go.mod h1:RtKwdUxye+Ildzzc577qngIfhBeKuOM+XUfV9O1yyyg=
+go.getarcane.app/streams v0.4.0 h1:MtBX1SVgt3nrcRNr5SYAvckGp9a5qeSjMTw/LAGwlzk=
+go.getarcane.app/streams v0.4.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/bytes v0.1.0/go.mod h1:R2mujqg+MmC2tr+97IPqaxzvBC8+ykng+5r+XNxwY+8=
@@ -2545,6 +2552,8 @@ go.getarcane.app/updater v0.7.0 h1:Rd6qJGtdJrMJ8SxfGpuP1+ZpJ604BNnhYb9UsB6O0Mg=
go.getarcane.app/updater v0.7.0/go.mod h1:6b8zVFJEUMhLzDOi4jwKBA/GmbVgguv0FeGOoO67JW8=
go.getarcane.app/updater v0.7.2 h1:kJUBUgc7DLgyMD0ZKbGa2FafsTiI+hjJpIFzlI93VUc=
go.getarcane.app/updater v0.7.2/go.mod h1:0zMnkBlRjcKTugKJE03c4ZAx/1HtwgHayFVroHrQcrg=
+go.getarcane.app/updater v0.7.3 h1:0RMN1ossGtsHY6QaycYEI+7piX58cm0i3AbCzcn0qj8=
+go.getarcane.app/updater v0.7.3/go.mod h1:lve1Gq09kl0GSubVWG+QChLKktTR7x2UkHvJ+T2yP78=
go.lsp.dev/jsonrpc2 v0.10.0 h1:Pr/YcXJoEOTMc/b6OTmcR1DPJ3mSWl/SWiU1Cct6VmI=
go.lsp.dev/jsonrpc2 v0.10.0/go.mod h1:fmEzIdXPi/rf6d4uFcayi8HpFP1nBF99ERP1htC72Ac=
go.lsp.dev/pkg v0.0.0-20210717090340-384b27a52fb2 h1:hCzQgh6UcwbKgNSRurYWSqh8MufqRRPODRBblutn4TE=