carlos / platform Public

Clone
git clone https://amadan.net/carlos/platform

Plain git — no account needed to clone.

Download

Download this file

1package schedule
2
3import (
4 "context"
5 "errors"
6 "github.com/carlosframework/platform/internal/hostwrite"
7 "github.com/carlosframework/platform/internal/registry"
8 "os"
9)
10
11type timerMutator interface {
12 MutateTimer(context.Context, registry.Timer, string, bool) (*registry.Timer, error)
13}
14
15func mutateSelectedTimer(ctx context.Context, t registry.Timer, expected string, remove bool) (*registry.Timer, bool, error) {
16 selected, ok := ctx.Value(timerWorkKey{}).(timerWork)
17 if !ok || selected.work == nil {
18 return nil, false, nil
19 }
20 m, ok := selected.work.(timerMutator)
21 if !ok {
22 return nil, false, nil
23 }
24 row, err := m.MutateTimer(ctx, t, expected, remove)
25 return row, true, err
26}
27
28func deleteSelectedTimer(ctx context.Context, reg *registry.Registry, t registry.Timer) error {
29 if _, handled, err := mutateSelectedTimer(ctx, t, t.Registration, true); handled {
30 return err
31 }
32 return withTimerWork(ctx, func() error { return reg.DeleteTimerRegistration(t.Host, t.Name, t.Registration) })
33}
34
35type ClaimTimers struct {
36 TimerStore
37 Writes hostwrite.Config
38 Context context.Context
39}
40
41func (s ClaimTimers) UpsertTimer(t registry.Timer) error {
42 work, err := s.Writes.Select(s.Context, t.Host, "timers")
43 if err != nil {
44 return err
45 }
46 return (SelectedTimers{Store: s.TimerStore, Work: work, Context: s.Context, Host: t.Host}).UpsertTimer(t)
47}
48func (s ClaimTimers) DeleteTimer(host, name string) error {
49 work, err := s.Writes.Select(s.Context, host, "timers")
50 if err != nil {
51 return err
52 }
53 return (SelectedTimers{Store: s.TimerStore, Work: work, Context: s.Context, Host: host}).DeleteTimer(host, name)
54}
55
56func (s SelectedTimers) mutate(t registry.Timer, remove bool) (bool, error) {
57 m, ok := s.Work.(timerMutator)
58 if !ok {
59 return false, nil
60 }
61 if s.Store == nil || s.Context == nil || t.Host != s.Host {
62 return true, hostwrite.ErrUnavailable
63 }
64 var old *registry.Timer
65 err := s.Work.With(s.Context, hostwrite.Identity{}, func() error {
66 var err error
67 old, err = s.Store.GetTimer(t.Host, t.Name)
68 if errors.Is(err, os.ErrNotExist) {
69 return nil
70 }
71 return err
72 })
73 if err != nil {
74 return true, err
75 }
76 expected := ""
77 if old != nil {
78 expected = old.Registration
79 if old.Kind != t.Kind && !remove {
80 return true, registry.ErrTimerKind
81 }
82 }
83 if remove {
84 if old == nil {
85 return true, nil
86 }
87 t = *old
88 }
89 _, err = m.MutateTimer(s.Context, t, expected, remove)
90 return true, err
91}
92
93func hasTimerMutator(ctx context.Context) bool {
94 s, ok := ctx.Value(timerWorkKey{}).(timerWork)
95 if !ok {
96 return false
97 }
98 _, ok = s.work.(timerMutator)
99 return ok
100}
101