This repository has been archived by the owner on Jun 19, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5
/
app.go
191 lines (164 loc) · 4.38 KB
/
app.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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
"os"
"sync"
"time"
)
const (
topStoriesUrl = "https://hacker-news.firebaseio.com/v0/topstories.json"
itemUrl = "https://hacker-news.firebaseio.com/v0/item/%d.json"
runInterval = 15 * time.Minute // Interval at which we fetch the items
maxTopStories = 150 // Maximum top stories fetched per cycle
)
var (
config = loadConfig()
Logger = log.New(os.Stdout, " ", log.LstdFlags|log.Lshortfile)
)
func main() {
initDb() // Will panic on failure
setupHandlers()
// set up a goroutine that will periodically call run()
go func() {
run()
ticker := time.NewTicker(runInterval)
for {
select {
case <-ticker.C:
run() // TODO: Consider executing run() in a separate goroutine
}
}
}()
Logger.Printf("Listening on %s...\n", config.Addr)
Logger.Fatal(http.ListenAndServe(config.Addr, nil))
}
// Item represents a HN story.
type Item struct {
By string // unused
Id int
Kids []int64 // unused
Score int
Time int64 // unused
Title string
Type string // unused
Url string
}
// run fetches the top HN stories and sends notifications according to each user's score threshold.
// The channel fan-in approach is fully inspired by the example in http://blog.golang.org/pipelines.
func run() {
Logger.Println("Notifier started...")
t0 := time.Now()
db := newDatabase()
defer db.close()
// Single http.Client concurrently used by all goroutines
client := &http.Client{}
ids, err := getTopStories(client)
if err != nil {
Logger.Println(err)
return // Just wait till the next cycle.
}
if len(ids) > maxTopStories {
ids = ids[:maxTopStories]
}
// fetcher runs a goroutine to fetch the item. Once completed, the result
// will be inserted in the returned channel, and the channel closed.
fetchItem := func(id int) chan Item {
out := make(chan Item)
go func() {
item, err := getItem(client, id)
if err != nil {
Logger.Println(err)
} else if id == item.Id { // Guard against null responses, coerced into an empty Item
out <- item
}
close(out)
}()
return out
}
// Fetch items concurrently. Each channel will just hold one item.
cs := make([]chan Item, len(ids))
for i, id := range ids {
cs[i] = fetchItem(id)
}
for item := range merge(cs...) {
if users := db.findUsersForItem(item); len(users) > 0 {
emails := make([]string, len(users)) // Create a slice with all the recipients for this item.
for i, u := range users {
emails[i] = u.Email
}
// Send the email.
if err := sendItem(item.Id, item.Title, item.Url, emails); err != nil {
Logger.Println("Error sending mail: ", err)
continue
}
Logger.Printf("Item %d sent to users: %v\n", item.Id, emails)
// Update items set.
if err := db.updateSentItems(emails, item.Id); err != nil {
Logger.Println("Error: updateItems() - ", err)
}
}
}
Logger.Printf("Notifier finished - Total time: %s\n", time.Now().Sub(t0).String())
}
// getTopStories reads the top stories IDs from the API.
func getTopStories(client *http.Client) ([]int, error) {
req, err := http.NewRequest("GET", topStoriesUrl, nil)
if err != nil {
return nil, err
}
req.Close = true
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
res := struct {
Items []int
}{}
err = json.NewDecoder(resp.Body).Decode(&res.Items)
return res.Items, err
}
// getItem reads the HN story item from the API.
func getItem(client *http.Client, id int) (item Item, err error) {
var req *http.Request
req, err = http.NewRequest("GET", fmt.Sprintf(itemUrl, id), nil)
if err != nil {
return
}
req.Close = true
var resp *http.Response
resp, err = client.Do(req)
if err != nil {
return
}
defer resp.Body.Close()
err = json.NewDecoder(resp.Body).Decode(&item)
return item, err
}
// merge converts a list of channels to a single channel.
func merge(cs ...chan Item) <-chan Item {
var wg sync.WaitGroup
out := make(chan Item)
// Start an output goroutine for each input channel in cs. output
// copies values from c to out until c is closed, then calls wg.Done.
output := func(c <-chan Item) {
for n := range c {
out <- n
}
wg.Done()
}
wg.Add(len(cs))
for _, c := range cs {
go output(c)
}
// Start a goroutine to close out once all the output goroutines are
// done. This must start after the wg.Add call.
go func() {
wg.Wait()
close(out)
}()
return out
}