| 1 | package Mojo::mysql::PubSub; | ||
| 2 | use Mojo::Base 'Mojo::EventEmitter'; | ||
| 3 | |||
| 4 | use Carp qw(croak); | ||
| 5 | use Scalar::Util qw(weaken); | ||
| 6 | |||
| 7 | use constant DEBUG => $ENV{MOJO_PUBSUB_DEBUG} || 0; | ||
| 8 | use constant RETRIES => $ENV{MOJO_MYSQL_PUBSUB_RETRIES} // 1; | ||
| 9 | |||
| 10 | has 'mysql'; | ||
| 11 | |||
| 12 | sub DESTROY { | ||
| 13 | my $self = shift; | ||
| 14 | return unless $self->{wait_db} and $self->mysql; | ||
| 15 | _query_with_retry($self->mysql->db, 'delete from mojo_pubsub_subscribe where pid = ?', $self->{wait_db}->pid); | ||
| 16 | } | ||
| 17 | |||
| 18 | sub listen { | ||
| 19 | my ($self, $channel, $cb) = @_; | ||
| 20 | my $sync_db = $self->mysql->db; | ||
| 21 | my $wait_pid = $self->_wait_db($sync_db)->pid; | ||
| 22 | warn qq|[PubSub] (@{[$wait_pid]}) listen "$channel"\n| if DEBUG; | ||
| 23 | _query_with_retry($sync_db, | ||
| 24 | 'insert into mojo_pubsub_subscribe (pid, channel) values (?, ?) on duplicate key update ts=current_timestamp', | ||
| 25 | $wait_pid, $channel); | ||
| 26 | push @{$self->{chans}{$channel}}, $cb; | ||
| 27 | return $cb; | ||
| 28 | } | ||
| 29 | |||
| 30 | sub notify { | ||
| 31 | my ($self, $channel, $payload) = @_; | ||
| 32 | my $sync_db = $self->mysql->db; | ||
| 33 | warn qq|[PubSub] channel:$channel <<< "@{[$payload // '']}"\n| if DEBUG; | ||
| 34 | $self->_init($sync_db) unless $self->{init}; | ||
| 35 | _query_with_retry($sync_db, 'insert into mojo_pubsub_notify (channel, payload) values (?, ?)', | ||
| 36 | $channel, $payload // ''); | ||
| 37 | return $self; | ||
| 38 | } | ||
| 39 | |||
| 40 | sub unlisten { | ||
| 41 | my ($self, $channel, $cb) = @_; | ||
| 42 | |||
| 43 | my $chan = $self->{chans}{$channel}; | ||
| 44 | @$chan = grep { $cb ne $_ } @$chan; | ||
| 45 | return $self if @$chan; | ||
| 46 | |||
| 47 | my $sync_db = $self->mysql->db; | ||
| 48 | my $wait_pid = $self->_wait_db($sync_db)->pid; | ||
| 49 | warn qq|[PubSub] ($wait_pid) unlisten "$channel"\n| if DEBUG; | ||
| 50 | _query_with_retry($sync_db, 'delete from mojo_pubsub_subscribe where pid = ? and channel = ?', $wait_pid, $channel); | ||
| 51 | delete $self->{chans}{$channel}; | ||
| 52 | return $self; | ||
| 53 | } | ||
| 54 | |||
| 55 | sub _init { | ||
| 56 | my ($self, $sync_db) = @_; | ||
| 57 | $self->mysql->migrations->name('pubsub')->from_data->migrate; | ||
| 58 | _query_with_retry($sync_db, | ||
| 59 | 'delete from mojo_pubsub_notify where ts < date_add(current_timestamp, interval -10 minute)'); | ||
| 60 | _query_with_retry($sync_db, | ||
| 61 | 'delete from mojo_pubsub_subscribe where ts < date_add(current_timestamp, interval -1 hour)'); | ||
| 62 | $self->{init} = 1; | ||
| 63 | } | ||
| 64 | |||
| 65 | sub _notifications { | ||
| 66 | my ($self, $sync_db) = @_; | ||
| 67 | my $result | ||
| 68 | = _query_with_retry($sync_db, 'select id, channel, payload from mojo_pubsub_notify where id > ? order by id', | ||
| 69 | $self->{last_id}); | ||
| 70 | while (my $row = $result->array) { | ||
| 71 | my ($id, $channel, $payload) = @$row; | ||
| 72 | $self->{last_id} = $id; | ||
| 73 | next unless exists $self->{chans}{$channel}; | ||
| 74 | warn qq/[PubSub] channel:$channel >>> "$payload"\n/ if DEBUG; | ||
| 75 | for my $cb (@{$self->{chans}{$channel}}) { $self->$cb($payload) } | ||
| 76 | } | ||
| 77 | } | ||
| 78 | |||
| 79 | sub _wait_db { | ||
| 80 | my ($self, $sync_db) = @_; | ||
| 81 | |||
| 82 | # Fork-safety | ||
| 83 | delete @$self{qw(wait_db chans pid)} if ($self->{pid} //= $$) ne $$; | ||
| 84 | |||
| 85 | return $self->{wait_db} if $self->{wait_db}; | ||
| 86 | |||
| 87 | $self->_init($sync_db) unless $self->{init}; | ||
| 88 | my $wait_db = $self->{wait_db} = $self->mysql->db; | ||
| 89 | my $wait_db_pid = $wait_db->pid; | ||
| 90 | _query_with_retry($sync_db, | ||
| 91 | 'insert into mojo_pubsub_subscribe (pid, channel) values (?, ?) on duplicate key update ts=current_timestamp', | ||
| 92 | $wait_db_pid, $_) | ||
| 93 | for keys %{$self->{chans}}; | ||
| 94 | |||
| 95 | if ($self->{last_id}) { | ||
| 96 | $self->_notifications($sync_db); | ||
| 97 | } | ||
| 98 | else { | ||
| 99 | my $last = _query_with_retry($sync_db, 'select id from mojo_pubsub_notify order by id desc limit 1')->array; | ||
| 100 | $self->{last_id} = defined $last ? $last->[0] : 0; | ||
| 101 | } | ||
| 102 | |||
| 103 | weaken $wait_db->{mysql}; | ||
| 104 | weaken $self; | ||
| 105 | my $cb; | ||
| 106 | $cb = sub { | ||
| 107 | my ($db, $err, $res) = @_; | ||
| 108 | return unless $self; | ||
| 109 | warn qq|[PubSub] (@{[$db->pid]}) sleep(600) @{[$err ? "!!! $err" : $res->array->[0]]}\n| if DEBUG; | ||
| 110 | my $sync_db = $self->mysql->db; | ||
| 111 | return (delete $self->{wait_db}, $self->_wait_db($sync_db)) if $err; | ||
| 112 | $res->finish; | ||
| 113 | _query_with_retry($db, 'select sleep(600)', $cb); | ||
| 114 | _query_with_retry($sync_db, 'update mojo_pubsub_subscribe set ts = current_timestamp where pid = ?', $db->pid); | ||
| 115 | $self->_notifications($self->mysql->db); | ||
| 116 | }; | ||
| 117 | |||
| 118 | warn qq|[PubSub] (@{[$wait_db->pid]}) reconnect\n| if DEBUG; | ||
| 119 | $self->emit(reconnect => $wait_db); | ||
| 120 | return _query_with_retry($wait_db, 'select sleep(600)', $cb); | ||
| 121 | } | ||
| 122 | |||
| 123 | sub _query_with_retry { | ||
| 124 | my ($db, $sql, @bind) = @_; | ||
| 125 | |||
| 126 | my $result; | ||
| 127 | |||
| 128 | my $remaining_attempts = RETRIES + 1; # including initial attempt | ||
| 129 | while ($remaining_attempts--) { | ||
| 130 | local $@; | ||
| 131 | eval { $result = $db->query($sql, @bind) }; | ||
| 132 | last unless $@; # success | ||
| 133 | croak $@ unless $remaining_attempts; # rethrow $@ if no remaining attempts | ||
| 134 | |||
| 135 | # If we are allowed to retry, check if the error message looks | ||
| 136 | # like it refers to something retryable. Only look within the | ||
| 137 | # first line to avoid potential spurious matches if the error | ||
| 138 | # e.g. contains a stack trace. | ||
| 139 | my $err = $@; # avoid stringifying $@ ... | ||
| 140 | croak $@ unless $err =~ /^\V*(?:retry|timeout)/i; # ... and maybe rethrow it | ||
| 141 | |||
| 142 | # If we got here, we are retrying the query: | ||
| 143 | warn qq|[PubSub] (@{[$db->pid]}) retry ($sql) !!! $err\n| if DEBUG; | ||
| 144 | } | ||
| 145 | |||
| 146 | return $result; | ||
| 147 | } | ||
| 148 | |||
| 149 | 1; | ||
| 150 | |||
| 151 | =encoding utf8 | ||
| 152 | |||
| 153 | =head1 NAME | ||
| 154 | |||
| 155 | Mojo::mysql::PubSub - Publish/Subscribe | ||
| 156 | |||
| 157 | =head1 SYNOPSIS | ||
| 158 | |||
| 159 | use Mojo::mysql::PubSub; | ||
| 160 | |||
| 161 | my $pubsub = Mojo::mysql::PubSub->new(mysql => $mysql); | ||
| 162 | my $cb = $pubsub->listen(foo => sub { | ||
| 163 | my ($pubsub, $payload) = @_; | ||
| 164 | say "Received: $payload"; | ||
| 165 | }); | ||
| 166 | $pubsub->notify(foo => 'bar'); | ||
| 167 | $pubsub->unlisten(foo => $cb); | ||
| 168 | |||
| 169 | =head1 DESCRIPTION | ||
| 170 | |||
| 171 | L<Mojo::mysql::PubSub> is implementation of the publish/subscribe pattern used | ||
| 172 | by L<Mojo::mysql>. The implementation should be considered an EXPERIMENT and | ||
| 173 | might be removed without warning! | ||
| 174 | |||
| 175 | Although MySQL does not have C<SUBSCRIBE/NOTIFY> like PostgreSQL and other RDBMs, | ||
| 176 | this module implements similar feature. | ||
| 177 | |||
| 178 | Single Database connection waits for notification by executing C<SLEEP> on server. | ||
| 179 | C<connection_id> and subscribed channels in stored in C<mojo_pubsub_subscribe> table. | ||
| 180 | Inserting new row in C<mojo_pubsub_notify> table triggers C<KILL QUERY> for | ||
| 181 | all connections waiting for notification. | ||
| 182 | |||
| 183 | C<PROCESS> privilege is needed for MySQL user to see other users processes. | ||
| 184 | C<SUPER> privilege is needed to be able to execute C<KILL QUERY> for statements | ||
| 185 | started by other users. | ||
| 186 | C<SUPER> privilege may be needed to be able to define trigger. | ||
| 187 | |||
| 188 | If your applications use this module using different MySQL users it is important | ||
| 189 | the migration script to be executed by user having C<SUPER> privilege on the database. | ||
| 190 | |||
| 191 | =head1 EVENTS | ||
| 192 | |||
| 193 | L<Mojo::mysql::PubSub> inherits all events from L<Mojo::EventEmitter> and can | ||
| 194 | emit the following new ones. | ||
| 195 | |||
| 196 | =head2 reconnect | ||
| 197 | |||
| 198 | $pubsub->on(reconnect => sub { | ||
| 199 | my ($pubsub, $db) = @_; | ||
| 200 | ... | ||
| 201 | }); | ||
| 202 | |||
| 203 | Emitted after switching to a new database connection for sending and receiving | ||
| 204 | notifications. | ||
| 205 | |||
| 206 | =head1 ATTRIBUTES | ||
| 207 | |||
| 208 | L<Mojo::mysql::PubSub> implements the following attributes. | ||
| 209 | |||
| 210 | =head2 mysql | ||
| 211 | |||
| 212 | my $mysql = $pubsub->mysql; | ||
| 213 | $pubsub = $pubsub->mysql(Mojo::mysql->new); | ||
| 214 | |||
| 215 | L<Mojo::mysql> object this publish/subscribe container belongs to. | ||
| 216 | |||
| 217 | =head1 METHODS | ||
| 218 | |||
| 219 | L<Mojo::mysql::PubSub> inherits all methods from L<Mojo::EventEmitter> and | ||
| 220 | implements the following new ones. | ||
| 221 | |||
| 222 | =head2 listen | ||
| 223 | |||
| 224 | my $cb = $pubsub->listen(foo => sub {...}); | ||
| 225 | |||
| 226 | Subscribe to a channel, there is no limit on how many subscribers a channel can | ||
| 227 | have. | ||
| 228 | |||
| 229 | # Subscribe to the same channel twice | ||
| 230 | $pubsub->listen(foo => sub { | ||
| 231 | my ($pubsub, $payload) = @_; | ||
| 232 | say "One: $payload"; | ||
| 233 | }); | ||
| 234 | $pubsub->listen(foo => sub { | ||
| 235 | my ($pubsub, $payload) = @_; | ||
| 236 | say "Two: $payload"; | ||
| 237 | }); | ||
| 238 | |||
| 239 | =head2 notify | ||
| 240 | |||
| 241 | $pubsub = $pubsub->notify('foo'); | ||
| 242 | $pubsub = $pubsub->notify(foo => 'bar'); | ||
| 243 | |||
| 244 | Notify a channel. | ||
| 245 | |||
| 246 | =head2 unlisten | ||
| 247 | |||
| 248 | $pubsub = $pubsub->unlisten(foo => $cb); | ||
| 249 | |||
| 250 | Unsubscribe from a channel. | ||
| 251 | |||
| 252 | =head1 DEBUGGING | ||
| 253 | |||
| 254 | You can set the C<MOJO_PUBSUB_DEBUG> environment variable to get some | ||
| 255 | advanced diagnostics information printed to C<STDERR>. | ||
| 256 | |||
| 257 | MOJO_PUBSUB_DEBUG=1 | ||
| 258 | |||
| 259 | =head1 SEE ALSO | ||
| 260 | |||
| 261 | L<Mojo::mysql>, L<Mojolicious::Guides>, L<http://mojolicio.us>. | ||
| 262 | |||
| 263 | =cut | ||
| 264 | |||
| 265 | __DATA__ |