Fix the nasty digging into action_hash
[catagits/Catalyst-Engine-STOMP.git] / lib / Catalyst / Engine / Stomp.pm
1 package Catalyst::Engine::Stomp;
2 use Moose;
3 use List::MoreUtils qw/ uniq /;
4 use HTTP::Request;
5 use Net::Stomp;
6 use namespace::autoclean;
7
8 extends 'Catalyst::Engine::Embeddable';
9
10 our $VERSION = '0.05';
11
12 has connection => (is => 'rw', isa => 'Net::Stomp');
13 has conn_desc => (is => 'rw', isa => 'Str');
14
15 =head1 NAME
16
17 Catalyst::Engine::Stomp - write message handling apps with Catalyst.
18
19 =head1 SYNOPSIS
20
21   # In a server script:
22
23   BEGIN {
24     $ENV{CATALYST_ENGINE} = 'Stomp';
25     require Catalyst::Engine::Stomp;
26   }
27
28   MyApp->config->{Engine::Stomp} =
29    {
30      hostname => '127.0.0.1',
31      port     => 61613,
32    };
33   MyApp->run();
34
35   # In a controller, or controller base class:
36   use base qw/ Catalyst::Controller::MessageDriven /;
37
38   # then create actions, which map as message types
39   sub testaction : Local {
40       my ($self, $c) = @_;
41
42       # Reply with a minimal response message
43       my $response = { type => 'testaction_response' };
44       $c->stash->{response} = $response;
45   }
46
47 =head1 DESCRIPTION
48
49 Write a Catalyst app connected to a Stomp messagebroker, not HTTP. You
50 need a controller that understands messaging, as well as this engine.
51
52 This is single-threaded and single process - you need to run multiple
53 instances of this engine to get concurrency, and configure your broker
54 to load-balance across multiple consumers of the same queue.
55
56 Controllers are mapped to Stomp queues, and a controller base class is
57 provided, Catalyst::Controller::MessageDriven, which implements
58 YAML-serialized messages, mapping a top-level YAML "type" key to
59 the action.
60
61 =head1 METHODS
62
63 =head2 run
64
65 App entry point. Starts a loop listening for messages.
66
67 =cut
68
69 sub run {
70         my ($self, $app, $oneshot) = @_;
71
72         die 'No Engine::Stomp configuration found'
73              unless ref $app->config->{'Engine::Stomp'} eq 'HASH';
74
75         my @queues = map { $app->controller($_)->action_namespace } $app->controllers;
76
77         # connect up
78         my %template = %{$app->config->{'Engine::Stomp'}};
79         $self->connection(Net::Stomp->new(\%template));
80         $self->connection->connect();
81         $self->conn_desc($template{hostname}.':'.$template{port});
82
83         # subscribe, with client ack.
84         foreach my $queue (@queues) {
85                 my $queue_name = "/queue/$queue";
86                 $self->connection->subscribe({
87                                               destination => $queue_name,
88                                               ack         => 'client'
89                                              });
90         }
91
92         # enter loop...
93         while (1) {
94                 my $frame = $self->connection->receive_frame();
95                 $self->handle_stomp_frame($app, $frame);
96                 last if $ENV{ENGINE_ONESHOT};
97         }
98         exit 0;
99 }
100
101 =head2 prepare_request
102
103 Overridden to add the source broker to the request, in place of the
104 client IP address.
105
106 =cut
107
108 sub prepare_request {
109     my ($self, $c, $req, $res_ref) = @_;
110     shift @_;
111     $self->next::method(@_);
112     $c->req->address($self->conn_desc);
113 }
114
115 =head2 finalize_headers
116
117 Overridden to dump out any errors encountered, since you won't get a
118 "debugging" message as for HTTP.
119
120 =cut
121
122 sub finalize_headers {
123     my ($self, $c) = @_;
124     my $error = join "\n", @{$c->error};
125     if ($error) {
126         $c->log->debug($error);
127     }
128     return $self->next::method($c);
129 }
130
131 =head2 handle_stomp_frame
132
133 Dispatch according to Stomp frame type.
134
135 =cut
136
137 sub handle_stomp_frame {
138     my ($self, $app, $frame) = @_;
139
140     my $command = $frame->command();
141     if ($command eq 'MESSAGE') {
142         $self->handle_stomp_message($app, $frame);
143     }
144     elsif ($command eq 'ERROR') {
145         $self->handle_stomp_error($app, $frame);
146     }
147     else {
148         $app->log->debug("Got unknown Stomp command: $command");
149     }
150 }
151
152 =head2 handle_stomp_message
153
154 Dispatch a Stomp message into the Catalyst app.
155
156 =cut
157
158 sub handle_stomp_message {
159     my ($self, $app, $frame) = @_;
160
161     # queue -> controller
162     my $queue = $frame->headers->{destination};
163     my ($controller) = $queue =~ m|^/queue/(.*)$|;
164
165     # set up request
166     my $config = $app->config->{'Engine::Stomp'};
167     my $url = 'stomp://'.$config->{hostname}.':'.$config->{port}.'/'.$controller;
168     my $req = HTTP::Request->new(POST => $url);
169     $req->content($frame->body);
170     $req->content_length(length $frame->body);
171
172     # dispatch
173     my $response;
174     $app->handle_request($req, \$response);
175
176     # reply, if header set
177     if (my $reply_to = $response->headers->header('X-Reply-Address')) {
178         my $reply_queue = '/remote-temp-queue/' . $reply_to;
179         $self->connection->send({ destination => $reply_queue, body => $response->content });
180     }
181
182     # ack the message off the queue now we've replied / processed
183     $self->connection->ack( { frame => $frame } );
184 }
185
186 =head2 handle_stomp_error
187
188 Log any Stomp error frames we receive.
189
190 =cut
191
192 sub handle_stomp_error {
193     my ($self, $app, $frame) = @_;
194
195     my $error = $frame->headers->{message};
196     $app->log->debug("Got Stomp error: $error");
197 }
198
199 __PACKAGE__->meta->make_immutable;
200