-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathoutbox.go
70 lines (57 loc) · 1.4 KB
/
outbox.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
package outbox
import (
"context"
"log"
"time"
)
type Outbox interface {
Listen(ctx context.Context)
}
type outbox struct {
storage Storage
producer Producer
}
func NewOutbox(storage Storage, producer Producer) Outbox {
return &outbox{storage, producer}
}
func (o *outbox) Listen(ctx context.Context) {
go o.deleteCheckedItems(ctx)
itemsFound := make(chan []Model)
deliveredChan := make(chan string)
go func(itemsFound chan []Model, deliveredChan chan string) {
for {
select {
case idempotencyID := <-deliveredChan:
o.updateItemToChecked(ctx, idempotencyID)
case i := <-itemsFound:
if err := o.producer.Produce(i, deliveredChan); err != nil {
log.Printf("error to produce message %v", err)
continue
}
}
}
}(itemsFound, deliveredChan)
for {
items, err := o.storage.ListAllItems(ctx)
if err != nil {
log.Printf("outbox: error deleting checked items %v", err)
}
itemsFound <- items
time.Sleep(time.Second * 2)
}
}
func (o *outbox) deleteCheckedItems(ctx context.Context) {
for {
err := o.storage.DeleteCheckedItems(ctx)
if err != nil {
log.Printf("outbox: error deleting checked items %v", err)
}
time.Sleep(time.Second * 1)
}
}
func (o *outbox) updateItemToChecked(ctx context.Context, idempotencyID string) {
err := o.storage.UpdateItemToCheck(ctx, idempotencyID)
if err != nil {
log.Printf("outbox: error update items %v", err)
}
}