-
Notifications
You must be signed in to change notification settings - Fork 0
/
processing.go
77 lines (69 loc) · 1.81 KB
/
processing.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
package processing
import (
"fmt"
"github.com/alekseyklimenko/go-proj-bootstrap/config"
"github.com/alekseyklimenko/go-proj-bootstrap/logger"
"github.com/alekseyklimenko/go-proj-bootstrap/models"
"github.com/alekseyklimenko/go-proj-bootstrap/services"
"gorm.io/gorm"
"sync"
)
type Service struct {
db *gorm.DB
mu sync.Mutex
processItemsCount uint
maxItemsProcess uint
items []models.Some
}
var startChan = make(chan models.Some)
func NewService(db *gorm.DB, conf *config.Config) *Service {
service := &Service{
db: db,
processItemsCount: 0,
maxItemsProcess: 2, //conf.Process.MaxItemsProcess,
}
service.items = make([]models.Some, 0, service.maxItemsProcess)
go service.startChanListener()
go service.initProcessing()
return service
}
func (s *Service) QueueItem(some models.Some) {
startChan <- some
}
func (s *Service) Shutdown() {
close(startChan)
for _, some := range s.items {
services.Some.FreeItem(some.ID)
}
}
func (s *Service) startChanListener() {
for {
item, ok := <-startChan
if !ok {
logger.NewEntry().Info("Closing Init processing chanel")
break
}
logger.NewEntry().WithField("id", item.ID).Info("Start processing")
err := services.Some.LockItem(item.ID)
if err != nil {
logger.NewEntry().WithField("id", item.ID).Error("Skip item, got error:")
logger.NewEntry().Error(err.Error())
}
s.items = append(s.items, item)
// some logic
}
}
func (s *Service) initProcessing() {
logger.NewEntry().Info(fmt.Sprintf("Getting to process %d items", s.maxItemsProcess))
items := services.Some.GetSomeToProcess(s.maxItemsProcess)
for _, item := range *items {
s.mu.Lock()
if s.processItemsCount == s.maxItemsProcess {
s.mu.Unlock()
break
}
s.processItemsCount++
s.mu.Unlock()
startChan <- item
}
}