-
Notifications
You must be signed in to change notification settings - Fork 0
/
subscription.go
86 lines (72 loc) · 2.01 KB
/
subscription.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
package govdata
import (
"context"
"log"
"time"
)
func listen(resourceID string, last time.Time, revisions chan<- Revision) {
for {
resource, err := DefaultClient.ResourceShow(context.Background(), resourceID)
if err != nil {
log.Println("ResourceShow:", err)
<-time.After(30 * time.Second)
continue
}
for i := len(resource.Revisions) - 1; i >= 0; i-- {
if resource.Revisions[i].ResourceCreated.After(last) {
revisions <- resource.Revisions[i]
}
}
last = time.Now()
<-time.After(10 * time.Minute)
}
}
// Subscribe starts listening revisions and dispatch them into a channel.
func Subscribe(resourceID string, last time.Time) <-chan Revision {
revisions := make(chan Revision)
go listen(resourceID, last, revisions)
return revisions
}
func listenPackage(packageID string, lastModified map[string]time.Time, events chan<- Resource) {
for {
pkg, err := DefaultClient.PackageShow(context.Background(), packageID)
if err != nil {
log.Println("PackageShow:", err)
<-time.After(30 * time.Second)
continue
}
for i := 0; i < len(pkg.Resources); i++ {
rid := pkg.Resources[i].ID
modified, ok := lastModified[rid]
if ok && !pkg.Resources[i].LastModified.After(modified) {
continue
}
resource, err := DefaultClient.ResourceShow(context.Background(), rid)
if err != nil {
log.Println("ResourceShow:", err)
<-time.After(30 * time.Second)
i--
continue
}
// Notify about new resource.
if !ok {
events <- *resource
lastModified[rid] = resource.LastModified.Time
continue
}
// Resource may not contain revisions.
if len(resource.Revisions) == 0 {
continue
}
// Notify about latest changes in the resource.
events <- *resource
lastModified[rid] = pkg.Resources[i].LastModified.Time
}
<-time.After(60 * time.Minute)
}
}
func SubscribePackage(packageID string, lastModified map[string]time.Time) <-chan Resource {
events := make(chan Resource)
go listenPackage(packageID, lastModified, events)
return events
}