Skip to content

Modern Docker Management, Designed for Everyone

fix(updater): run container updates through the activity system (#4167)

Kyle Mendell2e35dfda39ed
diff --git a/backend/internal/activity/service.go b/backend/internal/activity/service.go
index ea8a5c83f..5ac022c51 100644
--- a/backend/internal/activity/service.go
+++ b/backend/internal/activity/service.go
@@ -322,7 +322,9 @@ func (s *ActivityService) StartActivity(ctx context.Context, req StartActivityRe
status := activitytypes.StatusRunning
var slotRelease func()
if req.Queue {
- if release, ok := s.limiter.tryAcquireInternal(ctx, environmentID).Get(); ok {
+ if req.DeferSlot {
+ status = activitytypes.StatusQueued
+ } else if release, ok := s.limiter.tryAcquireInternal(ctx, environmentID).Get(); ok {
slotRelease = release
} else {
status = activitytypes.StatusQueued
@@ -366,6 +368,26 @@ func (s *ActivityService) StartActivity(ctx context.Context, req StartActivityRe
return &dto, nil
}
+// StartTrackedActivity holds the cancellation lock across persistence and
+// registration, so cancellation cannot treat the new row as untracked.
+func (s *ActivityService) StartTrackedActivity(ctx context.Context, req StartActivityRequest) (*activitytypes.Activity, context.Context, error) {
+ if err := s.checkInitInternal(); err != nil {
+ return nil, nil, err
+ }
+ s.runningMu.Lock()
+ defer s.runningMu.Unlock()
+ activity, err := s.StartActivity(ctx, req)
+ if err != nil {
+ return nil, nil, err
+ }
+ workCtx, cancel := context.WithCancelCause(ctx)
+ if s.running == nil {
+ s.running = map[string]context.CancelCauseFunc{}
+ }
+ s.running[activity.ID] = cancel
+ return activity, workCtx, nil
+}
+
func (s *ActivityService) registerSlotReleaseInternal(activityID string, release func()) {
s.slotMu.Lock()
if existing, ok := s.slotReleases[activityID]; ok {
@@ -458,6 +480,9 @@ func (s *ActivityService) UpdateActivity(ctx context.Context, activityID string,
if req.Status != "" {
updates["status"] = req.Status
}
+ if req.ResourceName != nil {
+ updates["resource_name"] = strings.TrimSpace(*req.ResourceName)
+ }
if req.Progress != nil {
updates["progress"] = *clampProgressPtrInternal(req.Progress)
}
diff --git a/backend/internal/activity/service_test.go b/backend/internal/activity/service_test.go
index 4034bd0aa..5027c0a3b 100644
--- a/backend/internal/activity/service_test.go
+++ b/backend/internal/activity/service_test.go
@@ -445,6 +445,19 @@ func TestActivityServiceQueuedActivityFlipsToRunningWhenSlotFreesInternal(t *tes
var model Activity
require.NoError(t, service.db.First(&model, "id = ?", second.ID).Error)
require.Equal(t, activitytypes.StatusRunning, model.Status)
+
+ _, err = service.CompleteActivity(ctx, second.ID, activitytypes.StatusSuccess, "done", nil)
+ require.NoError(t, err)
+ firstDeferred, err := service.StartActivity(ctx, StartActivityRequest{EnvironmentID: "0", Type: activitytypes.TypeImagePull, Queue: true, DeferSlot: true})
+ require.NoError(t, err)
+ secondDeferred, err := service.StartActivity(ctx, StartActivityRequest{EnvironmentID: "0", Type: activitytypes.TypeImagePull, Queue: true, DeferSlot: true})
+ require.NoError(t, err)
+ require.Equal(t, activitytypes.StatusQueued, firstDeferred.Status)
+ require.Equal(t, activitytypes.StatusQueued, secondDeferred.Status)
+ require.NoError(t, service.AwaitActivitySlot(ctx, firstDeferred.ID, "0"))
+ _, err = service.CompleteActivity(ctx, firstDeferred.ID, activitytypes.StatusSuccess, "done", nil)
+ require.NoError(t, err)
+ require.NoError(t, service.AwaitActivitySlot(ctx, secondDeferred.ID, "0"))
}
func TestActivityServiceLimitIncreaseKeepsCountingActiveSlotsInternal(t *testing.T) {
diff --git a/backend/internal/auth/huma_middleware.go b/backend/internal/auth/huma_middleware.go
index d982abe96..99ce386b0 100644
--- a/backend/internal/auth/huma_middleware.go
+++ b/backend/internal/auth/huma_middleware.go
@@ -18,6 +18,7 @@ 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/cookie"
+ activitytypes "github.com/getarcaneapp/arcane/types/v2/activity"
)
// securityRequirements holds parsed security requirements from an operation.
@@ -241,9 +242,21 @@ func tryAgentAuthCtxInternal(ctx huma.Context, cfg *config.Config) (huma.Context
return ctx, false
}
applyProxiedIconCatalogInternal(ctx, user)
+ authCtx := setUserInContextInternal(ctx.Context(), user, authz.SudoPermissionSet())
+ updatePath := strings.Contains(ctx.URL().Path, "/containers/") && strings.HasSuffix(ctx.URL().Path, "/update")
+ if ctx.Method() == http.MethodPost && updatePath {
+ if initiatorID := strings.TrimSpace(ctx.Header(utils.HeaderUpdateInitiatorID)); initiatorID != "" {
+ initiator := activitytypes.StartedBy{
+ UserID: initiatorID,
+ Username: strings.TrimSpace(ctx.Header(utils.HeaderUpdateInitiatorName)),
+ DisplayName: strings.TrimSpace(ctx.Header(utils.HeaderUpdateInitiatorDisplayName)),
+ }
+ authCtx = utils.WithUpdateInitiator(authCtx, initiator)
+ }
+ }
// The agent token path is infrastructure-level and not per-user, so it
// gets a sudo PermissionSet that bypasses every check.
- return huma.WithContext(ctx, setUserInContextInternal(ctx.Context(), user, authz.SudoPermissionSet())), true
+ return huma.WithContext(ctx, authCtx), true
}
// opportunisticBearerAuthInternal populates the user/session context if a valid
diff --git a/backend/internal/di/providers.go b/backend/internal/di/providers.go
index 0908b6d48..4610b6c78 100644
--- a/backend/internal/di/providers.go
+++ b/backend/internal/di/providers.go
@@ -326,6 +326,9 @@ func provideProjectServiceInternal(db *database.DB, settings *settings.SettingsS
type updaterServiceParams struct {
fx.In
+ Context context.Context
+ Lifecycle fx.Lifecycle
+ ActorRuntime *actors.Runtime
DB *database.DB
Settings *settings.SettingsService
Docker *docker.DockerClientService
@@ -340,19 +343,29 @@ type updaterServiceParams struct {
}
func provideUpdaterModuleInternal(p updaterServiceParams) (*updater.Module, error) {
- return updater.New(updater.Dependencies{
- DB: p.DB,
- Settings: p.Settings,
- Docker: p.Docker,
- Project: p.Project,
- ImageUpdate: p.ImageUpdate,
- Registry: p.Registry,
- Event: p.Event,
- Image: p.Image,
- Notification: p.Notification,
- SelfUpgrade: p.SystemUpgrade,
- Activity: p.Activity,
+ executor, err := actors.NewExecutor(p.Context, p.ActorRuntime, "updater", "single-container", 3)
+ if err != nil {
+ return nil, err
+ }
+ module, err := updater.New(updater.Dependencies{
+ DB: p.DB,
+ Settings: p.Settings,
+ Docker: p.Docker,
+ Project: p.Project,
+ ImageUpdate: p.ImageUpdate,
+ Registry: p.Registry,
+ Event: p.Event,
+ Image: p.Image,
+ Notification: p.Notification,
+ SelfUpgrade: p.SystemUpgrade,
+ Activity: p.Activity,
+ SingleUpdates: executor,
})
+ if err != nil {
+ return nil, errors.Combine(err, executor.Stop(p.Context))
+ }
+ p.Lifecycle.Append(fx.Hook{OnStop: executor.Stop})
+ return module, nil
}
func provideUserServiceInternal(db *database.DB, role *role.RoleService) *user.UserService {
diff --git a/backend/internal/middleware/environment_middleware.go b/backend/internal/middleware/environment_middleware.go
index 5d627a933..f2b68d6d1 100644
--- a/backend/internal/middleware/environment_middleware.go
+++ b/backend/internal/middleware/environment_middleware.go
@@ -144,6 +144,7 @@ func (m *EnvironmentMiddleware) Handle(c *echo.Context, next echo.HandlerFunc) e
}
m.setIconCatalogHeaderInternal(c, user)
+ m.setUpdateInitiatorHeadersInternal(c, user)
apiURL, accessToken, enabled, err := m.resolver(c.Request().Context(), envID)
if err != nil || apiURL == "" {
@@ -210,6 +211,25 @@ func (m *EnvironmentMiddleware) setIconCatalogHeaderInternal(c *echo.Context, us
c.Request().Header.Set(utils.HeaderIconCatalog, *user.Preferences.IconCatalog)
}
+func (m *EnvironmentMiddleware) setUpdateInitiatorHeadersInternal(c *echo.Context, user *common.User) {
+ headers := c.Request().Header
+ headers.Del(utils.HeaderUpdateInitiatorID)
+ headers.Del(utils.HeaderUpdateInitiatorName)
+ headers.Del(utils.HeaderUpdateInitiatorDisplayName)
+ updatePath := strings.Contains(c.Request().URL.Path, "/containers/") && strings.HasSuffix(c.Request().URL.Path, "/update")
+ if c.Request().Method != http.MethodPost || !updatePath {
+ return
+ }
+ if user == nil || user.ID == "" {
+ return
+ }
+ headers.Set(utils.HeaderUpdateInitiatorID, user.ID)
+ headers.Set(utils.HeaderUpdateInitiatorName, user.Username)
+ if user.DisplayName != nil {
+ headers.Set(utils.HeaderUpdateInitiatorDisplayName, *user.DisplayName)
+ }
+}
+
// proxyPermissionDenied reports whether the caller lacks permission to perform
// the proxied request against environment envID. It mirrors the per-operation
// RequirePermission checks enforced for the local environment: the permission
diff --git a/backend/internal/middleware/environment_middleware_test.go b/backend/internal/middleware/environment_middleware_test.go
index ee7e76a5e..fec7486cb 100644
--- a/backend/internal/middleware/environment_middleware_test.go
+++ b/backend/internal/middleware/environment_middleware_test.go
@@ -337,16 +337,23 @@ func TestEnvironmentMiddleware_ForwardsResolvedIconCatalogHeaderOnly(t *testing.
catalog *string
clientSupplied string
wantHeader string
+ userID string
+ userName string
+ wantInitiator string
}{
- {name: "forwards the caller's preference", catalog: new("dashboard-icons"), wantHeader: "dashboard-icons"},
+ {name: "forwards the caller's preference", catalog: new("dashboard-icons"), wantHeader: "dashboard-icons", userID: "user-1", userName: "operator", wantInitiator: "user-1"},
{name: "strips a client-supplied header when the caller has no preference", clientSupplied: "dashboard-icons", wantHeader: ""},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var forwarded string
+ var forwardedInitiator string
+ var forwardedName string
backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
forwarded = r.Header.Get(utils.HeaderIconCatalog)
+ forwardedInitiator = r.Header.Get(utils.HeaderUpdateInitiatorID)
+ forwardedName = r.Header.Get(utils.HeaderUpdateInitiatorName)
w.WriteHeader(http.StatusOK)
}))
defer backend.Close()
@@ -361,6 +368,8 @@ func TestEnvironmentMiddleware_ForwardsResolvedIconCatalogHeaderOnly(t *testing.
authValidator: func(ctx context.Context, c *echo.Context) (*authz.PermissionSet, *common.User, bool) {
_, _ = ctx, c
u := &common.User{}
+ u.ID = tt.userID
+ u.Username = tt.userName
u.Preferences.IconCatalog = tt.catalog
return authz.SudoPermissionSet(), u, true
},
@@ -370,11 +379,13 @@ func TestEnvironmentMiddleware_ForwardsResolvedIconCatalogHeaderOnly(t *testing.
router := echo.New()
api := attachMiddleware(router, mw)
- api.GET("/environments/:id/containers", func(c *echo.Context) error {
+ api.POST("/environments/:id/containers/:containerId/update", func(c *echo.Context) error {
return c.JSON(http.StatusOK, map[string]any{"success": true})
})
- req := httptest.NewRequest(http.MethodGet, "/api/environments/env-remote/containers", nil)
+ req := httptest.NewRequest(http.MethodPost, "/api/environments/env-remote/containers/container-1/update", nil)
+ req.Header.Set(utils.HeaderUpdateInitiatorID, "spoofed")
+ req.Header.Set(utils.HeaderUpdateInitiatorName, "spoofed")
if tt.clientSupplied != "" {
req.Header.Set(utils.HeaderIconCatalog, tt.clientSupplied)
}
@@ -383,6 +394,8 @@ func TestEnvironmentMiddleware_ForwardsResolvedIconCatalogHeaderOnly(t *testing.
require.Equal(t, http.StatusOK, recorder.Code)
assert.Equal(t, tt.wantHeader, forwarded)
+ assert.Equal(t, tt.wantInitiator, forwardedInitiator)
+ assert.Equal(t, tt.userName, forwardedName)
})
}
}
diff --git a/backend/internal/updater/handler.go b/backend/internal/updater/handler.go
index 2df50d67a..a87cb133f 100644
--- a/backend/internal/updater/handler.go
+++ b/backend/internal/updater/handler.go
@@ -3,6 +3,7 @@ package updater
import (
"context"
"net/http"
+ "reflect"
"emperror.dev/errors"
"github.com/danielgtaylor/huma/v2"
@@ -11,6 +12,7 @@ import (
"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"
+ activitytypes "github.com/getarcaneapp/arcane/types/v2/activity"
"github.com/getarcaneapp/arcane/types/v2/base"
projecttypes "github.com/getarcaneapp/arcane/types/v2/project"
"github.com/getarcaneapp/arcane/types/v2/updater"
@@ -32,6 +34,12 @@ type RunUpdaterInput struct {
type UpdateContainerInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
ContainerID string `path:"containerId" doc:"Container ID to update"`
+ Async bool `query:"async" doc:"Return an accepted activity immediately instead of waiting for the update"`
+}
+
+type updateContainerOutput struct {
+ Status int
+ Body base.ApiResponse[any]
}
type GetUpdaterStatusInput struct {
@@ -85,6 +93,8 @@ func RegisterUpdater(api huma.API, updaterService *UpdaterService, appCtx handle
Security: handlerutil.DefaultOperationSecurity(),
}, authz.PermImageUpdatesRead, h.GetUpdaterHistory)
+ acceptedSchema := huma.SchemaFromType(api.OpenAPI().Components.Schemas, reflect.TypeFor[base.ApiResponse[activitytypes.Activity]]())
+ completedSchema := huma.SchemaFromType(api.OpenAPI().Components.Schemas, reflect.TypeFor[base.ApiResponse[*updater.Result]]())
middleware.RegisterWithPermission(api, huma.Operation{
OperationID: "update-container",
Method: http.MethodPost,
@@ -93,7 +103,11 @@ func RegisterUpdater(api huma.API, updaterService *UpdaterService, appCtx handle
Description: "Pull the latest image and apply the appropriate update strategy for a specific container",
Tags: []string{"Updater", "Containers"},
Security: handlerutil.DefaultOperationSecurity(),
- }, authz.PermImageUpdatesCheck, h.UpdateContainer)
+ Responses: map[string]*huma.Response{
+ "200": {Description: "Container update completed", Content: map[string]*huma.MediaType{"application/json": {Schema: completedSchema}}},
+ "202": {Description: "Container update accepted", Content: map[string]*huma.MediaType{"application/json": {Schema: acceptedSchema}}},
+ },
+ }, authz.PermImageUpdatesCheck, h.updateContainerInternal)
}
// RunUpdater applies pending container updates.
@@ -152,16 +166,26 @@ func (h *UpdaterHandler) GetUpdaterHistory(ctx context.Context, input *GetUpdate
}, nil
}
-// 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) (*handlerutil.Out[*updater.Result], error) {
+func (h *UpdaterHandler) updateContainerInternal(ctx context.Context, input *UpdateContainerInput) (*updateContainerOutput, error) {
runtimeCtx := utils.ActivityRuntimeContext(ctx, h.appCtx)
+ if input.Async {
+ activity, err := h.updaterService.AcceptSingleContainerUpdate(runtimeCtx, input.ContainerID)
+ if err != nil {
+ return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to accept container update").Error())
+ }
+ return &updateContainerOutput{
+ Status: http.StatusAccepted,
+ Body: base.ApiResponse[any]{Success: true, Data: activity},
+ }, nil
+ }
out, err := h.updaterService.UpdateSingleContainer(runtimeCtx, input.ContainerID)
if err != nil {
return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to run updater").Error())
}
- return &handlerutil.Out[*updater.Result]{
- Body: base.ApiResponse[*updater.Result]{
+ return &updateContainerOutput{
+ Status: http.StatusOK,
+ Body: base.ApiResponse[any]{
Success: true,
Data: out,
},
diff --git a/backend/internal/updater/module.go b/backend/internal/updater/module.go
index 250495b37..73bf8d48c 100644
--- a/backend/internal/updater/module.go
+++ b/backend/internal/updater/module.go
@@ -6,6 +6,7 @@ import (
"github.com/danielgtaylor/huma/v2"
"github.com/getarcaneapp/arcane/backend/v2/internal/activity"
+ "github.com/getarcaneapp/arcane/backend/v2/internal/actors"
"github.com/getarcaneapp/arcane/backend/v2/internal/database"
"github.com/getarcaneapp/arcane/backend/v2/internal/docker"
"github.com/getarcaneapp/arcane/backend/v2/internal/event"
@@ -20,17 +21,18 @@ import (
// Dependencies are the collaborators the updater domain needs.
type Dependencies struct {
- DB *database.DB
- Settings *settings.SettingsService
- Docker *docker.DockerClientService
- Project *project.ProjectService
- ImageUpdate *imageupdate.ImageUpdateService
- Registry *registry.ContainerRegistryService
- Event *event.EventService
- Image *image.ImageService
- Notification *notification.NotificationService
- SelfUpgrade selfUpgradeServiceInternal
- Activity *activity.ActivityService
+ DB *database.DB
+ Settings *settings.SettingsService
+ Docker *docker.DockerClientService
+ Project *project.ProjectService
+ ImageUpdate *imageupdate.ImageUpdateService
+ Registry *registry.ContainerRegistryService
+ Event *event.EventService
+ Image *image.ImageService
+ Notification *notification.NotificationService
+ SelfUpgrade selfUpgradeServiceInternal
+ Activity *activity.ActivityService
+ SingleUpdates *actors.Executor
}
// Module wires the updater domain and mounts its routes.
@@ -56,6 +58,7 @@ func New(deps Dependencies) (*Module, error) {
if err != nil {
return nil, err
}
+ service.singleUpdates = deps.SingleUpdates
return &Module{service: service}, nil
}
diff --git a/backend/internal/updater/service.go b/backend/internal/updater/service.go
index 19eda88ed..d96586ac6 100644
--- a/backend/internal/updater/service.go
+++ b/backend/internal/updater/service.go
@@ -19,6 +19,7 @@ import (
"emperror.dev/errors"
"github.com/getarcaneapp/arcane/backend/v2/internal/activity"
+ "github.com/getarcaneapp/arcane/backend/v2/internal/actors"
"github.com/getarcaneapp/arcane/backend/v2/internal/common"
"github.com/getarcaneapp/arcane/backend/v2/internal/database"
"github.com/getarcaneapp/arcane/backend/v2/internal/docker"
@@ -48,8 +49,9 @@ import (
// UpdaterService is Arcane's handler-facing service for the standalone updater engine.
type UpdaterService struct {
- deps updaterDependenciesInternal
- engine *updater.Service
+ deps updaterDependenciesInternal
+ engine *updater.Service
+ singleUpdates *actors.Executor
// updateMu serializes per-container updates. docker compose's recreate
// pipeline is not concurrency-safe for sibling containers sharing a
// namespace. ponytail: global lock ceiling — all updates serialize; fine
@@ -438,12 +440,52 @@ func (s *UpdaterService) containerIDsForImagesInternal(ctx context.Context, imag
// UpdateSingleContainer updates a single container by ID to the latest available image.
func (s *UpdaterService) UpdateSingleContainer(ctx context.Context, containerID string) (out *arcaneupdater.Result, err error) {
+ activity, workCtx, err := s.startSingleContainerUpdateActivityInternal(ctx, containerID)
+ if err != nil {
+ return nil, err
+ }
+ activityID := ""
+ if activity != nil {
+ activityID = activity.ID
+ }
+ defer func() {
+ s.finishSingleContainerUpdateInternal(workCtx, activityID, out, err)
+ }()
+ defer utils.RecoverToError(&err, "single container update")
+ return s.runSingleContainerUpdateInternal(workCtx, containerID, activityID)
+}
+
+// AcceptSingleContainerUpdate persists and submits a cancellable update activity.
+func (s *UpdaterService) AcceptSingleContainerUpdate(ctx context.Context, containerID string) (*activitytypes.Activity, error) {
+ if s.deps.Activity == nil || s.singleUpdates == nil {
+ return nil, errors.New("asynchronous container updates unavailable")
+ }
+ activity, workCtx, err := s.startSingleContainerUpdateActivityInternal(ctx, containerID)
+ if err != nil {
+ return nil, err
+ }
+ _, err = s.singleUpdates.Submit(workCtx, "update container", func(actorCtx context.Context) (*arcaneupdater.Result, error) {
+ runCtx := utils.ActivityRuntimeContext(workCtx, actorCtx)
+ return s.runSingleContainerUpdateInternal(runCtx, containerID, activity.ID)
+ }, func(result *arcaneupdater.Result, runErr error) {
+ s.finishSingleContainerUpdateInternal(workCtx, activity.ID, result, runErr)
+ })
+ if err != nil {
+ s.finishSingleContainerUpdateInternal(workCtx, activity.ID, nil, err)
+ return nil, errors.WrapIf(err, "submit container update")
+ }
+ return activity, nil
+}
+
+func (s *UpdaterService) runSingleContainerUpdateInternal(ctx context.Context, containerID, activityID string) (out *arcaneupdater.Result, err error) {
start := time.Now()
- activityID := s.startSingleContainerUpdateActivityInternal(ctx, containerID)
out = &arcaneupdater.Result{Items: []arcaneupdater.ResourceResult{}, ActivityID: mo.EmptyableToOption(strings.TrimSpace(activityID)).ToPointer()}
- ctx = s.trackActivityInternal(ctx, activityID)
ctx = contextWithActivityIDInternal(ctx, activityID)
- activitylib.AwaitHandlerActivitySlot(ctx, s.deps.Activity, activityID, "0")
+ if s.deps.Activity != nil && activityID != "" {
+ if err := s.deps.Activity.AwaitActivitySlotBounded(ctx, activityID, "0"); err != nil {
+ return out, err
+ }
+ }
defer func() {
if out == nil {
@@ -453,11 +495,13 @@ func (s *UpdaterService) UpdateSingleContainer(ctx context.Context, containerID
out.Duration = time.Since(start).String()
}
out.ActivityID = mo.EmptyableToOption(strings.TrimSpace(activityID)).ToPointer()
- s.completeAutoUpdateActivityInternal(ctx, activityID, out, err)
}()
s.updateMu.Lock()
defer s.updateMu.Unlock()
+ if err := ctx.Err(); err != nil {
+ return out, err
+ }
// The caller picked this container, so the autoUpdateExcludedContainers
// setting does not apply: it only governs automatic and pending runs, which
@@ -904,26 +948,110 @@ func (s *UpdaterService) startAutoUpdateActivityInternal(ctx context.Context, dr
return activity.ID
}
-func (s *UpdaterService) startSingleContainerUpdateActivityInternal(ctx context.Context, containerID string) string {
+func (s *UpdaterService) startSingleContainerUpdateActivityInternal(ctx context.Context, containerID string) (*activitytypes.Activity, context.Context, error) {
if s.deps.Activity == nil {
- return ""
+ return nil, ctx, nil
+ }
+ name := containerID
+ lookupCtx, cancelLookup := context.WithTimeout(ctx, 2*time.Second)
+ if dockerClient, dockerErr := s.DockerClient(lookupCtx); dockerErr == nil && dockerClient != nil {
+ if inspected, inspectErr := libarcane.ContainerInspectWithCompatibility(lookupCtx, dockerClient, containerID, client.ContainerInspectOptions{}); inspectErr == nil {
+ if actualName := strings.TrimPrefix(strings.TrimSpace(inspected.Container.Name), "/"); actualName != "" {
+ name = actualName
+ }
+ }
}
- activity, err := s.deps.Activity.StartActivity(ctx, activitylib.StartRequest{
+ cancelLookup()
+ user, _ := common.CurrentUserFromContext(ctx)
+ if initiator, ok := utils.UpdateInitiatorFromContext(ctx); ok {
+ user = &common.User{Username: initiator.Username}
+ user.ID = initiator.UserID
+ if initiator.DisplayName != "" {
+ user.DisplayName = &initiator.DisplayName
+ }
+ }
+ activity, workCtx, err := s.deps.Activity.StartTrackedActivity(ctx, activitylib.StartRequest{
EnvironmentID: "0",
Type: activitytypes.TypeAutoUpdate,
Queue: true,
+ DeferSlot: true,
ResourceType: mo.EmptyableToOption(strings.TrimSpace("container")).ToPointer(),
ResourceID: &containerID,
- ResourceName: mo.EmptyableToOption(strings.TrimSpace(containerID)).ToPointer(),
+ ResourceName: &name,
+ StartedBy: user,
Step: "Updating container",
LatestMessage: "Container update started",
Metadata: database.JSON{"containerID": containerID},
})
if err != nil {
- slog.DebugContext(ctx, "failed to start container update activity", "containerID", containerID, "error", err)
- return ""
+ return nil, nil, errors.WrapIf(err, "start container update activity")
}
- return activity.ID
+ return activity, workCtx, nil
+}
+
+func (s *UpdaterService) finishSingleContainerUpdateInternal(ctx context.Context, activityID string, result *arcaneupdater.Result, runErr error) {
+ if s.deps.Activity == nil || activityID == "" {
+ return
+ }
+ metadata, message := singleContainerActivitySummaryInternal(result)
+ writeCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 30*time.Second)
+ defer cancel()
+ if containerName, ok := metadata["containerName"].(string); ok && containerName != "" {
+ if _, err := s.deps.Activity.UpdateActivity(writeCtx, activityID, activitylib.UpdateRequest{ResourceName: &containerName}); err != nil {
+ slog.WarnContext(writeCtx, "failed to update container activity name", "activityId", activityID, "error", err)
+ }
+ }
+ if err := s.deps.Activity.PatchActivityMetadata(writeCtx, activityID, metadata); err != nil {
+ slog.WarnContext(writeCtx, "failed to persist container update result", "activityId", activityID, "error", err)
+ }
+ if runErr == nil && result != nil && result.Failed == 0 {
+ if result.Updated > 0 || result.Restarted > 0 {
+ message = "Container updated"
+ }
+ if _, err := s.deps.Activity.CompleteActivity(writeCtx, activityID, activitytypes.StatusSuccess, message, nil); err != nil {
+ slog.ErrorContext(writeCtx, "failed to complete container update activity", "activityId", activityID, "error", err)
+ }
+ return
+ }
+ if runErr == nil && result == nil {
+ runErr = errors.New("container update produced no result")
+ }
+ if runErr == nil && result != nil && len(result.Items) > 0 && result.Items[0].Error != "" {
+ runErr = errors.New(result.Items[0].Error)
+ }
+ s.completeAutoUpdateActivityInternal(ctx, activityID, result, runErr)
+}
+
+func singleContainerActivitySummaryInternal(result *arcaneupdater.Result) (database.JSON, string) {
+ metadata := database.JSON{}
+ message := "Container update completed"
+ if result == nil {
+ return metadata, message
+ }
+ metadata["updated"] = result.Updated
+ metadata["restarted"] = result.Restarted
+ metadata["skipped"] = result.Skipped
+ metadata["failed"] = result.Failed
+ if len(result.Items) > 0 {
+ item := result.Items[0]
+ metadata["updateOutcome"] = item.Status
+ if item.ResourceName != "" {
+ metadata["containerName"] = item.ResourceName
+ }
+ if item.Error != "" {
+ metadata["updateReason"] = item.Error
+ if item.Status == string(updater.StatusSkipped) {
+ return metadata, "Container update skipped: " + item.Error
+ }
+ }
+ }
+ if result.Skipped > 0 {
+ return metadata, "Container update skipped"
+ }
+ if result.Updated == 0 && result.Restarted == 0 && result.Failed == 0 {
+ message = "Container already current"
+ }
+ return metadata, message
}
func (s *UpdaterService) appendAutoUpdateActivityMessageInternal(ctx context.Context, activityID, message, step string, progress int) {
diff --git a/backend/internal/updater/service_test.go b/backend/internal/updater/service_test.go
index c8a5863ad..19ccfb47e 100644
--- a/backend/internal/updater/service_test.go
+++ b/backend/internal/updater/service_test.go
@@ -13,6 +13,7 @@ import (
"github.com/getarcaneapp/arcane/backend/v2/internal/settings"
"github.com/getarcaneapp/arcane/backend/v2/internal/activity"
+ "github.com/getarcaneapp/arcane/backend/v2/internal/actors"
"github.com/getarcaneapp/arcane/backend/v2/internal/common"
activitylib "github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/activity"
activitytypes "github.com/getarcaneapp/arcane/types/v2/activity"
@@ -27,6 +28,7 @@ import (
"net/url"
"slices"
"strings"
+ "sync"
"sync/atomic"
"testing"
"time"
@@ -42,6 +44,7 @@ import (
"github.com/getarcaneapp/arcane/backend/v2/internal/notification"
"github.com/getarcaneapp/arcane/backend/v2/internal/project"
"github.com/getarcaneapp/arcane/backend/v2/internal/registry"
+ "github.com/getarcaneapp/arcane/backend/v2/pkg/utils"
arcaneupdater "github.com/getarcaneapp/arcane/types/v2/updater"
"github.com/libtnb/sqlite"
dockerauthconfig "github.com/moby/moby/api/pkg/authconfig"
@@ -56,6 +59,7 @@ import (
"go.getarcane.app/updater/labels"
"go.getarcane.app/updater/refs"
updatertypes "go.getarcane.app/updater/types"
+ "go.uber.org/fx/fxtest"
"gorm.io/gorm"
)
@@ -735,6 +739,151 @@ func TestUpdaterService_RecordUpdateRunAppendsActivityMessageInternal(t *testing
}
}
+func TestUpdaterService_AcceptSingleContainerUpdateUsesQueuedActivityInternal(t *testing.T) {
+ for _, cancelActivity := range []bool{false, true} {
+ name := "request disconnect"
+ if cancelActivity {
+ name = "activity cancellation while queued"
+ }
+ t.Run(name, func(t *testing.T) {
+ db := setupProjectTestDBInternal(t)
+ require.NoError(t, db.AutoMigrate(&activity.Activity{}, &activity.ActivityMessage{}))
+ sqlDB, err := db.DB.DB()
+ require.NoError(t, err)
+ sqlDB.SetMaxOpenConns(1)
+ activityService := activity.NewActivityService(db, nil)
+ svc, err := NewUpdaterService(db, nil, nil, nil, nil, nil, nil, nil, nil, nil, activityService)
+ require.NoError(t, err)
+
+ lifecycle := fxtest.NewLifecycle(t)
+ runtime, err := actors.NewRuntime(t.Context(), lifecycle)
+ require.NoError(t, err)
+ executor, err := actors.NewExecutor(t.Context(), runtime, "updater-test", t.Name(), 3)
+ require.NoError(t, err)
+ svc.singleUpdates = executor
+ release := make(chan struct{})
+ var releaseOnce sync.Once
+ defer releaseOnce.Do(func() { close(release) })
+ t.Cleanup(func() {
+ stopCtx, cancel := context.WithTimeout(context.Background(), time.Second)
+ defer cancel()
+ require.NoError(t, executor.Stop(stopCtx))
+ require.NoError(t, lifecycle.Stop(stopCtx))
+ })
+ started := make(chan struct{})
+ _, err = executor.Submit(t.Context(), "hold executor", func(context.Context) (int, error) {
+ close(started)
+ <-release
+ return 0, nil
+ }, nil)
+ require.NoError(t, err)
+ <-started
+
+ requestCtx, cancelRequest := context.WithCancel(context.Background())
+ workCtx := utils.ActivityRuntimeContext(requestCtx, t.Context())
+ type acceptedInternal struct {
+ activity *activitytypes.Activity
+ err error
+ }
+ accepted := make(chan acceptedInternal, 1)
+ go func() {
+ item, acceptErr := svc.AcceptSingleContainerUpdate(workCtx, "missing-container")
+ accepted <- acceptedInternal{activity: item, err: acceptErr}
+ }()
+ var item *activitytypes.Activity
+ select {
+ case result := <-accepted:
+ require.NoError(t, result.err)
+ item = result.activity
+ case <-time.After(time.Second):
+ require.FailNow(t, "acceptance waited for executor work")
+ }
+ require.Equal(t, activitytypes.StatusQueued, item.Status)
+ cancelRequest()
+ if cancelActivity {
+ _, err = activityService.CancelActivity(context.Background(), "0", item.ID, "test")
+ require.NoError(t, err)
+ }
+ releaseOnce.Do(func() { close(release) })
+
+ wantStatus := activitytypes.StatusFailed
+ if cancelActivity {
+ wantStatus = activitytypes.StatusCancelled
+ }
+ require.Eventually(t, func() bool {
+ var saved activity.Activity
+ return db.First(&saved, "id = ?", item.ID).Error == nil && saved.Status == wantStatus
+ }, 5*time.Second, 10*time.Millisecond)
+ })
+ }
+}
+
+func TestUpdaterService_AcceptSingleContainerUpdateFailureFinalizesInternal(t *testing.T) {
+ db := setupProjectTestDBInternal(t)
+ require.NoError(t, db.AutoMigrate(&activity.Activity{}, &activity.ActivityMessage{}))
+ activityService := activity.NewActivityService(db, nil)
+ svc, err := NewUpdaterService(db, nil, nil, nil, nil, nil, nil, nil, nil, nil, activityService)
+ require.NoError(t, err)
+ lifecycle := fxtest.NewLifecycle(t)
+ runtime, err := actors.NewRuntime(t.Context(), lifecycle)
+ require.NoError(t, err)
+ executor, err := actors.NewExecutor(t.Context(), runtime, "updater-test", t.Name(), 3)
+ require.NoError(t, err)
+ svc.singleUpdates = executor
+ stopCtx, cancelStop := context.WithTimeout(context.Background(), time.Second)
+ require.NoError(t, executor.Stop(stopCtx))
+ cancelStop()
+ t.Cleanup(func() {
+ cleanupCtx, cancel := context.WithTimeout(context.Background(), time.Second)
+ defer cancel()
+ require.NoError(t, lifecycle.Stop(cleanupCtx))
+ })
+
+ accepted, err := svc.AcceptSingleContainerUpdate(context.Background(), "container-1")
+ require.Nil(t, accepted)
+ require.ErrorContains(t, err, "submit container update")
+ var saved activity.Activity
+ require.NoError(t, db.First(&saved, "resource_id = ?", "container-1").Error)
+ require.Equal(t, activitytypes.StatusFailed, saved.Status)
+
+ unmigrated := setupProjectTestDBInternal(t)
+ svc.deps.Activity = activity.NewActivityService(unmigrated, nil)
+ accepted, err = svc.AcceptSingleContainerUpdate(context.Background(), "container-2")
+ require.Nil(t, accepted)
+ require.ErrorContains(t, err, "start container update activity")
+}
+
+func TestUpdaterService_SingleContainerActivityResultMessagesInternal(t *testing.T) {
+ for _, tt := range []struct {
+ name string
+ result *arcaneupdater.Result
+ wantStatus activitytypes.Status
+ wantMessage string
+ }{
+ {name: "updated", result: &arcaneupdater.Result{Updated: 1, Items: []arcaneupdater.ResourceResult{{Status: string(updater.StatusUpdated), ResourceName: "web"}}}, wantStatus: activitytypes.StatusSuccess, wantMessage: "Container updated"},
+ {name: "restarted", result: &arcaneupdater.Result{Restarted: 1, Items: []arcaneupdater.ResourceResult{{Status: string(updater.StatusRestarted), ResourceName: "web"}}}, wantStatus: activitytypes.StatusSuccess, wantMessage: "Container updated"},
+ {name: "skipped", result: &arcaneupdater.Result{Skipped: 1, Items: []arcaneupdater.ResourceResult{{Status: string(updater.StatusSkipped), Error: "immutable image reference"}}}, wantStatus: activitytypes.StatusSuccess, wantMessage: "Container update skipped: immutable image reference"},
+ {name: "already current", result: &arcaneupdater.Result{Checked: 1, Items: []arcaneupdater.ResourceResult{{Status: string(updater.StatusUpToDate)}}}, wantStatus: activitytypes.StatusSuccess, wantMessage: "Container already current"},
+ {name: "failed", result: &arcaneupdater.Result{Failed: 1, Items: []arcaneupdater.ResourceResult{{Status: string(updater.StatusFailed), Error: "pull failed"}}}, wantStatus: activitytypes.StatusFailed, wantMessage: "pull failed"},
+ } {
+ t.Run(tt.name, func(t *testing.T) {
+ db := setupProjectTestDBInternal(t)
+ require.NoError(t, db.AutoMigrate(&activity.Activity{}, &activity.ActivityMessage{}))
+ activityService := activity.NewActivityService(db, nil)
+ svc, err := NewUpdaterService(db, nil, nil, nil, nil, nil, nil, nil, nil, nil, activityService)
+ require.NoError(t, err)
+ started, err := activityService.StartActivity(t.Context(), activitylib.StartRequest{EnvironmentID: "0", Type: activitytypes.TypeAutoUpdate, Metadata: database.JSON{"containerID": "old-id"}})
+ require.NoError(t, err)
+ svc.finishSingleContainerUpdateInternal(t.Context(), started.ID, tt.result, nil)
+ var saved activity.Activity
+ require.NoError(t, db.First(&saved, "id = ?", started.ID).Error)
+ require.Equal(t, tt.wantStatus, saved.Status)
+ require.Equal(t, tt.wantMessage, saved.LatestMessage)
+ require.Equal(t, "old-id", saved.Metadata["containerID"])
+ })
+ }
+}
+
func TestUpdaterService_ApplyPending_ProjectFailureDoesNotBlockOtherProjectsInternal(t *testing.T) {
ctx := context.Background()
diff --git a/backend/pkg/libarcane/activity/requests.go b/backend/pkg/libarcane/activity/requests.go
index 52d845036..c476682bb 100644
--- a/backend/pkg/libarcane/activity/requests.go
+++ b/backend/pkg/libarcane/activity/requests.go
@@ -49,7 +49,11 @@ type StartRequest struct {
// limiter: with a free slot it starts running as usual; otherwise it is
// created with status queued and the caller must block on
// SlotWaiter.AwaitActivitySlot before doing the work.
- Queue bool
+ Queue bool
+ // DeferSlot persists a queued activity without reserving a slot until its
+ // serialized worker starts. It is used by actor-owned work submitted after
+ // activity creation so queued tasks cannot hold slots ahead of the actor.
+ DeferSlot bool
Type activitytypes.Type
ResourceType *string
ResourceID *string
@@ -63,6 +67,7 @@ type StartRequest struct {
type UpdateRequest struct {
Status activitytypes.Status
+ ResourceName *string
Progress *int
Step *string
LatestMessage *string
diff --git a/backend/pkg/utils/activity_context.go b/backend/pkg/utils/activity_context.go
index b8ddc3fc9..cc74b1e32 100644
--- a/backend/pkg/utils/activity_context.go
+++ b/backend/pkg/utils/activity_context.go
@@ -3,12 +3,33 @@ package utils
import (
"context"
"regexp"
+ "strings"
"time"
+
+ activitytypes "github.com/getarcaneapp/arcane/types/v2/activity"
)
type appLifecycleContextKey struct{}
type activityBatchIDContextKey struct{}
+type updateInitiatorContextKeyInternal struct{}
+
+// WithUpdateInitiator carries manager-authenticated attribution through an
+// agent request without changing the authenticated agent identity.
+func WithUpdateInitiator(ctx context.Context, initiator activitytypes.StartedBy) context.Context {
+ initiator.UserID = strings.TrimSpace(initiator.UserID)
+ initiator.Username = strings.TrimSpace(initiator.Username)
+ if initiator.UserID == "" || initiator.Username == "" {
+ return ctx
+ }
+ return context.WithValue(ctx, updateInitiatorContextKeyInternal{}, initiator)
+}
+
+// UpdateInitiatorFromContext returns trusted proxied update attribution.
+func UpdateInitiatorFromContext(ctx context.Context) (activitytypes.StartedBy, bool) {
+ initiator, ok := ctx.Value(updateInitiatorContextKeyInternal{}).(activitytypes.StartedBy)
+ return initiator, ok
+}
var activityBatchIDPattern = regexp.MustCompile(`^[A-Za-z0-9_-]{1,64}$`)
diff --git a/backend/pkg/utils/auth.go b/backend/pkg/utils/auth.go
index 17ced5f00..bb7f6eeeb 100644
--- a/backend/pkg/utils/auth.go
+++ b/backend/pkg/utils/auth.go
@@ -4,10 +4,13 @@ package utils
// (WebSocket/diagnostics) and the Huma auth bridge (REST). Keep these in one
// place so a change to a header name applies to every route type at once.
const (
- HeaderAgentBootstrap = "X-Arcane-Agent-Bootstrap"
- HeaderAgentToken = "X-Arcane-Agent-Token" // #nosec G101: header name, not a credential
- HeaderApiKey = "X-Api-Key" // #nosec G101: header name, not a credential
- HeaderActivityBatchID = "X-Arcane-Batch-Id"
+ HeaderAgentBootstrap = "X-Arcane-Agent-Bootstrap"
+ HeaderAgentToken = "X-Arcane-Agent-Token" // #nosec G101: header name, not a credential
+ HeaderApiKey = "X-Api-Key" // #nosec G101: header name, not a credential
+ HeaderActivityBatchID = "X-Arcane-Batch-Id"
+ HeaderUpdateInitiatorID = "X-Arcane-Update-Initiator-Id"
+ HeaderUpdateInitiatorName = "X-Arcane-Update-Initiator-Name"
+ HeaderUpdateInitiatorDisplayName = "X-Arcane-Update-Initiator-Display-Name"
// HeaderIconCatalog carries the requesting user's icon catalog preference to
// remote environments. Agents authenticate proxied calls as a synthetic user
// with no preferences, so without it every remote environment would resolve
diff --git a/frontend/messages/en.json b/frontend/messages/en.json
index 8ad023125..0239eff50 100644
--- a/frontend/messages/en.json
+++ b/frontend/messages/en.json
@@ -613,6 +613,8 @@
"images_not_pulled_count": "{notPulled} of {total} images not pulled",
"containers_update_confirm_message": "This will pull the latest image and apply the appropriate update for \"{name}\". Do you want to continue?",
"containers_update_pulling_image": "Pulling latest image...",
+ "containers_update_accepted": "Update started for container \"{name}\"",
+ "containers_update_accept_failed": "Could not confirm the update request for container \"{name}\"",
"containers_update_success": "Container \"{name}\" updated successfully",
"containers_update_failed": "Failed to update container \"{name}\"",
"containers_update_skipped": "Container \"{name}\" was not updated",
@@ -654,6 +656,9 @@
"containers_bulk_update_confirm_message": "Are you sure you want to update {count} container(s)?",
"containers_bulk_update_filtered_confirm_message": "Only {filteredCount} out of {totalCount} containers are eligible for updates. Are you sure you want to update {filteredCount} container(s)?",
"containers_bulk_update_success": "Successfully updated {count} container(s)",
+ "containers_bulk_update_accepted": "Started updates for {count} container(s)",
+ "containers_bulk_update_accept_failed": "Could not confirm the container update requests",
+ "containers_bulk_update_accept_partial": "Started {success} of {total} container update(s). {failed} could not start.",
"containers_bulk_update_partial": "Updated {success} of {total} container(s). {failed} failed.",
"containers_bulk_update_failed": "Failed to update containers",
"containers_group_by_project": "Group by Project",
diff --git a/frontend/src/lib/services/container-service.ts b/frontend/src/lib/services/container-service.ts
index 75615c784..bf6643ab6 100644
--- a/frontend/src/lib/services/container-service.ts
+++ b/frontend/src/lib/services/container-service.ts
@@ -12,7 +12,7 @@ import type {
ContainerEditRequest
} from '#lib/types/docker.js';
import type { SearchPaginationSortRequest, Paginated } from '#lib/types/shared.js';
-import type { AutoUpdateResult } from '#lib/types/automation.js';
+import type { Activity } from '#lib/types/activity.type.js';
import { transformPaginationParams } from '#lib/utils/tables.js';
import { downloadFromUrl } from '#lib/utils/browser-download.js';
import { tryCatch } from '#lib/utils/try-catch.js';
@@ -120,9 +120,12 @@ class ContainerService extends BaseAPIService {
return this.handleResponse(this.api.delete(`/environments/${envId}/containers/${containerId}`, { params }));
}
- async updateContainer(containerId: string): Promise<AutoUpdateResult> {
- const envId = await environmentStore.getCurrentEnvironmentId();
- return this.handleResponse(this.api.post(`/environments/${envId}/containers/${containerId}/update`));
+ updateContainer(containerId: string, environmentId: string): Promise<Activity> {
+ return this.handleResponse<Activity>(
+ this.api.post(`/environments/${environmentId}/containers/${containerId}/update`, undefined, {
+ params: { async: 'true' }
+ })
+ ).then((activity) => ({ ...activity, sourceEnvironmentId: environmentId }));
}
async redeployContainer(containerId: string): Promise<ContainerDetailsDto> {
diff --git a/frontend/src/lib/stores/activity.store.svelte.ts b/frontend/src/lib/stores/activity.store.svelte.ts
index 9ec4b7ccc..ebbd4bbbb 100644
--- a/frontend/src/lib/stores/activity.store.svelte.ts
+++ b/frontend/src/lib/stores/activity.store.svelte.ts
@@ -164,6 +164,7 @@ function createActivityStore() {
// Last observed status per activity, for completion-toast transition
// detection. Intentionally non-reactive: only stream handling reads it.
const observedStatusById = new Map<string, ActivityStatus>();
+ const completionToastQueuedIds = new Set<string>();
const activitySubscribers = new Set<(activities: readonly Activity[]) => void>();
// Toast when an activity this session observed as active reaches
@@ -173,7 +174,7 @@ function createActivityStore() {
function noteActivityStatusInternal(activity: Activity) {
const prev = observedStatusById.get(activity.id);
observedStatusById.set(activity.id, activity.status);
- if (!prev || !isActiveStatusInternal(prev) || prev === activity.status) {
+ if (!prev || !isActiveStatusInternal(prev) || prev === activity.status || completionToastQueuedIds.has(activity.id)) {
return;
}
if (activity.status !== 'success' && activity.status !== 'failed') {
@@ -188,6 +189,7 @@ function createActivityStore() {
if (!activity.startedBy?.userId || !currentUserId || activity.startedBy.userId !== currentUserId) {
return;
}
+ completionToastQueuedIds.add(activity.id);
queueActivityCompletionToast(activity, openCenterInternal);
}
@@ -350,6 +352,7 @@ function createActivityStore() {
for (const id of observedStatusById.keys()) {
if (!present.has(id)) {
observedStatusById.delete(id);
+ completionToastQueuedIds.delete(id);
}
}
for (const subscriber of activitySubscribers) subscriber(_activities);
@@ -545,6 +548,17 @@ function createActivityStore() {
}
return {
+ acceptActivity: (activity: Activity) => {
+ const current = _activities.find((item) => item.id === activity.id);
+ if (current) {
+ if (!isActiveStatusInternal(current.status) && isActiveStatusInternal(activity.status)) {
+ observedStatusById.set(activity.id, activity.status);
+ noteActivityStatusInternal(current);
+ }
+ return;
+ }
+ mergeActivityInternal(activity);
+ },
subscribeActivities(subscriber: (activities: readonly Activity[]) => void): () => void {
activitySubscribers.add(subscriber);
subscriber(_activities);
@@ -632,6 +646,7 @@ function createActivityStore() {
sessionGeneration += 1;
requestedEnvironments = {};
observedStatusById.clear();
+ completionToastQueuedIds.clear();
discardPendingActivityToasts();
_activities = [];
_environmentActivities = {};
diff --git a/frontend/src/lib/utils/activity-toast.ts b/frontend/src/lib/utils/activity-toast.ts
index 1e0591786..d1260100a 100644
--- a/frontend/src/lib/utils/activity-toast.ts
+++ b/frontend/src/lib/utils/activity-toast.ts
@@ -2,7 +2,7 @@ import { activityStore } from '#lib/stores/activity.store.svelte.js';
import { markActivityToastShown } from '#lib/components/activity/activity-completion-toasts.js';
import { m } from '#lib/paraglide/messages.js';
-export function activityToastOptions(activityId?: string, suppressCompletion = true) {
+export function activityToastOptions(activityId?: string, suppressCompletion = true, environmentId?: string) {
if (!activityId) {
return undefined;
}
@@ -14,7 +14,7 @@ export function activityToastOptions(activityId?: string, suppressCompletion = t
return {
action: {
label: m.activity_view_activity(),
- onClick: () => activityStore.openCenter(activityId)
+ onClick: () => activityStore.openCenter(activityId, undefined, environmentId)
}
};
}
diff --git a/frontend/src/lib/utils/bulk-actions.ts b/frontend/src/lib/utils/bulk-actions.ts
index 01179790c..f93d81306 100644
--- a/frontend/src/lib/utils/bulk-actions.ts
+++ b/frontend/src/lib/utils/bulk-actions.ts
@@ -7,6 +7,8 @@ import { handleApiResultWithCallbacks } from '#lib/utils/api.js';
import { tryCatch } from '#lib/utils/try-catch.js';
import type { Result } from '#lib/types/result.js';
import { activityToastOptions, extractActivityId } from '#lib/utils/activity-toast.js';
+import { activityStore } from '#lib/stores/activity.store.svelte.js';
+import type { Activity } from '#lib/types/activity.type.js';
/**
* Shared helpers for table bulk operations (start/stop/remove/prune/…). These
@@ -45,6 +47,10 @@ export interface RunBulkOperationOptions<T> {
onItemFailure?: (id: string, error: Error) => void;
/** Run operations one at a time instead of concurrently. Defaults to concurrent. */
sequential?: boolean;
+ /** The requests were accepted for background work; completion belongs to activities. */
+ acceptanceOnly?: boolean;
+ activityLink?: boolean;
+ onItemSuccess?: (id: string, value: T) => void;
}
/**
@@ -60,7 +66,10 @@ async function runBulkOperation<T>({
onComplete,
clearSelection,
onItemFailure,
- sequential = false
+ sequential = false,
+ acceptanceOnly = false,
+ activityLink = true,
+ onItemSuccess
}: RunBulkOperationOptions<T>): Promise<BulkOperationResult> {
const total = ids?.length ?? 0;
const result: BulkOperationResult = { total, success: 0, failed: 0 };
@@ -74,8 +83,10 @@ async function runBulkOperation<T>({
onItemFailure?.(id, outcome.error);
} else {
result.success += 1;
- const activityId = extractActivityId(outcome.data);
+ onItemSuccess?.(id, outcome.data as T);
+ const activityId = acceptanceOnly ? (outcome.data as Activity).id : extractActivityId(outcome.data);
if (activityId) {
+ if (acceptanceOnly && activityLink) activityStore.acceptActivity(outcome.data as Activity);
activityIds.push(activityId);
firstActivityId ??= activityId;
}
@@ -106,14 +117,17 @@ async function runBulkOperation<T>({
// The summary toast below covers every spawned activity; suppress the
// per-activity completion toasts for all of them, not just the linked one.
- for (const activityId of activityIds) {
- markActivityToastShown(activityId);
+ if (!acceptanceOnly) {
+ for (const activityId of activityIds) markActivityToastShown(activityId);
}
if (result.failed === 0) {
- toast.success(messages.success(result.success), activityToastOptions(firstActivityId));
+ const options = activityLink ? activityToastOptions(firstActivityId, !acceptanceOnly) : undefined;
+ if (acceptanceOnly) toast.info(messages.success(result.success), options);
+ else toast.success(messages.success(result.success), options);
} else if (result.success > 0) {
- toast.warning(messages.partial(result.success, total, result.failed));
+ const options = activityLink ? activityToastOptions(firstActivityId, !acceptanceOnly) : undefined;
+ toast.warning(messages.partial(result.success, total, result.failed), options);
} else {
toast.error(messages.failure());
}
@@ -158,7 +172,10 @@ export function bulkConfirmAndRun<T>({
onComplete,
clearSelection,
onItemFailure,
- sequential
+ sequential,
+ acceptanceOnly,
+ activityLink,
+ onItemSuccess
}: BulkConfirmAndRunOptions<T>): void {
if (!ids || ids.length === 0) return;
@@ -178,7 +195,10 @@ export function bulkConfirmAndRun<T>({
onComplete,
clearSelection,
onItemFailure,
- sequential
+ sequential,
+ acceptanceOnly,
+ activityLink,
+ onItemSuccess
});
}
}
diff --git a/frontend/src/lib/utils/container-actions.ts b/frontend/src/lib/utils/container-actions.ts
index fefee23eb..6945b6374 100644
--- a/frontend/src/lib/utils/container-actions.ts
+++ b/frontend/src/lib/utils/container-actions.ts
@@ -4,7 +4,10 @@ import { containerService } from '#lib/services/container-service.js';
import { handleApiResultWithCallbacks } from '#lib/utils/api.js';
import { tryCatch } from '#lib/utils/try-catch.js';
import { activityToastOptions, extractActivityId } from '#lib/utils/activity-toast.js';
-import type { AutoUpdateResult } from '#lib/types/automation.js';
+import type { Activity } from '#lib/types/activity.type.js';
+import { environmentStore } from '#lib/stores/environment.store.svelte.js';
+import { hasPermission } from '#lib/utils/auth.js';
+import { activityStore } from '#lib/stores/activity.store.svelte.js';
import { toast } from 'svelte-sonner';
type ContainerLifecycleAction = 'start' | 'stop' | 'restart' | 'pause' | 'unpause';
@@ -138,19 +141,19 @@ export function confirmAndRemoveContainer({
type ConfirmAndUpdateContainerOptions = {
containerId: string;
containerName: string;
- showPullingToast?: boolean;
- useActivityToast?: boolean;
+ environmentId: string;
setLoading?: (loading: boolean) => void;
onRefresh?: () => Promise<unknown> | unknown;
+ onAccepted?: (activity: Activity, environmentId: string) => void | Promise<void>;
};
export function confirmAndUpdateContainer({
containerId,
containerName,
- showPullingToast = false,
- useActivityToast = false,
+ environmentId,
setLoading,
- onRefresh
+ onRefresh,
+ onAccepted
}: ConfirmAndUpdateContainerOptions) {
openConfirmDialog({
title: m.update_container(),
@@ -160,61 +163,22 @@ export function confirmAndUpdateContainer({
destructive: false,
action: async () => {
setLoading?.(true);
- if (showPullingToast) {
- toast.info(m.containers_update_pulling_image());
- }
-
- const operationResult = await tryCatch(
- handleApiResultWithCallbacks({
- result: await tryCatch(containerService.updateContainer(containerId)),
- message: m.containers_update_failed({ name: containerName }),
- setLoadingState: (value) => setLoading?.(value),
- async onSuccess(result) {
- showContainerUpdateResultToast(result, containerName, useActivityToast);
- await onRefresh?.();
- }
- })
- );
- if (operationResult.error !== null) {
- const error = operationResult.error;
- console.error('Container update failed:', error);
- toast.error(m.containers_update_failed({ name: containerName }));
- setLoading?.(false);
- }
+ await handleApiResultWithCallbacks({
+ result: await tryCatch(containerService.updateContainer(containerId, environmentId)),
+ message: m.containers_update_accept_failed({ name: containerName }),
+ setLoadingState: (value) => setLoading?.(value),
+ async onSuccess(activity) {
+ const canReadActivity = hasPermission('activities:read', environmentId);
+ if (canReadActivity) activityStore.acceptActivity(activity);
+ toast.info(
+ m.containers_update_accepted({ name: containerName }),
+ canReadActivity ? activityToastOptions(activity.id, false, environmentId) : undefined
+ );
+ await onAccepted?.(activity, environmentId);
+ if (!canReadActivity && environmentStore.selected?.id === environmentId) await onRefresh?.();
+ }
+ });
}
}
});
}
-
-/**
- * A single-container update answers 200 with a one-item result, so the outcome
- * lives in the tally: failed, updated (or restarted), skipped with the engine's
- * reason, or nothing to do. A skip is not "up to date" — the engine did not
- * apply anything, and its reason says why.
- */
-function showContainerUpdateResultToast(result: AutoUpdateResult, containerName: string, useActivityToast: boolean) {
- const toastOptions = useActivityToast ? activityToastOptions(extractActivityId(result)) : undefined;
- const itemWithStatus = (status: AutoUpdateResult['items'][number]['status']) =>
- result.items?.find((item) => item.status === status);
-
- if ((result.failed ?? 0) > 0) {
- toast.error(m.containers_update_failed({ name: containerName }), {
- ...toastOptions,
- description: itemWithStatus('failed')?.error
- });
- return;
- }
- if ((result.updated ?? 0) + (result.restarted ?? 0) > 0) {
- toast.success(m.containers_update_success({ name: containerName }), toastOptions);
- return;
- }
- const skipped = itemWithStatus('skipped');
- if (skipped) {
- toast.info(m.containers_update_skipped({ name: containerName }), {
- ...toastOptions,
- description: skipped.error || m.containers_update_skipped_no_reason()
- });
- return;
- }
- toast.info(m.image_update_up_to_date_title(), toastOptions);
-}
diff --git a/frontend/src/lib/utils/container-update-activities.ts b/frontend/src/lib/utils/container-update-activities.ts
new file mode 100644
index 000000000..8831f5932
--- /dev/null
+++ b/frontend/src/lib/utils/container-update-activities.ts
@@ -0,0 +1,56 @@
+import { activityStore } from '#lib/stores/activity.store.svelte.js';
+import type { Activity } from '#lib/types/activity.type.js';
+
+/** Tracks accepted updates and updates that were already running when a view mounted. */
+export function createContainerUpdateActivityTracker(
+ environmentId: () => string,
+ onTerminal: (activity: Activity) => void,
+ resourceId?: () => string
+) {
+ const activeIds = new Set<string>();
+ const acceptedIds = new Set<string>();
+ const terminalIds = new Set<string>();
+ const refreshedIds = new Set<string>();
+ let observedKey = `${environmentId()}:${resourceId?.() ?? ''}`;
+
+ function observe(activities: readonly Activity[]) {
+ const currentKey = `${environmentId()}:${resourceId?.() ?? ''}`;
+ if (observedKey !== currentKey) {
+ activeIds.clear();
+ acceptedIds.clear();
+ terminalIds.clear();
+ refreshedIds.clear();
+ observedKey = currentKey;
+ }
+ for (const activity of activities) {
+ if (
+ activity.type !== 'auto_update' ||
+ activity.resourceType !== 'container' ||
+ (activity.sourceEnvironmentId || activity.environmentId) !== environmentId() ||
+ (resourceId && activity.resourceId !== resourceId())
+ )
+ continue;
+ if (activity.status === 'queued' || activity.status === 'running') {
+ activeIds.add(activity.id);
+ continue;
+ }
+ if (terminalIds.has(activity.id)) continue;
+ terminalIds.add(activity.id);
+ if (activeIds.has(activity.id) || acceptedIds.has(activity.id)) {
+ refreshedIds.add(activity.id);
+ onTerminal(activity);
+ }
+ activeIds.delete(activity.id);
+ acceptedIds.delete(activity.id);
+ }
+ }
+
+ function accept(activity: Activity) {
+ if (refreshedIds.has(activity.id)) return;
+ acceptedIds.add(activity.id);
+ terminalIds.delete(activity.id);
+ observe([activity, ...activityStore.activities]);
+ }
+
+ return { observe, accept };
+}
diff --git a/frontend/src/routes/(app)/containers/[containerId]/+page.svelte b/frontend/src/routes/(app)/containers/[containerId]/+page.svelte
index 7a2b89eda..c230a4927 100644
--- a/frontend/src/routes/(app)/containers/[containerId]/+page.svelte
+++ b/frontend/src/routes/(app)/containers/[containerId]/+page.svelte
@@ -7,7 +7,7 @@
import ActionButtons from '#lib/components/action-buttons.svelte';
import { Badge } from '#lib/components/ui/badge/index.js';
import { bytes } from '#lib/utils/formatting.js';
- import { tick } from 'svelte';
+ import { onMount, tick } from 'svelte';
import { page } from '$app/state';
import type { ContainerDetailsDto, ContainerNetworkSettings, ContainerStats as ContainerStatsType } from '#lib/types/docker.js';
import { m } from '#lib/paraglide/messages.js';
@@ -54,6 +54,12 @@
import { imageService } from '#lib/services/image-service.js';
import { createQuery, useQueryClient } from '@tanstack/svelte-query';
import { queryKeys } from '#lib/query/query-keys.js';
+ import { activityStore } from '#lib/stores/activity.store.svelte.js';
+ import { createContainerUpdateActivityTracker } from '#lib/utils/container-update-activities.js';
+ import { APIError } from '#lib/services/api-service.js';
+ import { containerService } from '#lib/services/container-service.js';
+ import { extractApiErrorMessage } from '#lib/utils/api.js';
+ import { toast } from 'svelte-sonner';
import userStore from '#lib/stores/user-store.svelte.js';
import { isAutoUpdateLabelDisabled } from '#lib/utils/container-auto-update.js';
import KillContainerDialog from '../components/kill-container-dialog.svelte';
@@ -186,17 +192,61 @@
return null;
});
let updateLoading = $state(false);
+ let updateViewMounted = false;
+ const updateActivities = createContainerUpdateActivityTracker(
+ () => currentEnvId,
+ () => {
+ void refreshAfterUpdate();
+ },
+ () => container.id
+ );
+ onMount(() => {
+ updateViewMounted = true;
+ const unsubscribe = activityStore.subscribeActivities(updateActivities.observe);
+ return () => {
+ updateViewMounted = false;
+ unsubscribe();
+ };
+ });
+
+ async function refreshAfterUpdate() {
+ const environmentId = currentEnvId;
+ const containerId = container.id;
+ const result = await tryCatch(containerService.getContainerForEnvironment(environmentId, containerId));
+ if (!updateViewMounted || environmentId !== currentEnvId || containerId !== container.id) return;
+ if (result.error instanceof APIError && result.error.status === 404) {
+ await queryClient.invalidateQueries({ queryKey: ['containers', environmentId] });
+ if (!updateViewMounted || environmentId !== currentEnvId || containerId !== container.id) return;
+ await goto('/containers');
+ return;
+ }
+ if (result.error !== null) {
+ toast.error(m.common_refresh_failed({ resource: m.containers() }), {
+ description: extractApiErrorMessage(result.error)
+ });
+ return;
+ }
+ await Promise.all([
+ queryClient.invalidateQueries({ queryKey: ['containers', environmentId] }),
+ queryClient.invalidateQueries({ queryKey: queryKeys.images.updateInfoByRef(environmentId, container.image) }),
+ queryClient.invalidateQueries({ queryKey: queryKeys.containers.detail(environmentId, containerId) })
+ ]);
+ if (updateViewMounted && environmentId === currentEnvId && containerId === container.id) await refreshAll();
+ }
function handleUpdateContainer() {
if (!container) return;
confirmAndUpdateContainer({
containerId: container.id,
containerName: containerDisplayName,
- showPullingToast: true,
+ environmentId: currentEnvId,
setLoading: (loading) => {
updateLoading = loading;
},
- onRefresh: () => refreshAll()
+ onRefresh: refreshAfterUpdate,
+ onAccepted: (activity) => {
+ if (updateViewMounted) updateActivities.accept(activity);
+ }
});
}
diff --git a/frontend/src/routes/(app)/containers/container-table.actions.ts b/frontend/src/routes/(app)/containers/container-table.actions.ts
index ebfae74ca..28002c5c1 100644
--- a/frontend/src/routes/(app)/containers/container-table.actions.ts
+++ b/frontend/src/routes/(app)/containers/container-table.actions.ts
@@ -15,7 +15,8 @@ import {
import type { TableActionConfig, TableBulkActionConfig } from '#lib/utils/table-action-types.js';
import { toast } from 'svelte-sonner';
import { getContainerDisplayName, type ActionStatus } from './container-table.helpers';
-import { throwOnContainerUpdateFailure } from '#lib/utils/update-actions.js';
+import type { Activity } from '#lib/types/activity.type.js';
+import { hasPermission } from '#lib/utils/auth.js';
type BulkLoadingState = {
start: boolean;
@@ -31,6 +32,9 @@ type ActionDeps = {
refreshContainers: () => Promise<ContainersPaginatedResponse>;
actionStatus: Record<string, ActionStatus>;
isBulkLoading: BulkLoadingState;
+ environmentId: () => string;
+ onUpdateAccepted: (activity: Activity) => void;
+ canRefreshUpdates: () => boolean;
};
type ContainerActionKind = 'start' | 'stop' | 'restart' | 'pause' | 'unpause' | 'redeploy';
@@ -55,7 +59,10 @@ export function createContainerActions({
setSelectedIds,
refreshContainers,
actionStatus,
- isBulkLoading
+ isBulkLoading,
+ environmentId,
+ onUpdateAccepted,
+ canRefreshUpdates
}: ActionDeps) {
const reloadContainers = async () => {
const result = await refreshContainers();
@@ -120,11 +127,12 @@ export function createContainerActions({
confirmAndUpdateContainer({
containerId: container.id,
containerName,
- useActivityToast: true,
+ environmentId: environmentId(),
setLoading: (loading) => {
actionStatus[container.id] = loading ? 'updating' : '';
},
- onRefresh: reloadContainers
+ onRefresh: () => (canRefreshUpdates() ? reloadContainers() : undefined),
+ onAccepted: onUpdateAccepted
});
}
@@ -214,6 +222,7 @@ export function createContainerActions({
}
function handleBulkUpdate(validIds: string[], allIds: string[]) {
+ const updateEnvironmentId = environmentId();
const totalCount = allIds.length;
const filteredCount = validIds.length;
const message =
@@ -227,16 +236,22 @@ export function createContainerActions({
message,
confirmLabel: m.common_update(),
destructive: false,
- run: (id) => containerService.updateContainer(id).then(throwOnContainerUpdateFailure),
+ run: (id) => containerService.updateContainer(id, updateEnvironmentId),
messages: {
- success: (count) => m.containers_bulk_update_success({ count }),
- partial: (success, total, failed) => m.containers_bulk_update_partial({ success, total, failed }),
- failure: () => m.containers_bulk_update_failed()
+ success: (count) => m.containers_bulk_update_accepted({ count }),
+ partial: (success, total, failed) => m.containers_bulk_update_accept_partial({ success, total, failed }),
+ failure: () => m.containers_bulk_update_accept_failed()
},
+ acceptanceOnly: true,
+ activityLink: hasPermission('activities:read', updateEnvironmentId),
+ onItemSuccess: (_id, activity) => onUpdateAccepted(activity),
setLoading: (loading) => {
isBulkLoading['update'] = loading;
},
- onComplete: () => reloadContainers(),
+ onComplete: () =>
+ canRefreshUpdates() && updateEnvironmentId === environmentId() && !hasPermission('activities:read', updateEnvironmentId)
+ ? reloadContainers()
+ : undefined,
clearSelection: () => setSelectedIds([])
});
}
diff --git a/frontend/src/routes/(app)/containers/container-table.svelte b/frontend/src/routes/(app)/containers/container-table.svelte
index 6fdde614c..02c9f840e 100644
--- a/frontend/src/routes/(app)/containers/container-table.svelte
+++ b/frontend/src/routes/(app)/containers/container-table.svelte
@@ -25,6 +25,9 @@
import ImageUpdateItem from '#lib/components/image-update-item.svelte';
import { PersistedState } from 'runed';
import { onMount } from 'svelte';
+ import { useQueryClient } from '@tanstack/svelte-query';
+ import { activityStore } from '#lib/stores/activity.store.svelte.js';
+ import { createContainerUpdateActivityTracker } from '#lib/utils/container-update-activities.js';
import { mode } from 'mode-watcher';
import { ContainerStatsManager } from './components/container-stats-manager.svelte';
import ContainerStatsSync from './components/container-stats-sync.svelte';
@@ -101,6 +104,17 @@
});
const statsManager = new ContainerStatsManager();
+ const queryClient = useQueryClient();
+ let updateTableMounted = false;
+ const updateActivities = createContainerUpdateActivityTracker(
+ () => environmentId,
+ () => {
+ if (!updateTableMounted || environmentId !== environmentStore.selected?.id) return;
+ void queryClient.invalidateQueries({ queryKey: ['containers', environmentId] });
+ void queryClient.invalidateQueries({ queryKey: ['container', environmentId] });
+ void refreshContainers(requestOptions);
+ }
+ );
const resourceSortSupported = $derived(containers.resourceSortSupported === true);
const resourceSortActive = $derived.by(() => {
@@ -203,7 +217,12 @@
},
refreshContainers: () => refreshContainers(requestOptions),
actionStatus,
- isBulkLoading
+ isBulkLoading,
+ environmentId: () => environmentId,
+ onUpdateAccepted: (activity) => {
+ if (updateTableMounted) updateActivities.accept(activity);
+ },
+ canRefreshUpdates: () => updateTableMounted && environmentId === environmentStore.selected?.id
});
const isAnyLoading = $derived(hasAnyLoadingState(actionStatus, isBulkLoading));
@@ -303,6 +322,8 @@
}
onMount(() => {
+ updateTableMounted = true;
+ const unsubscribeActivities = activityStore.subscribeActivities(updateActivities.observe);
collapsedGroupsState = new PersistedState<Record<string, boolean>>('container-groups-collapsed', {});
const persistedInternal = (customSettings['showInternalContainers'] as boolean) ?? false;
@@ -325,6 +346,8 @@
}
return () => {
+ updateTableMounted = false;
+ unsubscribeActivities();
statsManager.destroy();
};
});
diff --git a/frontend/src/routes/(app)/updates/+page.svelte b/frontend/src/routes/(app)/updates/+page.svelte
index 609785588..22e1f9805 100644
--- a/frontend/src/routes/(app)/updates/+page.svelte
+++ b/frontend/src/routes/(app)/updates/+page.svelte
@@ -227,9 +227,13 @@
bind:requestOptions={containerRequestOptions}
onIgnoreChanged={invalidateContainerQueries}
onRefreshData={async (options) => {
- containerRequestOptions = ensureStandaloneContainerUpdatesFilter(options);
- const next = await containerService.getContainersForEnvironment(envId, containerRequestOptions);
- containerSnapshot = { envId, value: next };
+ const requestedEnvId = envId;
+ const requestedOptions = ensureStandaloneContainerUpdatesFilter(options);
+ const next = await containerService.getContainersForEnvironment(requestedEnvId, requestedOptions);
+ if (requestedEnvId === envId) {
+ containerRequestOptions = requestedOptions;
+ containerSnapshot = { envId: requestedEnvId, value: next };
+ }
return next;
}}
/>
diff --git a/frontend/src/routes/(app)/updates/container-updates-table.svelte b/frontend/src/routes/(app)/updates/container-updates-table.svelte
index e9e145c56..df3975d7a 100644
--- a/frontend/src/routes/(app)/updates/container-updates-table.svelte
+++ b/frontend/src/routes/(app)/updates/container-updates-table.svelte
@@ -1,5 +1,9 @@
<script lang="ts">
import { tryCatch } from '#lib/utils/try-catch.js';
+ import { onMount } from 'svelte';
+ import { environmentStore } from '#lib/stores/environment.store.svelte.js';
+ import { activityStore } from '#lib/stores/activity.store.svelte.js';
+ import { createContainerUpdateActivityTracker } from '#lib/utils/container-update-activities.js';
import ArcaneTable from '#lib/components/arcane-table/arcane-table.svelte';
import RowActionsMenu from '#lib/components/arcane-table/row-actions-menu.svelte';
@@ -28,7 +32,6 @@
import { isAutoUpdateLabelDisabled } from '#lib/utils/container-auto-update.js';
import { extractApiErrorMessage } from '#lib/utils/api.js';
import { bulkConfirmAndRun } from '#lib/utils/bulk-actions.js';
- import { throwOnContainerUpdateFailure } from '#lib/utils/update-actions.js';
import { formatImageUpdateCheckedAt, formatImageUpdateValue } from '#lib/utils/image-updates.js';
import { toast } from 'svelte-sonner';
@@ -63,6 +66,22 @@
let updatingContainerIds = $state<Record<string, boolean>>({});
let ignoringContainerIds = $state<Record<string, boolean>>({});
let bulkUpdating = $state(false);
+ let updateTableMounted = false;
+ const currentEnvironmentId = $derived(environmentStore.selected?.id || '0');
+ const updateActivities = createContainerUpdateActivityTracker(
+ () => currentEnvironmentId,
+ () => {
+ if (updateTableMounted) void refreshRows();
+ }
+ );
+ onMount(() => {
+ updateTableMounted = true;
+ const unsubscribe = activityStore.subscribeActivities(updateActivities.observe);
+ return () => {
+ updateTableMounted = false;
+ unsubscribe();
+ };
+ });
function mapContainerRow(container: ContainerSummaryDto): ContainerUpdateRow {
const name = getContainerDisplayName(container);
@@ -112,7 +131,9 @@
];
async function refreshRows() {
- containers = await onRefreshData(requestOptions as ContainerListRequestOptions);
+ const requestedEnvId = currentEnvironmentId;
+ const next = await onRefreshData(requestOptions as ContainerListRequestOptions);
+ if (updateTableMounted && requestedEnvId === currentEnvironmentId) containers = next;
}
async function handleUpdateContainer(container: ContainerSummaryDto) {
@@ -121,11 +142,14 @@
confirmAndUpdateContainer({
containerId: container.id,
containerName,
- showPullingToast: true,
+ environmentId: currentEnvironmentId,
setLoading: (loading) => {
updatingContainerIds = { ...updatingContainerIds, [container.id]: loading };
},
- onRefresh: refreshRows
+ onRefresh: () => (updateTableMounted ? refreshRows() : undefined),
+ onAccepted: (activity) => {
+ if (updateTableMounted) updateActivities.accept(activity);
+ }
});
}
@@ -160,19 +184,30 @@
}
function handleBulkUpdate(ids: string[]) {
+ const updateEnvironmentId = currentEnvironmentId;
bulkConfirmAndRun({
ids,
title: m.updates_bulk_update_confirm_title({ count: ids.length }),
message: m.updates_bulk_update_confirm_message({ count: ids.length }),
confirmLabel: m.common_update(),
- run: (id) => containerService.updateContainer(id).then(throwOnContainerUpdateFailure),
+ run: (id) => containerService.updateContainer(id, updateEnvironmentId),
messages: {
- success: (count) => m.updates_bulk_update_success({ count }),
- partial: (success, total, failed) => m.updates_bulk_update_partial({ success, total, failed }),
- failure: () => m.updates_bulk_update_failed()
+ success: (count) => m.containers_bulk_update_accepted({ count }),
+ partial: (success, total, failed) => m.containers_bulk_update_accept_partial({ success, total, failed }),
+ failure: () => m.containers_bulk_update_accept_failed()
+ },
+ acceptanceOnly: true,
+ activityLink: hasPermission('activities:read', updateEnvironmentId),
+ onItemSuccess: (_id, activity) => {
+ if (updateTableMounted) updateActivities.accept(activity);
},
setLoading: (loading) => (bulkUpdating = loading),
- onComplete: refreshRows,
+ onComplete: () =>
+ updateTableMounted &&
+ updateEnvironmentId === currentEnvironmentId &&
+ !hasPermission('activities:read', updateEnvironmentId)
+ ? refreshRows()
+ : undefined,
clearSelection: () => (selectedIds = [])
});
}
diff --git a/tests/spec/updates.spec.ts b/tests/spec/updates.spec.ts
index f983aabd7..11f2b3f44 100644
--- a/tests/spec/updates.spec.ts
+++ b/tests/spec/updates.spec.ts
@@ -2,7 +2,7 @@ import { test, expect, type Page, type Route } from '../fixtures/test.fixture';
import { openRowActionsMenu } from '../utils/table-actions.util';
const UPDATES_ROUTE = '/updates';
-const CONTAINER_UPDATE_ROUTE = /\/api\/environments\/0\/containers\/[^/]+\/update$/;
+const CONTAINER_UPDATE_ROUTE = /\/api\/environments\/0\/containers\/[^/]+\/update\?async=true$/;
const CONTAINER_LIST_ROUTE = /\/api\/environments\/0\/containers(?:\?.*)?$/;
const CONTAINERS = [
@@ -145,17 +145,6 @@ type ContainerUpdateOutcome =
| { kind: 'failed'; error: string }
| { kind: 'request-error'; error: string };
-function containerUpdateItem(containerId: string, status: string, error?: string) {
- const container = CONTAINERS.find((candidate) => candidate.id === containerId)!;
- return {
- resourceId: containerId,
- resourceName: container.name,
- resourceType: 'container',
- status,
- error
- };
-}
-
/** Answers `POST .../containers/{id}/update` per container and records which ids were requested. */
async function stubContainerUpdates(page: Page, outcomes: Record<string, ContainerUpdateOutcome>) {
const requested: string[] = [];
@@ -171,32 +160,22 @@ async function stubContainerUpdates(page: Page, outcomes: Record<string, Contain
});
return;
}
- const data =
- outcome.kind === 'updated'
- ? {
- checked: 1,
- updated: 1,
- skipped: 0,
- failed: 0,
- items: [containerUpdateItem(containerId, 'updated')]
- }
- : outcome.kind === 'skipped'
- ? {
- checked: 1,
- updated: 0,
- skipped: 1,
- failed: 0,
- items: [containerUpdateItem(containerId, 'skipped', outcome.reason)]
- }
- : {
- checked: 1,
- updated: 0,
- skipped: 0,
- failed: 1,
- items: [containerUpdateItem(containerId, 'failed', outcome.error)]
- };
+ const container = CONTAINERS.find((candidate) => candidate.id === containerId)!;
+ const now = new Date().toISOString();
+ const data = {
+ id: `update-activity-${requested.length}`,
+ environmentId: '0',
+ sourceEnvironmentId: '0',
+ type: 'auto_update',
+ status: 'queued',
+ resourceType: 'container',
+ resourceId: containerId,
+ resourceName: container.name,
+ createdAt: now,
+ startedAt: now
+ };
await route.fulfill({
- status: 200,
+ status: 202,
contentType: 'application/json',
json: { success: true, data }
});
@@ -248,10 +227,10 @@ test.describe('Updates Page Project Rows', () => {
});
test.describe('Updates Page Actions', () => {
- test('applies updates to the selected container rows, including an ignored one', async ({
+ test('accepts updates for the selected container rows, including an ignored one', async ({
page
}) => {
- const listFetches = await stubContainersWithUpdates(page);
+ await stubContainersWithUpdates(page);
const requested = await stubContainerUpdates(page, {});
await page.goto(UPDATES_ROUTE);
@@ -259,16 +238,16 @@ test.describe('Updates Page Actions', () => {
await expect(
containerRow(page, IGNORED_CONTAINER).getByText('Ignored', { exact: true })
).toBeVisible();
- const fetchesBeforeUpdate = listFetches.count;
await selectAllContainerRows(page);
await confirmBulkUpdate(page);
- await expect(page.getByText(`Updated ${CONTAINERS.length} resource(s)`)).toBeVisible({
+ await expect(
+ page.getByText(`Started updates for ${CONTAINERS.length} container(s)`)
+ ).toBeVisible({
timeout: 15_000
});
expect(requested.sort()).toEqual(CONTAINERS.map((c) => c.id).sort());
- expect(listFetches.count).toBeGreaterThan(fetchesBeforeUpdate);
for (const container of CONTAINERS) {
await expect(
containerRow(page, container).getByRole('checkbox', { name: 'Select row' })
@@ -276,12 +255,12 @@ test.describe('Updates Page Actions', () => {
}
});
- test('does not count skipped or failed container updates as updated', async ({ page }) => {
+ test('counts submission failures separately from later update outcomes', async ({ page }) => {
await stubContainersWithUpdates(page);
const [alpha, beta] = CONTAINERS;
const requested = await stubContainerUpdates(page, {
- [beta.id]: { kind: 'skipped', reason: 'immutable image reference' },
- [IGNORED_CONTAINER.id]: { kind: 'failed', error: 'pull failed: registry unreachable' }
+ [beta.id]: { kind: 'failed', error: 'pull failed: registry unreachable' },
+ [IGNORED_CONTAINER.id]: { kind: 'request-error', error: 'executor unavailable' }
});
await page.goto(UPDATES_ROUTE);
@@ -291,15 +270,16 @@ test.describe('Updates Page Actions', () => {
await confirmBulkUpdate(page);
await expect(
- page.getByText(`Updated 1 of ${CONTAINERS.length} resource(s), 2 failed`)
+ page.getByText(`Started 2 of ${CONTAINERS.length} container update(s). 1 could not start.`)
).toBeVisible({
timeout: 15_000
});
+ await expect(page.getByText(`Updated ${CONTAINERS.length} resource(s)`)).toHaveCount(0);
expect(requested.sort()).toEqual([alpha.id, beta.id, IGNORED_CONTAINER.id].sort());
});
- test('row update reports a skipped reason or the server error and recovers', async ({ page }) => {
- const listFetches = await stubContainersWithUpdates(page);
+ test('row update acknowledges acceptance and reports submission errors', async ({ page }) => {
+ await stubContainersWithUpdates(page);
const outcomes: Record<string, ContainerUpdateOutcome> = {
[IGNORED_CONTAINER.id]: { kind: 'skipped', reason: 'immutable image reference' }
};
@@ -307,18 +287,16 @@ test.describe('Updates Page Actions', () => {
await page.goto(UPDATES_ROUTE);
await page.waitForLoadState('load');
- const fetchesBeforeUpdate = listFetches.count;
await updateContainerFromRow(page, IGNORED_CONTAINER);
await expect(
- page.getByText(`Container "${IGNORED_CONTAINER.name}" was not updated`)
+ page.getByText(`Update started for container "${IGNORED_CONTAINER.name}"`)
).toBeVisible({
timeout: 15_000
});
- await expect(page.getByText('immutable image reference')).toBeVisible();
+ await expect(page.getByText('immutable image reference')).toHaveCount(0);
await expect(page.getByText('Up to Date')).toHaveCount(0);
expect(requested).toEqual([IGNORED_CONTAINER.id]);
- await expect.poll(() => listFetches.count).toBeGreaterThan(fetchesBeforeUpdate);
outcomes[IGNORED_CONTAINER.id] = {
kind: 'request-error',
@@ -326,7 +304,9 @@ test.describe('Updates Page Actions', () => {
};
await updateContainerFromRow(page, IGNORED_CONTAINER);
await expect(
- page.getByText(`Failed to update container "${IGNORED_CONTAINER.name}"`)
+ page.getByText(
+ `Could not confirm the update request for container "${IGNORED_CONTAINER.name}"`
+ )
).toBeVisible({
timeout: 15_000
});