-
Notifications
You must be signed in to change notification settings - Fork 71
/
Copy pathchannel_event.go
206 lines (168 loc) · 7.05 KB
/
channel_event.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
package rapidpro
import (
"context"
"database/sql/driver"
"encoding/json"
"fmt"
"log"
"log/slog"
"os"
"strconv"
"time"
"github.com/lib/pq"
"github.com/nyaruka/courier"
"github.com/nyaruka/gocommon/urns"
"github.com/nyaruka/gocommon/uuids"
"github.com/nyaruka/null/v3"
)
// ChannelEventID is the type of our channel event ids
type ChannelEventID null.Int
const NilChannelEventID = ChannelEventID(0)
func (i *ChannelEventID) Scan(value any) error { return null.ScanInt(value, i) }
func (i ChannelEventID) Value() (driver.Value, error) { return null.IntValue(i) }
func (i *ChannelEventID) UnmarshalJSON(b []byte) error { return null.UnmarshalInt(b, i) }
func (i ChannelEventID) MarshalJSON() ([]byte, error) { return null.MarshalInt(i) }
// String satisfies the Stringer interface
func (i ChannelEventID) String() string {
if i != NilChannelEventID {
return strconv.FormatInt(int64(i), 10)
}
return "null"
}
// ChannelEvent represents an event on a channel.. that isn't a new message or status update
type ChannelEvent struct {
ID_ ChannelEventID ` db:"id"`
UUID_ courier.ChannelEventUUID `json:"uuid" db:"uuid"`
OrgID_ OrgID `json:"org_id" db:"org_id"`
ChannelUUID_ courier.ChannelUUID `json:"channel_uuid" db:"channel_uuid"`
ChannelID_ courier.ChannelID `json:"channel_id" db:"channel_id"`
URN_ urns.URN `json:"urn" db:"urn"`
EventType_ courier.ChannelEventType `json:"event_type" db:"event_type"`
OptInID_ null.Int `json:"optin_id" db:"optin_id"`
Extra_ null.Map[string] `json:"extra" db:"extra"`
OccurredOn_ time.Time `json:"occurred_on" db:"occurred_on"`
CreatedOn_ time.Time `json:"created_on" db:"created_on"`
LogUUIDs pq.StringArray `json:"log_uuids" db:"log_uuids"`
ContactID_ ContactID `json:"-" db:"contact_id"`
ContactURNID_ ContactURNID `json:"-" db:"contact_urn_id"`
// used to update contact
ContactName_ string `json:"contact_name"`
URNAuthTokens_ map[string]string `json:"auth_tokens"`
channel *Channel
}
// newChannelEvent creates a new channel event
func newChannelEvent(channel courier.Channel, eventType courier.ChannelEventType, urn urns.URN, clog *courier.ChannelLog) *ChannelEvent {
dbChannel := channel.(*Channel)
return &ChannelEvent{
UUID_: courier.ChannelEventUUID(uuids.NewV4()),
ChannelUUID_: dbChannel.UUID_,
OrgID_: dbChannel.OrgID_,
ChannelID_: dbChannel.ID_,
URN_: urn,
EventType_: eventType,
OccurredOn_: time.Now().In(time.UTC),
LogUUIDs: []string{string(clog.UUID)},
channel: dbChannel,
}
}
func (e *ChannelEvent) EventID() int64 { return int64(e.ID_) }
func (e *ChannelEvent) UUID() courier.ChannelEventUUID { return e.UUID_ }
func (e *ChannelEvent) ChannelID() courier.ChannelID { return e.ChannelID_ }
func (e *ChannelEvent) ChannelUUID() courier.ChannelUUID { return e.ChannelUUID_ }
func (e *ChannelEvent) EventType() courier.ChannelEventType { return e.EventType_ }
func (e *ChannelEvent) URN() urns.URN { return e.URN_ }
func (e *ChannelEvent) Extra() map[string]string { return e.Extra_ }
func (e *ChannelEvent) OccurredOn() time.Time { return e.OccurredOn_ }
func (e *ChannelEvent) CreatedOn() time.Time { return e.CreatedOn_ }
func (e *ChannelEvent) Channel() *Channel { return e.channel }
func (e *ChannelEvent) WithContactName(name string) courier.ChannelEvent {
e.ContactName_ = name
return e
}
func (e *ChannelEvent) WithURNAuthTokens(tokens map[string]string) courier.ChannelEvent {
e.URNAuthTokens_ = tokens
return e
}
func (e *ChannelEvent) WithExtra(extra map[string]string) courier.ChannelEvent {
if e.EventType_ == courier.EventTypeOptIn || e.EventType_ == courier.EventTypeOptOut {
optInID := extra["payload"]
if optInID != "" {
asInt, _ := strconv.Atoi(optInID)
e.OptInID_ = null.Int(asInt)
}
}
e.Extra_ = null.Map[string](extra)
return e
}
func (e *ChannelEvent) WithOccurredOn(time time.Time) courier.ChannelEvent {
e.OccurredOn_ = time
return e
}
// writeChannelEvent writes the passed in event to the database, queueing it to our spool in case the database is down
func writeChannelEvent(ctx context.Context, b *backend, event courier.ChannelEvent, clog *courier.ChannelLog) error {
dbEvent := event.(*ChannelEvent)
err := writeChannelEventToDB(ctx, b, dbEvent, clog)
// failed writing, write to our spool instead
if err != nil {
slog.Error("error writing channel event to db", "error", err, "channel_id", dbEvent.ChannelID, "event_type", dbEvent.EventType_)
}
if err != nil {
err = courier.WriteToSpool(b.config.SpoolDir, "events", dbEvent)
}
return err
}
const sqlInsertChannelEvent = `
INSERT INTO
channels_channelevent( org_id, uuid, channel_id, contact_id, contact_urn_id, event_type, optin_id, extra, occurred_on, created_on, status, log_uuids)
VALUES(:org_id, :uuid, :channel_id, :contact_id, :contact_urn_id, :event_type, :optin_id, :extra, :occurred_on, NOW(), 'P', :log_uuids)
RETURNING id, created_on`
// writeChannelEventToDB writes the passed in channel event to our db
func writeChannelEventToDB(ctx context.Context, b *backend, e *ChannelEvent, clog *courier.ChannelLog) error {
// grab the contact for this event
contact, err := contactForURN(ctx, b, e.OrgID_, e.channel, e.URN_, e.URNAuthTokens_, e.ContactName_, clog)
if err != nil {
return err
}
// set our contact and urn id
e.ContactID_ = contact.ID_
e.ContactURNID_ = contact.URNID_
rows, err := b.db.NamedQueryContext(ctx, sqlInsertChannelEvent, e)
if err != nil {
return err
}
defer rows.Close()
rows.Next()
if err = rows.Scan(&e.ID_, &e.CreatedOn_); err != nil {
return err
}
// queue it up for handling by RapidPro
rc := b.rp.Get()
defer rc.Close()
// if we had a problem queueing the event, log it
err = queueEventHandling(rc, contact, e)
if err != nil {
slog.Error("error queueing channel event", "error", err, "evt_id", e.ID_)
}
return nil
}
func (b *backend) flushChannelEventFile(filename string, contents []byte) error {
ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
defer cancel()
event := &ChannelEvent{}
err := json.Unmarshal(contents, event)
if err != nil {
log.Printf("ERROR unmarshalling spool file '%s', renaming: %s\n", filename, err)
os.Rename(filename, fmt.Sprintf("%s.error", filename))
return nil
}
// look up our channel
channel, err := b.GetChannel(ctx, courier.AnyChannelType, event.ChannelUUID_)
if err != nil {
return err
}
event.channel = channel.(*Channel)
// create log tho it won't be written
clog := courier.NewChannelLog(courier.ChannelLogTypeMsgReceive, channel, nil)
// try to flush to our database
return writeChannelEventToDB(ctx, b, event, clog)
}