Skip to content

Commit

Permalink
fix(document): race condition on view increment
Browse files Browse the repository at this point in the history
  • Loading branch information
MrMissx committed Feb 10, 2024
1 parent f3ef421 commit b30b450
Showing 1 changed file with 14 additions and 4 deletions.
18 changes: 14 additions & 4 deletions model/document.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ type Document struct {

func insertDocument(db *sqlx.DB, doc *Document, retry int) error {
if retry > 3 {
utils.Logger.Warning("Failed to insert document after 3 retries")
return nil
}

Expand All @@ -33,6 +34,7 @@ func insertDocument(db *sqlx.DB, doc *Document, retry int) error {
pgErr, ok := err.(*pq.Error)
// duplicate slug
if ok && pgErr.Code == "23505" && retry <= 3 {
utils.Logger.Warning("Slug %s already exists, retrying...", doc.Slug)
return insertDocument(db, doc, retry+1)
}
}
Expand All @@ -45,10 +47,18 @@ func (doc *Document) Create(db *sqlx.DB) error {
}

func (doc *Document) incrementViews(db *sqlx.DB) {
_, err := db.Exec("UPDATE documents SET views = views + 1 WHERE slug = $1", doc.Slug)
if err != nil {
utils.Logger.Error("Failed to update document '%v' : %v", doc.Slug, err)
}
tx, err := db.Beginx()

defer func() {
if err != nil {
tx.Rollback()
utils.Logger.Error("Failed to start transaction: %v", err)
} else {
tx.Commit()
}
}()

_, err = tx.Exec("UPDATE documents SET views = views + 1 WHERE slug = $1", doc.Slug)
}

func (doc *Document) GetBySlug(db *sqlx.DB, slug string) error {
Expand Down

0 comments on commit b30b450

Please sign in to comment.