Skip to content

Modern Docker Management, Designed for Everyone

15.9 KB
Raw Blame
package scheduler

import (
	"context"
	"errors"
	"sync"
	"testing"
	"time"

	schedulertypes "github.com/getarcaneapp/arcane/types/v2/scheduler"
	"github.com/italypaleale/francis/actor"
	"github.com/stretchr/testify/require"
)

type testSchedulerJob struct {
	name     string
	schedule string
	run      func(context.Context)
}

func (j *testSchedulerJob) Name() string { return j.name }

func (j *testSchedulerJob) Schedule(context.Context) string { return j.schedule }

func (j *testSchedulerJob) Run(ctx context.Context) (schedulertypes.Outcome, error) {
	if j.run != nil {
		j.run(ctx)
	}
	return schedulertypes.Outcome{Status: schedulertypes.Succeeded}, nil
}

type conditionalTestSchedulerJob struct {
	*testSchedulerJob
	shouldSchedule func(context.Context) bool
}

type testBusWatcherInternal struct {
	name    string
	started chan struct{}
	stopped chan struct{}
	ranNow  chan context.Context
}

type orderedStopBusWatcherInternal struct {
	name         string
	started      chan struct{}
	runnerExited chan struct{}
}

func (w *orderedStopBusWatcherInternal) Name() string {
	return w.name
}

func (w *orderedStopBusWatcherInternal) Start(ctx context.Context) error {
	close(w.started)
	<-ctx.Done()
	close(w.runnerExited)
	return nil
}

func (*orderedStopBusWatcherInternal) RunNow(context.Context) error {
	return nil
}

func (w *orderedStopBusWatcherInternal) Stop(context.Context) error {
	select {
	case <-w.runnerExited:
		return nil
	default:
		return errors.New("watcher stopped before its runner exited")
	}
}

func (w *testBusWatcherInternal) RunNow(ctx context.Context) error {
	if w.ranNow != nil {
		w.ranNow <- ctx
	}
	return nil
}

func (w *testBusWatcherInternal) Name() string { return w.name }

func (w *testBusWatcherInternal) Start(ctx context.Context) error {
	close(w.started)
	<-ctx.Done()
	close(w.stopped)
	return nil
}

func (j *conditionalTestSchedulerJob) ShouldSchedule(ctx context.Context) bool {
	if j.shouldSchedule == nil {
		return true
	}

	return j.shouldSchedule(ctx)
}

func TestJobScheduler_StartScheduler_SkipsDisabledConditionalJobs(t *testing.T) {
	js := newJobSchedulerForTestInternal(t, t.Context(), nil)

	job := &conditionalTestSchedulerJob{
		testSchedulerJob: &testSchedulerJob{
			name:     "test-disabled-startup",
			schedule: "*/1 * * * * *",
		},
		shouldSchedule: func(context.Context) bool { return false },
	}

	require.NoError(t, js.RegisterJob(job))
	require.NoError(t, js.StartScheduler(t.Context()))

	state, ok := js.GetJobRuntimeState(job.Name())
	require.True(t, ok)
	require.False(t, state.Scheduled)
	record, err := js.coordinator.ScheduleState(t.Context(), job.Name())
	require.NoError(t, err)
	require.True(t, record.NextRun.IsZero())
}

func TestJobScheduler_StartScheduler_ReportsInvalidJobSchedule(t *testing.T) {
	js := newJobSchedulerForTestInternal(t, t.Context(), nil)
	invalid := &testSchedulerJob{name: "invalid-startup-job", schedule: "not a cron schedule"}
	valid := &testSchedulerJob{name: "valid-startup-job", schedule: "*/1 * * * * *"}

	require.NoError(t, js.RegisterJob(invalid))
	require.NoError(t, js.RegisterJob(valid))
	require.Error(t, js.StartScheduler(t.Context()))

	invalidState, ok := js.GetJobRuntimeState(invalid.Name())
	require.True(t, ok)
	require.False(t, invalidState.Scheduled)
	validState, ok := js.GetJobRuntimeState(valid.Name())
	require.True(t, ok)
	require.True(t, validState.Scheduled)
	requireScheduledJobInternal(t, js, valid.Name())
}

func TestJobScheduler_StopWaitsForBusWatchers(t *testing.T) {
	ctx, cancel := context.WithCancel(t.Context())
	js := newJobSchedulerForTestInternal(t, ctx, nil)
	watcher := &testBusWatcherInternal{
		name:    "test-bus-watcher",
		started: make(chan struct{}),
		stopped: make(chan struct{}),
		ranNow:  make(chan context.Context, 1),
	}

	require.NoError(t, js.RegisterBusWatcher(watcher, true))
	require.NoError(t, js.StartScheduler(t.Context()))

	select {
	case <-watcher.started:
	case <-time.After(time.Second):
		require.FailNow(t, "timed out waiting for bus watcher to start")
	}

	stopDone := make(chan error, 1)
	go func() { stopDone <- js.Stop(t.Context()) }()
	cancel()

	select {
	case <-watcher.stopped:
	case <-time.After(time.Second):
		require.FailNow(t, "timed out waiting for bus watcher to stop")
	}
	select {
	case err := <-stopDone:
		require.NoError(t, err)
	case <-time.After(time.Second):
		require.FailNow(t, "scheduler did not stop after bus watcher finished")
	}
}

func TestJobScheduler_StopJoinsRunnerBeforeStoppingWatcher(t *testing.T) {
	js := newJobSchedulerForTestInternal(t, t.Context(), nil)
	watcher := &orderedStopBusWatcherInternal{
		name:         "ordered-stop-watcher",
		started:      make(chan struct{}),
		runnerExited: make(chan struct{}),
	}

	require.NoError(t, js.RegisterBusWatcher(watcher, false))
	select {
	case <-watcher.started:
	case <-time.After(time.Second):
		require.FailNow(t, "timed out waiting for bus watcher to start")
	}
	require.NoError(t, js.Stop(t.Context()))
}

func TestJobScheduler_RegisterBusWatcherManualRunOption(t *testing.T) {
	ctx := t.Context()

	js := newJobSchedulerForTestInternal(t, ctx, nil)
	manualWatcher := &testBusWatcherInternal{
		name:    "manual-bus-watcher",
		started: make(chan struct{}),
		stopped: make(chan struct{}),
		ranNow:  make(chan context.Context, 1),
	}
	automaticOnlyWatcher := &testBusWatcherInternal{
		name:    "automatic-only-bus-watcher",
		started: make(chan struct{}),
		stopped: make(chan struct{}),
	}

	require.NoError(t, js.RegisterBusWatcher(manualWatcher, true))
	require.NoError(t, js.RegisterBusWatcher(automaticOnlyWatcher, false))

	runCtx := t.Context()
	require.NoError(t, js.RunBusWatcherNow(runCtx, manualWatcher.Name()))
	require.Equal(t, runCtx, <-manualWatcher.ranNow)
	require.Error(t, js.RunBusWatcherNow(runCtx, automaticOnlyWatcher.Name()))
}

func TestJobScheduler_RescheduleJob_RemovesEntryWhenDisabled(t *testing.T) {
	js := newJobSchedulerForTestInternal(t, t.Context(), nil)
	require.NoError(t, js.StartScheduler(t.Context()))
	enabled := true

	job := &conditionalTestSchedulerJob{
		testSchedulerJob: &testSchedulerJob{
			name:     "test-disabled-reschedule",
			schedule: "*/1 * * * * *",
		},
		shouldSchedule: func(context.Context) bool { return enabled },
	}

	require.NoError(t, js.RescheduleJob(t.Context(), job))
	state, ok := js.GetJobRuntimeState(job.Name())
	require.True(t, ok)
	require.True(t, state.Scheduled)

	enabled = false

	require.NoError(t, js.RescheduleJob(t.Context(), job))
	state, ok = js.GetJobRuntimeState(job.Name())
	require.True(t, ok)
	require.False(t, state.Scheduled)
	record, err := js.coordinator.ScheduleState(t.Context(), job.Name())
	require.NoError(t, err)
	require.True(t, record.NextRun.IsZero())
}

func TestJobScheduler_RescheduleJob_AddsEntryWhenEnabled(t *testing.T) {
	js := newJobSchedulerForTestInternal(t, t.Context(), nil)
	require.NoError(t, js.StartScheduler(t.Context()))
	enabled := false

	job := &conditionalTestSchedulerJob{
		testSchedulerJob: &testSchedulerJob{
			name:     "test-enabled-reschedule",
			schedule: "*/1 * * * * *",
		},
		shouldSchedule: func(context.Context) bool { return enabled },
	}

	require.NoError(t, js.RescheduleJob(t.Context(), job))
	state, ok := js.GetJobRuntimeState(job.Name())
	require.True(t, ok)
	require.False(t, state.Scheduled)

	enabled = true

	require.NoError(t, js.RescheduleJob(t.Context(), job))
	state, ok = js.GetJobRuntimeState(job.Name())
	require.True(t, ok)
	require.True(t, state.Scheduled)
	requireScheduledJobInternal(t, js, job.Name())
}

func TestJobScheduler_StartScheduler_SchedulesNonConditionalJobs(t *testing.T) {
	js := newJobSchedulerForTestInternal(t, t.Context(), nil)
	watcher := &testBusWatcherInternal{
		name:    "image-polling",
		started: make(chan struct{}),
		stopped: make(chan struct{}),
	}
	require.NoError(t, js.RegisterBusWatcher(watcher, true))
	nextPolling := time.Now().UTC().Add(time.Hour)
	require.NoError(t, js.coordinator.Checkpoint(t.Context(), watcher.Name(), "0 0 * * * *", nextPolling))
	require.NoError(t, js.coordinator.Checkpoint(t.Context(), "removed-job", "0 0 * * * *", nextPolling))
	executed := make(chan struct{}, 1)

	job := &testSchedulerJob{
		name:     "test-non-conditional-startup",
		schedule: "*/1 * * * * *",
		run: func(context.Context) {
			select {
			case executed <- struct{}{}:
			default:
			}
		},
	}

	require.NoError(t, js.RegisterJob(job))
	require.NoError(t, js.StartScheduler(t.Context()))

	state, ok := js.GetJobRuntimeState(job.Name())
	require.True(t, ok)
	require.True(t, state.Scheduled)
	requireScheduledJobInternal(t, js, job.Name())
	polling, err := js.coordinator.ScheduleState(t.Context(), watcher.Name())
	require.NoError(t, err)
	require.Equal(t, "0 0 * * * *", polling.Schedule)
	require.True(t, nextPolling.Equal(polling.NextRun))
	_, err = js.coordinator.ScheduleState(t.Context(), "removed-job")
	require.ErrorIs(t, err, actor.ErrStateNotFound)
	select {
	case <-executed:
	case <-time.After(5 * time.Second):
		require.FailNow(t, "scheduled job did not execute through Francis")
	}
}

func TestJobScheduler_RescheduleJob_UsesProvidedContext(t *testing.T) {
	js := newJobSchedulerForTestInternal(t, t.Context(), nil)

	var once sync.Once
	runErrCh := make(chan error, 1)
	runCtx := t.Context()

	job := &testSchedulerJob{
		name:     "test-reschedule-provided-context",
		schedule: "*/1 * * * * *",
		run: func(ctx context.Context) {
			once.Do(func() { runErrCh <- ctx.Err() })
		},
	}

	require.NoError(t, js.RescheduleJob(runCtx, job))
	require.NoError(t, js.StartScheduler(t.Context()))

	select {
	case err := <-runErrCh:
		require.NoError(t, err)
	case <-time.After(2500 * time.Millisecond):
		require.FailNow(t, "timed out waiting for scheduled run")
	}
}

func TestJobScheduler_RescheduleJob_UsesLifecycleContextForShutdown(t *testing.T) {
	lifecycleCtx, cancelLifecycle := context.WithCancel(t.Context())
	js := newJobSchedulerForTestInternal(t, lifecycleCtx, nil)

	startedCh := make(chan struct{}, 1)
	stoppedCh := make(chan struct{}, 1)
	job := &testSchedulerJob{
		name:     "test-reschedule-lifecycle-shutdown",
		schedule: "*/1 * * * * *",
		run: func(ctx context.Context) {
			select {
			case startedCh <- struct{}{}:
			default:
			}
			<-ctx.Done()
			select {
			case stoppedCh <- struct{}{}:
			default:
			}
		},
	}

	require.NoError(t, js.RescheduleJob(lifecycleCtx, job))
	require.NoError(t, js.StartScheduler(t.Context()))

	select {
	case <-startedCh:
	case <-time.After(2500 * time.Millisecond):
		require.FailNow(t, "timed out waiting for scheduled run")
	}

	cancelLifecycle()

	select {
	case <-stoppedCh:
	case <-time.After(1500 * time.Millisecond):
		require.FailNow(t, "scheduled job did not observe lifecycle cancellation")
	}
}

func TestJobScheduler_AddJob_UpsertReplacesEntryWithoutLeaking(t *testing.T) {
	js := newJobSchedulerForTestInternal(t, t.Context(), nil)
	require.NoError(t, js.StartScheduler(t.Context()))

	job := &testSchedulerJob{name: "dyn-upsert", schedule: "*/5 * * * * *"}
	require.NoError(t, js.AddJob(t.Context(), job))
	require.True(t, js.HasJob(job.Name()))
	requireScheduledJobInternal(t, js, job.Name())
	firstState, err := js.coordinator.ScheduleState(t.Context(), job.Name())
	require.NoError(t, err)

	// Re-adding with a changed schedule (e.g. a new sync interval) must replace the
	// existing cron entry, not leak a second one that keeps firing forever.
	job.schedule = "*/10 * * * * *"
	require.NoError(t, js.AddJob(t.Context(), job))
	requireScheduledJobInternal(t, js, job.Name())
	nextState, err := js.coordinator.ScheduleState(t.Context(), job.Name())
	require.NoError(t, err)
	require.Greater(t, nextState.Generation, firstState.Generation)

	state, ok := js.GetJobRuntimeState(job.Name())
	require.True(t, ok)
	require.True(t, state.Scheduled)
	require.Equal(t, "*/10 * * * * *", state.Schedule)
	require.NotNil(t, state.NextRun)
}

func TestJobScheduler_AddJob_InvalidRescheduleKeepsExistingEntry(t *testing.T) {
	js := newJobSchedulerForTestInternal(t, t.Context(), nil)
	require.NoError(t, js.StartScheduler(t.Context()))

	job := &testSchedulerJob{name: "dyn-invalid-reschedule", schedule: "*/5 * * * * *"}
	require.NoError(t, js.AddJob(t.Context(), job))
	require.True(t, js.HasJob(job.Name()))
	requireScheduledJobInternal(t, js, job.Name())
	firstState, err := js.coordinator.ScheduleState(t.Context(), job.Name())
	require.NoError(t, err)

	job.schedule = "not a cron schedule"
	require.Error(t, js.AddJob(t.Context(), job))
	require.True(t, js.HasJob(job.Name()))
	nextState, err := js.coordinator.ScheduleState(t.Context(), job.Name())
	require.NoError(t, err)
	require.Equal(t, firstState.Generation, nextState.Generation)
	requireScheduledJobInternal(t, js, job.Name())

	state, ok := js.GetJobRuntimeState(job.Name())
	require.True(t, ok)
	require.True(t, state.Scheduled)
	require.Equal(t, "*/5 * * * * *", state.Schedule)
}

func TestJobScheduler_RemoveJob_RemovesEntryAndIsNoopWhenAbsent(t *testing.T) {
	js := newJobSchedulerForTestInternal(t, t.Context(), nil)
	require.NoError(t, js.StartScheduler(t.Context()))

	// Removing an unknown job must be a safe no-op (e.g. deleting a sync that never
	// had auto-sync enabled).
	js.RemoveJob(t.Context(), "never-registered")

	job := &testSchedulerJob{name: "dyn-remove", schedule: "*/5 * * * * *"}
	require.NoError(t, js.AddJob(t.Context(), job))
	require.True(t, js.HasJob(job.Name()))
	requireScheduledJobInternal(t, js, job.Name())

	js.RemoveJob(t.Context(), job.Name())
	require.False(t, js.HasJob(job.Name()))
	_, err := js.coordinator.ScheduleState(t.Context(), job.Name())
	require.ErrorIs(t, err, actor.ErrStateNotFound)
}

func TestJobScheduler_AddJob_GenericJobWithoutShouldRunIsScheduled(t *testing.T) {
	js := newJobSchedulerForTestInternal(t, t.Context(), nil)
	require.NoError(t, js.StartScheduler(t.Context()))

	job := &schedulertypes.GenericJob{
		JobName:    "generic-dyn",
		ScheduleFn: func(context.Context) string { return "@every 1m" },
		RunFn:      func(context.Context) (schedulertypes.Outcome, error) { return schedulertypes.Outcome{}, nil },
	}
	require.NoError(t, js.AddJob(t.Context(), job))
	require.True(t, js.HasJob(job.Name()))
	requireScheduledJobInternal(t, js, job.Name())
}

func TestJobScheduler_StopWaitsForCanceledJobToFinish(t *testing.T) {
	lifecycleCtx, cancelLifecycle := context.WithCancel(t.Context())
	jobStarted := make(chan struct{}, 1)
	cancellationObserved := make(chan struct{}, 1)
	releaseJob := make(chan struct{}, 1)
	jobFinished := make(chan struct{}, 1)
	var runOnce sync.Once

	js := newJobSchedulerForTestInternal(t, lifecycleCtx, nil)
	require.NoError(t, js.RegisterJob(&testSchedulerJob{
		name:     "test-shutdown-waits",
		schedule: "*/1 * * * * *",
		run: func(ctx context.Context) {
			runOnce.Do(func() {
				jobStarted <- struct{}{}
				<-ctx.Done()
				cancellationObserved <- struct{}{}
				<-releaseJob
				jobFinished <- struct{}{}
			})
		},
	}))
	require.NoError(t, js.StartScheduler(t.Context()))
	t.Cleanup(func() {
		cancelLifecycle()
		select {
		case releaseJob <- struct{}{}:
		default:
		}
	})

	select {
	case <-jobStarted:
	case <-time.After(2500 * time.Millisecond):
		require.FailNow(t, "timed out waiting for scheduled job to start")
	}

	cancelLifecycle()
	select {
	case <-cancellationObserved:
	case <-time.After(time.Second):
		require.FailNow(t, "scheduled job did not observe lifecycle cancellation")
	}

	stopDone := make(chan error, 1)
	go func() { stopDone <- stopJobSchedulerForTestInternal(t.Context(), js) }()

	select {
	case err := <-stopDone:
		require.FailNowf(t, "unexpected failure", "scheduler stopped before the running job finished: %v", err)
	case <-time.After(100 * time.Millisecond):
	}

	releaseJob <- struct{}{}
	select {
	case <-jobFinished:
	case <-time.After(time.Second):
		require.FailNow(t, "scheduled job did not finish after release")
	}
	select {
	case err := <-stopDone:
		require.NoError(t, err)
	case <-time.After(time.Second):
		require.FailNow(t, "scheduler did not stop after the running job finished")
	}
}

func requireScheduledJobInternal(t *testing.T, js *jobSchedulerInternal, id string) {
	t.Helper()
	state, found := js.GetJobRuntimeState(id)
	require.True(t, found)
	require.True(t, state.Scheduled)
	require.NotNil(t, state.NextRun)
}