|
| 1 | +package database |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "database/sql" |
| 6 | + "errors" |
| 7 | + "sync" |
| 8 | + "time" |
| 9 | + |
| 10 | + "github.com/google/uuid" |
| 11 | + "github.com/lib/pq" |
| 12 | + "golang.org/x/xerrors" |
| 13 | +) |
| 14 | + |
| 15 | +// Listener represents a pubsub handler. |
| 16 | +type Listener func(ctx context.Context, message []byte) |
| 17 | + |
| 18 | +// Pubsub is a generic interface for broadcasting and receiving messages. |
| 19 | +// Implementors should assume high-availability with the backing implementation. |
| 20 | +type Pubsub interface { |
| 21 | + Subscribe(event string, listener Listener) (cancel func(), err error) |
| 22 | + Publish(event string, message []byte) error |
| 23 | + Close() error |
| 24 | +} |
| 25 | + |
| 26 | +// Pubsub implementation using PostgreSQL. |
| 27 | +type pgPubsub struct { |
| 28 | + pgListener *pq.Listener |
| 29 | + db *sql.DB |
| 30 | + mut sync.Mutex |
| 31 | + listeners map[string]map[string]Listener |
| 32 | +} |
| 33 | + |
| 34 | +// Subscribe calls the listener when an event matching the name is received. |
| 35 | +func (p *pgPubsub) Subscribe(event string, listener Listener) (cancel func(), err error) { |
| 36 | + p.mut.Lock() |
| 37 | + defer p.mut.Unlock() |
| 38 | + |
| 39 | + err = p.pgListener.Listen(event) |
| 40 | + if errors.Is(err, pq.ErrChannelAlreadyOpen) { |
| 41 | + // It's ok if it's already open! |
| 42 | + err = nil |
| 43 | + } |
| 44 | + if err != nil { |
| 45 | + return nil, xerrors.Errorf("listen: %w", err) |
| 46 | + } |
| 47 | + |
| 48 | + var listeners map[string]Listener |
| 49 | + var ok bool |
| 50 | + if listeners, ok = p.listeners[event]; !ok { |
| 51 | + listeners = map[string]Listener{} |
| 52 | + p.listeners[event] = listeners |
| 53 | + } |
| 54 | + var id string |
| 55 | + for { |
| 56 | + id = uuid.New().String() |
| 57 | + if _, ok = listeners[id]; !ok { |
| 58 | + break |
| 59 | + } |
| 60 | + } |
| 61 | + listeners[id] = listener |
| 62 | + return func() { |
| 63 | + p.mut.Lock() |
| 64 | + defer p.mut.Unlock() |
| 65 | + listeners := p.listeners[event] |
| 66 | + delete(listeners, id) |
| 67 | + |
| 68 | + if len(listeners) == 0 { |
| 69 | + _ = p.pgListener.Unlisten(event) |
| 70 | + } |
| 71 | + }, nil |
| 72 | +} |
| 73 | + |
| 74 | +func (p *pgPubsub) Publish(event string, message []byte) error { |
| 75 | + _, err := p.db.ExecContext(context.Background(), `select pg_notify(`+pq.QuoteLiteral(event)+`, $1)`, message) |
| 76 | + if err != nil { |
| 77 | + return xerrors.Errorf("exec: %w", err) |
| 78 | + } |
| 79 | + return nil |
| 80 | +} |
| 81 | + |
| 82 | +// Close closes the pubsub instance. |
| 83 | +func (p *pgPubsub) Close() error { |
| 84 | + return p.pgListener.Close() |
| 85 | +} |
| 86 | + |
| 87 | +// listen begins receiving messages on the pq listener. |
| 88 | +func (p *pgPubsub) listen(ctx context.Context) { |
| 89 | + var ( |
| 90 | + notif *pq.Notification |
| 91 | + ok bool |
| 92 | + ) |
| 93 | + defer p.pgListener.Close() |
| 94 | + for { |
| 95 | + select { |
| 96 | + case <-ctx.Done(): |
| 97 | + return |
| 98 | + case notif, ok = <-p.pgListener.Notify: |
| 99 | + if !ok { |
| 100 | + return |
| 101 | + } |
| 102 | + } |
| 103 | + // A nil notification can be dispatched on reconnect. |
| 104 | + if notif == nil { |
| 105 | + continue |
| 106 | + } |
| 107 | + p.listenReceive(ctx, notif) |
| 108 | + } |
| 109 | +} |
| 110 | + |
| 111 | +func (p *pgPubsub) listenReceive(ctx context.Context, notif *pq.Notification) { |
| 112 | + p.mut.Lock() |
| 113 | + defer p.mut.Unlock() |
| 114 | + listeners, ok := p.listeners[notif.Channel] |
| 115 | + if !ok { |
| 116 | + return |
| 117 | + } |
| 118 | + extra := []byte(notif.Extra) |
| 119 | + for _, listener := range listeners { |
| 120 | + go listener(ctx, extra) |
| 121 | + } |
| 122 | +} |
| 123 | + |
| 124 | +// NewPubsub creates a new Pubsub implementation using a PostgreSQL connection. |
| 125 | +func NewPubsub(ctx context.Context, db *sql.DB, connectURL string) (Pubsub, error) { |
| 126 | + // Creates a new listener using pq. |
| 127 | + errCh := make(chan error) |
| 128 | + listener := pq.NewListener(connectURL, time.Second*10, time.Minute, func(event pq.ListenerEventType, err error) { |
| 129 | + // This callback gets events whenever the connection state changes. |
| 130 | + // Don't send if the errChannel has already been closed. |
| 131 | + select { |
| 132 | + case <-errCh: |
| 133 | + return |
| 134 | + default: |
| 135 | + errCh <- err |
| 136 | + close(errCh) |
| 137 | + } |
| 138 | + }) |
| 139 | + select { |
| 140 | + case err := <-errCh: |
| 141 | + if err != nil { |
| 142 | + return nil, xerrors.Errorf("create pq listener: %w", err) |
| 143 | + } |
| 144 | + case <-ctx.Done(): |
| 145 | + return nil, ctx.Err() |
| 146 | + } |
| 147 | + pg := &pgPubsub{ |
| 148 | + db: db, |
| 149 | + pgListener: listener, |
| 150 | + listeners: make(map[string]map[string]Listener), |
| 151 | + } |
| 152 | + go pg.listen(ctx) |
| 153 | + |
| 154 | + return pg, nil |
| 155 | +} |
0 commit comments