Skip to content
This repository has been archived by the owner on May 6, 2018. It is now read-only.

Commit

Permalink
Added EmailStatus and EmailQueue; Also added Email.SaveAndSend() which
Browse files Browse the repository at this point in the history
executes saving and senting independantly/async.

related to #17 #18 #19 #20
  • Loading branch information
ajvb committed Feb 21, 2014
1 parent c8b56c4 commit c75afb4
Showing 1 changed file with 60 additions and 1 deletion.
61 changes: 60 additions & 1 deletion types/email.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,10 @@ import (
)

// TODO: Replace with Postgres DB
var emailDB = map[string]*Email{}
var (
emailDB = map[string]*Email{}
EmailQueue = make(chan *Email)
)

type Email struct {
Id string `json:"id"`
Expand All @@ -23,6 +26,62 @@ type Email struct {
ModifiedAt time.Time `json:"modified_at"`
}

type SentStatus string

const (
QUEUED SentStatus = "queued"
SENDING SentStatus = "sending"
SUCCESS SentStatus = "success"
FAILED SentStatus = "failed"
)

type EmailStatus struct {
Email *Email
EmailId string
Status SentStatus
}

func (e *Email) SaveAndSend() {
// Save
go func() {
if err := e.Save(); err != nil {
//TODO: Handle error
}
}()
// Send
go func() {
EmailQueue <- e
}()
}

func StartEmailQueue() {
var semaphore = make(chan bool, 10) // Can only send 10 at once

go func() {
for {
email := <-EmailQueue
// Spawn goroutine immediately
go func(e *Email) {
// Will only block if 10 emails are already being sent.
semaphore <- true
defer func() {
// Drain value from channel to make room
// for another email sender
<-semaphore
}()

err := e.Send()
if err != nil {
// FAILED
//TODO: Handle error
return
}
// SUCCESS
}(email)
}
}()
}

func (e *Email) Save() error {
if e == nil {
return fmt.Errorf("Cannot save nil *Email to DB!\n")
Expand Down

0 comments on commit c75afb4

Please sign in to comment.