Added: hashing background task

This commit is contained in:
Aleksandr Soloshenko 2023-12-13 23:12:57 +07:00
parent 571604eab2
commit 4547296cc0
4 changed files with 85 additions and 13 deletions

View File

@ -42,11 +42,11 @@ Content-Type: application/json
[
{
"id": "ZoK8jU8y74cZRnZH1xNIH",
"id": "-rnEaUz7KObDdokPrzKpM",
"state": "Delivered",
"recipients": [
{
"phoneNumber": "79504241345",
"phoneNumber": "{{phone}}",
"state": "Delivered"
}
]

View File

@ -11,6 +11,7 @@ import (
"github.com/capcom6/sms-gateway/internal/sms-gateway/models"
"github.com/capcom6/sms-gateway/internal/sms-gateway/repositories"
"github.com/capcom6/sms-gateway/internal/sms-gateway/services"
"github.com/capcom6/sms-gateway/internal/sms-gateway/tasks"
"go.uber.org/fx"
"go.uber.org/fx/fxevent"
"go.uber.org/zap"
@ -29,6 +30,7 @@ var Module = fx.Module(
repositories.Module,
models.Module,
db.Module,
tasks.Module,
)
func Run() {
@ -40,16 +42,5 @@ func Run() {
logOption.UseLogLevel(zapcore.DebugLevel)
return &logOption
}),
// fx.Invoke(
// func(lc fx.Lifecycle, logger *zap.Logger, messagesSvc *services.MessagesService) {
// lc.Append(
// fx.Hook{
// OnStart: func(ctx context.Context) error {
// return messagesSvc.HashProcessed()
// },
// },
// )
// },
// ),
).Run()
}

View File

@ -1 +1,45 @@
package tasks
import (
"context"
"time"
"github.com/capcom6/sms-gateway/internal/sms-gateway/services"
"go.uber.org/fx"
"go.uber.org/zap"
)
type HashingTaskParams struct {
fx.In
MessagesSvc *services.MessagesService
Logger *zap.Logger
}
type HashingTask struct {
MessagesSvc *services.MessagesService
Logger *zap.Logger
}
func (t *HashingTask) Run(ctx context.Context) {
t.Logger.Info("Starting hashing task...")
for {
select {
case <-ctx.Done():
t.Logger.Info("Stopping hashing task...")
return
case <-time.After(15 * time.Minute):
t.Logger.Debug("Hashing messages...")
if err := t.MessagesSvc.HashProcessed(); err != nil {
t.Logger.Error("Failed to hash processed messages", zap.Error(err))
}
}
}
}
func NewHashingTask(params HashingTaskParams) *HashingTask {
return &HashingTask{
MessagesSvc: params.MessagesSvc,
Logger: params.Logger,
}
}

View File

@ -0,0 +1,37 @@
package tasks
import (
"context"
"go.uber.org/fx"
"go.uber.org/zap"
)
var Module = fx.Module(
"tasks",
fx.Decorate(func(log *zap.Logger) *zap.Logger {
return log.Named("tasks")
}),
fx.Provide(
NewHashingTask,
fx.Private,
),
fx.Invoke(
func(lc fx.Lifecycle, task *HashingTask) error {
ctx, cancel := context.WithCancel(context.Background())
lc.Append(fx.Hook{
OnStart: func(_ context.Context) error {
go task.Run(ctx)
return nil
},
OnStop: func(_ context.Context) error {
cancel()
return nil
},
})
return nil
},
),
)