Log messages are lower-case event names with their details as key/value
attributes ("error" for errors), in place of formatted strings.
Loggable package take a WithLogger option as part of their "New*" call,
defaulting to slog.Default(). Each tags its lines with its `component`.
Some debug loggers print directly rather than using slog when in
terminal logging mode.
57 lines
1.4 KiB
Go
57 lines
1.4 KiB
Go
package fetcher
|
|
|
|
import (
|
|
"context"
|
|
"log/slog"
|
|
"time"
|
|
|
|
"git.avsdev.uk/Go/job-search/internal/config"
|
|
"git.avsdev.uk/Go/job-search/internal/util"
|
|
)
|
|
|
|
// sleepDuration is how long the sleeper's simulated work takes.
|
|
const sleepDuration = 60 * time.Second
|
|
|
|
// runSleeper runs the sleeper test source until ctx is cancelled: every
|
|
// configured interval it simulates work by sleeping for sleepDuration.
|
|
func runSleeper(
|
|
ctx context.Context, logger *slog.Logger, conf *config.JobSearchConfig, since time.Time,
|
|
) error {
|
|
blockShutdown := conf.Sources.Sleeper.BlockShutdown
|
|
w := util.Worker{
|
|
Logger: logger,
|
|
Name: "Sleeper",
|
|
Interval: conf.Sources.Sleeper.Interval,
|
|
Task: func(taskCtx context.Context, since time.Time) error {
|
|
if blockShutdown {
|
|
return sleep(taskCtx, true, sleepDuration)
|
|
} else {
|
|
return sleep(ctx, false, sleepDuration)
|
|
}
|
|
},
|
|
}
|
|
return w.Run(ctx, since)
|
|
}
|
|
|
|
// sleep simulates work taking duration, returning early with ctx.Err() if ctx
|
|
// is cancelled. With blockShutdown, the work itself ignores ctx (as a
|
|
// non-cooperative call would) and only the wait for it stops.
|
|
func sleep(
|
|
ctx context.Context, blockShutdown bool, duration time.Duration,
|
|
) error {
|
|
return util.AwaitTaskE(ctx, func() error {
|
|
if blockShutdown {
|
|
time.Sleep(duration)
|
|
return nil
|
|
}
|
|
timer := time.NewTimer(duration)
|
|
defer timer.Stop()
|
|
select {
|
|
case <-timer.C:
|
|
return nil
|
|
case <-ctx.Done():
|
|
return ctx.Err()
|
|
}
|
|
})
|
|
}
|