Skip to content

Commit

Permalink
wrap follow and unfollow queries with transactions
Browse files Browse the repository at this point in the history
  • Loading branch information
dimkr committed Oct 1, 2023
1 parent 394518b commit ecfd8b6
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 4 deletions.
14 changes: 12 additions & 2 deletions outbox/follow.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,13 @@ func Follow(ctx context.Context, follower *ap.Actor, followed string, db *sql.DB

isLocal := strings.HasPrefix(followed, fmt.Sprintf("https://%s/", cfg.Domain))

if _, err := db.ExecContext(
tx, err := db.BeginTx(ctx, nil)
if err != nil {
return fmt.Errorf("Failed to begin transaction: %w", err)
}
defer tx.Rollback()

if _, err := tx.ExecContext(
ctx,
`INSERT INTO follows (id, follower, followed, accepted) VALUES(?,?,?,?)`,
followID,
Expand All @@ -62,13 +68,17 @@ func Follow(ctx context.Context, follower *ap.Actor, followed string, db *sql.DB
return fmt.Errorf("Failed to insert follow: %w", err)
}

if _, err := db.ExecContext(
if _, err := tx.ExecContext(
ctx,
`INSERT INTO outbox (activity) VALUES(?)`,
string(body),
); err != nil {
return fmt.Errorf("Failed to insert follow activity: %w", err)
}

if err := tx.Commit(); err != nil {
return fmt.Errorf("%s failed to follow %s: %w", follower.ID, followed, err)
}

return nil
}
14 changes: 12 additions & 2 deletions outbox/unfollow.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,17 +55,27 @@ func Unfollow(ctx context.Context, log *slog.Logger, db *sql.DB, follower *ap.Ac
return fmt.Errorf("%s cannot unfollow %s: %w", follower.ID, followed, err)
}

if _, err := db.ExecContext(
tx, err := db.BeginTx(ctx, nil)
if err != nil {
return fmt.Errorf("Failed to begin transaction: %w", err)
}
defer tx.Rollback()

if _, err := tx.ExecContext(
ctx,
`INSERT INTO outbox (activity) VALUES(?)`,
string(body),
); err != nil {
return fmt.Errorf("Failed to insert undo for %s: %w", followID, err)
}

if _, err := db.ExecContext(ctx, `delete from follows where id = ?`, followID); err != nil && !errors.Is(err, sql.ErrNoRows) {
if _, err := tx.ExecContext(ctx, `delete from follows where id = ?`, followID); err != nil && !errors.Is(err, sql.ErrNoRows) {
return fmt.Errorf("Failed to unfollow %s: %w", followID, err)
}

if err := tx.Commit(); err != nil {
return fmt.Errorf("%s failed to unfollow %s: %w", follower.ID, followed, err)
}

return nil
}

0 comments on commit ecfd8b6

Please sign in to comment.