You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

worker.go 1.4 kB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. package exec
  2. import (
  3. "context"
  4. "sync"
  5. "github.com/samber/lo"
  6. "gitlink.org.cn/cloudream/common/pkgs/future"
  7. "gitlink.org.cn/cloudream/common/utils/lo2"
  8. )
  9. type finding struct {
  10. PlanID PlanID
  11. Callback *future.SetValueFuture[*Executor]
  12. }
  13. type Worker struct {
  14. lock sync.Mutex
  15. executors map[PlanID]*Executor
  16. findings []*finding
  17. }
  18. func NewWorker() Worker {
  19. return Worker{
  20. executors: make(map[PlanID]*Executor),
  21. }
  22. }
  23. func (s *Worker) Add(exe *Executor) {
  24. s.lock.Lock()
  25. defer s.lock.Unlock()
  26. s.executors[exe.Plan().ID] = exe
  27. s.findings = lo.Reject(s.findings, func(f *finding, idx int) bool {
  28. if f.PlanID != exe.Plan().ID {
  29. return false
  30. }
  31. f.Callback.SetValue(exe)
  32. return true
  33. })
  34. }
  35. func (s *Worker) Remove(sw *Executor) {
  36. s.lock.Lock()
  37. defer s.lock.Unlock()
  38. delete(s.executors, sw.Plan().ID)
  39. }
  40. func (s *Worker) FindByID(id PlanID) *Executor {
  41. s.lock.Lock()
  42. defer s.lock.Unlock()
  43. return s.executors[id]
  44. }
  45. func (s *Worker) FindByIDContexted(ctx context.Context, id PlanID) *Executor {
  46. s.lock.Lock()
  47. sw := s.executors[id]
  48. if sw != nil {
  49. s.lock.Unlock()
  50. return sw
  51. }
  52. cb := future.NewSetValue[*Executor]()
  53. f := &finding{
  54. PlanID: id,
  55. Callback: cb,
  56. }
  57. s.findings = append(s.findings, f)
  58. s.lock.Unlock()
  59. sw, _ = cb.WaitValue(ctx)
  60. s.lock.Lock()
  61. defer s.lock.Unlock()
  62. s.findings = lo2.Remove(s.findings, f)
  63. return sw
  64. }