Skip to content

Instantly share code, notes, and snippets.

@geoffreybennett
Last active November 7, 2018 13:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save geoffreybennett/b5b3b673c309e886824361d4f4d62a00 to your computer and use it in GitHub Desktop.
Save geoffreybennett/b5b3b673c309e886824361d4f4d62a00 to your computer and use it in GitHub Desktop.
Mojo::Pg notify on db close
--- PubSub.pm.orig 2018-11-07 22:09:03.636066615 +1030
+++ PubSub.pm 2018-11-07 22:21:28.613982320 +1030
@@ -29,8 +29,12 @@
sub unlisten {
my ($self, $name, $cb) = @_;
my $chan = $self->{chans}{$name};
+ my $unlisten = $cb ? grep { $cb eq $_ } @$chan : 1;
@$chan = $cb ? grep { $cb ne $_ } @$chan : ();
- $self->_db->unlisten($name) and delete $self->{chans}{$name} unless @$chan;
+ if (!@$chan) {
+ $self->_db->unlisten($name) if $unlisten;
+ delete $self->{chans}{$name};
+ }
return $self;
}
@@ -50,7 +54,11 @@
for my $cb (@cbs) { $self->$cb($payload) }
}
);
- $db->once(close => sub { $self->{pg} and $self->_db if delete $self->{db} });
+ $db->once(close => sub {
+ $self->emit(disconnect => $db);
+ delete $self->{db};
+ $self->reset;
+ });
$db->listen($_) for keys %{$self->{chans}}, 'mojo.pubsub';
$self->emit(reconnect => $db);
-----8<-----
#!/usr/bin/perl
use Mojolicious::Lite;
use Mojo::Pg;
helper pg => sub { state $pg = Mojo::Pg->new('postgresql:///') };
get '/' => sub {
my $c = shift;
my $pubsub = $c->pg->pubsub;
my $listen_cb = eval {
$pubsub->listen(test => sub {
$c->write("notify\n");
});
};
if ($@) {
$c->write("db connection failed: $@\n");
$c->finish;
return;
}
$c->write;
$c->write("ready!\n");
my $disconnect_cb = $pubsub->on(disconnect => sub {
$c->finish;
});
$c->on(finish => sub {
$pubsub->unlisten(test => $listen_cb);
$pubsub->unsubscribe(disconnect => $disconnect_cb);
});
};
app->start;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment