-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: orchestrate saga flow for creating subscriptions
- Loading branch information
1 parent
20981c8
commit 55c9a08
Showing
6 changed files
with
222 additions
and
16 deletions.
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
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,59 @@ | ||
package gormsubscriber | ||
|
||
import ( | ||
"context" | ||
"errors" | ||
"time" | ||
|
||
"github.com/jackc/pgx/v5/pgconn" | ||
"github.com/vladyslavpavlenko/genesis-api-project/internal/email" | ||
"github.com/vladyslavpavlenko/genesis-api-project/internal/models" | ||
"github.com/vladyslavpavlenko/genesis-api-project/internal/storage/gormstorage" | ||
) | ||
|
||
var ErrorInvalidEmail = errors.New("invalid email") | ||
|
||
// validateSubscription is an action that validates a subscription by validating an | ||
// email address and checking if it already exists. | ||
func validateSubscription(saga *State, s *Subscriber) error { | ||
// Validate the email format | ||
if !email.Email(saga.Email).Validate() { | ||
return ErrorInvalidEmail | ||
} | ||
|
||
// Check if the subscription already exists | ||
ctx, cancel := context.WithTimeout(context.Background(), gormstorage.RequestTimeout) | ||
defer cancel() | ||
|
||
var count int64 | ||
err := s.db.WithContext(ctx).Model(&models.Subscription{}).Where("email = ?", saga.Email).Count(&count).Error | ||
if err != nil { | ||
return err | ||
} | ||
|
||
if count > 0 { | ||
return ErrorDuplicateSubscription | ||
} | ||
|
||
return nil | ||
} | ||
|
||
// addSubscription is an action that creates a new models.Subscription record. | ||
func addSubscription(saga *State, s *Subscriber) error { | ||
ctx, cancel := context.WithTimeout(context.Background(), gormstorage.RequestTimeout) | ||
defer cancel() | ||
|
||
subscription := models.Subscription{ | ||
Email: saga.Email, | ||
CreatedAt: time.Now(), | ||
} | ||
result := s.db.WithContext(ctx).Create(&subscription) | ||
if result.Error != nil { | ||
var pgErr *pgconn.PgError | ||
if errors.As(result.Error, &pgErr) && pgErr.Code == "23505" { | ||
return ErrorDuplicateSubscription | ||
} | ||
return result.Error | ||
} | ||
return nil | ||
} |
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,21 @@ | ||
package gormsubscriber | ||
|
||
import ( | ||
"context" | ||
|
||
"github.com/vladyslavpavlenko/genesis-api-project/internal/models" | ||
"github.com/vladyslavpavlenko/genesis-api-project/internal/storage/gormstorage" | ||
) | ||
|
||
// deleteSubscription is a compensation to addSubscription that deletes a | ||
// models.Subscription record, queried by an email address. | ||
func deleteSubscription(saga *State, s *Subscriber) error { | ||
ctx, cancel := context.WithTimeout(context.Background(), gormstorage.RequestTimeout) | ||
defer cancel() | ||
|
||
result := s.db.WithContext(ctx).Where("email = ?", saga.Email).Delete(&models.Subscription{}) | ||
if result.Error != nil { | ||
return result.Error | ||
} | ||
return nil | ||
} |
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,127 @@ | ||
package gormsubscriber | ||
|
||
import ( | ||
"context" | ||
|
||
"github.com/google/uuid" | ||
"github.com/pkg/errors" | ||
"github.com/vladyslavpavlenko/genesis-api-project/internal/storage/gormstorage" | ||
"gorm.io/gorm" | ||
) | ||
|
||
const ( | ||
StatusCompleted = "completed" | ||
StatusInProgress = "in_progress" | ||
StatusFailed = "failed" | ||
) | ||
|
||
// State represents the current state of the SAGA transaction. | ||
type State struct { | ||
ID string `gorm:"primary_key"` | ||
CurrentStep int | ||
Email string | ||
IsCompensating bool | ||
Status string // StatusCompleted, StatusInProgress, StatusFailed | ||
} | ||
|
||
// Step represents a single step in the SAGA transaction. | ||
type Step struct { | ||
Action func(saga *State, s *Subscriber) error | ||
Compensation func(saga *State, s *Subscriber) error | ||
} | ||
|
||
// Orchestrator manages the execution of SAGA steps. | ||
type Orchestrator struct { | ||
Steps []Step | ||
State State | ||
db *gorm.DB | ||
} | ||
|
||
// NewSagaOrchestrator creates a new SAGA Orchestrator. | ||
func NewSagaOrchestrator(email string, db *gorm.DB) (*Orchestrator, error) { | ||
err := db.AutoMigrate(&State{}) | ||
if err != nil { | ||
return nil, errors.Wrap(err, "failed to migrate events") | ||
} | ||
|
||
return &Orchestrator{ | ||
Steps: []Step{ | ||
{ | ||
Action: validateSubscription, | ||
Compensation: nil, | ||
}, | ||
{ | ||
Action: addSubscription, | ||
Compensation: deleteSubscription, | ||
}, | ||
}, | ||
State: State{ | ||
ID: uuid.New().String(), | ||
CurrentStep: 0, | ||
Email: email, | ||
IsCompensating: false, | ||
Status: StatusInProgress, | ||
}, | ||
db: db, | ||
}, nil | ||
} | ||
|
||
// Run runs the SAGA Orchestrator. | ||
func (o *Orchestrator) Run(s *Subscriber) error { | ||
for o.State.CurrentStep < len(o.Steps) { | ||
step := o.Steps[o.State.CurrentStep] | ||
var err error | ||
|
||
if o.State.IsCompensating { | ||
if step.Compensation != nil { | ||
err = step.Compensation(&o.State, s) | ||
} | ||
} else { | ||
err = step.Action(&o.State, s) | ||
} | ||
|
||
if err != nil { | ||
o.State.IsCompensating = true | ||
err = o.saveState() | ||
if err != nil { | ||
return err | ||
} | ||
continue | ||
} | ||
|
||
if o.State.IsCompensating { | ||
o.State.CurrentStep-- | ||
if o.State.CurrentStep < 0 { | ||
o.State.Status = StatusFailed | ||
err = o.saveState() | ||
if err != nil { | ||
return err | ||
} | ||
return err | ||
} | ||
} else { | ||
o.State.CurrentStep++ | ||
} | ||
err = o.saveState() | ||
if err != nil { | ||
return err | ||
} | ||
} | ||
|
||
if !o.State.IsCompensating { | ||
o.State.Status = StatusCompleted | ||
err := o.saveState() | ||
if err != nil { | ||
return err | ||
} | ||
} | ||
return nil | ||
} | ||
|
||
// saveState saves the SAGA transaction to the database. | ||
func (o *Orchestrator) saveState() error { | ||
ctx, cancel := context.WithTimeout(context.Background(), gormstorage.RequestTimeout) | ||
defer cancel() | ||
|
||
return o.db.WithContext(ctx).Save(&o.State).Error | ||
} |
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