-
Notifications
You must be signed in to change notification settings - Fork 0
/
worker.go
126 lines (93 loc) · 2.38 KB
/
worker.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
package worker
import (
"context"
"sync"
"github.com/comunidade-shallom/peristera/pkg/config"
"github.com/comunidade-shallom/peristera/pkg/cron"
"github.com/comunidade-shallom/peristera/pkg/database"
"github.com/comunidade-shallom/peristera/pkg/telegram/commands"
"github.com/comunidade-shallom/peristera/pkg/ytube"
"github.com/rs/zerolog"
"gopkg.in/telebot.v3"
)
type Worker struct {
bot *telebot.Bot
jobs *cron.Jobs
db database.Database
youtube ytube.Service
cfg config.AppConfig
stop chan error
}
func (w *Worker) Start(parentCtx context.Context) {
ctx, cancel := context.WithCancel(parentCtx)
defer cancel()
w.stop = make(chan error, 1)
defer close(w.stop)
go func() {
for {
select {
case <-ctx.Done():
zerolog.Ctx(ctx).Warn().Err(ctx.Err()).Msg("Context done")
cancel()
return
case err := <-w.stop:
if err != nil {
zerolog.Ctx(ctx).Warn().Err(err).Msg("Stop signal")
cancel()
}
}
}
}()
var wg sync.WaitGroup
wg.Add(3) //nolint:gomnd
go w.JobsWorker(ctx, &wg)
go w.DatabaseWorker(ctx, &wg)
go w.TelegramWorker(ctx, &wg)
wg.Wait()
if err := w.db.DB().Close(); err != nil {
zerolog.Ctx(ctx).Warn().Err(err).Msg("Fail to close database")
}
zerolog.Ctx(ctx).Warn().Msg("Worker stopped")
}
func (w *Worker) JobsWorker(ctx context.Context, wg *sync.WaitGroup) {
defer wg.Done()
if w.jobs == nil {
zerolog.Ctx(ctx).Warn().Msg("Cron jobs are disabled")
return
}
err := w.jobs.Start(ctx)
switch err { //nolint:errorlint
case context.Canceled:
case nil:
return
default:
zerolog.Ctx(ctx).Warn().Err(err).Msg("Fail start jobs")
w.stop <- err
return
}
}
func (w *Worker) DatabaseWorker(ctx context.Context, wg *sync.WaitGroup) {
defer wg.Done()
zerolog.Ctx(ctx).Info().Msg("Starting database worker...")
w.db.Worker(ctx)
zerolog.Ctx(ctx).Warn().Msg("Database worker stopped")
}
func (w *Worker) TelegramWorker(ctx context.Context, wg *sync.WaitGroup) {
defer wg.Done()
logger := zerolog.Ctx(ctx)
go func() {
logger.Info().Msg("Starting telegram bot...")
cmds := commands.New(w.cfg, w.youtube, w.db)
err := cmds.Setup(ctx, w.bot)
if err != nil {
logger.Warn().Err(err).Msg("Fail start telegram bot")
w.stop <- err
return
}
w.bot.Start()
}()
<-ctx.Done()
logger.Warn().Err(ctx.Err()).Msg("Stopping telegram bot...")
w.bot.Stop()
logger.Warn().Msg("Telegram stopped")
}