Skip to content

Commit

Permalink
Merge pull request #565 from nyaruka/simpler_uuids
Browse files Browse the repository at this point in the history
Switch to gocommon/uuids for UUID types
  • Loading branch information
rowanseymour authored Feb 6, 2023
2 parents 66f256d + 55e0e76 commit a526396
Show file tree
Hide file tree
Showing 21 changed files with 58 additions and 106 deletions.
4 changes: 2 additions & 2 deletions backends/rapidpro/backend.go
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,7 @@ RETURNING

// DeleteMsgWithExternalID delete a message we receive an event that it should be deleted
func (b *backend) DeleteMsgWithExternalID(ctx context.Context, channel courier.Channel, externalID string) error {
_, err := b.db.ExecContext(ctx, updateMsgVisibilityDeletedBySender, string(channel.UUID().String()), externalID)
_, err := b.db.ExecContext(ctx, updateMsgVisibilityDeletedBySender, string(channel.UUID()), externalID)
if err != nil {
return err
}
Expand Down Expand Up @@ -619,7 +619,7 @@ func (b *backend) Status() string {
tps := parts[1]

// try to look up our channel
channelUUID, _ := courier.NewChannelUUID(uuid)
channelUUID := courier.ChannelUUID(uuid)
channel, err := getChannel(context.Background(), b.db, courier.AnyChannelType, channelUUID)
channelType := "!!"
if err == nil {
Expand Down
37 changes: 18 additions & 19 deletions backends/rapidpro/backend_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -94,8 +94,7 @@ func (ts *BackendTestSuite) TearDownSuite() {
}

func (ts *BackendTestSuite) getChannel(cType string, cUUID string) *DBChannel {
channelUUID, err := courier.NewChannelUUID(cUUID)
ts.Require().NoError(err, "error building channel uuid")
channelUUID := courier.ChannelUUID(cUUID)

channel, err := ts.b.GetChannel(context.Background(), courier.ChannelType(cType), channelUUID)
ts.Require().NoError(err, "error getting channel")
Expand Down Expand Up @@ -137,18 +136,18 @@ func (ts *BackendTestSuite) TestMsgUnmarshal() {
msg := DBMsg{}
err := json.Unmarshal([]byte(msgJSON), &msg)
ts.NoError(err)
ts.Equal(msg.ChannelUUID_.String(), "f3ad3eb6-d00d-4dc3-92e9-9f34f32940ba")
ts.Equal(msg.ChannelID_, courier.NewChannelID(11))
ts.Equal(courier.ChannelUUID("f3ad3eb6-d00d-4dc3-92e9-9f34f32940ba"), msg.ChannelUUID_)
ts.Equal(courier.NewChannelID(11), msg.ChannelID_)
ts.Equal([]string{"https://foo.bar/image.jpg"}, msg.Attachments())
ts.Equal(msg.URNAuth_, "5ApPVsFDcFt:RZdK9ne7LgfvBYdtCYg7tv99hC9P2")
ts.Equal(msg.ExternalID(), "")
ts.Equal("5ApPVsFDcFt:RZdK9ne7LgfvBYdtCYg7tv99hC9P2", msg.URNAuth_)
ts.Equal("", msg.ExternalID())
ts.Equal([]string{"Yes", "No"}, msg.QuickReplies())
ts.Equal("event", msg.Topic())
ts.Equal("external-id", msg.ResponseToExternalID())
ts.True(msg.HighPriority())
ts.True(msg.IsResend())
flow_ref := courier.FlowReference{UUID: "9de3663f-c5c5-4c92-9f45-ecbc09abcc85", Name: "Favorites"}
ts.Equal(msg.Flow(), &flow_ref)
ts.Equal(&flow_ref, msg.Flow())
ts.Equal("Favorites", msg.FlowName())
ts.Equal("9de3663f-c5c5-4c92-9f45-ecbc09abcc85", msg.FlowUUID())

Expand Down Expand Up @@ -282,7 +281,7 @@ func (ts *BackendTestSuite) TestContact() {
ts.NotNil(contact)

ts.Equal(null.String(""), contact.Name_)
ts.Equal("a984069d-0008-4d8c-a772-b14a8a6acccc", contact.UUID_.String())
ts.Equal(courier.ContactUUID("a984069d-0008-4d8c-a772-b14a8a6acccc"), contact.UUID_)

urn, _ = urns.NewTelURNForCountry("12065551519", "US")

Expand Down Expand Up @@ -771,22 +770,22 @@ func (ts *BackendTestSuite) TestDupes() {
ts.NoError(err)

// grab our UUID
uuid1 := msg.UUID().String()
uuid1 := msg.UUID()

// trying again should lead to same UUID
msg = ts.b.NewIncomingMsg(knChannel, urn, "ping", clog).(*DBMsg)
err = ts.b.WriteMsg(ctx, msg, clog)
ts.NoError(err)

ts.Equal(uuid1, msg.UUID().String())
ts.Equal(uuid1, msg.UUID())

// different message should change that
msg = ts.b.NewIncomingMsg(knChannel, urn, "test", clog).(*DBMsg)
err = ts.b.WriteMsg(ctx, msg, clog)
ts.NoError(err)

ts.NotEqual(uuid1, msg.UUID().String())
uuid2 := msg.UUID().String()
ts.NotEqual(uuid1, msg.UUID())
uuid2 := msg.UUID()

// an outgoing message should clear things
dbMsg := readMsgFromDB(ts.b, 10000)
Expand All @@ -808,7 +807,7 @@ func (ts *BackendTestSuite) TestDupes() {
err = ts.b.WriteMsg(ctx, msg, clog)
ts.NoError(err)

ts.NotEqual(uuid2, msg.UUID().String())
ts.NotEqual(uuid2, msg.UUID())
}

func (ts *BackendTestSuite) TestExternalIDDupes() {
Expand Down Expand Up @@ -841,7 +840,7 @@ func (ts *BackendTestSuite) TestStatus() {
defer r.Close()

dbMsg := readMsgFromDB(ts.b, 10000)
dbMsg.ChannelUUID_, _ = courier.NewChannelUUID("dbc126ed-66bc-4e28-b67b-81dc3327c95d")
dbMsg.ChannelUUID_ = courier.ChannelUUID("dbc126ed-66bc-4e28-b67b-81dc3327c95d")
ts.NotNil(dbMsg)

// serialize our message
Expand All @@ -862,7 +861,7 @@ func (ts *BackendTestSuite) TestOutgoingQueue() {
defer r.Close()

dbMsg := readMsgFromDB(ts.b, 10000)
dbMsg.ChannelUUID_, _ = courier.NewChannelUUID("dbc126ed-66bc-4e28-b67b-81dc3327c95d")
dbMsg.ChannelUUID_ = courier.ChannelUUID("dbc126ed-66bc-4e28-b67b-81dc3327c95d")
ts.NotNil(dbMsg)

// serialize our message
Expand Down Expand Up @@ -983,8 +982,8 @@ func (ts *BackendTestSuite) TestChannel() {
func (ts *BackendTestSuite) TestGetChannel() {
ctx := context.Background()

knUUID, _ := courier.NewChannelUUID("dbc126ed-66bc-4e28-b67b-81dc3327c95d")
xxUUID, _ := courier.NewChannelUUID("0a1256fe-c6e4-494d-99d3-576286f31d3b") // doesn't exist
knUUID := courier.ChannelUUID("dbc126ed-66bc-4e28-b67b-81dc3327c95d")
xxUUID := courier.ChannelUUID("0a1256fe-c6e4-494d-99d3-576286f31d3b") // doesn't exist

ch, err := ts.b.GetChannel(ctx, courier.ChannelType("KN"), knUUID)
ts.Assert().NoError(err)
Expand Down Expand Up @@ -1169,7 +1168,7 @@ func (ts *BackendTestSuite) TestWriteMsg() {
"org_id": float64(1),
"channel_id": float64(10),
"msg_id": float64(msg.ID_),
"msg_uuid": msg.UUID_.String(),
"msg_uuid": string(msg.UUID()),
"msg_external_id": msg.ExternalID(),
"urn": msg.URN().String(),
"urn_id": float64(msg.ContactURNID_),
Expand Down Expand Up @@ -1205,7 +1204,7 @@ func (ts *BackendTestSuite) TestWriteMsgWithAttachments() {
// should have actually fetched and saved it to storage, with the correct content type
err = ts.b.WriteMsg(ctx, msg, clog)
ts.NoError(err)
ts.Equal([]string{"image/jpeg:_test_storage/media/1/547d/eaf7/547deaf7-7620-4434-95b3-58675999c4b7.jpg"}, msg.Attachments())
ts.Equal([]string{"image/jpeg:_test_storage/media/1/9b95/5e36/9b955e36-ac16-4c6b-8ab6-9b9af5cd042a.jpg"}, msg.Attachments())

// try an invalid embedded attachment
msg = ts.b.NewIncomingMsg(knChannel, urn, "invalid embedded attachment data", clog).(*DBMsg)
Expand Down
2 changes: 1 addition & 1 deletion backends/rapidpro/channel.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ func getChannel(ctx context.Context, db *sqlx.DB, channelType courier.ChannelTyp
// if it wasn't found in the DB, clear our cache and return that it wasn't found
if dbErr == courier.ErrChannelNotFound {
clearLocalChannel(channelUUID)
return cachedChannel, fmt.Errorf("unable to find channel with type: %s and uuid: %s", channelType.String(), channelUUID.String())
return cachedChannel, fmt.Errorf("unable to find channel with type: %s and uuid: %s", channelType, channelUUID)
}

// if we had some other db error, return it if our cached channel was only just expired
Expand Down
2 changes: 1 addition & 1 deletion backends/rapidpro/contact.go
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ func contactForURN(ctx context.Context, b *backend, org OrgID, channel *DBChanne

// didn't find it, we need to create it instead
contact.OrgID_ = org
contact.UUID_, _ = courier.NewContactUUID(string(uuids.New()))
contact.UUID_ = courier.ContactUUID(uuids.New())
contact.CreatedOn_ = time.Now()
contact.ModifiedOn_ = time.Now()
contact.IsNew_ = true
Expand Down
13 changes: 7 additions & 6 deletions backends/rapidpro/msg.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import (
"github.com/nyaruka/courier"
"github.com/nyaruka/courier/queue"
"github.com/nyaruka/gocommon/urns"
"github.com/nyaruka/gocommon/uuids"
"github.com/nyaruka/null/v2"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
Expand Down Expand Up @@ -86,7 +87,7 @@ func writeMsg(ctx context.Context, b *backend, msg courier.Msg, clog *courier.Ch

// fail? log
if err != nil {
logrus.WithError(err).WithField("msg", m.UUID().String()).Error("error writing to db")
logrus.WithError(err).WithField("msg", m.UUID()).Error("error writing to db")
}

// if we failed write to spool
Expand All @@ -105,7 +106,7 @@ func newMsg(direction MsgDirection, channel courier.Channel, urn urns.URN, text

return &DBMsg{
OrgID_: dbChannel.OrgID(),
UUID_: courier.NewMsgUUID(),
UUID_: courier.MsgUUID(uuids.New()),
Direction_: direction,
Status_: courier.MsgPending,
Visibility_: MsgVisible,
Expand Down Expand Up @@ -275,7 +276,7 @@ func (b *backend) checkMsgSeen(msg *DBMsg) courier.MsgUUID {

// if it is the same, return the UUID
if prevText == msg.Text() {
return courier.NewMsgUUIDFromString(uuidAndText[:36])
return courier.MsgUUID(uuidAndText[:36])
}
}
return courier.NilMsgUUID
Expand All @@ -287,7 +288,7 @@ func (b *backend) writeMsgSeen(msg *DBMsg) {
rc := b.redisPool.Get()
defer rc.Close()

b.seenMsgs.Set(rc, msg.fingerprint(false), fmt.Sprintf("%s|%s", msg.UUID().String(), msg.Text()))
b.seenMsgs.Set(rc, msg.fingerprint(false), fmt.Sprintf("%s|%s", msg.UUID(), msg.Text()))
}

// clearMsgSeen clears our seen incoming messages for the passed in channel and URN
Expand All @@ -307,7 +308,7 @@ func (b *backend) checkExternalIDSeen(msg *DBMsg) courier.MsgUUID {

// if it is the same, return the UUID
if prevText == msg.Text() {
return courier.NewMsgUUIDFromString(uuidAndText[:36])
return courier.MsgUUID(uuidAndText[:36])
}
}
return courier.NilMsgUUID
Expand All @@ -317,7 +318,7 @@ func (b *backend) writeExternalIDSeen(msg *DBMsg) {
rc := b.redisPool.Get()
defer rc.Close()

b.seenExternalIDs.Set(rc, msg.fingerprint(true), fmt.Sprintf("%s|%s", msg.UUID().String(), msg.Text()))
b.seenExternalIDs.Set(rc, msg.fingerprint(true), fmt.Sprintf("%s|%s", msg.UUID(), msg.Text()))
}

//-----------------------------------------------------------------------------
Expand Down
2 changes: 1 addition & 1 deletion backends/rapidpro/task.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ func queueMsgHandling(rc redis.Conn, c *DBContact, m *DBMsg) error {
"org_id": channel.OrgID_,
"channel_id": channel.ID_,
"msg_id": m.ID_,
"msg_uuid": m.UUID_.String(),
"msg_uuid": m.UUID(),
"msg_external_id": m.ExternalID(),
"urn": m.URN().String(),
"urn_id": m.ContactURNID_,
Expand Down
19 changes: 3 additions & 16 deletions channel.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,9 @@ package courier
import (
"database/sql/driver"
"errors"
"strings"

"github.com/nyaruka/gocommon/uuids"
"github.com/nyaruka/null/v2"

"github.com/gofrs/uuid"
)

const (
Expand Down Expand Up @@ -79,21 +77,10 @@ const (
)

// ChannelUUID is our typing of a channel's UUID
type ChannelUUID struct {
uuid.UUID
}
type ChannelUUID uuids.UUID

// NilChannelUUID is our nil value for channel UUIDs
var NilChannelUUID = ChannelUUID{uuid.Nil}

// NewChannelUUID creates a new ChannelUUID for the passed in string
func NewChannelUUID(u string) (ChannelUUID, error) {
channelUUID, err := uuid.FromString(strings.ToLower(u))
if err != nil {
return NilChannelUUID, err
}
return ChannelUUID{channelUUID}, nil
}
var NilChannelUUID = ChannelUUID("")

// ChannelID is our SQL type for a channel's id
type ChannelID null.Int
Expand Down
19 changes: 3 additions & 16 deletions contact.go
Original file line number Diff line number Diff line change
@@ -1,27 +1,14 @@
package courier

import (
"strings"

"github.com/gofrs/uuid"
"github.com/nyaruka/gocommon/uuids"
)

// ContactUUID is our typing of a contact's UUID
type ContactUUID struct {
uuid.UUID
}
type ContactUUID uuids.UUID

// NilContactUUID is our nil value for contact UUIDs
var NilContactUUID = ContactUUID{uuid.Nil}

// NewContactUUID creates a new ContactUUID for the passed in string
func NewContactUUID(u string) (ContactUUID, error) {
contactUUID, err := uuid.FromString(strings.ToLower(u))
if err != nil {
return NilContactUUID, err
}
return ContactUUID{contactUUID}, nil
}
var NilContactUUID = ContactUUID("")

//-----------------------------------------------------------------------------
// Contact Interface
Expand Down
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ require (
github.com/dghubble/oauth1 v0.7.1
github.com/evalphobia/logrus_sentry v0.8.2
github.com/go-chi/chi v4.1.2+incompatible
github.com/gofrs/uuid v4.3.1+incompatible
github.com/gomodule/redigo v1.8.9
github.com/gorilla/schema v1.2.0
github.com/jmoiron/sqlx v1.3.5
Expand All @@ -36,6 +35,7 @@ require (
github.com/getsentry/raven-go v0.2.0 // indirect
github.com/go-playground/locales v0.14.0 // indirect
github.com/go-playground/universal-translator v0.18.0 // indirect
github.com/gofrs/uuid v4.3.1+incompatible // indirect
github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da // indirect
github.com/golang/protobuf v1.5.2 // indirect
github.com/jmespath/go-jmespath v0.4.0 // indirect
Expand Down
6 changes: 1 addition & 5 deletions handlers/base.go
Original file line number Diff line number Diff line change
Expand Up @@ -83,11 +83,7 @@ func (h *BaseHandler) RedactValues(ch courier.Channel) []string {

// GetChannel returns the channel
func (h *BaseHandler) GetChannel(ctx context.Context, r *http.Request) (courier.Channel, error) {
uuid, err := courier.NewChannelUUID(chi.URLParam(r, "uuid"))
if err != nil {
return nil, err
}

uuid := courier.ChannelUUID(chi.URLParam(r, "uuid"))
return h.backend.GetChannel(ctx, h.ChannelType(), uuid)
}

Expand Down
2 changes: 1 addition & 1 deletion handlers/discord/discord.go
Original file line number Diff line number Diff line change
Expand Up @@ -174,7 +174,7 @@ func (h *handler) Send(ctx context.Context, msg courier.Msg, clog *courier.Chann
ID: msg.ID().String(),
Text: msg.Text(),
To: msg.URN().Path(),
Channel: msg.Channel().UUID().String(),
Channel: string(msg.Channel().UUID()),
Attachments: attachmentURLs,
QuickReplies: msg.QuickReplies(),
}
Expand Down
2 changes: 1 addition & 1 deletion handlers/external/external.go
Original file line number Diff line number Diff line change
Expand Up @@ -299,7 +299,7 @@ func (h *handler) Send(ctx context.Context, msg courier.Msg, clog *courier.Chann
"to_no_plus": strings.TrimPrefix(msg.URN().Path(), "+"),
"from": msg.Channel().Address(),
"from_no_plus": strings.TrimPrefix(msg.Channel().Address(), "+"),
"channel": msg.Channel().UUID().String(),
"channel": string(msg.Channel().UUID()),
"session_status": msg.SessionStatus(),
}

Expand Down
2 changes: 1 addition & 1 deletion handlers/firebase/firebase.go
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ func (h *handler) registerContact(ctx context.Context, channel courier.Channel,

// return our contact UUID
w.Header().Set("Content-Type", "application/json")
err = json.NewEncoder(w).Encode(map[string]string{"contact_uuid": contact.UUID().String()})
err = json.NewEncoder(w).Encode(map[string]string{"contact_uuid": string(contact.UUID())})
return nil, err
}

Expand Down
2 changes: 1 addition & 1 deletion handlers/jiochat/jiochat.go
Original file line number Diff line number Diff line change
Expand Up @@ -261,7 +261,7 @@ func (h *handler) getAccessToken(ctx context.Context, channel courier.Channel, c
rc := h.Backend().RedisPool().Get()
defer rc.Close()

tokenKey := fmt.Sprintf("channel-token:%s", channel.UUID().String())
tokenKey := fmt.Sprintf("channel-token:%s", channel.UUID())

h.fetchTokenMutex.Lock()
defer h.fetchTokenMutex.Unlock()
Expand Down
2 changes: 1 addition & 1 deletion handlers/mtarget/mtarget.go
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ func (h *handler) receiveMsg(ctx context.Context, c courier.Channel, w http.Resp
defer rc.Close()

// first things first, populate the new part we just received
mapKey := fmt.Sprintf("%s:%s", c.UUID().String(), longID)
mapKey := fmt.Sprintf("%s:%s", c.UUID(), longID)
rc.Send("MULTI")
rc.Send("HSET", mapKey, longRef, text)
rc.Send("EXPIRE", mapKey, 300)
Expand Down
2 changes: 1 addition & 1 deletion handlers/wechat/wechat.go
Original file line number Diff line number Diff line change
Expand Up @@ -281,7 +281,7 @@ func (h *handler) getAccessToken(ctx context.Context, channel courier.Channel, c
rc := h.Backend().RedisPool().Get()
defer rc.Close()

tokenKey := fmt.Sprintf("channel-token:%s", channel.UUID().String())
tokenKey := fmt.Sprintf("channel-token:%s", channel.UUID())

h.fetchTokenMutex.Lock()
defer h.fetchTokenMutex.Unlock()
Expand Down
Loading

0 comments on commit a526396

Please sign in to comment.