package main import ( "context" "crypto/rand" "encoding/hex" "fmt" "time" "github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5/pgconn" ) type queryExecutor interface { Exec(context.Context, string, ...any) (pgconn.CommandTag, error) } func notificationID() string { buffer := make([]byte, 16) if _, err := rand.Read(buffer); err == nil { return hex.EncodeToString(buffer) } return fmt.Sprintf("%d", time.Now().UnixNano()) } func enqueueNotification( ctx context.Context, executor queryExecutor, deviceID string, eventType string, entityType string, entityID string, listID string, createdAt int64, ) error { _, err := executor.Exec(ctx, ` INSERT INTO notifications (id, deviceidorigin, eventtype, entitytype, entityid, listid, createdat) VALUES ($1, $2, $3, $4, $5, $6, $7) `, notificationID(), nullableString(deviceID), eventType, entityType, nullableString(entityID), nullableString(listID), createdAt) return err } // enqueueNotificationInTx writes a notification inside a savepoint. PostgreSQL // aborts the whole transaction after any failing statement, so without the // savepoint a failed notification insert would make the data mutation's commit // fail too. func enqueueNotificationInTx( ctx context.Context, tx pgx.Tx, deviceID string, eventType string, entityType string, entityID string, listID string, createdAt int64, ) error { savepoint, err := tx.Begin(ctx) if err != nil { return err } if err := enqueueNotification(ctx, savepoint, deviceID, eventType, entityType, entityID, listID, createdAt); err != nil { _ = savepoint.Rollback(ctx) return err } return savepoint.Commit(ctx) } func nullableString(value string) any { if value == "" { return nil } return value } // ignoreNotificationError logs a failed notification. Use it only for // notifications written by enqueueNotificationInTx or outside a transaction. func ignoreNotificationError(err error) { if err != nil { // Notifications are an acceleration path for clients that poll. A failed // notification must never roll back the data mutation that produced it. fmt.Printf("[notifications] enqueue failed: %v\n", err) } }