Skip to content

Modern Docker Management, Designed for Everyone

fix: decouple context for activities (#2754)

Kyle Mendell2afd24a787e7
diff --git a/backend/api/api.go b/backend/api/api.go
index 40f83d3ec..131fbdc84 100644
--- a/backend/api/api.go
+++ b/backend/api/api.go
@@ -1,6 +1,7 @@
package api
import (
+ "context"
"net/http"
"reflect"
"strings"
@@ -138,6 +139,7 @@ func capitalizeFirst(s string) string {
// Services holds all service dependencies needed by Huma handlers.
type Services struct {
+ AppContext context.Context
User *services.UserService
Auth *services.AuthService
Oidc *services.OidcService
@@ -347,9 +349,11 @@ func registerHandlers(api huma.API, svc *Services) {
var vulnerabilitySvc *services.VulnerabilityService
var dashboardSvc *services.DashboardService
var roleSvc *services.RoleService
+ var appCtx context.Context
var cfg *config.Config
if svc != nil {
+ appCtx = svc.AppContext
userSvc = svc.User
authSvc = svc.Auth
oidcSvc = svc.Oidc
@@ -388,13 +392,14 @@ func registerHandlers(api huma.API, svc *Services) {
roleSvc = svc.Role
cfg = svc.Config
}
+ handlerAppCtx := handlers.NewActivityAppContext(appCtx)
handlers.RegisterHealth(api)
handlers.RegisterAuth(api, userSvc, authSvc, oidcSvc)
handlers.RegisterApiKeys(api, apiKeySvc)
handlers.RegisterRoles(api, roleSvc)
handlers.RegisterAppImages(api, appImagesSvc)
handlers.RegisterUsers(api, userSvc, authSvc)
- handlers.RegisterProjects(api, projectSvc, activitySvc)
+ handlers.RegisterProjects(api, projectSvc, activitySvc, handlerAppCtx)
handlers.RegisterVersion(api, versionSvc)
handlers.RegisterEvents(api, eventSvc, apiKeySvc)
handlers.RegisterActivities(api, activitySvc, environmentSvc)
@@ -402,23 +407,23 @@ func registerHandlers(api huma.API, svc *Services) {
handlers.RegisterEnvironments(api, environmentSvc, settingsSvc, apiKeySvc, eventSvc, cfg)
handlers.RegisterContainerRegistries(api, containerRegistrySvc, environmentSvc)
handlers.RegisterTemplates(api, templateSvc, environmentSvc)
- handlers.RegisterImages(api, dockerSvc, imageSvc, imageUpdateSvc, settingsSvc, buildSvc, activitySvc)
+ handlers.RegisterImages(api, dockerSvc, imageSvc, imageUpdateSvc, settingsSvc, buildSvc, activitySvc, handlerAppCtx)
handlers.RegisterBuildWorkspaces(api, buildWorkspaceSvc)
- handlers.RegisterImageUpdates(api, imageUpdateSvc, imageSvc)
+ handlers.RegisterImageUpdates(api, imageUpdateSvc, imageSvc, handlerAppCtx)
handlers.RegisterSettings(api, settingsSvc, settingsSearchSvc, environmentSvc, cfg)
handlers.RegisterJobSchedules(api, jobScheduleSvc, environmentSvc)
- handlers.RegisterVolumes(api, dockerSvc, volumeSvc, activitySvc)
- handlers.RegisterContainers(api, containerSvc, dockerSvc, settingsSvc, activitySvc)
+ handlers.RegisterVolumes(api, dockerSvc, volumeSvc, activitySvc, handlerAppCtx)
+ handlers.RegisterContainers(api, containerSvc, dockerSvc, settingsSvc, activitySvc, handlerAppCtx)
handlers.RegisterPorts(api, portSvc)
- handlers.RegisterNetworks(api, networkSvc, dockerSvc, activitySvc)
+ handlers.RegisterNetworks(api, networkSvc, dockerSvc, activitySvc, handlerAppCtx)
handlers.RegisterSwarm(api, swarmSvc, environmentSvc, eventSvc, cfg)
handlers.RegisterNotifications(api, notificationSvc, cfg)
- handlers.RegisterUpdater(api, updaterSvc)
+ handlers.RegisterUpdater(api, updaterSvc, handlerAppCtx)
handlers.RegisterCustomize(api, customizeSearchSvc)
- handlers.RegisterSystem(api, dockerSvc, systemSvc, systemUpgradeSvc, cfg, activitySvc)
+ handlers.RegisterSystem(api, dockerSvc, systemSvc, systemUpgradeSvc, cfg, activitySvc, handlerAppCtx)
handlers.RegisterGitRepositories(api, gitRepositorySvc)
handlers.RegisterGitOpsSyncs(api, gitOpsSyncSvc)
handlers.RegisterWebhooks(api, webhookSvc)
- handlers.RegisterVulnerability(api, vulnerabilitySvc)
+ handlers.RegisterVulnerability(api, vulnerabilitySvc, handlerAppCtx)
handlers.RegisterDashboard(api, dashboardSvc)
}
diff --git a/backend/api/handlers/containers.go b/backend/api/handlers/containers.go
index a7a80d4e8..ead17960c 100644
--- a/backend/api/handlers/containers.go
+++ b/backend/api/handlers/containers.go
@@ -30,6 +30,7 @@ type ContainerHandler struct {
dockerService *services.DockerClientService
settingsService *services.SettingsService
activityService *services.ActivityService
+ appCtx context.Context
}
// Paginated response
@@ -142,12 +143,13 @@ type SetAutoUpdateOutput struct {
Body ContainerActionResponse
}
-func RegisterContainers(api huma.API, containerSvc *services.ContainerService, dockerSvc *services.DockerClientService, settingsSvc *services.SettingsService, activitySvc *services.ActivityService) {
+func RegisterContainers(api huma.API, containerSvc *services.ContainerService, dockerSvc *services.DockerClientService, settingsSvc *services.SettingsService, activitySvc *services.ActivityService, appCtx ActivityAppContext) {
h := &ContainerHandler{
containerService: containerSvc,
dockerService: dockerSvc,
settingsService: settingsSvc,
activityService: activitySvc,
+ appCtx: appCtx.contextInternal(),
}
huma.Register(api, huma.Operation{
@@ -622,12 +624,13 @@ func (h *ContainerHandler) StartContainer(ctx context.Context, input *ContainerA
return nil, huma.Error401Unauthorized("not authenticated")
}
- activityID := activitylib.StartHandlerActivityForUser(ctx, h.activityService, input.EnvironmentID, models.ActivityTypeContainerStart, "container", input.ContainerID, input.ContainerID, user, "Starting container", "Container start requested", models.JSON{"containerID": input.ContainerID})
- if err := h.containerService.StartContainer(ctx, input.ContainerID, *user); err != nil {
- activitylib.CompleteHandlerActivity(ctx, h.activityService, activityID, "Container started", err)
+ runtimeCtx := utils.ActivityRuntimeContext(ctx, h.appCtx)
+ activityID := activitylib.StartHandlerActivityForUser(runtimeCtx, h.activityService, input.EnvironmentID, models.ActivityTypeContainerStart, "container", input.ContainerID, input.ContainerID, user, "Starting container", "Container start requested", models.JSON{"containerID": input.ContainerID})
+ if err := h.containerService.StartContainer(runtimeCtx, input.ContainerID, *user); err != nil {
+ activitylib.CompleteHandlerActivity(runtimeCtx, h.activityService, activityID, "Container started", err)
return nil, huma.Error500InternalServerError((&common.ContainerStartError{Err: err}).Error())
}
- activitylib.CompleteHandlerActivity(ctx, h.activityService, activityID, "Container started", nil)
+ activitylib.CompleteHandlerActivity(runtimeCtx, h.activityService, activityID, "Container started", nil)
return &ContainerActionOutput{
Body: ContainerActionResponse{
@@ -647,12 +650,13 @@ func (h *ContainerHandler) StopContainer(ctx context.Context, input *ContainerAc
return nil, huma.Error401Unauthorized("not authenticated")
}
- activityID := activitylib.StartHandlerActivityForUser(ctx, h.activityService, input.EnvironmentID, models.ActivityTypeContainerStop, "container", input.ContainerID, input.ContainerID, user, "Stopping container", "Container stop requested", models.JSON{"containerID": input.ContainerID})
- if err := h.containerService.StopContainer(ctx, input.ContainerID, *user); err != nil {
- activitylib.CompleteHandlerActivity(ctx, h.activityService, activityID, "Container stopped", err)
+ runtimeCtx := utils.ActivityRuntimeContext(ctx, h.appCtx)
+ activityID := activitylib.StartHandlerActivityForUser(runtimeCtx, h.activityService, input.EnvironmentID, models.ActivityTypeContainerStop, "container", input.ContainerID, input.ContainerID, user, "Stopping container", "Container stop requested", models.JSON{"containerID": input.ContainerID})
+ if err := h.containerService.StopContainer(runtimeCtx, input.ContainerID, *user); err != nil {
+ activitylib.CompleteHandlerActivity(runtimeCtx, h.activityService, activityID, "Container stopped", err)
return nil, huma.Error500InternalServerError((&common.ContainerStopError{Err: err}).Error())
}
- activitylib.CompleteHandlerActivity(ctx, h.activityService, activityID, "Container stopped", nil)
+ activitylib.CompleteHandlerActivity(runtimeCtx, h.activityService, activityID, "Container stopped", nil)
return &ContainerActionOutput{
Body: ContainerActionResponse{
@@ -672,12 +676,13 @@ func (h *ContainerHandler) RestartContainer(ctx context.Context, input *Containe
return nil, huma.Error401Unauthorized("not authenticated")
}
- activityID := activitylib.StartHandlerActivityForUser(ctx, h.activityService, input.EnvironmentID, models.ActivityTypeContainerRestart, "container", input.ContainerID, input.ContainerID, user, "Restarting container", "Container restart requested", models.JSON{"containerID": input.ContainerID})
- if err := h.containerService.RestartContainer(ctx, input.ContainerID, *user); err != nil {
- activitylib.CompleteHandlerActivity(ctx, h.activityService, activityID, "Container restarted", err)
+ runtimeCtx := utils.ActivityRuntimeContext(ctx, h.appCtx)
+ activityID := activitylib.StartHandlerActivityForUser(runtimeCtx, h.activityService, input.EnvironmentID, models.ActivityTypeContainerRestart, "container", input.ContainerID, input.ContainerID, user, "Restarting container", "Container restart requested", models.JSON{"containerID": input.ContainerID})
+ if err := h.containerService.RestartContainer(runtimeCtx, input.ContainerID, *user); err != nil {
+ activitylib.CompleteHandlerActivity(runtimeCtx, h.activityService, activityID, "Container restarted", err)
return nil, huma.Error500InternalServerError((&common.ContainerRestartError{Err: err}).Error())
}
- activitylib.CompleteHandlerActivity(ctx, h.activityService, activityID, "Container restarted", nil)
+ activitylib.CompleteHandlerActivity(runtimeCtx, h.activityService, activityID, "Container restarted", nil)
return &ContainerActionOutput{
Body: ContainerActionResponse{
@@ -697,20 +702,21 @@ func (h *ContainerHandler) RedeployContainer(ctx context.Context, input *Contain
return nil, huma.Error401Unauthorized("not authenticated")
}
- activityID := activitylib.StartHandlerActivityForUser(ctx, h.activityService, input.EnvironmentID, models.ActivityTypeContainerRedeploy, "container", input.ContainerID, input.ContainerID, user, "Starting redeploy", "Container redeploy requested", models.JSON{"containerID": input.ContainerID})
- activityWriter := activitylib.NewWriter(ctx, h.activityService, activityID, io.Discard, "Redeploying container")
- redeployCtx := context.WithValue(ctx, projects.ProgressWriterKey{}, activityWriter)
+ runtimeCtx := utils.ActivityRuntimeContext(ctx, h.appCtx)
+ activityID := activitylib.StartHandlerActivityForUser(runtimeCtx, h.activityService, input.EnvironmentID, models.ActivityTypeContainerRedeploy, "container", input.ContainerID, input.ContainerID, user, "Starting redeploy", "Container redeploy requested", models.JSON{"containerID": input.ContainerID})
+ activityWriter := activitylib.NewWriter(runtimeCtx, h.activityService, activityID, io.Discard, "Redeploying container")
+ redeployCtx := context.WithValue(runtimeCtx, projects.ProgressWriterKey{}, activityWriter)
newContainerID, err := h.containerService.RedeployContainer(redeployCtx, input.ContainerID, *user)
if err != nil {
activitylib.FlushWriter(activityWriter)
- activitylib.CompleteHandlerActivity(ctx, h.activityService, activityID, "Container redeploy failed", err)
+ activitylib.CompleteHandlerActivity(runtimeCtx, h.activityService, activityID, "Container redeploy failed", err)
return nil, huma.Error500InternalServerError((&common.ContainerRedeployError{Err: err}).Error())
}
activitylib.FlushWriter(activityWriter)
- activitylib.CompleteHandlerActivity(ctx, h.activityService, activityID, "Container redeployed", nil)
+ activitylib.CompleteHandlerActivity(runtimeCtx, h.activityService, activityID, "Container redeployed", nil)
// Fetch full container details to return (consistent with other endpoints)
- details, inspectErr := h.containerService.GetContainerDetails(ctx, newContainerID)
+ details, inspectErr := h.containerService.GetContainerDetails(runtimeCtx, newContainerID)
if inspectErr == nil {
details.ActivityID = utils.StringPtrFromTrimmed(activityID)
@@ -745,12 +751,13 @@ func (h *ContainerHandler) DeleteContainer(ctx context.Context, input *DeleteCon
return nil, huma.Error401Unauthorized("not authenticated")
}
- activityID := activitylib.StartHandlerActivityForUser(ctx, h.activityService, input.EnvironmentID, models.ActivityTypeContainerDelete, "container", input.ContainerID, input.ContainerID, user, "Deleting container", "Container delete requested", models.JSON{"containerID": input.ContainerID, "force": input.Force, "removeVolumes": input.RemoveVolumes})
- if err := h.containerService.DeleteContainer(ctx, input.ContainerID, input.Force, input.RemoveVolumes, *user); err != nil {
- activitylib.CompleteHandlerActivity(ctx, h.activityService, activityID, "Container deleted", err)
+ runtimeCtx := utils.ActivityRuntimeContext(ctx, h.appCtx)
+ activityID := activitylib.StartHandlerActivityForUser(runtimeCtx, h.activityService, input.EnvironmentID, models.ActivityTypeContainerDelete, "container", input.ContainerID, input.ContainerID, user, "Deleting container", "Container delete requested", models.JSON{"containerID": input.ContainerID, "force": input.Force, "removeVolumes": input.RemoveVolumes})
+ if err := h.containerService.DeleteContainer(runtimeCtx, input.ContainerID, input.Force, input.RemoveVolumes, *user); err != nil {
+ activitylib.CompleteHandlerActivity(runtimeCtx, h.activityService, activityID, "Container deleted", err)
return nil, huma.Error500InternalServerError((&common.ContainerDeleteError{Err: err}).Error())
}
- activitylib.CompleteHandlerActivity(ctx, h.activityService, activityID, "Container deleted", nil)
+ activitylib.CompleteHandlerActivity(runtimeCtx, h.activityService, activityID, "Container deleted", nil)
return &DeleteContainerOutput{
Body: ContainerActionResponse{
diff --git a/backend/api/handlers/helpers.go b/backend/api/handlers/helpers.go
index f7f37d107..20ad2937e 100644
--- a/backend/api/handlers/helpers.go
+++ b/backend/api/handlers/helpers.go
@@ -11,6 +11,25 @@ import (
"github.com/getarcaneapp/arcane/backend/pkg/remenv"
)
+// ActivityAppContext carries the app lifecycle context through handler registration.
+type ActivityAppContext struct {
+ ctx context.Context
+}
+
+// NewActivityAppContext wraps the app lifecycle context for handler constructors.
+func NewActivityAppContext(ctx context.Context) ActivityAppContext {
+ return ActivityAppContext{ctx: ctx}
+}
+
+// ContextInternal returns the wrapped app lifecycle context.
+func (c ActivityAppContext) ContextInternal() context.Context {
+ return c.contextInternal()
+}
+
+func (c ActivityAppContext) contextInternal() context.Context {
+ return c.ctx
+}
+
// buildPaginationParamsInternal converts query parameters to pagination.QueryParams.
// A limit of -1 means "show all items" (no pagination).
func buildPaginationParamsInternal(start, limit int, sortCol, sortDir, search string) pagination.QueryParams {
diff --git a/backend/api/handlers/image_updates.go b/backend/api/handlers/image_updates.go
index 6ec286773..fe859a591 100644
--- a/backend/api/handlers/image_updates.go
+++ b/backend/api/handlers/image_updates.go
@@ -10,6 +10,7 @@ import (
"github.com/getarcaneapp/arcane/backend/internal/common"
"github.com/getarcaneapp/arcane/backend/internal/services"
"github.com/getarcaneapp/arcane/backend/pkg/authz"
+ "github.com/getarcaneapp/arcane/backend/pkg/utils"
"github.com/getarcaneapp/arcane/types/base"
imagetypes "github.com/getarcaneapp/arcane/types/image"
"github.com/getarcaneapp/arcane/types/imageupdate"
@@ -18,6 +19,7 @@ import (
type ImageUpdateHandler struct {
imageUpdateService *services.ImageUpdateService
imageService *services.ImageService
+ appCtx context.Context
}
type CheckImageUpdateInput struct {
@@ -74,10 +76,11 @@ type GetUpdateSummaryOutput struct {
}
// RegisterImageUpdates registers image update endpoints.
-func RegisterImageUpdates(api huma.API, imageUpdateSvc *services.ImageUpdateService, imageSvc *services.ImageService) {
+func RegisterImageUpdates(api huma.API, imageUpdateSvc *services.ImageUpdateService, imageSvc *services.ImageService, appCtx ActivityAppContext) {
h := &ImageUpdateHandler{
imageUpdateService: imageUpdateSvc,
imageService: imageSvc,
+ appCtx: appCtx.contextInternal(),
}
huma.Register(api, huma.Operation{
@@ -156,7 +159,8 @@ func (h *ImageUpdateHandler) CheckImageUpdate(ctx context.Context, input *CheckI
return nil, huma.Error400BadRequest((&common.ImageRefRequiredError{}).Error())
}
- result, err := h.imageUpdateService.CheckImageUpdate(ctx, input.ImageRef)
+ runtimeCtx := utils.ActivityRuntimeContext(ctx, h.appCtx)
+ result, err := h.imageUpdateService.CheckImageUpdate(runtimeCtx, input.ImageRef)
if err != nil {
return nil, huma.Error500InternalServerError((&common.ImageUpdateCheckError{Err: err}).Error())
}
@@ -174,7 +178,8 @@ func (h *ImageUpdateHandler) CheckImageUpdateByID(ctx context.Context, input *Ch
return nil, huma.Error400BadRequest((&common.ImageIDRequiredError{}).Error())
}
- result, err := h.imageUpdateService.CheckImageUpdateByID(ctx, input.ImageID)
+ runtimeCtx := utils.ActivityRuntimeContext(ctx, h.appCtx)
+ result, err := h.imageUpdateService.CheckImageUpdateByID(runtimeCtx, input.ImageID)
if err != nil {
return nil, huma.Error500InternalServerError((&common.ImageUpdateCheckError{Err: err}).Error())
}
@@ -198,7 +203,8 @@ func (h *ImageUpdateHandler) CheckMultipleImages(ctx context.Context, input *Che
}, nil
}
- results, err := h.imageUpdateService.CheckMultipleImages(ctx, input.Body.ImageRefs, input.Body.Credentials)
+ runtimeCtx := utils.ActivityRuntimeContext(ctx, h.appCtx)
+ results, err := h.imageUpdateService.CheckMultipleImages(runtimeCtx, input.Body.ImageRefs, input.Body.Credentials)
if err != nil {
return nil, huma.Error500InternalServerError((&common.BatchImageUpdateCheckError{Err: err}).Error())
}
@@ -212,7 +218,8 @@ func (h *ImageUpdateHandler) CheckMultipleImages(ctx context.Context, input *Che
}
func (h *ImageUpdateHandler) CheckAllImages(ctx context.Context, input *CheckAllImagesInput) (*CheckAllImagesOutput, error) {
- results, err := h.imageUpdateService.CheckAllImages(ctx, 0, input.Body.Credentials)
+ runtimeCtx := utils.ActivityRuntimeContext(ctx, h.appCtx)
+ results, err := h.imageUpdateService.CheckAllImages(runtimeCtx, 0, input.Body.Credentials)
if err != nil {
return nil, huma.Error500InternalServerError((&common.AllImageUpdateCheckError{Err: err}).Error())
}
diff --git a/backend/api/handlers/images.go b/backend/api/handlers/images.go
index c3b377c1b..63a85fcae 100644
--- a/backend/api/handlers/images.go
+++ b/backend/api/handlers/images.go
@@ -16,6 +16,7 @@ import (
"github.com/getarcaneapp/arcane/backend/pkg/authz"
activitylib "github.com/getarcaneapp/arcane/backend/pkg/libarcane/activity"
"github.com/getarcaneapp/arcane/backend/pkg/pagination"
+ "github.com/getarcaneapp/arcane/backend/pkg/utils"
"github.com/getarcaneapp/arcane/types/base"
"github.com/getarcaneapp/arcane/types/image"
"github.com/getarcaneapp/arcane/types/system"
@@ -30,6 +31,7 @@ type ImageHandler struct {
settingsService *services.SettingsService
buildService *services.BuildService
activityService *services.ActivityService
+ appCtx context.Context
}
// --- Huma Input/Output Wrappers ---
@@ -153,7 +155,7 @@ type UploadImageOutput struct {
}
// RegisterImages registers image management routes using Huma.
-func RegisterImages(api huma.API, dockerService *services.DockerClientService, imageService *services.ImageService, imageUpdateService *services.ImageUpdateService, settingsService *services.SettingsService, buildService *services.BuildService, activityService *services.ActivityService) {
+func RegisterImages(api huma.API, dockerService *services.DockerClientService, imageService *services.ImageService, imageUpdateService *services.ImageUpdateService, settingsService *services.SettingsService, buildService *services.BuildService, activityService *services.ActivityService, appCtx ActivityAppContext) {
h := &ImageHandler{
dockerService: dockerService,
imageService: imageService,
@@ -161,6 +163,7 @@ func RegisterImages(api huma.API, dockerService *services.DockerClientService, i
settingsService: settingsService,
buildService: buildService,
activityService: activityService,
+ appCtx: appCtx.contextInternal(),
}
huma.Register(api, huma.Operation{
@@ -448,9 +451,10 @@ func (h *ImageHandler) PullImage(ctx context.Context, input *PullImageInput) (*h
humaCtx.SetHeader("Connection", "keep-alive")
humaCtx.SetHeader("X-Accel-Buffering", "no")
+ runtimeCtx := utils.ActivityRuntimeContext(humaCtx.Context(), h.appCtx)
rawWriter := humaCtx.BodyWriter()
activityID := activitylib.StartHandlerActivityForUser(
- humaCtx.Context(),
+ runtimeCtx,
h.activityService,
input.EnvironmentID,
models.ActivityTypeImagePull,
@@ -467,15 +471,15 @@ func (h *ImageHandler) PullImage(ctx context.Context, input *PullImageInput) (*h
f.Flush()
}
- writer := activitylib.NewWriter(humaCtx.Context(), h.activityService, activityID, rawWriter, "Pulling image")
- if err := h.imageService.PullImage(humaCtx.Context(), fullImageName, writer, *user, credentials); err != nil {
+ writer := activitylib.NewWriter(runtimeCtx, h.activityService, activityID, rawWriter, "Pulling image")
+ if err := h.imageService.PullImage(runtimeCtx, fullImageName, writer, *user, credentials); err != nil {
activitylib.FlushWriter(writer)
- activitylib.CompleteHandlerActivity(humaCtx.Context(), h.activityService, activityID, "Image pull failed", err)
+ activitylib.CompleteHandlerActivity(runtimeCtx, h.activityService, activityID, "Image pull failed", err)
_, _ = fmt.Fprintf(writer, `{"error":%q}`+"\n", err.Error())
return
}
activitylib.FlushWriter(writer)
- activitylib.CompleteHandlerActivity(humaCtx.Context(), h.activityService, activityID, "Image pull completed", nil)
+ activitylib.CompleteHandlerActivity(runtimeCtx, h.activityService, activityID, "Image pull completed", nil)
},
}, nil
}
@@ -502,13 +506,14 @@ func (h *ImageHandler) BuildImage(ctx context.Context, input *BuildImageInput) (
humaCtx.SetHeader("Connection", "keep-alive")
humaCtx.SetHeader("X-Accel-Buffering", "no")
+ runtimeCtx := utils.ActivityRuntimeContext(humaCtx.Context(), h.appCtx)
rawWriter := humaCtx.BodyWriter()
resourceName := strings.Join(input.Body.Tags, ", ")
if strings.TrimSpace(resourceName) == "" {
resourceName = input.Body.ContextDir
}
activityID := activitylib.StartHandlerActivityForUser(
- humaCtx.Context(),
+ runtimeCtx,
h.activityService,
input.EnvironmentID,
models.ActivityTypeImageBuild,
@@ -525,15 +530,15 @@ func (h *ImageHandler) BuildImage(ctx context.Context, input *BuildImageInput) (
f.Flush()
}
- writer := activitylib.NewWriter(humaCtx.Context(), h.activityService, activityID, rawWriter, "Building image")
- if _, err := h.buildService.BuildImage(humaCtx.Context(), input.EnvironmentID, input.Body, writer, "", user); err != nil {
+ writer := activitylib.NewWriter(runtimeCtx, h.activityService, activityID, rawWriter, "Building image")
+ if _, err := h.buildService.BuildImage(runtimeCtx, input.EnvironmentID, input.Body, writer, "", user); err != nil {
activitylib.FlushWriter(writer)
- activitylib.CompleteHandlerActivity(humaCtx.Context(), h.activityService, activityID, "Image build failed", err)
+ activitylib.CompleteHandlerActivity(runtimeCtx, h.activityService, activityID, "Image build failed", err)
_, _ = fmt.Fprintf(writer, `{"error":%q}`+"\n", err.Error())
return
}
activitylib.FlushWriter(writer)
- activitylib.CompleteHandlerActivity(humaCtx.Context(), h.activityService, activityID, "Image build completed", nil)
+ activitylib.CompleteHandlerActivity(runtimeCtx, h.activityService, activityID, "Image build completed", nil)
},
}, nil
}
diff --git a/backend/api/handlers/networks.go b/backend/api/handlers/networks.go
index 81a8fc348..bd7039d42 100644
--- a/backend/api/handlers/networks.go
+++ b/backend/api/handlers/networks.go
@@ -27,6 +27,7 @@ type NetworkHandler struct {
networkService *services.NetworkService
dockerService *services.DockerClientService
activityService *services.ActivityService
+ appCtx context.Context
}
type NetworkPaginatedResponse struct {
@@ -137,11 +138,12 @@ type PruneNetworksOutput struct {
}
// RegisterNetworks registers network endpoints.
-func RegisterNetworks(api huma.API, networkSvc *services.NetworkService, dockerSvc *services.DockerClientService, activitySvc *services.ActivityService) {
+func RegisterNetworks(api huma.API, networkSvc *services.NetworkService, dockerSvc *services.DockerClientService, activitySvc *services.ActivityService, appCtx ActivityAppContext) {
h := &NetworkHandler{
networkService: networkSvc,
dockerService: dockerSvc,
activityService: activitySvc,
+ appCtx: appCtx.contextInternal(),
}
huma.Register(api, huma.Operation{
@@ -285,7 +287,8 @@ func (h *NetworkHandler) CreateNetwork(ctx context.Context, input *CreateNetwork
dockerOptions := input.Body.Options.ToDockerCreateOptions()
var response *dockernetwork.CreateResponse
- activityID, err := activitylib.RunHandlerActivity(ctx, h.activityService, activitylib.HandlerOptions{
+ runtimeCtx := utils.ActivityRuntimeContext(ctx, h.appCtx)
+ activityID, err := activitylib.RunHandlerActivity(runtimeCtx, h.activityService, activitylib.HandlerOptions{
EnvironmentID: input.EnvironmentID,
Type: models.ActivityTypeResourceAction,
ResourceType: "network",
@@ -301,7 +304,7 @@ func (h *NetworkHandler) CreateNetwork(ctx context.Context, input *CreateNetwork
},
}, func() error {
var createErr error
- response, createErr = h.networkService.CreateNetwork(ctx, input.Body.Name, dockerOptions, *user)
+ response, createErr = h.networkService.CreateNetwork(runtimeCtx, input.Body.Name, dockerOptions, *user)
return createErr
})
if err != nil {
@@ -430,7 +433,8 @@ func (h *NetworkHandler) DeleteNetwork(ctx context.Context, input *DeleteNetwork
return nil, huma.Error401Unauthorized("not authenticated")
}
- activityID, err := activitylib.RunHandlerActivity(ctx, h.activityService, activitylib.HandlerOptions{
+ runtimeCtx := utils.ActivityRuntimeContext(ctx, h.appCtx)
+ activityID, err := activitylib.RunHandlerActivity(runtimeCtx, h.activityService, activitylib.HandlerOptions{
EnvironmentID: input.EnvironmentID,
Type: models.ActivityTypeResourceAction,
ResourceType: "network",
@@ -444,7 +448,7 @@ func (h *NetworkHandler) DeleteNetwork(ctx context.Context, input *DeleteNetwork
"action": "remove_network",
},
}, func() error {
- return h.networkService.RemoveNetwork(ctx, input.NetworkID, *user)
+ return h.networkService.RemoveNetwork(runtimeCtx, input.NetworkID, *user)
})
if err != nil {
return nil, huma.Error500InternalServerError((&common.NetworkRemovalError{Err: err}).Error())
@@ -460,7 +464,8 @@ func (h *NetworkHandler) DeleteNetwork(ctx context.Context, input *DeleteNetwork
func (h *NetworkHandler) PruneNetworks(ctx context.Context, input *PruneNetworksInput) (*PruneNetworksOutput, error) {
var report *dockernetwork.PruneReport
- activityID, err := activitylib.RunHandlerActivity(ctx, h.activityService, activitylib.HandlerOptions{
+ runtimeCtx := utils.ActivityRuntimeContext(ctx, h.appCtx)
+ activityID, err := activitylib.RunHandlerActivity(runtimeCtx, h.activityService, activitylib.HandlerOptions{
EnvironmentID: input.EnvironmentID,
Type: models.ActivityTypeResourceAction,
ResourceType: "network",
@@ -470,7 +475,7 @@ func (h *NetworkHandler) PruneNetworks(ctx context.Context, input *PruneNetworks
Metadata: models.JSON{"action": "prune_networks"},
}, func() error {
var pruneErr error
- report, pruneErr = h.networkService.PruneNetworks(ctx)
+ report, pruneErr = h.networkService.PruneNetworks(runtimeCtx)
return pruneErr
})
if err != nil {
diff --git a/backend/api/handlers/projects.go b/backend/api/handlers/projects.go
index 051b6758d..d2cfad1c7 100644
--- a/backend/api/handlers/projects.go
+++ b/backend/api/handlers/projects.go
@@ -28,6 +28,7 @@ import (
type ProjectHandler struct {
projectService *services.ProjectService
activityService *services.ActivityService
+ appCtx context.Context
}
// --- Huma Input/Output Wrappers ---
@@ -207,10 +208,11 @@ type PullProgressEvent struct {
// RegisterProjects registers project management routes using Huma.
// Note: WebSocket and streaming endpoints remain as Gin handlers.
-func RegisterProjects(api huma.API, projectService *services.ProjectService, activityService *services.ActivityService) {
+func RegisterProjects(api huma.API, projectService *services.ProjectService, activityService *services.ActivityService, appCtx ActivityAppContext) {
h := &ProjectHandler{
projectService: projectService,
activityService: activityService,
+ appCtx: appCtx.contextInternal(),
}
huma.Register(api, huma.Operation{
@@ -599,9 +601,10 @@ func (h *ProjectHandler) DeployProject(ctx context.Context, input *DeployProject
humaCtx.SetHeader("Connection", "keep-alive")
humaCtx.SetHeader("X-Accel-Buffering", "no")
+ runtimeCtx := utils.ActivityRuntimeContext(humaCtx.Context(), h.appCtx)
rawWriter := humaCtx.BodyWriter()
activityID := activitylib.StartHandlerActivityForUser(
- humaCtx.Context(),
+ runtimeCtx,
h.activityService,
input.EnvironmentID,
models.ActivityTypeProjectDeploy,
@@ -618,16 +621,16 @@ func (h *ProjectHandler) DeployProject(ctx context.Context, input *DeployProject
f.Flush()
}
- writer := activitylib.NewWriter(humaCtx.Context(), h.activityService, activityID, rawWriter, "Deploying project")
+ writer := activitylib.NewWriter(runtimeCtx, h.activityService, activityID, rawWriter, "Deploying project")
_, _ = writer.Write([]byte(`{"type":"deploy","phase":"begin"}` + "\n"))
if f, ok := writer.(http.Flusher); ok {
f.Flush()
}
- deployCtx := context.WithValue(humaCtx.Context(), projects.ProgressWriterKey{}, writer)
+ deployCtx := context.WithValue(runtimeCtx, projects.ProgressWriterKey{}, writer)
if err := h.projectService.DeployProject(deployCtx, input.ProjectID, *user, input.Body); err != nil {
activitylib.FlushWriter(writer)
- activitylib.CompleteHandlerActivity(humaCtx.Context(), h.activityService, activityID, "Project deployment failed", err)
+ activitylib.CompleteHandlerActivity(runtimeCtx, h.activityService, activityID, "Project deployment failed", err)
_, _ = fmt.Fprintf(writer, `{"error":%q}`+"\n", err.Error())
if f, ok := writer.(http.Flusher); ok {
f.Flush()
@@ -639,7 +642,7 @@ func (h *ProjectHandler) DeployProject(ctx context.Context, input *DeployProject
if f, ok := writer.(http.Flusher); ok {
f.Flush()
}
- activitylib.CompleteHandlerActivity(humaCtx.Context(), h.activityService, activityID, "Project deployment completed", nil)
+ activitylib.CompleteHandlerActivity(runtimeCtx, h.activityService, activityID, "Project deployment completed", nil)
},
}, nil
}
@@ -655,12 +658,13 @@ func (h *ProjectHandler) DownProject(ctx context.Context, input *DownProjectInpu
return nil, huma.Error401Unauthorized((&common.NotAuthenticatedError{}).Error())
}
- activityID := activitylib.StartHandlerActivityForUser(ctx, h.activityService, input.EnvironmentID, models.ActivityTypeProjectDown, "project", input.ProjectID, input.ProjectID, user, "Stopping project", "Project stop requested", models.JSON{"projectID": input.ProjectID})
- activityWriter := activitylib.NewWriter(ctx, h.activityService, activityID, io.Discard, "Stopping project")
- downCtx := context.WithValue(ctx, projects.ProgressWriterKey{}, activityWriter)
+ runtimeCtx := utils.ActivityRuntimeContext(ctx, h.appCtx)
+ activityID := activitylib.StartHandlerActivityForUser(runtimeCtx, h.activityService, input.EnvironmentID, models.ActivityTypeProjectDown, "project", input.ProjectID, input.ProjectID, user, "Stopping project", "Project stop requested", models.JSON{"projectID": input.ProjectID})
+ activityWriter := activitylib.NewWriter(runtimeCtx, h.activityService, activityID, io.Discard, "Stopping project")
+ downCtx := context.WithValue(runtimeCtx, projects.ProgressWriterKey{}, activityWriter)
if err := h.projectService.DownProject(downCtx, input.ProjectID, *user); err != nil {
activitylib.FlushWriter(activityWriter)
- activitylib.CompleteHandlerActivity(ctx, h.activityService, activityID, "Project stopped", err)
+ activitylib.CompleteHandlerActivity(runtimeCtx, h.activityService, activityID, "Project stopped", err)
var archivedErr *common.ProjectArchivedError
if errors.As(err, &archivedErr) {
return nil, huma.Error400BadRequest((&common.ProjectDownError{Err: err}).Error())
@@ -668,7 +672,7 @@ func (h *ProjectHandler) DownProject(ctx context.Context, input *DownProjectInpu
return nil, huma.Error500InternalServerError((&common.ProjectDownError{Err: err}).Error())
}
activitylib.FlushWriter(activityWriter)
- activitylib.CompleteHandlerActivity(ctx, h.activityService, activityID, "Project stopped", nil)
+ activitylib.CompleteHandlerActivity(runtimeCtx, h.activityService, activityID, "Project stopped", nil)
return &DownProjectOutput{
Body: base.ApiResponse[base.MessageResponse]{
@@ -693,7 +697,8 @@ func (h *ProjectHandler) CreateProject(ctx context.Context, input *CreateProject
}
var proj *models.Project
- activityID, err := activitylib.RunHandlerActivity(ctx, h.activityService, activitylib.HandlerOptions{
+ runtimeCtx := utils.ActivityRuntimeContext(ctx, h.appCtx)
+ activityID, err := activitylib.RunHandlerActivity(runtimeCtx, h.activityService, activitylib.HandlerOptions{
EnvironmentID: input.EnvironmentID,
Type: models.ActivityTypeResourceAction,
ResourceType: "project",
@@ -706,7 +711,7 @@ func (h *ProjectHandler) CreateProject(ctx context.Context, input *CreateProject
Metadata: models.JSON{"action": "create_project"},
}, func() error {
var createErr error
- proj, createErr = h.projectService.CreateProject(ctx, input.Body.Name, input.Body.ComposeContent, input.Body.EnvContent, *user)
+ proj, createErr = h.projectService.CreateProject(runtimeCtx, input.Body.Name, input.Body.ComposeContent, input.Body.EnvContent, *user)
return createErr
})
if err != nil {
@@ -860,8 +865,9 @@ func (h *ProjectHandler) RedeployProject(ctx context.Context, input *RedeployPro
return nil, huma.Error401Unauthorized((&common.NotAuthenticatedError{}).Error())
}
+ runtimeCtx := utils.ActivityRuntimeContext(ctx, h.appCtx)
activityID := activitylib.StartHandlerActivityForUser(
- ctx,
+ runtimeCtx,
h.activityService,
input.EnvironmentID,
models.ActivityTypeProjectRedeploy,
@@ -873,11 +879,11 @@ func (h *ProjectHandler) RedeployProject(ctx context.Context, input *RedeployPro
"Project redeploy started",
models.JSON{"projectID": input.ProjectID},
)
- activityWriter := activitylib.NewWriter(ctx, h.activityService, activityID, io.Discard, "Redeploying project")
- redeployCtx := context.WithValue(ctx, projects.ProgressWriterKey{}, activityWriter)
+ activityWriter := activitylib.NewWriter(runtimeCtx, h.activityService, activityID, io.Discard, "Redeploying project")
+ redeployCtx := context.WithValue(runtimeCtx, projects.ProgressWriterKey{}, activityWriter)
if err := h.projectService.RedeployProject(redeployCtx, input.ProjectID, *user, input.Body); err != nil {
activitylib.FlushWriter(activityWriter)
- activitylib.CompleteHandlerActivity(ctx, h.activityService, activityID, "Project redeploy failed", err)
+ activitylib.CompleteHandlerActivity(runtimeCtx, h.activityService, activityID, "Project redeploy failed", err)
var archivedErr *common.ProjectArchivedError
if errors.As(err, &archivedErr) {
return nil, huma.Error400BadRequest(err.Error())
@@ -885,7 +891,7 @@ func (h *ProjectHandler) RedeployProject(ctx context.Context, input *RedeployPro
return nil, huma.Error400BadRequest((&common.ProjectRedeploymentError{Err: err}).Error())
}
activitylib.FlushWriter(activityWriter)
- activitylib.CompleteHandlerActivity(ctx, h.activityService, activityID, "Project redeploy completed", nil)
+ activitylib.CompleteHandlerActivity(runtimeCtx, h.activityService, activityID, "Project redeploy completed", nil)
return &RedeployProjectOutput{
Body: base.ApiResponse[base.MessageResponse]{
@@ -923,16 +929,17 @@ func (h *ProjectHandler) DestroyProject(ctx context.Context, input *DestroyProje
"projectID", input.ProjectID)
}
- activityID := activitylib.StartHandlerActivityForUser(ctx, h.activityService, input.EnvironmentID, models.ActivityTypeProjectDestroy, "project", input.ProjectID, input.ProjectID, user, "Destroying project", "Project destroy requested", models.JSON{"projectID": input.ProjectID, "removeFiles": removeFiles, "removeVolumes": removeVolumes})
- activityWriter := activitylib.NewWriter(ctx, h.activityService, activityID, io.Discard, "Destroying project")
- destroyCtx := context.WithValue(ctx, projects.ProgressWriterKey{}, activityWriter)
+ runtimeCtx := utils.ActivityRuntimeContext(ctx, h.appCtx)
+ activityID := activitylib.StartHandlerActivityForUser(runtimeCtx, h.activityService, input.EnvironmentID, models.ActivityTypeProjectDestroy, "project", input.ProjectID, input.ProjectID, user, "Destroying project", "Project destroy requested", models.JSON{"projectID": input.ProjectID, "removeFiles": removeFiles, "removeVolumes": removeVolumes})
+ activityWriter := activitylib.NewWriter(runtimeCtx, h.activityService, activityID, io.Discard, "Destroying project")
+ destroyCtx := context.WithValue(runtimeCtx, projects.ProgressWriterKey{}, activityWriter)
if err := h.projectService.DestroyProject(destroyCtx, input.ProjectID, removeFiles, removeVolumes, *user); err != nil {
activitylib.FlushWriter(activityWriter)
- activitylib.CompleteHandlerActivity(ctx, h.activityService, activityID, "Project destroyed", err)
+ activitylib.CompleteHandlerActivity(runtimeCtx, h.activityService, activityID, "Project destroyed", err)
return nil, huma.Error500InternalServerError((&common.ProjectDestroyError{Err: err}).Error())
}
activitylib.FlushWriter(activityWriter)
- activitylib.CompleteHandlerActivity(ctx, h.activityService, activityID, "Project destroyed", nil)
+ activitylib.CompleteHandlerActivity(runtimeCtx, h.activityService, activityID, "Project destroyed", nil)
return &DestroyProjectOutput{
Body: base.ApiResponse[base.MessageResponse]{
@@ -960,7 +967,8 @@ func (h *ProjectHandler) UpdateProject(ctx context.Context, input *UpdateProject
return nil, huma.Error401Unauthorized((&common.NotAuthenticatedError{}).Error())
}
- activityID, err := activitylib.RunHandlerActivity(ctx, h.activityService, activitylib.HandlerOptions{
+ runtimeCtx := utils.ActivityRuntimeContext(ctx, h.appCtx)
+ activityID, err := activitylib.RunHandlerActivity(runtimeCtx, h.activityService, activitylib.HandlerOptions{
EnvironmentID: input.EnvironmentID,
Type: models.ActivityTypeResourceAction,
ResourceType: "project",
@@ -972,14 +980,14 @@ func (h *ProjectHandler) UpdateProject(ctx context.Context, input *UpdateProject
SuccessMessage: "Project updated successfully",
Metadata: models.JSON{"action": "update_project", "projectID": input.ProjectID},
}, func() error {
- _, updateErr := h.projectService.UpdateProject(ctx, input.ProjectID, input.Body.Name, input.Body.ComposeContent, input.Body.EnvContent, *user)
+ _, updateErr := h.projectService.UpdateProject(runtimeCtx, input.ProjectID, input.Body.Name, input.Body.ComposeContent, input.Body.EnvContent, *user)
return updateErr
})
if err != nil {
return nil, huma.Error400BadRequest((&common.ProjectUpdateError{Err: err}).Error())
}
- details, err := h.projectService.GetProjectDetails(ctx, input.ProjectID, project.AllDetails())
+ details, err := h.projectService.GetProjectDetails(runtimeCtx, input.ProjectID, project.AllDetails())
if err != nil {
return nil, huma.Error500InternalServerError((&common.ProjectDetailsError{Err: err}).Error())
}
@@ -1008,7 +1016,8 @@ func (h *ProjectHandler) UpdateProjectInclude(ctx context.Context, input *Update
return nil, huma.Error401Unauthorized((&common.NotAuthenticatedError{}).Error())
}
- activityID, err := activitylib.RunHandlerActivity(ctx, h.activityService, activitylib.HandlerOptions{
+ runtimeCtx := utils.ActivityRuntimeContext(ctx, h.appCtx)
+ activityID, err := activitylib.RunHandlerActivity(runtimeCtx, h.activityService, activitylib.HandlerOptions{
EnvironmentID: input.EnvironmentID,
Type: models.ActivityTypeResourceAction,
ResourceType: "project",
@@ -1024,13 +1033,13 @@ func (h *ProjectHandler) UpdateProjectInclude(ctx context.Context, input *Update
"relativePath": input.Body.RelativePath,
},
}, func() error {
- return h.projectService.UpdateProjectIncludeFile(ctx, input.ProjectID, input.Body.RelativePath, input.Body.Content, *user)
+ return h.projectService.UpdateProjectIncludeFile(runtimeCtx, input.ProjectID, input.Body.RelativePath, input.Body.Content, *user)
})
if err != nil {
return nil, huma.Error400BadRequest((&common.ProjectUpdateError{Err: err}).Error())
}
- details, err := h.projectService.GetProjectDetails(ctx, input.ProjectID, project.AllDetails())
+ details, err := h.projectService.GetProjectDetails(runtimeCtx, input.ProjectID, project.AllDetails())
if err != nil {
return nil, huma.Error500InternalServerError((&common.ProjectDetailsError{Err: err}).Error())
}
@@ -1059,12 +1068,13 @@ func (h *ProjectHandler) RestartProject(ctx context.Context, input *RestartProje
return nil, huma.Error401Unauthorized((&common.NotAuthenticatedError{}).Error())
}
- activityID := activitylib.StartHandlerActivityForUser(ctx, h.activityService, input.EnvironmentID, models.ActivityTypeProjectRestart, "project", input.ProjectID, input.ProjectID, user, "Restarting project", "Project restart requested", models.JSON{"projectID": input.ProjectID})
- activityWriter := activitylib.NewWriter(ctx, h.activityService, activityID, io.Discard, "Restarting project")
- restartCtx := context.WithValue(ctx, projects.ProgressWriterKey{}, activityWriter)
+ runtimeCtx := utils.ActivityRuntimeContext(ctx, h.appCtx)
+ activityID := activitylib.StartHandlerActivityForUser(runtimeCtx, h.activityService, input.EnvironmentID, models.ActivityTypeProjectRestart, "project", input.ProjectID, input.ProjectID, user, "Restarting project", "Project restart requested", models.JSON{"projectID": input.ProjectID})
+ activityWriter := activitylib.NewWriter(runtimeCtx, h.activityService, activityID, io.Discard, "Restarting project")
+ restartCtx := context.WithValue(runtimeCtx, projects.ProgressWriterKey{}, activityWriter)
if err := h.projectService.RestartProject(restartCtx, input.ProjectID, *user); err != nil {
activitylib.FlushWriter(activityWriter)
- activitylib.CompleteHandlerActivity(ctx, h.activityService, activityID, "Project restarted", err)
+ activitylib.CompleteHandlerActivity(runtimeCtx, h.activityService, activityID, "Project restarted", err)
var archivedErr *common.ProjectArchivedError
if errors.As(err, &archivedErr) {
return nil, huma.Error400BadRequest(err.Error())
@@ -1072,7 +1082,7 @@ func (h *ProjectHandler) RestartProject(ctx context.Context, input *RestartProje
return nil, huma.Error400BadRequest((&common.ProjectRestartError{Err: err}).Error())
}
activitylib.FlushWriter(activityWriter)
- activitylib.CompleteHandlerActivity(ctx, h.activityService, activityID, "Project restarted", nil)
+ activitylib.CompleteHandlerActivity(runtimeCtx, h.activityService, activityID, "Project restarted", nil)
return &RestartProjectOutput{
Body: base.ApiResponse[base.MessageResponse]{
@@ -1163,9 +1173,10 @@ func (h *ProjectHandler) PullProjectImages(ctx context.Context, input *PullProje
humaCtx.SetHeader("Connection", "keep-alive")
humaCtx.SetHeader("X-Accel-Buffering", "no")
+ runtimeCtx := utils.ActivityRuntimeContext(humaCtx.Context(), h.appCtx)
rawWriter := humaCtx.BodyWriter()
activityID := activitylib.StartHandlerActivityForUser(
- humaCtx.Context(),
+ runtimeCtx,
h.activityService,
input.EnvironmentID,
models.ActivityTypeProjectPull,
@@ -1179,15 +1190,15 @@ func (h *ProjectHandler) PullProjectImages(ctx context.Context, input *PullProje
)
activitylib.WriteStartedLine(rawWriter, activityID)
- writer := activitylib.NewWriter(humaCtx.Context(), h.activityService, activityID, rawWriter, "Pulling project images")
+ writer := activitylib.NewWriter(runtimeCtx, h.activityService, activityID, rawWriter, "Pulling project images")
_, _ = writer.Write([]byte(`{"status":"starting project image pull"}` + "\n"))
if f, ok := writer.(http.Flusher); ok {
f.Flush()
}
- if err := h.projectService.PullProjectImages(humaCtx.Context(), input.ProjectID, writer, *user, nil); err != nil {
+ if err := h.projectService.PullProjectImages(runtimeCtx, input.ProjectID, writer, *user, nil); err != nil {
activitylib.FlushWriter(writer)
- activitylib.CompleteHandlerActivity(humaCtx.Context(), h.activityService, activityID, "Project image pull failed", err)
+ activitylib.CompleteHandlerActivity(runtimeCtx, h.activityService, activityID, "Project image pull failed", err)
_, _ = fmt.Fprintf(writer, `{"error":%q}`+"\n", err.Error())
if f, ok := writer.(http.Flusher); ok {
f.Flush()
@@ -1199,7 +1210,7 @@ func (h *ProjectHandler) PullProjectImages(ctx context.Context, input *PullProje
if f, ok := writer.(http.Flusher); ok {
f.Flush()
}
- activitylib.CompleteHandlerActivity(humaCtx.Context(), h.activityService, activityID, "Project image pull completed", nil)
+ activitylib.CompleteHandlerActivity(runtimeCtx, h.activityService, activityID, "Project image pull completed", nil)
},
}, nil
}
@@ -1234,9 +1245,10 @@ func (h *ProjectHandler) BuildProjectImages(ctx context.Context, input *BuildPro
humaCtx.SetHeader("Connection", "keep-alive")
humaCtx.SetHeader("X-Accel-Buffering", "no")
+ runtimeCtx := utils.ActivityRuntimeContext(humaCtx.Context(), h.appCtx)
rawWriter := humaCtx.BodyWriter()
activityID := activitylib.StartHandlerActivityForUser(
- humaCtx.Context(),
+ runtimeCtx,
h.activityService,
input.EnvironmentID,
models.ActivityTypeProjectBuild,
@@ -1250,15 +1262,15 @@ func (h *ProjectHandler) BuildProjectImages(ctx context.Context, input *BuildPro
)
activitylib.WriteStartedLine(rawWriter, activityID)
- writer := activitylib.NewWriter(humaCtx.Context(), h.activityService, activityID, rawWriter, "Building project images")
+ writer := activitylib.NewWriter(runtimeCtx, h.activityService, activityID, rawWriter, "Building project images")
_, _ = writer.Write([]byte(`{"type":"build","phase":"begin"}` + "\n"))
if f, ok := writer.(http.Flusher); ok {
f.Flush()
}
- if err := h.projectService.BuildProjectServices(humaCtx.Context(), input.ProjectID, options, writer, user); err != nil {
+ if err := h.projectService.BuildProjectServices(runtimeCtx, input.ProjectID, options, writer, user); err != nil {
activitylib.FlushWriter(writer)
- activitylib.CompleteHandlerActivity(humaCtx.Context(), h.activityService, activityID, "Project image build failed", err)
+ activitylib.CompleteHandlerActivity(runtimeCtx, h.activityService, activityID, "Project image build failed", err)
_, _ = fmt.Fprintf(writer, `{"error":%q}`+"\n", err.Error())
if f, ok := writer.(http.Flusher); ok {
f.Flush()
@@ -1270,7 +1282,7 @@ func (h *ProjectHandler) BuildProjectImages(ctx context.Context, input *BuildPro
if f, ok := writer.(http.Flusher); ok {
f.Flush()
}
- activitylib.CompleteHandlerActivity(humaCtx.Context(), h.activityService, activityID, "Project image build completed", nil)
+ activitylib.CompleteHandlerActivity(runtimeCtx, h.activityService, activityID, "Project image build completed", nil)
},
}, nil
}
diff --git a/backend/api/handlers/system.go b/backend/api/handlers/system.go
index de9a9eb18..a72ca4876 100644
--- a/backend/api/handlers/system.go
+++ b/backend/api/handlers/system.go
@@ -13,6 +13,7 @@ import (
"github.com/getarcaneapp/arcane/backend/internal/services"
"github.com/getarcaneapp/arcane/backend/pkg/authz"
docker "github.com/getarcaneapp/arcane/backend/pkg/dockerutil"
+ "github.com/getarcaneapp/arcane/backend/pkg/utils"
"github.com/getarcaneapp/arcane/types/base"
containertypes "github.com/getarcaneapp/arcane/types/container"
"github.com/getarcaneapp/arcane/types/dockerinfo"
@@ -28,6 +29,7 @@ type SystemHandler struct {
upgradeService *services.SystemUpgradeService
activityService *services.ActivityService
cfg *config.Config
+ appCtx context.Context
}
// --- Input/Output Types ---
@@ -115,13 +117,14 @@ type TriggerUpgradeOutput struct {
// RegisterSystem registers system management endpoints using Huma.
// Note: WebSocket endpoints (stats) remain in the Gin handler.
-func RegisterSystem(api huma.API, dockerService *services.DockerClientService, systemService *services.SystemService, upgradeService *services.SystemUpgradeService, cfg *config.Config, activityService *services.ActivityService) {
+func RegisterSystem(api huma.API, dockerService *services.DockerClientService, systemService *services.SystemService, upgradeService *services.SystemUpgradeService, cfg *config.Config, activityService *services.ActivityService, appCtx ActivityAppContext) {
h := &SystemHandler{
dockerService: dockerService,
systemService: systemService,
upgradeService: upgradeService,
activityService: activityService,
cfg: cfg,
+ appCtx: appCtx.contextInternal(),
}
huma.Register(api, huma.Operation{
@@ -376,9 +379,10 @@ func (h *SystemHandler) PruneAll(ctx context.Context, input *PruneAllInput) (*Pr
"networks", input.Body.Networks,
"build_cache", input.Body.BuildCache)
- result := h.systemService.StartPruneAll(ctx, input.EnvironmentID, input.Body)
+ runtimeCtx := utils.ActivityRuntimeContext(ctx, h.appCtx)
+ result := h.systemService.StartPruneAll(runtimeCtx, input.EnvironmentID, input.Body)
- slog.InfoContext(ctx, "System prune background activity started", "activityId", result.ActivityID)
+ slog.InfoContext(runtimeCtx, "System prune background activity started", "activityId", result.ActivityID)
return &PruneAllOutput{
Body: base.ApiResponse[system.PruneAllResult]{
@@ -394,7 +398,8 @@ func (h *SystemHandler) StartAllContainers(ctx context.Context, input *StartAllC
return nil, huma.Error500InternalServerError("service not available")
}
- result, err := h.systemService.StartAllContainers(ctx, input.EnvironmentID)
+ runtimeCtx := utils.ActivityRuntimeContext(ctx, h.appCtx)
+ result, err := h.systemService.StartAllContainers(runtimeCtx, input.EnvironmentID)
if err != nil {
return nil, huma.Error500InternalServerError((&common.ContainerStartAllError{Err: err}).Error())
}
@@ -413,7 +418,8 @@ func (h *SystemHandler) StartAllStoppedContainers(ctx context.Context, input *St
return nil, huma.Error500InternalServerError("service not available")
}
- result, err := h.systemService.StartAllStoppedContainers(ctx, input.EnvironmentID)
+ runtimeCtx := utils.ActivityRuntimeContext(ctx, h.appCtx)
+ result, err := h.systemService.StartAllStoppedContainers(runtimeCtx, input.EnvironmentID)
if err != nil {
return nil, huma.Error500InternalServerError((&common.ContainerStartStoppedError{Err: err}).Error())
}
@@ -432,7 +438,8 @@ func (h *SystemHandler) StopAllContainers(ctx context.Context, input *StopAllCon
return nil, huma.Error500InternalServerError("service not available")
}
- result, err := h.systemService.StopAllContainers(ctx, input.EnvironmentID)
+ runtimeCtx := utils.ActivityRuntimeContext(ctx, h.appCtx)
+ result, err := h.systemService.StopAllContainers(runtimeCtx, input.EnvironmentID)
if err != nil {
return nil, huma.Error500InternalServerError((&common.ContainerStopAllError{Err: err}).Error())
}
diff --git a/backend/api/handlers/updater.go b/backend/api/handlers/updater.go
index c168bf2f7..5621dd6f8 100644
--- a/backend/api/handlers/updater.go
+++ b/backend/api/handlers/updater.go
@@ -10,6 +10,7 @@ import (
"github.com/getarcaneapp/arcane/backend/internal/models"
"github.com/getarcaneapp/arcane/backend/internal/services"
"github.com/getarcaneapp/arcane/backend/pkg/authz"
+ "github.com/getarcaneapp/arcane/backend/pkg/utils"
"github.com/getarcaneapp/arcane/types/base"
"github.com/getarcaneapp/arcane/types/updater"
)
@@ -17,6 +18,7 @@ import (
// UpdaterHandler provides Huma-based updater management endpoints.
type UpdaterHandler struct {
updaterService *services.UpdaterService
+ appCtx context.Context
}
// --- Huma Input/Output Wrappers ---
@@ -57,9 +59,10 @@ type GetUpdaterHistoryOutput struct {
}
// RegisterUpdater registers updater management routes using Huma.
-func RegisterUpdater(api huma.API, updaterService *services.UpdaterService) {
+func RegisterUpdater(api huma.API, updaterService *services.UpdaterService, appCtx ActivityAppContext) {
h := &UpdaterHandler{
updaterService: updaterService,
+ appCtx: appCtx.contextInternal(),
}
huma.Register(api, huma.Operation{
@@ -130,7 +133,8 @@ func (h *UpdaterHandler) RunUpdater(ctx context.Context, input *RunUpdaterInput)
dryRun = input.Body.DryRun
}
- out, err := h.updaterService.ApplyPending(ctx, dryRun)
+ runtimeCtx := utils.ActivityRuntimeContext(ctx, h.appCtx)
+ out, err := h.updaterService.ApplyPending(runtimeCtx, dryRun)
if err != nil {
return nil, huma.Error500InternalServerError((&common.UpdaterRunError{Err: err}).Error())
}
@@ -189,7 +193,8 @@ func (h *UpdaterHandler) UpdateContainer(ctx context.Context, input *UpdateConta
return nil, huma.Error500InternalServerError("service not available")
}
- out, err := h.updaterService.UpdateSingleContainer(ctx, input.ContainerID)
+ runtimeCtx := utils.ActivityRuntimeContext(ctx, h.appCtx)
+ out, err := h.updaterService.UpdateSingleContainer(runtimeCtx, input.ContainerID)
if err != nil {
return nil, huma.Error500InternalServerError((&common.UpdaterRunError{Err: err}).Error())
}
diff --git a/backend/api/handlers/volumes.go b/backend/api/handlers/volumes.go
index 156d3a127..8ace14d2a 100644
--- a/backend/api/handlers/volumes.go
+++ b/backend/api/handlers/volumes.go
@@ -27,6 +27,7 @@ type VolumeHandler struct {
volumeService *services.VolumeService
dockerService *services.DockerClientService
activityService *services.ActivityService
+ appCtx context.Context
}
// --- Huma Input/Output Wrappers ---
@@ -299,11 +300,12 @@ type UploadAndRestoreOutput struct {
}
// RegisterVolumes registers volume management routes using Huma.
-func RegisterVolumes(api huma.API, dockerService *services.DockerClientService, volumeService *services.VolumeService, activityService *services.ActivityService) {
+func RegisterVolumes(api huma.API, dockerService *services.DockerClientService, volumeService *services.VolumeService, activityService *services.ActivityService, appCtx ActivityAppContext) {
h := &VolumeHandler{
volumeService: volumeService,
dockerService: dockerService,
activityService: activityService,
+ appCtx: appCtx.contextInternal(),
}
huma.Register(api, huma.Operation{
@@ -749,7 +751,8 @@ func (h *VolumeHandler) CreateVolume(ctx context.Context, input *CreateVolumeInp
}
var response *volumetypes.Volume
- activityID, err := activitylib.RunHandlerActivity(ctx, h.activityService, activitylib.HandlerOptions{
+ runtimeCtx := utils.ActivityRuntimeContext(ctx, h.appCtx)
+ activityID, err := activitylib.RunHandlerActivity(runtimeCtx, h.activityService, activitylib.HandlerOptions{
EnvironmentID: input.EnvironmentID,
Type: models.ActivityTypeResourceAction,
ResourceType: "volume",
@@ -765,7 +768,7 @@ func (h *VolumeHandler) CreateVolume(ctx context.Context, input *CreateVolumeInp
},
}, func() error {
var createErr error
- response, createErr = h.volumeService.CreateVolume(ctx, options, *user)
+ response, createErr = h.volumeService.CreateVolume(runtimeCtx, options, *user)
return createErr
})
if err != nil {
@@ -792,7 +795,8 @@ func (h *VolumeHandler) RemoveVolume(ctx context.Context, input *RemoveVolumeInp
return nil, huma.Error401Unauthorized((&common.NotAuthenticatedError{}).Error())
}
- activityID, err := activitylib.RunHandlerActivity(ctx, h.activityService, activitylib.HandlerOptions{
+ runtimeCtx := utils.ActivityRuntimeContext(ctx, h.appCtx)
+ activityID, err := activitylib.RunHandlerActivity(runtimeCtx, h.activityService, activitylib.HandlerOptions{
EnvironmentID: input.EnvironmentID,
Type: models.ActivityTypeResourceAction,
ResourceType: "volume",
@@ -807,7 +811,7 @@ func (h *VolumeHandler) RemoveVolume(ctx context.Context, input *RemoveVolumeInp
"force": input.Force,
},
}, func() error {
- return h.volumeService.DeleteVolume(ctx, input.VolumeName, input.Force, *user)
+ return h.volumeService.DeleteVolume(runtimeCtx, input.VolumeName, input.Force, *user)
})
if err != nil {
return nil, huma.Error500InternalServerError((&common.VolumeDeletionError{Err: err}).Error())
@@ -831,7 +835,8 @@ func (h *VolumeHandler) PruneVolumes(ctx context.Context, input *PruneVolumesInp
}
var report *volumetypes.PruneReport
- activityID, err := activitylib.RunHandlerActivity(ctx, h.activityService, activitylib.HandlerOptions{
+ runtimeCtx := utils.ActivityRuntimeContext(ctx, h.appCtx)
+ activityID, err := activitylib.RunHandlerActivity(runtimeCtx, h.activityService, activitylib.HandlerOptions{
EnvironmentID: input.EnvironmentID,
Type: models.ActivityTypeResourceAction,
ResourceType: "volume",
@@ -841,7 +846,7 @@ func (h *VolumeHandler) PruneVolumes(ctx context.Context, input *PruneVolumesInp
Metadata: models.JSON{"action": "prune_volumes"},
}, func() error {
var pruneErr error
- report, pruneErr = h.volumeService.PruneVolumes(ctx)
+ report, pruneErr = h.volumeService.PruneVolumes(runtimeCtx)
return pruneErr
})
if err != nil {
@@ -1011,7 +1016,8 @@ func (h *VolumeHandler) UploadFile(ctx context.Context, input *UploadFileInput)
defer func() { _ = file.Close() }()
user, _ := humamw.GetCurrentUserFromContext(ctx)
- activityID, err := activitylib.RunHandlerActivity(ctx, h.activityService, activitylib.HandlerOptions{
+ runtimeCtx := utils.ActivityRuntimeContext(ctx, h.appCtx)
+ activityID, err := activitylib.RunHandlerActivity(runtimeCtx, h.activityService, activitylib.HandlerOptions{
EnvironmentID: input.EnvironmentID,
Type: models.ActivityTypeResourceAction,
ResourceType: "volume",
@@ -1027,7 +1033,7 @@ func (h *VolumeHandler) UploadFile(ctx context.Context, input *UploadFileInput)
"filename": fileHeader.Filename,
},
}, func() error {
- return h.volumeService.UploadFile(ctx, input.VolumeName, input.Path, file, fileHeader.Filename, user)
+ return h.volumeService.UploadFile(runtimeCtx, input.VolumeName, input.Path, file, fileHeader.Filename, user)
})
if err != nil {
return nil, huma.Error500InternalServerError(err.Error())
@@ -1043,7 +1049,8 @@ func (h *VolumeHandler) CreateDirectory(ctx context.Context, input *CreateDirect
return nil, huma.Error500InternalServerError("service not available")
}
user, _ := humamw.GetCurrentUserFromContext(ctx)
- activityID, err := activitylib.RunHandlerActivity(ctx, h.activityService, activitylib.HandlerOptions{
+ runtimeCtx := utils.ActivityRuntimeContext(ctx, h.appCtx)
+ activityID, err := activitylib.RunHandlerActivity(runtimeCtx, h.activityService, activitylib.HandlerOptions{
EnvironmentID: input.EnvironmentID,
Type: models.ActivityTypeResourceAction,
ResourceType: "volume",
@@ -1058,7 +1065,7 @@ func (h *VolumeHandler) CreateDirectory(ctx context.Context, input *CreateDirect
"path": input.Path,
},
}, func() error {
- return h.volumeService.CreateDirectory(ctx, input.VolumeName, input.Path, user)
+ return h.volumeService.CreateDirectory(runtimeCtx, input.VolumeName, input.Path, user)
})
if err != nil {
return nil, huma.Error500InternalServerError(err.Error())
@@ -1074,7 +1081,8 @@ func (h *VolumeHandler) DeleteFile(ctx context.Context, input *DeleteFileInput)
return nil, huma.Error500InternalServerError("service not available")
}
user, _ := humamw.GetCurrentUserFromContext(ctx)
- activityID, err := activitylib.RunHandlerActivity(ctx, h.activityService, activitylib.HandlerOptions{
+ runtimeCtx := utils.ActivityRuntimeContext(ctx, h.appCtx)
+ activityID, err := activitylib.RunHandlerActivity(runtimeCtx, h.activityService, activitylib.HandlerOptions{
EnvironmentID: input.EnvironmentID,
Type: models.ActivityTypeResourceAction,
ResourceType: "volume",
@@ -1089,7 +1097,7 @@ func (h *VolumeHandler) DeleteFile(ctx context.Context, input *DeleteFileInput)
"path": input.Path,
},
}, func() error {
- return h.volumeService.DeleteFile(ctx, input.VolumeName, input.Path, user)
+ return h.volumeService.DeleteFile(runtimeCtx, input.VolumeName, input.Path, user)
})
if err != nil {
return nil, huma.Error500InternalServerError(err.Error())
@@ -1163,7 +1171,8 @@ func (h *VolumeHandler) CreateBackup(ctx context.Context, input *CreateBackupInp
}
var backup *models.VolumeBackup
- activityID, err := activitylib.RunHandlerActivity(ctx, h.activityService, activitylib.HandlerOptions{
+ runtimeCtx := utils.ActivityRuntimeContext(ctx, h.appCtx)
+ activityID, err := activitylib.RunHandlerActivity(runtimeCtx, h.activityService, activitylib.HandlerOptions{
EnvironmentID: input.EnvironmentID,
Type: models.ActivityTypeResourceAction,
ResourceType: "volume",
@@ -1176,7 +1185,7 @@ func (h *VolumeHandler) CreateBackup(ctx context.Context, input *CreateBackupInp
Metadata: models.JSON{"action": "create_volume_backup"},
}, func() error {
var backupErr error
- backup, backupErr = h.volumeService.CreateBackup(ctx, input.VolumeName, *user)
+ backup, backupErr = h.volumeService.CreateBackup(runtimeCtx, input.VolumeName, *user)
return backupErr
})
if err != nil {
@@ -1200,7 +1209,8 @@ func (h *VolumeHandler) RestoreBackup(ctx context.Context, input *RestoreBackupI
return nil, huma.Error401Unauthorized((&common.NotAuthenticatedError{}).Error())
}
- activityID, err := activitylib.RunHandlerActivity(ctx, h.activityService, activitylib.HandlerOptions{
+ runtimeCtx := utils.ActivityRuntimeContext(ctx, h.appCtx)
+ activityID, err := activitylib.RunHandlerActivity(runtimeCtx, h.activityService, activitylib.HandlerOptions{
EnvironmentID: input.EnvironmentID,
Type: models.ActivityTypeResourceAction,
ResourceType: "volume",
@@ -1215,7 +1225,7 @@ func (h *VolumeHandler) RestoreBackup(ctx context.Context, input *RestoreBackupI
"backupId": input.BackupID,
},
}, func() error {
- return h.volumeService.RestoreBackup(ctx, input.VolumeName, input.BackupID, *user)
+ return h.volumeService.RestoreBackup(runtimeCtx, input.VolumeName, input.BackupID, *user)
})
if err != nil {
return nil, huma.Error500InternalServerError(err.Error())
@@ -1242,7 +1252,8 @@ func (h *VolumeHandler) RestoreBackupFiles(ctx context.Context, input *RestoreBa
return nil, huma.Error400BadRequest("paths are required")
}
- activityID, err := activitylib.RunHandlerActivity(ctx, h.activityService, activitylib.HandlerOptions{
+ runtimeCtx := utils.ActivityRuntimeContext(ctx, h.appCtx)
+ activityID, err := activitylib.RunHandlerActivity(runtimeCtx, h.activityService, activitylib.HandlerOptions{
EnvironmentID: input.EnvironmentID,
Type: models.ActivityTypeResourceAction,
ResourceType: "volume",
@@ -1258,7 +1269,7 @@ func (h *VolumeHandler) RestoreBackupFiles(ctx context.Context, input *RestoreBa
"paths": input.Body.Paths,
},
}, func() error {
- return h.volumeService.RestoreBackupFiles(ctx, input.VolumeName, input.BackupID, input.Body.Paths, *user)
+ return h.volumeService.RestoreBackupFiles(runtimeCtx, input.VolumeName, input.BackupID, input.Body.Paths, *user)
})
if err != nil {
return nil, huma.Error500InternalServerError(err.Error())
@@ -1317,7 +1328,8 @@ func (h *VolumeHandler) DeleteBackup(ctx context.Context, input *DeleteBackupInp
return nil, huma.Error500InternalServerError("service not available")
}
user, _ := humamw.GetCurrentUserFromContext(ctx)
- activityID, err := activitylib.RunHandlerActivity(ctx, h.activityService, activitylib.HandlerOptions{
+ runtimeCtx := utils.ActivityRuntimeContext(ctx, h.appCtx)
+ activityID, err := activitylib.RunHandlerActivity(runtimeCtx, h.activityService, activitylib.HandlerOptions{
EnvironmentID: input.EnvironmentID,
Type: models.ActivityTypeResourceAction,
ResourceType: "volume_backup",
@@ -1332,7 +1344,7 @@ func (h *VolumeHandler) DeleteBackup(ctx context.Context, input *DeleteBackupInp
"backupId": input.BackupID,
},
}, func() error {
- return h.volumeService.DeleteBackup(ctx, input.BackupID, user)
+ return h.volumeService.DeleteBackup(runtimeCtx, input.BackupID, user)
})
if err != nil {
return nil, huma.Error500InternalServerError(err.Error())
@@ -1390,7 +1402,8 @@ func (h *VolumeHandler) UploadAndRestore(ctx context.Context, input *UploadAndRe
}
defer func() { _ = file.Close() }()
- activityID, err := activitylib.RunHandlerActivity(ctx, h.activityService, activitylib.HandlerOptions{
+ runtimeCtx := utils.ActivityRuntimeContext(ctx, h.appCtx)
+ activityID, err := activitylib.RunHandlerActivity(runtimeCtx, h.activityService, activitylib.HandlerOptions{
EnvironmentID: input.EnvironmentID,
Type: models.ActivityTypeResourceAction,
ResourceType: "volume",
@@ -1405,7 +1418,7 @@ func (h *VolumeHandler) UploadAndRestore(ctx context.Context, input *UploadAndRe
"filename": fileHeader.Filename,
},
}, func() error {
- return h.volumeService.UploadAndRestore(ctx, input.VolumeName, file, fileHeader.Filename, *user)
+ return h.volumeService.UploadAndRestore(runtimeCtx, input.VolumeName, file, fileHeader.Filename, *user)
})
if err != nil {
return nil, huma.Error500InternalServerError(err.Error())
diff --git a/backend/api/handlers/vulnerabilities.go b/backend/api/handlers/vulnerabilities.go
index e555bf827..65c7186f0 100644
--- a/backend/api/handlers/vulnerabilities.go
+++ b/backend/api/handlers/vulnerabilities.go
@@ -9,6 +9,7 @@ import (
"github.com/getarcaneapp/arcane/backend/internal/common"
"github.com/getarcaneapp/arcane/backend/internal/services"
"github.com/getarcaneapp/arcane/backend/pkg/authz"
+ "github.com/getarcaneapp/arcane/backend/pkg/utils"
"github.com/getarcaneapp/arcane/types/base"
"github.com/getarcaneapp/arcane/types/vulnerability"
)
@@ -16,6 +17,7 @@ import (
// VulnerabilityHandler provides Huma-based vulnerability scanning endpoints.
type VulnerabilityHandler struct {
vulnerabilityService *services.VulnerabilityService
+ appCtx context.Context
}
// --- Huma Input/Output Types ---
@@ -122,9 +124,10 @@ type GetScannerStatusOutput struct {
}
// RegisterVulnerability registers vulnerability scanning routes using Huma.
-func RegisterVulnerability(api huma.API, vulnerabilityService *services.VulnerabilityService) {
+func RegisterVulnerability(api huma.API, vulnerabilityService *services.VulnerabilityService, appCtx ActivityAppContext) {
h := &VulnerabilityHandler{
vulnerabilityService: vulnerabilityService,
+ appCtx: appCtx.contextInternal(),
}
huma.Register(api, huma.Operation{
@@ -307,7 +310,8 @@ func (h *VulnerabilityHandler) ScanImage(ctx context.Context, input *ScanImageIn
return nil, huma.Error401Unauthorized((&common.NotAuthenticatedError{}).Error())
}
- result, err := h.vulnerabilityService.ScanImage(ctx, input.EnvironmentID, input.ImageID, *user)
+ runtimeCtx := utils.ActivityRuntimeContext(ctx, h.appCtx)
+ result, err := h.vulnerabilityService.ScanImage(runtimeCtx, input.EnvironmentID, input.ImageID, *user)
if err != nil {
return nil, huma.Error500InternalServerError((&common.VulnerabilityScanError{Err: err}).Error())
}
diff --git a/backend/api/webhooks_trigger.go b/backend/api/webhooks_trigger.go
index 7cd72f693..b24b1a787 100644
--- a/backend/api/webhooks_trigger.go
+++ b/backend/api/webhooks_trigger.go
@@ -4,21 +4,23 @@ import (
"errors"
"net/http"
+ "github.com/getarcaneapp/arcane/backend/api/handlers"
"github.com/getarcaneapp/arcane/backend/internal/services"
+ "github.com/getarcaneapp/arcane/backend/pkg/utils"
"github.com/labstack/echo/v4"
)
// RegisterWebhookTrigger registers the public (unauthenticated) trigger endpoint.
// The token in the URL is the sole authentication mechanism.
// Rate-limited via PerIPRateLimitForPaths in router_bootstrap.go.
-func RegisterWebhookTrigger(g *echo.Group, webhookService *services.WebhookService) {
+func RegisterWebhookTrigger(g *echo.Group, webhookService *services.WebhookService, appCtx handlers.ActivityAppContext) {
g.POST("/webhooks/trigger/:token", func(c echo.Context) error {
if webhookService == nil {
return c.JSON(http.StatusInternalServerError, map[string]any{"success": false, "error": "service not available"})
}
token := c.Param("token")
- result, err := webhookService.TriggerByToken(c.Request().Context(), token)
+ result, err := webhookService.TriggerByToken(utils.ActivityRuntimeContext(c.Request().Context(), appCtx.ContextInternal()), token)
if err != nil {
status := http.StatusInternalServerError
if errors.Is(err, services.ErrWebhookNotFound) || errors.Is(err, services.ErrWebhookInvalid) {
diff --git a/backend/internal/bootstrap/bootstrap.go b/backend/internal/bootstrap/bootstrap.go
index d4daf87dd..9ee6a0b43 100644
--- a/backend/internal/bootstrap/bootstrap.go
+++ b/backend/internal/bootstrap/bootstrap.go
@@ -23,6 +23,7 @@ import (
tunnelpb "github.com/getarcaneapp/arcane/backend/pkg/libarcane/edge/proto/tunnel/v1"
"github.com/getarcaneapp/arcane/backend/pkg/libarcane/startup"
"github.com/getarcaneapp/arcane/backend/pkg/scheduler"
+ "github.com/getarcaneapp/arcane/backend/pkg/utils"
httputils "github.com/getarcaneapp/arcane/backend/pkg/utils/httpx"
"google.golang.org/grpc"
)
@@ -49,6 +50,7 @@ func Bootstrap(ctx context.Context) error {
slog.InfoContext(ctx, "Arcane Identity Configuration", "PUID", os.Getuid(), "PGID", os.Getgid())
appCtx, cancelApp := context.WithCancel(ctx)
+ appCtx = utils.WithAppLifecycleContext(appCtx)
defer cancelApp()
db, err := initializeDBAndMigrate(appCtx, cfg)
diff --git a/backend/internal/bootstrap/router_bootstrap.go b/backend/internal/bootstrap/router_bootstrap.go
index 726b7ee0e..a937fdab2 100644
--- a/backend/internal/bootstrap/router_bootstrap.go
+++ b/backend/internal/bootstrap/router_bootstrap.go
@@ -14,6 +14,7 @@ import (
slogecho "github.com/samber/slog-echo"
"github.com/getarcaneapp/arcane/backend/api"
+ "github.com/getarcaneapp/arcane/backend/api/handlers"
"github.com/getarcaneapp/arcane/backend/api/ws"
"github.com/getarcaneapp/arcane/backend/frontend"
"github.com/getarcaneapp/arcane/backend/internal/config"
@@ -160,6 +161,7 @@ func setupRouter(ctx context.Context, cfg *config.Config, appServices *Services)
apiGroup.Use(middleware.PerIPRateLimitForPaths(
[]string{"/api/webhooks/trigger/:token"}, 60, 10,
))
+ handlerAppCtx := handlers.NewActivityAppContext(ctx)
tunnelRegistry := edge.NewTunnelRegistry()
edge.SetDefaultRegistry(tunnelRegistry)
@@ -172,7 +174,7 @@ func setupRouter(ctx context.Context, cfg *config.Config, appServices *Services)
}
// Register public webhook trigger endpoint before auth middleware (token in URL is the sole auth)
- api.RegisterWebhookTrigger(apiGroup, appServices.Webhook) //nolint:contextcheck
+ api.RegisterWebhookTrigger(apiGroup, appServices.Webhook, handlerAppCtx) //nolint:contextcheck // app lifecycle context is intentionally wrapped for detached activity work.
//nolint:contextcheck // Echo middleware reads context from echo.Context.Request().Context(), not a parameter.
envProxyMiddleware := middleware.NewEnvProxyMiddlewareWithParam(
@@ -184,6 +186,7 @@ func setupRouter(ctx context.Context, cfg *config.Config, appServices *Services)
apiGroup.Use(envProxyMiddleware)
humaServices := &api.Services{
+ AppContext: ctx,
User: appServices.User,
Auth: appServices.Auth,
Oidc: appServices.Oidc,
@@ -223,7 +226,7 @@ func setupRouter(ctx context.Context, cfg *config.Config, appServices *Services)
Config: cfg,
}
- _ = api.SetupAPI(e, apiGroup, cfg, humaServices)
+ _ = api.SetupAPI(e, apiGroup, cfg, humaServices) //nolint:contextcheck // app lifecycle context is carried in humaServices for detached activity work.
for _, register := range registerBuildableRoutes {
register(apiGroup, appServices)
diff --git a/backend/internal/services/activity_service.go b/backend/internal/services/activity_service.go
index 7cadce737..99ab86605 100644
--- a/backend/internal/services/activity_service.go
+++ b/backend/internal/services/activity_service.go
@@ -275,13 +275,14 @@ func (s *ActivityService) CompleteActivity(ctx context.Context, activityID strin
level = models.ActivityMessageLevelWarning
case models.ActivityStatusQueued, models.ActivityStatusRunning, models.ActivityStatusSuccess:
}
- if _, err := s.AppendMessage(context.WithoutCancel(ctx), activityID, AppendActivityMessageRequest{
+ activityCtx := utils.ActivityRuntimeContext(ctx, nil)
+ if _, err := s.AppendMessage(activityCtx, activityID, AppendActivityMessageRequest{
Level: level,
Message: finalMessage,
}); err != nil {
slog.DebugContext(ctx, "failed to append final activity message", "activityId", activityID, "error", err)
}
- if err := s.db.WithContext(context.WithoutCancel(ctx)).First(&model, "id = ?", activityID).Error; err != nil {
+ if err := s.db.WithContext(activityCtx).First(&model, "id = ?", activityID).Error; err != nil {
slog.DebugContext(ctx, "failed to reload activity after appending message", "activityId", activityID, "error", err)
}
}
diff --git a/backend/internal/services/image_update_service.go b/backend/internal/services/image_update_service.go
index c75690a88..c0ac2e17c 100644
--- a/backend/internal/services/image_update_service.go
+++ b/backend/internal/services/image_update_service.go
@@ -120,7 +120,7 @@ func (s *ImageUpdateService) completeImageUpdateActivityInternal(ctx context.Con
message = "Image update check completed"
}
step := "Image update check complete"
- if _, err := s.activityService.CompleteActivity(context.WithoutCancel(ctx), activityID, status, message, errMessage, step); err != nil {
+ if _, err := s.activityService.CompleteActivity(utils.ActivityRuntimeContext(ctx, nil), activityID, status, message, errMessage, step); err != nil {
slog.DebugContext(ctx, "failed to complete image update activity", "activityId", activityID, "error", err)
}
}
@@ -1045,6 +1045,7 @@ func (s *ImageUpdateService) CheckMultipleImages(ctx context.Context, imageRefs
if err := g.Wait(); err != nil {
slog.ErrorContext(ctx, "Batch check error", "error", err)
+ s.completeImageUpdateActivityInternal(ctx, activityID, false, fmt.Sprintf("Image update check failed: %s", err.Error()))
return results, err
}
diff --git a/backend/internal/services/image_update_service_test.go b/backend/internal/services/image_update_service_test.go
index 3440215ea..786773ae2 100644
--- a/backend/internal/services/image_update_service_test.go
+++ b/backend/internal/services/image_update_service_test.go
@@ -582,6 +582,53 @@ func TestImageUpdateService_CheckMultipleImages_UsesRegistryFallback(t *testing.
assert.Equal(t, remoteDigest, stringPtrToString(saved.LatestDigest))
}
+func TestImageUpdateService_CheckMultipleImagesCompletesActivityWhenRequestContextCanceledInternal(t *testing.T) {
+ db := setupImageUpdateTestDB(t)
+ require.NoError(t, db.AutoMigrate(&models.Activity{}, &models.ActivityMessage{}))
+
+ activityService := NewActivityService(db)
+ svc := NewImageUpdateService(db, nil, nil, nil, nil, nil, activityService)
+
+ for range 5 {
+ require.NoError(t, svc.registryLimiter.Acquire(context.Background(), "docker.io"))
+ }
+ defer func() {
+ for range 5 {
+ svc.registryLimiter.Release("docker.io")
+ }
+ }()
+
+ ctx, cancel := context.WithCancel(context.Background())
+ errCh := make(chan error, 1)
+ go func() {
+ _, err := svc.CheckMultipleImages(ctx, []string{"nginx:latest"}, nil)
+ errCh <- err
+ }()
+
+ var activity models.Activity
+ require.Eventually(t, func() bool {
+ return db.Where("type = ?", models.ActivityTypeImageUpdateCheck).First(&activity).Error == nil
+ }, time.Second, 10*time.Millisecond)
+
+ cancel()
+
+ select {
+ case err := <-errCh:
+ require.ErrorIs(t, err, context.Canceled)
+ case <-time.After(time.Second):
+ t.Fatal("timed out waiting for image update check to return")
+ }
+
+ require.Eventually(t, func() bool {
+ if err := db.First(&activity, "id = ?", activity.ID).Error; err != nil {
+ return false
+ }
+ return activity.Status == models.ActivityStatusFailed
+ }, time.Second, 10*time.Millisecond)
+ assert.Equal(t, "Image update check complete", activity.Step)
+ assert.Contains(t, activity.LatestMessage, "Image update check failed")
+}
+
func TestImageUpdateService_CheckMultipleImages_UsesDockerHubCredentialsOnFirstAttempt(t *testing.T) {
_, db := setupImageServiceAuthTest(t)
require.NoError(t, db.AutoMigrate(&models.ImageUpdateRecord{}, &models.Event{}))
diff --git a/backend/internal/services/system_service.go b/backend/internal/services/system_service.go
index b31b5ec89..bbf354036 100644
--- a/backend/internal/services/system_service.go
+++ b/backend/internal/services/system_service.go
@@ -91,7 +91,7 @@ func (s *SystemService) StartPruneAll(ctx context.Context, environmentID string,
return &system.PruneAllResult{Success: true, ActivityID: utils.StringPtrFromTrimmed(activityID)}
}
- backgroundCtx := context.WithoutCancel(ctx)
+ backgroundCtx := utils.ActivityRuntimeContext(ctx, nil)
go func() {
defer s.finishSystemPruneInternal(environmentID)
@@ -282,7 +282,7 @@ func (s *SystemService) completeSystemPruneActivityInternal(ctx context.Context,
joined := strings.Join(result.Errors, "; ")
errMessage = &joined
}
- if _, err := s.activityService.CompleteActivity(context.WithoutCancel(ctx), activityID, status, message, errMessage); err != nil {
+ if _, err := s.activityService.CompleteActivity(utils.ActivityRuntimeContext(ctx, nil), activityID, status, message, errMessage); err != nil {
slog.DebugContext(ctx, "failed to complete system prune activity", "activityId", activityID, "error", err)
}
}
@@ -433,7 +433,7 @@ func (s *SystemService) completeSystemContainerActivityInternal(ctx context.Cont
errMessage = &message
}
- if _, err := s.activityService.CompleteActivity(context.WithoutCancel(ctx), activityID, status, message, errMessage); err != nil {
+ if _, err := s.activityService.CompleteActivity(utils.ActivityRuntimeContext(ctx, nil), activityID, status, message, errMessage); err != nil {
slog.DebugContext(ctx, "failed to complete system container activity", "activityId", activityID, "error", err)
}
}
diff --git a/backend/internal/services/updater_service.go b/backend/internal/services/updater_service.go
index d32b9e2d1..e66dccb83 100644
--- a/backend/internal/services/updater_service.go
+++ b/backend/internal/services/updater_service.go
@@ -490,7 +490,7 @@ func (s *UpdaterService) completeAutoUpdateActivityInternal(ctx context.Context,
message = errText
}
- if _, err := s.activityService.CompleteActivity(context.WithoutCancel(ctx), activityID, status, message, errMessage); err != nil {
+ if _, err := s.activityService.CompleteActivity(utils.ActivityRuntimeContext(ctx, nil), activityID, status, message, errMessage); err != nil {
slog.DebugContext(ctx, "failed to complete auto-update activity", "activityId", activityID, "error", err)
}
}
diff --git a/backend/internal/services/vulnerability_service.go b/backend/internal/services/vulnerability_service.go
index 7bc73e8ea..408361521 100644
--- a/backend/internal/services/vulnerability_service.go
+++ b/backend/internal/services/vulnerability_service.go
@@ -246,7 +246,7 @@ func NewVulnerabilityService(db *database.DB, dockerService *DockerClientService
// ScanImage scans an image for vulnerabilities using Trivy
func (s *VulnerabilityService) ScanImage(ctx context.Context, envID string, imageID string, user models.User) (*vulnerability.ScanResult, error) {
- scanCtx := context.WithoutCancel(ctx)
+ scanCtx := utils.ActivityRuntimeContext(ctx, nil)
// Get Docker client to inspect the image
dockerClient, err := s.dockerService.GetClient(ctx)
@@ -496,7 +496,7 @@ func (s *VulnerabilityService) completeVulnerabilityScanActivityInternal(ctx con
}
}
- if _, err := s.activityService.CompleteActivity(context.WithoutCancel(ctx), activityID, status, message, errorPtr); err != nil {
+ if _, err := s.activityService.CompleteActivity(utils.ActivityRuntimeContext(ctx, nil), activityID, status, message, errorPtr); err != nil {
slog.DebugContext(ctx, "failed to complete vulnerability scan activity", "activityId", activityID, "error", err)
}
}
diff --git a/backend/pkg/libarcane/activity/handler.go b/backend/pkg/libarcane/activity/handler.go
index cca3dcdac..e23f72568 100644
--- a/backend/pkg/libarcane/activity/handler.go
+++ b/backend/pkg/libarcane/activity/handler.go
@@ -75,7 +75,7 @@ func CompleteHandlerActivity(ctx context.Context, activityService Service, activ
finalMessage = errText
}
- activityCtx := context.WithoutCancel(ctx)
+ activityCtx := utils.ActivityRuntimeContext(ctx, nil)
if _, completeErr := activityService.CompleteActivity(activityCtx, activityID, status, finalMessage, errMessage); completeErr != nil {
slog.DebugContext(activityCtx, "failed to complete background activity", "activityId", activityID, "error", completeErr)
}
diff --git a/backend/pkg/libarcane/activity/writer.go b/backend/pkg/libarcane/activity/writer.go
index 9931d4fbc..e56e5af34 100644
--- a/backend/pkg/libarcane/activity/writer.go
+++ b/backend/pkg/libarcane/activity/writer.go
@@ -72,9 +72,8 @@ func NewWriter(ctx context.Context, activityService MessageAppender, activityID
func (w *Writer) Write(p []byte) (int, error) {
if w.writer != nil {
- if _, err := w.writer.Write(p); err != nil {
- return 0, err
- }
+ // Keep activity capture alive when the client-side response stream disconnects.
+ _, _ = w.writer.Write(p)
}
w.mu.Lock()
diff --git a/backend/pkg/libarcane/activity/writer_test.go b/backend/pkg/libarcane/activity/writer_test.go
new file mode 100644
index 000000000..ae02cbe6f
--- /dev/null
+++ b/backend/pkg/libarcane/activity/writer_test.go
@@ -0,0 +1,54 @@
+package activity
+
+import (
+ "context"
+ "errors"
+ "io"
+ "testing"
+ "time"
+
+ "github.com/getarcaneapp/arcane/backend/internal/models"
+ activitytypes "github.com/getarcaneapp/arcane/types/activity"
+ "github.com/stretchr/testify/require"
+)
+
+type recordingAppender struct {
+ messages []AppendMessageRequest
+}
+
+func (a *recordingAppender) AppendMessage(_ context.Context, _ string, req AppendMessageRequest) (*activitytypes.Message, error) {
+ a.messages = append(a.messages, req)
+ return &activitytypes.Message{}, nil
+}
+
+type failingWriter struct{}
+
+func (f failingWriter) Write(_ []byte) (int, error) {
+ return 0, errors.New("client disconnected")
+}
+
+func TestWriterContinuesActivityCaptureWhenResponseWriterFailsInternal(t *testing.T) {
+ appender := &recordingAppender{}
+ writer := NewWriter(context.Background(), appender, "activity-1", failingWriter{}, "Pulling image")
+
+ n, err := writer.Write([]byte("Downloading layer\n"))
+ require.NoError(t, err)
+ require.Equal(t, len("Downloading layer\n"), n)
+
+ FlushWriter(writer)
+ require.Eventually(t, func() bool {
+ return len(appender.messages) == 1
+ }, time.Second, 10*time.Millisecond)
+ require.Equal(t, "Downloading layer", appender.messages[0].Message)
+ require.Equal(t, models.ActivityMessageLevelInfo, appender.messages[0].Level)
+}
+
+func TestWriterReturnsWrappedWriteErrorWithoutActivityInternal(t *testing.T) {
+ writer := NewWriter(context.Background(), nil, "", failingWriter{}, "Pulling image")
+
+ _, err := writer.Write([]byte("Downloading layer\n"))
+ require.ErrorContains(t, err, "client disconnected")
+}
+
+var _ MessageAppender = (*recordingAppender)(nil)
+var _ io.Writer = failingWriter{}
diff --git a/backend/pkg/projects/cmds.go b/backend/pkg/projects/cmds.go
index 111719688..52afa8ff2 100644
--- a/backend/pkg/projects/cmds.go
+++ b/backend/pkg/projects/cmds.go
@@ -11,6 +11,8 @@ import (
"github.com/docker/compose/v5/pkg/api"
"github.com/moby/moby/api/types/container"
"github.com/moby/moby/client"
+
+ "github.com/getarcaneapp/arcane/backend/pkg/utils"
)
// ProgressWriterKey can be set on a context to enable JSON-line progress updates.
@@ -45,6 +47,9 @@ const defaultComposeTimeout = 30 * time.Minute
// timeouts and proxy deadline cancellations. A standalone timeout is applied
// so the operation cannot run forever. See #1209.
func detachFromHTTPContextInternal(parent context.Context) (context.Context, context.CancelFunc) {
+ if utils.IsAppLifecycleContext(parent) {
+ return context.WithTimeout(parent, defaultComposeTimeout)
+ }
ctx := context.WithoutCancel(parent)
return context.WithTimeout(ctx, defaultComposeTimeout)
}
diff --git a/backend/pkg/projects/cmds_test.go b/backend/pkg/projects/cmds_test.go
index cde19de0d..54fb9784b 100644
--- a/backend/pkg/projects/cmds_test.go
+++ b/backend/pkg/projects/cmds_test.go
@@ -7,6 +7,7 @@ import (
composetypes "github.com/compose-spec/compose-go/v2/types"
"github.com/docker/compose/v5/pkg/api"
+ "github.com/getarcaneapp/arcane/backend/pkg/utils"
"github.com/stretchr/testify/require"
)
@@ -60,6 +61,16 @@ func TestDetachFromHTTPContextInternal(t *testing.T) {
require.True(t, ok)
require.InDelta(t, float64(defaultComposeTimeout), float64(time.Until(deadline)), float64(5*time.Second))
})
+
+ t.Run("app lifecycle context cancels detached work on shutdown", func(t *testing.T) {
+ appCtx, cancelApp := context.WithCancel(utils.WithAppLifecycleContext(context.Background()))
+ detached, detachedCancel := detachFromHTTPContextInternal(appCtx)
+ defer detachedCancel()
+
+ cancelApp()
+
+ require.ErrorIs(t, detached.Err(), context.Canceled)
+ })
}
func TestComposeStopSkipsWhenNoServicesSpecified(t *testing.T) {
diff --git a/backend/pkg/utils/activity_context.go b/backend/pkg/utils/activity_context.go
new file mode 100644
index 000000000..c13f3a666
--- /dev/null
+++ b/backend/pkg/utils/activity_context.go
@@ -0,0 +1,73 @@
+package utils
+
+import (
+ "context"
+ "time"
+)
+
+type appLifecycleContextKey struct{}
+
+type activityRuntimeContext struct {
+ valueCtx context.Context
+ lifecycleCtx context.Context
+}
+
+// WithAppLifecycleContext marks ctx as the application lifecycle context.
+func WithAppLifecycleContext(ctx context.Context) context.Context {
+ if ctx == nil {
+ ctx = context.Background()
+ }
+ return context.WithValue(ctx, appLifecycleContextKey{}, true)
+}
+
+// IsAppLifecycleContext reports whether ctx is tied to the application lifecycle.
+func IsAppLifecycleContext(ctx context.Context) bool {
+ isLifecycle, _ := ctx.Value(appLifecycleContextKey{}).(bool)
+ return isLifecycle
+}
+
+// ActivityRuntimeContext returns a context suitable for activity-backed work.
+func ActivityRuntimeContext(requestCtx context.Context, appCtx context.Context) context.Context {
+ if appCtx != nil {
+ if requestCtx == nil || requestCtx == appCtx {
+ return appCtx
+ }
+ return activityRuntimeContext{
+ valueCtx: requestCtx,
+ lifecycleCtx: appCtx,
+ }
+ }
+ if IsAppLifecycleContext(requestCtx) {
+ return requestCtx
+ }
+ if requestCtx != nil {
+ return context.WithoutCancel(requestCtx)
+ }
+ return context.Background()
+}
+
+func (c activityRuntimeContext) Deadline() (time.Time, bool) {
+ return c.lifecycleCtx.Deadline()
+}
+
+func (c activityRuntimeContext) Done() <-chan struct{} {
+ return c.lifecycleCtx.Done()
+}
+
+func (c activityRuntimeContext) Err() error {
+ return c.lifecycleCtx.Err()
+}
+
+func (c activityRuntimeContext) Value(key any) any {
+ if _, ok := key.(appLifecycleContextKey); ok {
+ if value := c.lifecycleCtx.Value(key); value != nil {
+ return value
+ }
+ }
+ if c.valueCtx != nil {
+ if value := c.valueCtx.Value(key); value != nil {
+ return value
+ }
+ }
+ return c.lifecycleCtx.Value(key)
+}
diff --git a/backend/pkg/utils/activity_context_test.go b/backend/pkg/utils/activity_context_test.go
new file mode 100644
index 000000000..c9e06490d
--- /dev/null
+++ b/backend/pkg/utils/activity_context_test.go
@@ -0,0 +1,82 @@
+package utils
+
+import (
+ "context"
+ "testing"
+ "time"
+
+ "github.com/stretchr/testify/require"
+)
+
+type activityContextTestKey string
+
+func TestActivityRuntimeContextPrefersAppContextInternal(t *testing.T) {
+ requestCtx, cancelRequest := context.WithCancel(context.Background())
+ appCtx, cancelApp := context.WithCancel(context.Background())
+ defer cancelApp()
+
+ ctx := ActivityRuntimeContext(requestCtx, appCtx)
+
+ cancelRequest()
+ require.NoError(t, ctx.Err())
+
+ cancelApp()
+ require.ErrorIs(t, ctx.Err(), context.Canceled)
+}
+
+func TestActivityRuntimeContextPreservesRequestValuesWithAppCancellationInternal(t *testing.T) {
+ requestCtx, cancelRequest := context.WithCancel(context.WithValue(context.Background(), activityContextTestKey("request-id"), "req-123"))
+ appCtx, cancelApp := context.WithCancel(WithAppLifecycleContext(context.Background()))
+ defer cancelApp()
+
+ ctx := ActivityRuntimeContext(requestCtx, appCtx)
+
+ require.Equal(t, "req-123", ctx.Value(activityContextTestKey("request-id")))
+ require.True(t, IsAppLifecycleContext(ctx))
+
+ cancelRequest()
+ require.NoError(t, ctx.Err())
+
+ cancelApp()
+ require.ErrorIs(t, ctx.Err(), context.Canceled)
+}
+
+func TestActivityRuntimeContextUsesAppDeadlineWithRequestValuesInternal(t *testing.T) {
+ requestDeadline := time.Now().Add(time.Hour)
+ appDeadline := time.Now().Add(time.Minute)
+ requestCtx, cancelRequest := context.WithDeadline(context.WithValue(context.Background(), activityContextTestKey("trace-id"), "trace-123"), requestDeadline)
+ defer cancelRequest()
+ appCtx, cancelApp := context.WithDeadline(context.Background(), appDeadline)
+ defer cancelApp()
+
+ ctx := ActivityRuntimeContext(requestCtx, appCtx)
+
+ deadline, ok := ctx.Deadline()
+ require.True(t, ok)
+ require.Equal(t, appDeadline, deadline)
+ require.Equal(t, "trace-123", ctx.Value(activityContextTestKey("trace-id")))
+}
+
+func TestActivityRuntimeContextFallsBackToDetachedRequestContextInternal(t *testing.T) {
+ requestCtx, cancelRequest := context.WithCancel(context.Background())
+
+ ctx := ActivityRuntimeContext(requestCtx, nil)
+
+ cancelRequest()
+ require.NoError(t, ctx.Err())
+}
+
+func TestActivityRuntimeContextPreservesMarkedAppContextInternal(t *testing.T) {
+ appCtx, cancelApp := context.WithCancel(WithAppLifecycleContext(context.Background()))
+
+ ctx := ActivityRuntimeContext(appCtx, nil)
+
+ cancelApp()
+ require.ErrorIs(t, ctx.Err(), context.Canceled)
+}
+
+func TestWithAppLifecycleContextMarksContextInternal(t *testing.T) {
+ ctx := WithAppLifecycleContext(context.Background())
+
+ require.True(t, IsAppLifecycleContext(ctx))
+}