0815cb35fb
Basic Lint Checks * basic
97 lines
1.8 KiB
Go
97 lines
1.8 KiB
Go
package job
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"log/slog"
|
|
|
|
"queryorchestration/internal/database"
|
|
"queryorchestration/internal/database/repository"
|
|
"queryorchestration/internal/validation"
|
|
|
|
"github.com/google/uuid"
|
|
)
|
|
|
|
type Update struct {
|
|
ID uuid.UUID
|
|
CanSync *bool
|
|
}
|
|
|
|
func (s *Service) Update(ctx context.Context, update *Update) error {
|
|
if update == nil {
|
|
return errors.New("Update required")
|
|
}
|
|
|
|
current, err := s.Get(ctx, update.ID)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
err = s.normalizeUpdate(ctx, current, update)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
err = s.submitUpdate(ctx, update)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
func (s *Service) normalizeUpdate(ctx context.Context, current *Job, update *Update) error {
|
|
err := s.normalizeCanSync(ctx, current, update)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
if validation.AreAllPointersNilExcept(update) {
|
|
return errors.New("no changes")
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
func (s *Service) submitUpdate(ctx context.Context, update *Update) error {
|
|
err := s.cfg.ExecuteDBTransaction(ctx, func(ctx context.Context, q *repository.Queries) error {
|
|
if update.CanSync != nil {
|
|
err := q.AddJobCanSync(ctx, &repository.AddJobCanSyncParams{
|
|
Jobid: database.MustToDBUUID(update.ID),
|
|
Cansync: *update.CanSync,
|
|
})
|
|
if err != nil {
|
|
return err
|
|
}
|
|
}
|
|
|
|
slog.Debug("job updated", "update", *update)
|
|
|
|
return nil
|
|
})
|
|
|
|
return err
|
|
}
|
|
|
|
func (s *Service) normalizeCanSync(ctx context.Context, current *Job, update *Update) error {
|
|
if update.CanSync == nil {
|
|
return nil
|
|
} else if current.CanSync == *update.CanSync {
|
|
update.CanSync = nil
|
|
return nil
|
|
}
|
|
|
|
if !*update.CanSync {
|
|
return nil
|
|
}
|
|
|
|
client, err := s.svc.Client.Get(ctx, current.ClientID)
|
|
if err != nil {
|
|
return err
|
|
} else if !client.CanSync {
|
|
return errors.New("client not allowing sync")
|
|
}
|
|
|
|
return nil
|
|
}
|