Snippets

Brian Medley Attempt to add tracing to Mojo::Pg for use in Mojolicious. Probably broken in not so interesting ways.

Created by Brian Medley
package Trace;

use Mojo::Base 'Mojo::Pg';

use File::Temp qw(tempfile);
use Mojo::Util qw(spurt);

my %h;

sub _enqueue {
    my $dbh = pop;

    my $h = delete $h{$dbh};

    spurt(${ $h->{trace} }, $h->{filename});

    warn("filename: $$h{filename}");

    shift->SUPER::_enqueue($dbh);
}

sub _dequeue {
    my $dbh = shift->SUPER::_dequeue(@_);

    my ($fh, $trace);
    my (undef, $filename) = tempfile("pg_trace_XXXXXX", TMPDIR => 1, UNLINK => 0, SUFFIX => ".log");

    open($fh, "+>:scalar", \$trace);
    $dbh->trace(1, $fh);

    $h{$dbh} = {};
    $h{$dbh}{fh} = $fh;
    $h{$dbh}{trace} = \$trace;
    $h{$dbh}{filename} = $filename;

    warn("filename: $filename");

    return $dbh;
}

package main;

use Mojolicious::Lite;

use PerlIO::via::DBLog;
use DBLog;

helper pg => sub { state $pg = Trace->new("postgresql://$ENV{DBI_USER}:$ENV{DBI_PASS}\@127.0.0.1/test") };

get '/' => 'chat';

websocket '/channel' => sub {
  my $c = shift;

  $c->inactivity_timeout(3600);

  # Forward messages from the browser to PostgreSQL
  $c->on(message => sub { 
    my $c = shift;
    my $msg = shift;

    $c->pg->db->query('insert into log (text) values (?)', $msg);

    $c->pg->pubsub->notify(mojochat => $msg)
  });

  # Forward messages from PostgreSQL to the browser
  my $cb = $c->pg->pubsub->listen(mojochat => sub { $c->send(pop) });
  $c->on(finish => sub { shift->pg->pubsub->unlisten(mojochat => $cb) });
};

app->pg->db->query('create table IF NOT EXISTS log (id serial primary key, text text)');

app->start;
__DATA__

@@ chat.html.ep
<form onsubmit="sendChat(this.children[0]); return false"><input></form>
<div id="log"></div>
<script>
  var ws  = new WebSocket('<%= url_for('channel')->to_abs %>');
  ws.onmessage = function (e) {
    document.getElementById('log').innerHTML += '<p>' + e.data + '</p>';
  };
  function sendChat(input) { ws.send(input.value); input.value = '' }
</script>

Comments (0)

HTTPS SSH

You can clone a snippet to your computer for local editing. Learn more.