Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

pkg/utils: add NewSleeperTaskCtx(WorkerCtx) #868

Merged
merged 1 commit into from
Oct 23, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 27 additions & 6 deletions pkg/utils/sleeper_task.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package utils

import (
"context"
"fmt"
"time"

Expand All @@ -13,12 +14,18 @@ type Worker interface {
Name() string
}

// WorkerCtx is like Worker but includes [context.Context].
type WorkerCtx interface {
Work(ctx context.Context)
Name() string
}

// SleeperTask represents a task that waits in the background to process some work.
type SleeperTask struct {
services.StateMachine
worker Worker
worker WorkerCtx
chQueue chan struct{}
chStop chan struct{}
chStop services.StopChan
chDone chan struct{}
chWorkDone chan struct{}
}
Expand All @@ -31,16 +38,27 @@ type SleeperTask struct {
// immediately after it is finished. For this reason you should take care to
// make sure that Worker is idempotent.
// WakeUp does not block.
func NewSleeperTask(worker Worker) *SleeperTask {
func NewSleeperTask(w Worker) *SleeperTask {
return NewSleeperTaskCtx(&worker{w})
}

type worker struct {
Worker
}

func (w *worker) Work(ctx context.Context) { w.Worker.Work() }

// NewSleeperTaskCtx is like NewSleeperTask but accepts a WorkerCtx with a [context.Context].
func NewSleeperTaskCtx(w WorkerCtx) *SleeperTask {
s := &SleeperTask{
worker: worker,
worker: w,
chQueue: make(chan struct{}, 1),
chStop: make(chan struct{}),
chDone: make(chan struct{}),
chWorkDone: make(chan struct{}, 10),
}

_ = s.StartOnce("SleeperTask-"+worker.Name(), func() error {
_ = s.StartOnce("SleeperTask-"+w.Name(), func() error {
go s.workerLoop()
return nil
})
Expand Down Expand Up @@ -98,10 +116,13 @@ func (s *SleeperTask) WorkDone() <-chan struct{} {
func (s *SleeperTask) workerLoop() {
defer close(s.chDone)

ctx, cancel := s.chStop.NewCtx()
defer cancel()

for {
select {
case <-s.chQueue:
s.worker.Work()
s.worker.Work(ctx)
s.workDone()
case <-s.chStop:
return
Expand Down
Loading