Skip to content

Modern Docker Management, Designed for Everyone

refactor: move job bootstrap into job service (#2523)

Kyle Mendell1671a3da5dcb
diff --git a/AGENTS.md b/AGENTS.md
index 543756e01..cf28ab276 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -4,6 +4,10 @@
Arcane is a modern Docker management UI with a **Go backend** (Huma v2 API), **SvelteKit frontend** (Svelte 5), and an optional headless agent. Three Go modules unified via `go.work`: `backend/`, `cli/`, `types/`.
+### Domain docs
+
+Single-context domain docs live at `CONTEXT.md`;
+
## Development Environment
```bash
@@ -29,6 +33,7 @@ internal/
```
**Key patterns:**
+
- Handlers are thin: extract user from context, call service, return response
- Services receive dependencies via constructor injection (see [bootstrap.go](backend/internal/bootstrap/bootstrap.go))
- Use `slog` for structured logging with context
@@ -38,7 +43,7 @@ internal/
```
routes/(app)/ # Main app pages (dashboard, containers, images, etc.)
-routes/(auth)/ # Auth pages
+routes/(auth)/ # Auth pages
lib/components/ # Reusable Svelte components (shadcn-svelte based)
lib/services/ # API service classes extending BaseAPIService
lib/stores/ # Svelte stores (*.store.svelte files use runes)
@@ -119,7 +124,9 @@ Backend tests use in-memory SQLite and testify. See [auth_service_test.go](backe
## Anti-Patterns to Avoid
### Anti-Pattern 1: Business Logic in Handlers
+
**Bad**: Handler contains business logic
+
```go
func (h *ContainerHandler) RestartContainer(ctx context.Context, input *RestartInput) (*RestartOutput, error) {
container, err := h.dockerClient.ContainerInspect(ctx, input.ID)
@@ -131,6 +138,7 @@ func (h *ContainerHandler) RestartContainer(ctx context.Context, input *RestartI
```
**Good**: Handler calls service
+
```go
func (h *ContainerHandler) RestartContainer(ctx context.Context, input *RestartInput) (*RestartOutput, error) {
err := h.containerService.Restart(ctx, input.EnvironmentID, input.ID)
@@ -142,7 +150,9 @@ func (h *ContainerHandler) RestartContainer(ctx context.Context, input *RestartI
```
### Anti-Pattern 2: Svelte 4 Syntax
+
**Bad**: Using deprecated Svelte 4 patterns
+
```svelte
<script>
export let name;
@@ -152,6 +162,7 @@ func (h *ContainerHandler) RestartContainer(ctx context.Context, input *RestartI
```
**Good**: Using Svelte 5 runes
+
```svelte
<script lang="ts">
let { name }: { name: string } = $props();
@@ -161,7 +172,9 @@ func (h *ContainerHandler) RestartContainer(ctx context.Context, input *RestartI
```
### Anti-Pattern 3: Missing Multi-Environment Support
+
**Bad**: Hardcoded API path without environment
+
```typescript
async getContainers() {
return this.api.get('/containers');
@@ -169,6 +182,7 @@ async getContainers() {
```
**Good**: Include environment ID in path
+
```typescript
async getContainers() {
const envId = await environmentStore.getCurrentEnvironmentId();
@@ -177,7 +191,9 @@ async getContainers() {
```
### Anti-Pattern 4: Missing BaseModel
+
**Bad**: Model without standard fields
+
```go
type Stack struct {
ID string `json:"id"`
@@ -186,6 +202,7 @@ type Stack struct {
```
**Good**: Model with BaseModel
+
```go
type Stack struct {
models.BaseModel
@@ -196,19 +213,22 @@ func (Stack) TableName() string { return "stacks" }
```
### Anti-Pattern 5: Using TypeScript `any`
+
**Bad**: Untyped data
+
```typescript
function processContainer(data: any) {
- return data.name;
+ return data.name;
}
```
**Good**: Properly typed
+
```typescript
-import type { Container } from '$lib/types';
+import type { Container } from "$lib/types";
function processContainer(data: Container): string {
- return data.name;
+ return data.name;
}
```
@@ -231,7 +251,8 @@ this.api.get(`/environments/${envId}/containers`);
```
**Key patterns:**
-- Environment ID `"0"` = local Docker connection
+
+- Environment ID `"0"` = local Docker connection
- Remote environments connect via agents (standard or edge)
- `environmentStore.ready` is a Promise — await before accessing environment-specific data
- When environment changes, resource detail pages redirect to list pages (resources don't exist across environments)
@@ -319,10 +340,12 @@ Use `models.JSON` for arbitrary JSON fields and `models.StringSlice` for string
Edge agents connect to a central Arcane manager via WebSocket tunnel, allowing management of Docker hosts behind NAT/firewalls.
**Architecture:**
+
- Manager: Receives tunnel connections, proxies HTTP requests over WebSocket
- Agent: Connects outbound to manager, executes requests locally
**Configuration** (agent side):
+
```bash
ARCANE_EDGE_AGENT=true
ARCANE_MANAGER_API_URL=https://manager.example.com
@@ -330,11 +353,13 @@ ARCANE_AGENT_TOKEN=<api-key>
```
**Message types** (see [tunnel.go](backend/pkg/libarcane/edge/tunnel.go)):
+
- `request` / `response`: HTTP request/response proxying
- `heartbeat` / `heartbeat_ack`: Connection keepalive
- `ws_start` / `ws_data` / `ws_close`: WebSocket streaming (logs, stats)
**When implementing agent features:**
+
- Check `cfg.AgentMode` to skip manager-only logic (e.g., environment health checks)
- Agent auto-pairs with manager on startup if token is configured
- Edge connections are stateless — each request is independent
@@ -362,6 +387,7 @@ When working with Arcane:
❌ **Don't skip BaseModel**: All database models must embed `models.BaseModel` for UUID and timestamps.
❌ **Don't ignore existing patterns**: Before writing new code, search for similar functionality:
+
```bash
# Find existing patterns
git grep "func.*Service" backend/internal/services/
@@ -404,22 +430,27 @@ If any of these fail, **do not submit the PR**. Fix the issues first.
```markdown
## Summary
+
[One paragraph explaining what this PR does and why]
## Related Issue
+
Fixes #[issue number]
## Changes
+
- [Specific change 1 with rationale]
- [Specific change 2 with rationale]
## Testing
+
- [ ] Dev environment starts successfully
- [ ] Backend tests pass: `cd backend && go test ./...`
- [ ] Frontend type checks pass: `just lint frontend`
- [ ] Manually tested: [describe how]
## AI Tool Used
+
AI Tool: [e.g., Claude Code, GitHub Copilot, Cursor]
Assistance Level: [Significant/Moderate/Minor]
```
diff --git a/CONTEXT.md b/CONTEXT.md
new file mode 100644
index 000000000..59784420c
--- /dev/null
+++ b/CONTEXT.md
@@ -0,0 +1,69 @@
+# Arcane Context
+
+Arcane is a Docker management product with a Go backend, a SvelteKit frontend, shared TypeScript/Go-facing types, and an optional headless agent.
+
+## Glossary
+
+### Arcane Manager
+
+The main Arcane application. It serves the web UI and Huma API, stores application state, manages the local Docker environment, and coordinates remote environments.
+
+### Docker Environment
+
+A Docker host managed by Arcane. The local Docker environment uses ID `0`. Remote environments are managed through standard agents or edge agents.
+
+### Local Docker Environment
+
+The Docker environment available to the Arcane Manager through the local Docker socket. Code and docs should use ID `0` when referring to the local environment.
+
+### Remote Environment
+
+A Docker environment that is not the manager's local Docker socket. Remote environments communicate through an agent API, edge tunnel, or polling transport.
+
+### Agent
+
+A headless Arcane process running near a Docker host. It accepts manager requests and executes them against its local Docker daemon.
+
+### Edge Agent
+
+An agent that connects outbound to the Arcane Manager over the edge transport so Docker hosts behind NAT or firewalls can be managed.
+
+### Project
+
+An Arcane-managed Docker Compose project stored under the configured projects directory. Projects have compose files, optional env files, persisted metadata, deployment state, and related Docker resources.
+
+### Stack
+
+A Docker Swarm stack managed through Arcane. Stack source, rendering, deployment, services, and tasks are handled separately from Compose projects.
+
+### Container Registry
+
+A registry configuration Arcane uses for image pulls, image update checks, and remote environment synchronization. Registry handling should remain provider-generic unless a provider-specific path is required.
+
+### Image Update
+
+Arcane's record of whether a container or image reference has a newer digest available. Image update behavior is used by manual checks, scheduled polling, notifications, and updater workflows.
+
+### Vulnerability Scan
+
+Arcane's Trivy-backed scan lifecycle for Docker images. The lifecycle includes scan phase tracking, scanner container setup, result persistence, ignore filtering, summaries, and notifications.
+
+### Job Schedule
+
+The persisted schedule and runtime registration for background jobs such as image polling, auto-update, vulnerability scanning, pruning, GitOps sync, Docker client refresh, and environment health checks.
+
+### GitOps Sync
+
+The workflow that pulls configured Git repositories and applies their project or stack definitions into Arcane-managed resources.
+
+### Notification
+
+An outbound message Arcane sends for update, vulnerability, prune, auto-heal, and test events through configured providers.
+
+## Architecture Notes
+
+- Backend handlers should be thin wrappers over domain behavior.
+- Frontend API calls for Docker resources should include the active Docker environment ID.
+- Svelte code must use Svelte 5 runes syntax.
+- Database models should embed `models.BaseModel` unless a record has a deliberate persistence reason not to.
+- Architecture reviews should use this vocabulary when proposing module names or seams.
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 75c05cfb6..4e640c263 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -1,4 +1,4 @@
-# Contributing to Arcane
+ # Contributing to Arcane
Thanks for helping make Arcane better! We've built a modern, streamlined development experience that gets you up and running in minutes.
diff --git a/backend/internal/bootstrap/bootstrap.go b/backend/internal/bootstrap/bootstrap.go
index fbdb26856..28a239e5d 100644
--- a/backend/internal/bootstrap/bootstrap.go
+++ b/backend/internal/bootstrap/bootstrap.go
@@ -75,7 +75,7 @@ func Bootstrap(ctx context.Context) error {
cronLocation := cfg.GetLocation()
scheduler := scheduler.NewJobScheduler(appCtx, cronLocation)
- appServices.JobSchedule.SetScheduler(scheduler)
+ appServices.JobSchedule.SetScheduler(appCtx, scheduler)
registerJobs(appCtx, scheduler, appServices, cfg)
router, tunnelServer := setupRouter(appCtx, cfg, appServices)
diff --git a/backend/internal/bootstrap/jobs_bootstrap.go b/backend/internal/bootstrap/jobs_bootstrap.go
index e76d544e6..dc04e4380 100644
--- a/backend/internal/bootstrap/jobs_bootstrap.go
+++ b/backend/internal/bootstrap/jobs_bootstrap.go
@@ -51,123 +51,9 @@ func registerJobs(appCtx context.Context, newScheduler *pkg_scheduler.JobSchedul
autoHealJob := pkg_scheduler.NewAutoHealJob(appServices.Docker, appServices.Settings, appServices.Event, appServices.Notification)
newScheduler.RegisterJob(autoHealJob)
- setupJobScheduleCallbacks(
- appCtx,
- appServices,
- appConfig,
- newScheduler,
- imagePollingJob,
- autoUpdateJob,
- dockerClientRefreshJob,
- environmentHealthJob,
- eventCleanupJob,
- scheduledPruneJob,
- gitOpsSyncJob,
- vulnerabilityScanJob,
- autoHealJob,
- )
setupSettingsCallbacks(appCtx, appServices, appConfig, newScheduler, imagePollingJob, autoUpdateJob, environmentHealthJob, fsWatcherJob, scheduledPruneJob, vulnerabilityScanJob, autoHealJob)
}
-func setupJobScheduleCallbacks(
- lifecycleCtx context.Context,
- appServices *Services,
- appConfig *config.Config,
- newScheduler *pkg_scheduler.JobScheduler,
- imagePollingJob *pkg_scheduler.ImagePollingJob,
- autoUpdateJob *pkg_scheduler.AutoUpdateJob,
- dockerClientRefreshJob *pkg_scheduler.DockerClientRefreshJob,
- environmentHealthJob *pkg_scheduler.EnvironmentHealthJob,
- eventCleanupJob *pkg_scheduler.EventCleanupJob,
- scheduledPruneJob *pkg_scheduler.ScheduledPruneJob,
- gitOpsSyncJob *pkg_scheduler.GitOpsSyncJob,
- vulnerabilityScanJob *pkg_scheduler.VulnerabilityScanJob,
- autoHealJob *pkg_scheduler.AutoHealJob,
-) {
- if appServices.JobSchedule == nil {
- return
- }
-
- appServices.JobSchedule.OnJobSchedulesChanged = func(ctx context.Context, changedKeys []string) {
- for _, key := range changedKeys {
- slog.DebugContext(lifecycleCtx, "Processing job schedule change", "key", key, "triggerContextCanceled", ctx.Err() != nil)
- handleJobScheduleChangeInternal(
- lifecycleCtx,
- key,
- appConfig,
- newScheduler,
- imagePollingJob,
- autoUpdateJob,
- dockerClientRefreshJob,
- environmentHealthJob,
- eventCleanupJob,
- scheduledPruneJob,
- gitOpsSyncJob,
- vulnerabilityScanJob,
- autoHealJob,
- )
- }
- }
-}
-
-func handleJobScheduleChangeInternal(
- ctx context.Context,
- key string,
- appConfig *config.Config,
- newScheduler *pkg_scheduler.JobScheduler,
- imagePollingJob *pkg_scheduler.ImagePollingJob,
- autoUpdateJob *pkg_scheduler.AutoUpdateJob,
- dockerClientRefreshJob *pkg_scheduler.DockerClientRefreshJob,
- environmentHealthJob *pkg_scheduler.EnvironmentHealthJob,
- eventCleanupJob *pkg_scheduler.EventCleanupJob,
- scheduledPruneJob *pkg_scheduler.ScheduledPruneJob,
- gitOpsSyncJob *pkg_scheduler.GitOpsSyncJob,
- vulnerabilityScanJob *pkg_scheduler.VulnerabilityScanJob,
- autoHealJob *pkg_scheduler.AutoHealJob,
-) {
- switch key {
- case "pollingInterval":
- if err := newScheduler.RescheduleJob(ctx, imagePollingJob); err != nil {
- slog.WarnContext(ctx, "Failed to reschedule image-polling job", "error", err)
- }
- case "autoUpdateInterval":
- if err := newScheduler.RescheduleJob(ctx, autoUpdateJob); err != nil {
- slog.WarnContext(ctx, "Failed to reschedule auto-update job", "error", err)
- }
- case "dockerClientRefreshInterval":
- if err := newScheduler.RescheduleJob(ctx, dockerClientRefreshJob); err != nil {
- slog.WarnContext(ctx, "Failed to reschedule docker-client-refresh job", "error", err)
- }
- case "environmentHealthInterval":
- if appConfig.AgentMode {
- return
- }
- if err := newScheduler.RescheduleJob(ctx, environmentHealthJob); err != nil {
- slog.WarnContext(ctx, "Failed to reschedule environment-health job", "error", err)
- }
- case "eventCleanupInterval":
- if err := newScheduler.RescheduleJob(ctx, eventCleanupJob); err != nil {
- slog.WarnContext(ctx, "Failed to reschedule event cleanup job", "error", err)
- }
- case "scheduledPruneInterval":
- if err := newScheduler.RescheduleJob(ctx, scheduledPruneJob); err != nil {
- slog.WarnContext(ctx, "Failed to reschedule scheduled-prune job", "error", err)
- }
- case "gitopsSyncInterval":
- if err := newScheduler.RescheduleJob(ctx, gitOpsSyncJob); err != nil {
- slog.WarnContext(ctx, "Failed to reschedule gitops sync job", "error", err)
- }
- case "vulnerabilityScanInterval":
- if err := newScheduler.RescheduleJob(ctx, vulnerabilityScanJob); err != nil {
- slog.WarnContext(ctx, "Failed to reschedule vulnerability-scan job", "error", err)
- }
- case "autoHealInterval":
- if err := newScheduler.RescheduleJob(ctx, autoHealJob); err != nil {
- slog.WarnContext(ctx, "Failed to reschedule auto-heal job", "error", err)
- }
- }
-}
-
func setupSettingsCallbacks(lifecycleCtx context.Context, appServices *Services, appConfig *config.Config, newScheduler *pkg_scheduler.JobScheduler, imagePollingJob *pkg_scheduler.ImagePollingJob, autoUpdateJob *pkg_scheduler.AutoUpdateJob, environmentHealthJob *pkg_scheduler.EnvironmentHealthJob, fsWatcherJob *pkg_scheduler.FilesystemWatcherJob, scheduledPruneJob *pkg_scheduler.ScheduledPruneJob, vulnerabilityScanJob *pkg_scheduler.VulnerabilityScanJob, autoHealJob *pkg_scheduler.AutoHealJob) {
appServices.Settings.OnImagePollingSettingsChanged = func(_ context.Context) {
if err := newScheduler.RescheduleJob(lifecycleCtx, imagePollingJob); err != nil {
diff --git a/backend/internal/services/job_service.go b/backend/internal/services/job_service.go
index f7e589d34..1034f82f1 100644
--- a/backend/internal/services/job_service.go
+++ b/backend/internal/services/job_service.go
@@ -3,6 +3,7 @@ package services
import (
"context"
"fmt"
+ "log/slog"
"sort"
"time"
@@ -18,24 +19,24 @@ import (
type JobRunner interface {
GetJob(jobID string) (schedulertypes.Job, bool)
+ RescheduleJob(ctx context.Context, job schedulertypes.Job) error
}
// JobService manages configuration for background job schedules.
//
// Intervals are persisted in the existing settings table as individual keys.
-// After updates, the SettingsService cache is reloaded and a callback can be
-// triggered so the running scheduler can reschedule active jobs.
+// After updates, the SettingsService cache is reloaded and active jobs are
+// rescheduled through the configured scheduler.
//
// NOTE: This is intentionally separate from SettingsService to keep the API
// surface job-focused and to centralize schedule validation/rescheduling.
type JobService struct {
- db *database.DB
- settings *SettingsService
- cfg *config.Config
- scheduler JobRunner
- location *time.Location // Timezone for cron schedule calculations
-
- OnJobSchedulesChanged func(ctx context.Context, changedKeys []string)
+ db *database.DB
+ settings *SettingsService
+ cfg *config.Config
+ scheduler JobRunner
+ lifecycleCtx context.Context
+ location *time.Location // Timezone for cron schedule calculations
}
func NewJobService(db *database.DB, settings *SettingsService, cfg *config.Config) *JobService {
@@ -47,7 +48,11 @@ func NewJobService(db *database.DB, settings *SettingsService, cfg *config.Confi
}
}
-func (s *JobService) SetScheduler(scheduler JobRunner) {
+func (s *JobService) SetScheduler(ctx context.Context, scheduler JobRunner) { //nolint:contextcheck // scheduler jobs must capture the app lifecycle context, not request contexts
+ if ctx == nil {
+ ctx = context.Background()
+ }
+ s.lifecycleCtx = ctx
s.scheduler = scheduler
}
@@ -135,14 +140,62 @@ func (s *JobService) UpdateJobSchedules(ctx context.Context, updates jobschedule
return jobschedule.Config{}, fmt.Errorf("failed to reload settings after job schedule update: %w", err)
}
- if s.OnJobSchedulesChanged != nil {
- s.OnJobSchedulesChanged(ctx, changedKeys)
- }
+ s.RescheduleJobsForSettingKeys(ctx, changedKeys)
}
return s.GetJobSchedules(ctx), nil
}
+func (s *JobService) RescheduleJobsForSettingKeys(ctx context.Context, changedKeys []string) {
+ if s == nil || s.scheduler == nil || len(changedKeys) == 0 {
+ return
+ }
+
+ changed := make(map[string]struct{}, len(changedKeys))
+ for _, key := range changedKeys {
+ changed[key] = struct{}{}
+ }
+
+ for jobID, jobMeta := range meta.GetAllJobMetadata() {
+ if !jobMetadataAffectedBySettingInternal(jobMeta, changed) {
+ continue
+ }
+ if s.cfg != nil && s.cfg.AgentMode && jobMeta.ManagerOnly {
+ slog.DebugContext(ctx, "Skipping manager-only job reschedule in agent mode", "job", jobID)
+ continue
+ }
+
+ job, ok := s.scheduler.GetJob(jobID)
+ if !ok {
+ slog.DebugContext(ctx, "Skipping reschedule for unregistered job", "job", jobID)
+ continue
+ }
+
+ slog.DebugContext(ctx, "Processing job setting change", "job", jobID, "settingsKey", jobMeta.SettingsKey, "enabledKey", jobMeta.EnabledKey)
+ rescheduleCtx := ctx //nolint:contextcheck // fallback only; lifecycle context is preferred so cron jobs outlive HTTP requests
+ if s.lifecycleCtx != nil {
+ rescheduleCtx = s.lifecycleCtx
+ }
+ if err := s.scheduler.RescheduleJob(rescheduleCtx, job); err != nil {
+ slog.WarnContext(ctx, "Failed to reschedule job", "job", jobID, "error", err)
+ }
+ }
+}
+
+func jobMetadataAffectedBySettingInternal(jobMeta meta.JobMetadata, changed map[string]struct{}) bool {
+ if jobMeta.SettingsKey != "" {
+ if _, ok := changed[jobMeta.SettingsKey]; ok {
+ return true
+ }
+ }
+ if jobMeta.EnabledKey != "" {
+ if _, ok := changed[jobMeta.EnabledKey]; ok {
+ return true
+ }
+ }
+ return false
+}
+
func (s *JobService) ListJobs(ctx context.Context) (*jobschedule.JobListResponse, error) {
if s == nil || s.settings == nil {
return nil, fmt.Errorf("job service not initialized")
diff --git a/backend/internal/services/job_service_test.go b/backend/internal/services/job_service_test.go
index 10c2aa243..737155467 100644
--- a/backend/internal/services/job_service_test.go
+++ b/backend/internal/services/job_service_test.go
@@ -6,6 +6,7 @@ import (
"github.com/getarcaneapp/arcane/backend/internal/config"
"github.com/getarcaneapp/arcane/types/jobschedule"
+ schedulertypes "github.com/getarcaneapp/arcane/types/scheduler"
"github.com/stretchr/testify/require"
)
@@ -90,6 +91,74 @@ func TestJobService_ListJobs_IncludesDockerClientRefreshJob(t *testing.T) {
require.Equal(t, "*/30 * * * * *", refreshJob.Schedule)
}
+func TestJobService_UpdateJobSchedules_ReschedulesChangedJob(t *testing.T) {
+ ctx := context.Background()
+ db := setupSettingsTestDB(t)
+
+ settingsSvc, err := NewSettingsService(ctx, db)
+ require.NoError(t, err)
+
+ jobSvc := NewJobService(db, settingsSvc, &config.Config{})
+ scheduler := newFakeJobSchedulerInternal("image-polling", "auto-update")
+ jobSvc.SetScheduler(ctx, scheduler)
+
+ nextPollingInterval := "0 */10 * * * *"
+ _, err = jobSvc.UpdateJobSchedules(ctx, jobschedule.Update{
+ PollingInterval: &nextPollingInterval,
+ })
+ require.NoError(t, err)
+
+ require.Equal(t, []string{"image-polling"}, scheduler.rescheduled)
+}
+
+func TestJobService_UpdateJobSchedules_UsesLifecycleContextForReschedule(t *testing.T) {
+ ctx := context.Background()
+ db := setupSettingsTestDB(t)
+
+ settingsSvc, err := NewSettingsService(ctx, db)
+ require.NoError(t, err)
+
+ type lifecycleContextKey struct{}
+ lifecycleCtx := context.WithValue(context.Background(), lifecycleContextKey{}, true)
+ requestCtx, cancelRequest := context.WithCancel(context.Background())
+
+ jobSvc := NewJobService(db, settingsSvc, &config.Config{})
+ scheduler := newFakeJobSchedulerInternal("image-polling")
+ jobSvc.SetScheduler(lifecycleCtx, scheduler)
+
+ nextPollingInterval := "0 */10 * * * *"
+ _, err = jobSvc.UpdateJobSchedules(requestCtx, jobschedule.Update{
+ PollingInterval: &nextPollingInterval,
+ })
+ require.NoError(t, err)
+
+ cancelRequest()
+
+ require.Len(t, scheduler.rescheduleContexts, 1)
+ require.NoError(t, scheduler.rescheduleContexts[0].Err())
+ require.Equal(t, true, scheduler.rescheduleContexts[0].Value(lifecycleContextKey{}))
+}
+
+func TestJobService_UpdateJobSchedules_SkipsManagerOnlyJobsInAgentMode(t *testing.T) {
+ ctx := context.Background()
+ db := setupSettingsTestDB(t)
+
+ settingsSvc, err := NewSettingsService(ctx, db)
+ require.NoError(t, err)
+
+ jobSvc := NewJobService(db, settingsSvc, &config.Config{AgentMode: true})
+ scheduler := newFakeJobSchedulerInternal("environment-health")
+ jobSvc.SetScheduler(ctx, scheduler)
+
+ nextHealthInterval := "0 */5 * * * *"
+ _, err = jobSvc.UpdateJobSchedules(ctx, jobschedule.Update{
+ EnvironmentHealthInterval: &nextHealthInterval,
+ })
+ require.NoError(t, err)
+
+ require.Empty(t, scheduler.rescheduled)
+}
+
func findJobStatusByIDInternal(t *testing.T, jobs []jobschedule.JobStatus, id string) jobschedule.JobStatus {
t.Helper()
@@ -102,3 +171,45 @@ func findJobStatusByIDInternal(t *testing.T, jobs []jobschedule.JobStatus, id st
t.Fatalf("job %q not found", id)
return jobschedule.JobStatus{}
}
+
+type fakeJobSchedulerInternal struct {
+ jobs map[string]schedulertypes.Job
+ rescheduled []string
+ rescheduleContexts []context.Context
+}
+
+func newFakeJobSchedulerInternal(jobIDs ...string) *fakeJobSchedulerInternal {
+ jobs := make(map[string]schedulertypes.Job, len(jobIDs))
+ for _, jobID := range jobIDs {
+ jobs[jobID] = fakeJobInternal{name: jobID}
+ }
+
+ return &fakeJobSchedulerInternal{
+ jobs: jobs,
+ }
+}
+
+func (s *fakeJobSchedulerInternal) GetJob(jobID string) (schedulertypes.Job, bool) {
+ job, ok := s.jobs[jobID]
+ return job, ok
+}
+
+func (s *fakeJobSchedulerInternal) RescheduleJob(ctx context.Context, job schedulertypes.Job) error {
+ s.rescheduled = append(s.rescheduled, job.Name())
+ s.rescheduleContexts = append(s.rescheduleContexts, ctx)
+ return nil
+}
+
+type fakeJobInternal struct {
+ name string
+}
+
+func (j fakeJobInternal) Name() string {
+ return j.name
+}
+
+func (j fakeJobInternal) Schedule(context.Context) string {
+ return "0 0 0 * * *"
+}
+
+func (j fakeJobInternal) Run(context.Context) {}