forked from 5calls/5calls
-
Notifications
You must be signed in to change notification settings - Fork 0
/
airtable.go
217 lines (192 loc) · 5 KB
/
airtable.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
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
package main
import (
"encoding/json"
"fmt"
"log"
"sync"
"sync/atomic"
"time"
"github.com/fabioberger/airtable-go"
)
const (
issuesTable = "Issues list"
contactsTable = "Contact"
)
var minRefreshInterval = time.Minute
// IssueLister is something that can produce a list of all issues.
type IssueLister interface {
AllIssues() ([]Issue, error)
}
func asJson(data interface{}) string {
b, err := json.Marshal(data)
if err != nil {
return fmt.Sprint(data)
}
return string(b)
}
// atIssueInfo is the record definition of an issue, minus its key
type atIssueInfo struct {
Name string `json:"Name"`
Action string `json:"Action requested"`
Script string `json:"Script"`
ContactLinks []string `json:"Contact"`
}
// atIssue is an airtable issue record.
type atIssue struct {
ID string `json:"id"`
atIssueInfo `json:"fields"`
Contacts []*atContact `json:"contacts"`
}
func (i *atIssue) String() string { return asJson(i) }
func (i *atIssue) toIssue(contacts []Contact) Issue {
return Issue{
ID: i.ID,
Name: i.Name,
Reason: i.Action,
Script: i.Script,
Contacts: contacts,
}
}
// atContactInfo is the record definition of a contact minus its key.
type atContactInfo struct {
Name string `json:"Name"`
Phone string `json:"Phone"`
PhotoURL string `json:"PhotoURL"`
Area string `json:"Area"`
Reason string `json:"Contact Reason"`
}
// atContact is an airtable contact record.
type atContact struct {
ID string `json:"id"`
atContactInfo `json:"fields"`
}
func (c *atContact) String() string { return asJson(c) }
func (c *atContact) toContact() Contact {
return Contact{
ID: c.ID,
Name: c.Name,
Phone: c.Phone,
PhotoURL: c.PhotoURL,
Reason: c.Reason,
Area: c.Area,
}
}
// AirtableConfig is the configuration for the airtable client.
type AirtableConfig struct {
BaseID string // ID of the airtable base
APIKey string // API key for HTTP calls
}
// AirtableClient provides a semantic API to the backend database.
type AirtableClient struct {
client *airtable.Client
}
func NewAirtableClient(config AirtableConfig) *AirtableClient {
c, _ := airtable.New(config.APIKey, config.BaseID)
return &AirtableClient{client: c}
}
// AllIssues returns a list of issues with standard contacts, if any, linked to them.
func (c *AirtableClient) AllIssues() ([]Issue, error) {
// load all contacts first
var cList []*atContact
err := c.client.ListRecords(contactsTable, &cList, airtable.ListParameters{
FilterByFormula: `NOT(NAME = "")`,
})
if err != nil {
return nil, fmt.Errorf("unable to load contacts, %v", err)
}
// index contacts by ID for easy joins
contactsMap := map[string]*atContact{}
for _, c := range cList {
contactsMap[c.ID] = c
}
// load all issues
var list []*atIssue
err = c.client.ListRecords(issuesTable, &list, airtable.ListParameters{
FilterByFormula: `NOT(OR(NAME = "", INACTIVE))`,
Sort: []airtable.SortParameter{
airtable.SortParameter{
Field: "Sort",
ShouldSortDesc: false,
},
},
})
if err != nil {
return nil, fmt.Errorf("unable to load issues, %v", err)
}
// normalize and join with contacts
var ret []Issue
for _, i := range list {
var contacts []Contact
for _, id := range i.ContactLinks {
contact := contactsMap[id]
if contact == nil {
log.Println("[WARN] unable to find contact with ID", id)
continue
}
contacts = append(contacts, contact.toContact())
}
ret = append(ret, i.toIssue(contacts))
}
return ret, nil
}
// issueCache stores an in-memory copy of the issue list with automatic refresh.
type issueCache struct {
delegate IssueLister
stop chan struct{} // close-only
force chan struct{}
val atomic.Value // of []Issue
stopOnce sync.Once
}
// NewIssueCache returns an issue cache after ensuring that the issue list is loaded.
func NewIssueCache(delegate IssueLister, refreshInterval time.Duration) (IssueLister, error) {
issues, err := delegate.AllIssues()
if err != nil {
return nil, err
}
if refreshInterval <= minRefreshInterval {
refreshInterval = minRefreshInterval
}
ic := &issueCache{
delegate: delegate,
stop: make(chan struct{}),
force: make(chan struct{}, 1),
}
ic.val.Store(issues)
go ic.refresh(refreshInterval)
return ic, nil
}
// Reload immediately reloads the database in the background.
func (ic *issueCache) Reload() {
ic.force <- struct{}{}
}
func (ic *issueCache) Close() error {
ic.stopOnce.Do(func() { close(ic.stop) })
return nil
}
func (ic *issueCache) refresh(interval time.Duration) {
reload := func() {
issues, err := ic.delegate.AllIssues()
if err != nil {
log.Println("Error loading issues,", err)
}
log.Println(len(issues), "issues loaded")
ic.val.Store(issues)
}
t := time.NewTimer(interval)
defer t.Stop()
for {
select {
case <-t.C:
t.Reset(interval)
reload()
case <-ic.force:
t.Reset(interval)
reload()
case <-ic.stop:
return
}
}
}
func (ic *issueCache) AllIssues() ([]Issue, error) {
return ic.val.Load().([]Issue), nil
}