-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add transactional publishing, queue length querying
- Loading branch information
Showing
6 changed files
with
290 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,138 @@ | ||
// This example shows how to use transactional publisher in order to | ||
// store data and publish events in one transaction. | ||
package main | ||
|
||
import ( | ||
"context" | ||
"encoding/json" | ||
"errors" | ||
"math/rand" | ||
"time" | ||
|
||
"github.com/Pallinder/go-randomdata" | ||
"cloud.google.com/go/firestore" | ||
"github.com/ThreeDotsLabs/watermill" | ||
"github.com/ThreeDotsLabs/watermill/message" | ||
watermillFirestore "github.com/czeslavo/watermill-firestore/pkg/firestore" | ||
) | ||
|
||
const projectID = "test" | ||
|
||
type User struct { | ||
Name string `firestore:"name"` | ||
} | ||
|
||
type UserAdded struct { | ||
When time.Time `json:"when"` | ||
Name string `json:"name"` | ||
} | ||
|
||
type UserStore struct { | ||
client *firestore.Client | ||
} | ||
|
||
func NewUserStore() *UserStore { | ||
client, err := firestore.NewClient(context.Background(), projectID) | ||
if err != nil { | ||
panic(err) | ||
} | ||
|
||
return &UserStore{ | ||
client: client, | ||
} | ||
} | ||
|
||
func (r *UserStore) Add(u User, t *firestore.Transaction) error { | ||
if err := t.Create(r.client.Collection("users").NewDoc(), u); err != nil { | ||
return err | ||
} | ||
|
||
// 3/4 for success | ||
if rand.Intn(4) == 1 { | ||
return errors.New("random error") | ||
} | ||
return nil | ||
} | ||
|
||
func main() { | ||
client, err := firestore.NewClient(context.Background(), projectID) | ||
if err != nil { | ||
panic(err) | ||
} | ||
|
||
logger := watermill.NewStdLogger(true, false) | ||
|
||
go addUsers(client, logger) | ||
subscriber, err := watermillFirestore.NewSubscriber(watermillFirestore.SubscriberConfig{ | ||
ProjectID: projectID, | ||
}, logger) | ||
if err != nil { | ||
panic(err) | ||
} | ||
go monitorQueueLength(subscriber, "user_added", logger) | ||
|
||
userAddedCh, err := subscriber.Subscribe(context.Background(), "user_added") | ||
if err != nil { | ||
panic(err) | ||
} | ||
consume(userAddedCh, logger) | ||
} | ||
|
||
func addUsers(client *firestore.Client, logger watermill.LoggerAdapter) { | ||
publisher, err := watermillFirestore.NewPublisher(watermillFirestore.PublisherConfig{ | ||
ProjectID: projectID, | ||
}, logger) | ||
if err != nil { | ||
panic(err) | ||
} | ||
|
||
userStore := NewUserStore() | ||
for { | ||
if err := client.RunTransaction(context.Background(), func(ctx context.Context, t *firestore.Transaction) error { | ||
user := User{Name: randomdata.FirstName(randomdata.RandomGender)} | ||
if err := userStore.Add(user, t); err != nil { | ||
return err | ||
} | ||
|
||
payload, err := json.Marshal(&UserAdded{When: time.Now(), Name: user.Name}) | ||
if err != nil { | ||
return err | ||
} | ||
|
||
msg := message.NewMessage(watermill.NewShortUUID(), payload) | ||
if err := publisher.PublishInTransaction("user_added", t, msg); err != nil { | ||
return err | ||
} | ||
|
||
return nil | ||
}); err != nil { | ||
logger.Debug("Transaction failed", nil) | ||
} | ||
<-time.After(time.Second * 5) | ||
} | ||
} | ||
|
||
func consume(ch <-chan *message.Message, logger watermill.LoggerAdapter) { | ||
for msg := range ch { | ||
var event UserAdded | ||
if err := json.Unmarshal(msg.Payload, &event); err != nil { | ||
panic(err) | ||
} | ||
|
||
logger.Debug("Received userAdded", watermill.LogFields{"event": event}) | ||
<-time.After(time.Second) | ||
msg.Ack() | ||
} | ||
} | ||
|
||
func monitorQueueLength(sub *watermillFirestore.Subscriber, topic string, logger watermill.LoggerAdapter) { | ||
for { | ||
length, err := sub.QueueLength(topic) | ||
if err != nil { | ||
panic(err) | ||
} | ||
logger.Debug("Read queue length", watermill.LogFields{"queue_length": length}) | ||
<-time.After(time.Second) | ||
} | ||
} | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,99 @@ | ||
package firestore | ||
|
||
import ( | ||
"context" | ||
|
||
"cloud.google.com/go/firestore" | ||
"github.com/ThreeDotsLabs/watermill" | ||
"github.com/ThreeDotsLabs/watermill/message" | ||
"google.golang.org/grpc/codes" | ||
"google.golang.org/grpc/status" | ||
) | ||
|
||
type firestoreDocCreator interface { | ||
Create(doc *firestore.DocumentRef, data interface{}) (*firestore.WriteResult, error) | ||
} | ||
|
||
type transactionalDocCreator struct { | ||
*firestore.Transaction | ||
} | ||
|
||
type docCreator struct { | ||
} | ||
|
||
func (c *docCreator) Create(doc *firestore.DocumentRef, data interface{}) (*firestore.WriteResult, error) { | ||
return doc.Create(context.Background(), data) | ||
} | ||
|
||
type TransactionalPublisher struct { | ||
client *firestore.Client | ||
creator firestoreDocCreator | ||
logger watermill.LoggerAdapter | ||
} | ||
|
||
func NewTransactionalPublisher(config PublisherConfig, creator firestoreDocCreator, logger watermill.LoggerAdapter) (*TransactionalPublisher, error) { | ||
client, err := firestore.NewClient(context.Background(), config.ProjectID) | ||
if err != nil { | ||
return nil, err | ||
} | ||
|
||
return &TransactionalPublisher{ | ||
client: client, | ||
creator: creator, | ||
logger: logger, | ||
}, nil | ||
} | ||
|
||
func (p *TransactionalPublisher) Publish(topic string, messages ...*message.Message) error { | ||
subscriptions, err := p.client.Collection("pubsub").Doc(topic).Collection("subscriptions").Documents(context.Background()).GetAll() | ||
if err != nil { | ||
return err | ||
} | ||
|
||
logger := p.logger.With(watermill.LogFields{"subscriptions_count": len(subscriptions), "topic": topic}) | ||
|
||
logger.Debug("Publishing", nil) | ||
|
||
for _, msg := range messages { | ||
firestoreMsg := Message{ | ||
UUID: msg.UUID, | ||
Payload: msg.Payload, | ||
Metadata: make(map[string]interface{}), | ||
} | ||
for k, v := range msg.Metadata { | ||
firestoreMsg.Metadata[k] = v | ||
} | ||
|
||
logger := logger.With(watermill.LogFields{"message_uuid": msg.UUID}) | ||
|
||
for _, sub := range subscriptions { | ||
logger := logger.With(watermill.LogFields{"collection": sub.Ref.ID}) | ||
|
||
docRef := p.client.Collection("pubsub").Doc(topic).Collection(sub.Ref.ID).NewDoc() | ||
|
||
_, err = p.creator.Create(docRef, firestoreMsg) | ||
if err != nil { | ||
p.logger.Error("Failed to send msg", err, watermill.LogFields{}) | ||
return err | ||
} | ||
|
||
logger.Debug("Published message", nil) | ||
} | ||
} | ||
|
||
return nil | ||
} | ||
|
||
func (p *TransactionalPublisher) Close() error { | ||
if err := p.client.Close(); err != nil { | ||
if status.Code(err) == codes.Canceled { | ||
// client is already closed | ||
return nil | ||
} | ||
|
||
p.logger.Error("closing client failed", err, watermill.LogFields{}) | ||
return err | ||
} | ||
|
||
return nil | ||
} |