package worker import ( "context" "git.sr.ht/~gabrielgio/midr/db" "git.sr.ht/~gabrielgio/midr/yt" work "git.sr.ht/~sircmpwn/dowork" ) const ( statusNotQueued = "NOTQUEUED" statusQueued = "QUEUED" statusStarted = "RUNNING" commandStart = "START" commandEnqueue = "ENQUEUE" commandDequeue = "DEQUEUE" ) type command struct { action string index uint } type Worker struct { jobs map[uint]string c chan command } type Job struct { Id uint Status string } func NewWorkder() Worker { return Worker{ c: make(chan command), jobs: make(map[uint]string), } } func (w *Worker) CanEnqueue(index uint) bool { v, found := w.jobs[index] return !found || v == statusNotQueued } func (w *Worker) RemoveJob(id uint) { delete(w.jobs, id) } func (w *Worker) SpawnWorker(entry *db.Entry) { if !w.CanEnqueue(entry.ID) { return } w.c <- command{action: commandEnqueue, index: entry.ID} task := work.NewTask(func(ctx context.Context) error { w.c <- command{action: commandStart, index: entry.ID} yt.RunYtDlpProcess(entry) return nil }).After(func(ctx context.Context, task *work.Task) { w.c <- command{action: commandDequeue, index: entry.ID} }) work.Enqueue(task) } func (w *Worker) startReader() { for { command := <-w.c if command.action == commandEnqueue { w.jobs[command.index] = statusQueued } else if command.action == commandStart { w.jobs[command.index] = statusStarted } else if command.action == commandDequeue { w.jobs[command.index] = statusNotQueued } else { panic(1) } } } func (w *Worker) StartReader() { go w.startReader() } func (w *Worker) GetJobs() []Job { jobs := make([]Job, len(w.jobs)) count := 0 for k, v := range w.jobs { jobs[count] = Job{Id: k, Status: v} count++ } return jobs }