ops_advisory_lock.go 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. package service
  2. import (
  3. "context"
  4. "database/sql"
  5. "fmt"
  6. "hash/fnv"
  7. "time"
  8. )
  9. func hashAdvisoryLockID(key string) int64 {
  10. h := fnv.New64a()
  11. _, _ = h.Write([]byte(key))
  12. return int64(h.Sum64())
  13. }
  14. func tryAcquireDBAdvisoryLock(ctx context.Context, db *sql.DB, lockID int64) (func(), bool) {
  15. release, acquired, _ := tryAcquireDBAdvisoryLockWithError(ctx, db, lockID)
  16. return release, acquired
  17. }
  18. func tryAcquireDBAdvisoryLockWithError(ctx context.Context, db *sql.DB, lockID int64) (func(), bool, error) {
  19. if db == nil {
  20. return nil, false, nil
  21. }
  22. if ctx == nil {
  23. ctx = context.Background()
  24. }
  25. conn, err := db.Conn(ctx)
  26. if err != nil {
  27. return nil, false, fmt.Errorf("open advisory-lock connection: %w", err)
  28. }
  29. acquired := false
  30. if err := conn.QueryRowContext(ctx, "SELECT pg_try_advisory_lock($1)", lockID).Scan(&acquired); err != nil {
  31. _ = conn.Close()
  32. return nil, false, fmt.Errorf("query advisory lock: %w", err)
  33. }
  34. if !acquired {
  35. _ = conn.Close()
  36. return nil, false, nil
  37. }
  38. release := func() {
  39. unlockCtx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
  40. defer cancel()
  41. _, _ = conn.ExecContext(unlockCtx, "SELECT pg_advisory_unlock($1)", lockID)
  42. _ = conn.Close()
  43. }
  44. return release, true, nil
  45. }