| 1 | package equipo |
| 2 | |
| 3 | import ( |
| 4 | "amadan.net/oficina/equipo/internal/equipo/notifications" |
| 5 | "context" |
| 6 | "database/sql" |
| 7 | "net/http" |
| 8 | "time" |
| 9 | |
| 10 | "amadan.net/oficina/equipo/internal/equipo/conversation" |
| 11 | "amadan.net/oficina/equipo/internal/equipo/kernel" |
| 12 | "amadan.net/oficina/equipo/internal/equipo/team" |
| 13 | "amadan.net/rastrillo/rastrillo/live" |
| 14 | "gorm.io/gorm" |
| 15 | ) |
| 16 | |
| 17 | type JobNotifier interface { |
| 18 | Notify(...string) |
| 19 | NotifyAt(time.Time, ...string) |
| 20 | } |
| 21 | |
| 22 | // SetJobNotifier is a startup injection, before requests or runner work start. |
| 23 | func (s *Store) SetJobNotifier(n JobNotifier) { s.notifier = n } |
| 24 | |
| 25 | func jobTopic(teamID string, id JobID) string { return kernel.JobTopic(teamID, int64(id)) } |
| 26 | |
| 27 | func CloseLive(h http.Handler) { |
| 28 | if a, ok := h.(*application); ok && a.live != nil { |
| 29 | a.live.Close() |
| 30 | } |
| 31 | } |
| 32 | |
| 33 | type liveState struct{ deadlines map[string][]time.Time } |
| 34 | |
| 35 | func (s *Store) observeWrite(ctx context.Context, tx *sql.Tx) (team.CommitObserver, error) { |
| 36 | return notifications.ObserveWrite(ctx, tx, s.notifier) |
| 37 | } |
| 38 | func (s *Store) scheduleState(st liveState) { |
| 39 | for topic, dates := range st.deadlines { |
| 40 | for _, at := range dates { |
| 41 | if at.After(time.Now()) { |
| 42 | s.notifier.NotifyAt(at, topic) |
| 43 | } |
| 44 | } |
| 45 | } |
| 46 | } |
| 47 | func (s *Store) restoreLiveSchedules(ctx context.Context) error { |
| 48 | return s.db.G.WithContext(ctx).Transaction(func(g *gorm.DB) error { |
| 49 | tx, err := executionTx(g) |
| 50 | if err != nil { |
| 51 | return err |
| 52 | } |
| 53 | var teamID string |
| 54 | if err := tx.QueryRowContext(ctx, "SELECT id FROM teams ORDER BY id LIMIT 1").Scan(&teamID); err == sql.ErrNoRows { |
| 55 | return nil |
| 56 | } else if err != nil { |
| 57 | return err |
| 58 | } |
| 59 | st := liveState{deadlines: map[string][]time.Time{}} |
| 60 | if err := conversation.ConversationDeadlines(ctx, tx, st.deadlines); err != nil { |
| 61 | return err |
| 62 | } |
| 63 | if err := conversation.JobDeadlines(ctx, tx, st.deadlines, teamID, nil); err != nil { |
| 64 | return err |
| 65 | } |
| 66 | s.scheduleState(st) |
| 67 | return nil |
| 68 | }) |
| 69 | } |
| 70 | func readTime(v any) time.Time { return kernel.ReadTime(v) } |
| 71 | func weekStart(now time.Time) time.Time { return kernel.WeekStart(now) } |
| 72 | |
| 73 | var _ JobNotifier = (*live.Hub)(nil) |
| 74 | |
| 75 | func installLiveChanges(ctx context.Context, tx *sql.Tx) error { |
| 76 | return conversation.InstallJobChanges(ctx, tx) |
| 77 | } |
| 78 | |