factor dispatcher out into Web::Dispatch
Matt S Trout [Fri, 19 Nov 2010 17:57:05 +0000 (17:57 +0000)]
14 files changed:
Changes
examples/bloggery/bloggery.cgi
lib/Plack/Middleware/Dispatch.pm [new file with mode: 0644]
lib/Web/Dispatch.pm [new file with mode: 0644]
lib/Web/Dispatch/Node.pm [new file with mode: 0644]
lib/Web/Dispatch/Parser.pm
lib/Web/Dispatch/Predicates.pm
lib/Web/Dispatch/ToApp.pm [new file with mode: 0644]
lib/Web/Dispatch/Wrapper.pm [new file with mode: 0644]
lib/Web/Simple.pm
lib/Web/Simple/Application.pm
lib/Web/Simple/DispatchNode.pm [new file with mode: 0644]
t/bloggery.t
t/sub-dispatch-args.t [new file with mode: 0644]

diff --git a/Changes b/Changes
index 7f33bd6..f0fa473 100644 (file)
--- a/Changes
+++ b/Changes
@@ -1,5 +1,6 @@
 Change log for Web::Simple
 
+  - Factor dispatcher code out into Web::Dispatch
   - Support 'use Web::Simple;' to default to current package
 
 0.004 - Thu Jul 08 2010 22:08 UTC
index 1a2fee1..d771be7 100755 (executable)
@@ -85,17 +85,17 @@ sub post {
 }
 
 dispatch {
-  sub (.html) {
-    response_filter { $self->render_html($_[1]) },
-  },
   sub (GET + /) {
     redispatch_to '/index.html';
   },
+  sub (.html) {
+    response_filter { $self->render_html($_[1]) },
+  },
   sub (GET + /index) {
     $self->post_list
   },
   sub (GET + /*) {
-    $self->post($_[1]);
+    $self->post($_[1])
   },
   sub (GET) {
     [ 404, [ 'Content-type', 'text/plain' ], [ 'Not found' ] ]
diff --git a/lib/Plack/Middleware/Dispatch.pm b/lib/Plack/Middleware/Dispatch.pm
new file mode 100644 (file)
index 0000000..6d95716
--- /dev/null
@@ -0,0 +1,19 @@
+package Plack::Middleware::Dispatch;
+
+use Moo;
+
+extends 'Web::Dispatch';
+
+has app => (is => 'ro', writer => '_set_app');
+
+sub wrap {
+  my ($self, $app, @args) = @_;
+  if (ref $self) {
+    $self->_set_app($app);
+  } else {
+    $self = $self->new({ app => $app, @args });
+  }
+  return $self->to_app;
+}
+
+1;
diff --git a/lib/Web/Dispatch.pm b/lib/Web/Dispatch.pm
new file mode 100644 (file)
index 0000000..01ebb3e
--- /dev/null
@@ -0,0 +1,87 @@
+package Web::Dispatch;
+
+use Sub::Quote;
+use Scalar::Util qw(blessed);
+use Moo;
+use Web::Dispatch::Parser;
+use Web::Dispatch::Node;
+
+with 'Web::Dispatch::ToApp';
+
+has app => (is => 'ro', required => 1);
+has parser_class => (
+  is => 'ro', default => quote_sub q{ 'Web::Dispatch::Parser' }
+);
+has node_class => (
+  is => 'ro', default => quote_sub q{ 'Web::Dispatch::Node' }
+);
+has node_args => (is => 'ro', default => quote_sub q{ {} });
+has _parser => (is => 'lazy');
+
+sub _build__parser {
+  my ($self) = @_;
+  $self->parser_class->new;
+}
+
+sub call {
+  my ($self, $env) = @_;
+  $self->_dispatch($env, $self->app);
+}
+
+sub _dispatch {
+  my ($self, $env, @match) = @_;
+  while (my $try = shift @match) {
+    if (ref($try) eq 'HASH') {
+      $env = { %$env, %$try };
+      next;
+    } elsif (ref($try) eq 'ARRAY') {
+      return $try;
+    }
+    my @result = $self->_to_try($try)->($env, @match);
+    next unless @result and defined($result[0]);
+    if (ref($result[0]) eq 'ARRAY') {
+      return $result[0];
+    } elsif (blessed($result[0]) && $result[0]->can('wrap')) {
+      return $result[0]->wrap(sub {
+        $self->_dispatch($_[0], @match)
+      })->($env);
+    } elsif (blessed($result[0]) && !$result[0]->can('to_app')) {
+      return $result[0];
+    } else {
+      # make a copy so we don't screw with it assigning further up
+      my $env = $env;
+      # try not to end up quite so bloody deep in the call stack
+      if (@match) {
+        unshift @match, sub { $self->_dispatch($env, @result) };
+      } else {
+        @match = @result;
+      }
+    }
+  }
+  return;
+}
+
+sub _to_try {
+  my ($self, $try) = @_;
+  if (ref($try) eq 'CODE') {
+    if (defined(my $proto = prototype($try))) {
+      $self->_construct_node(
+        match => $self->_parser->parse($proto), run => $try
+      )->to_app;
+    } else {
+      $try
+    }
+  } elsif (blessed($try) && $try->can('to_app')) {
+    $try->to_app;
+  } else {
+    die "No idea how we got here with $try";
+  }
+}
+
+sub _construct_node {
+  my ($self, %args) = @_;
+  @args{keys %$_} = values %$_ for $self->node_args;
+  $self->node_class->new(\%args);
+}
+
+1;
diff --git a/lib/Web/Dispatch/Node.pm b/lib/Web/Dispatch/Node.pm
new file mode 100644 (file)
index 0000000..4fbc46d
--- /dev/null
@@ -0,0 +1,26 @@
+package Web::Dispatch::Node;
+
+use Moo;
+
+with 'Web::Dispatch::ToApp';
+
+for (qw(match run)) {
+  has "_${_}" => (is => 'ro', required => 1, init_arg => $_);
+}
+
+sub call {
+  my ($self, $env) = @_;
+  if (my ($env_delta, @match) = $self->_match->($env)) {
+    $self->_curry(@match)->({ %$env, %$env_delta });
+  } else {
+    ()
+  }
+}
+
+sub _curry {
+  my ($self, @args) = @_;
+  my $run = $self->_run;
+  sub { $run->(@args, $_[0]) };
+}
+
+1;
index 422182c..b731b17 100644 (file)
@@ -144,7 +144,9 @@ sub _url_path_match {
       push @path, $self->_url_path_segment_match($_)
         or $self->_blam("Couldn't parse path match segment");
     }
-    !$end and length and $_ .= '(?:\.\w+)?' for $path[-1];
+    if (@path && !$end) {
+      length and $_ .= '(?:\.\w+)?' for $path[-1];
+    }
     my $re = '^('.join('/','',@path).')'.$end.'$';
     $re = qr/$re/;
     if ($end) {
@@ -170,7 +172,7 @@ sub _url_path_segment_match {
       return '(.*?[^/])';
     # * -> capture path part
     /\G\*/gc and
-      return '([^/]+)';
+      return '([^/]+?)';
   }
   return ();
 }
index fff7542..7008efe 100644 (file)
@@ -14,12 +14,12 @@ sub match_and {
     my @got;
     foreach my $match (@match) {
       if (my @this_got = $match->($my_env)) {
-       my %change_env = %{shift(@this_got)};
-       @{$my_env}{keys %change_env} = values %change_env;
-       @{$new_env}{keys %change_env} = values %change_env;
-       push @got, @this_got;
+        my %change_env = %{shift(@this_got)};
+        @{$my_env}{keys %change_env} = values %change_env;
+        @{$new_env}{keys %change_env} = values %change_env;
+        push @got, @this_got;
       } else {
-       return;
+        return;
       }
     }
     return ($new_env, @got);
@@ -63,8 +63,8 @@ sub match_path_strip {
     my ($env) = @_;
     if (my @cap = ($env->{PATH_INFO} =~ /$re/)) {
       $cap[0] = {
-       SCRIPT_NAME => ($env->{SCRIPT_NAME}||'').$cap[0],
-       PATH_INFO => pop(@cap),
+        SCRIPT_NAME => ($env->{SCRIPT_NAME}||'').$cap[0],
+        PATH_INFO => pop(@cap),
       };
       return @cap;
     }
diff --git a/lib/Web/Dispatch/ToApp.pm b/lib/Web/Dispatch/ToApp.pm
new file mode 100644 (file)
index 0000000..ed5df37
--- /dev/null
@@ -0,0 +1,12 @@
+package Web::Dispatch::ToApp;
+
+use Moo::Role;
+
+requires 'call';
+
+sub to_app {
+  my ($self) = @_;
+  sub { $self->call(@_) }
+}
+
+1;
diff --git a/lib/Web/Dispatch/Wrapper.pm b/lib/Web/Dispatch/Wrapper.pm
new file mode 100644 (file)
index 0000000..5ff6068
--- /dev/null
@@ -0,0 +1,16 @@
+package Web::Dispatch::Wrapper;
+
+use strictures 1;
+
+sub from_code {
+  my ($class, $code) = @_;
+  bless(\$code, $class);
+}
+
+sub wrap {
+  my $code = ${$_[0]};
+  my $app = $_[1];
+  sub { $code->($_[0], $app) }
+}
+
+1;
index 9d5efbb..960fc01 100644 (file)
@@ -31,7 +31,7 @@ sub _export_into {
   {
     no strict 'refs';
     *{"${app_package}::dispatch"} = sub (&) {
-      $app_package->_setup_dispatcher([ $_[0]->() ]);
+      $app_package->_setup_dispatcher($_[0]);
     };
     *{"${app_package}::response_filter"} = sub (&) {
       $app_package->_construct_response_filter($_[0]);
@@ -39,9 +39,6 @@ sub _export_into {
     *{"${app_package}::redispatch_to"} = sub {
       $app_package->_construct_redispatch($_[0]);
     };
-    *{"${app_package}::subdispatch"} = sub ($) {
-      $app_package->_construct_subdispatch($_[0]);
-    };
     *{"${app_package}::default_config"} = sub {
       $app_package->_setup_default_config(@_);
     };
index 4021170..a6ada44 100644 (file)
@@ -3,61 +3,6 @@ package Web::Simple::Application;
 use strict;
 use warnings FATAL => 'all';
 
-{
-  package Web::Simple::Dispatcher;
-
-  sub _is_dispatcher {
-    ref($_[1])
-      and "$_[1]" =~ /\w+=[A-Z]/
-      and $_[1]->isa(__PACKAGE__);
-  }
-
-  sub next {
-    @_ > 1
-      ? $_[0]->{next} = $_[1]
-      : shift->{next}
-  }
-
-  sub set_next {
-    $_[0]->{next} = $_[1];
-    $_[0]
-  }
-
-  sub dispatch {
-    my ($self, $env, @args) = @_;
-    my $next = $self->_has_match ? $self->next : undef;
-    if (my ($env_delta, @match) = $self->_match_against($env)) {
-      if (my ($result) = $self->_execute_with(@args, @match, $env)) {
-        if ($self->_is_dispatcher($result)) {
-          $next = $result->set_next($next);
-          $env = { %$env, %$env_delta };
-        } else {
-          return $result;
-        }
-      }
-    }
-    return () unless $next;
-    return $next->dispatch($env, @args);
-  }
-
-  sub call {
-    @_ > 1
-      ? $_[0]->{call} = $_[1]
-      : shift->{call}
-  }
-
-  sub _has_match { $_[0]->{match} }
-
-  sub _match_against {
-     return ({}, $_[1]) unless $_[0]->{match};
-     $_[0]->{match}->($_[1]);
-  }
-
-  sub _execute_with {
-    $_[0]->{call}->(@_);
-  }
-}
-
 sub new {
   my ($class, $data) = @_;
   my $config = { $class->_default_config, %{($data||{})->{config}||{}} };
@@ -107,26 +52,25 @@ sub config {
 }
 
 sub _construct_response_filter {
-  my $code = $_[1];
-  $_[0]->_build_dispatcher({
-    call => sub {
-      my ($d, $self, $env) = (shift, shift, shift);
-      my @next = $d->next->dispatch($env, $self, @_);
-      return unless @next;
-      $self->_run_with_self($code, @next);
-    },
+  my ($class, $code) = @_;
+  my $self = do { no strict 'refs'; ${"${class}::self"} };
+  require Web::Dispatch::Wrapper;
+  Web::Dispatch::Wrapper->from_code(sub {
+    my @result = $_[1]->($_[0]);
+    if (@result) {
+      $self->_run_with_self($code, @result);
+    } else {
+      @result;
+    }
   });
 }
 
 sub _construct_redispatch {
-  my ($self, $new_path) = @_;
-  $self->_build_dispatcher({
-    call => sub {
-      shift;
-      my ($self, $env) = @_;
-      $self->_dispatch({ %{$env}, PATH_INFO => $new_path })
-    }
-  })
+  my ($class, $new_path) = @_;
+  require Web::Dispatch::Wrapper;
+  Web::Dispatch::Wrapper->from_code(sub {
+    $_[1]->({ %{$_[0]}, PATH_INFO => $new_path });
+  });
 }
 
 sub _build_dispatch_parser {
@@ -144,95 +88,21 @@ sub _cannot_call_twice {
 }
 
 sub _setup_dispatcher {
-  my ($class, $dispatch_specs) = @_;
+  my ($class, $dispatcher) = @_;
   {
     no strict 'refs';
     if (${"${class}::_dispatcher"}{CODE}) {
       $class->_cannot_call_twice('_setup_dispatcher', 'dispatch');
     }
   }
-  my $chain = $class->_build_dispatch_chain(
-    [ @$dispatch_specs, $class->_build_final_dispatcher ]
-  );
   {
     no strict 'refs';
-    *{"${class}::_dispatcher"} = sub { $chain };
-  }
-}
-
-sub _construct_subdispatch {
-  my ($class, $dispatch_spec) = @_;
-  my $disp = $class->_build_dispatcher_from_spec($dispatch_spec);
-  my $call = $disp->call;
-  $disp->call(sub {
-    my @res = $call->(@_);
-    return unless @res;
-    my $chain = $class->_build_dispatch_chain(@res);
-    return $class->_build_dispatcher({
-      call => sub {
-        my ($d, $self, $env) = (shift, shift, shift); pop; # lose trailing $env
-        return $chain->dispatch($env, $self, @_);
-      }
-    });
-  });
-  return $class->_build_dispatcher({
-    call => sub {
-      my ($d, $self, $env) = (shift, shift, shift); pop; # lose trailing $env
-      my @sub = $disp->dispatch($env, $self, @_);
-      return @sub if @sub;
-      return unless (my $next = $d->next);
-      return $next->dispatch($env, $self, @_);
-    },
-  });
-}
-
-sub _build_dispatcher_from_spec {
-  my ($class, $spec) = @_;
-  return $spec unless ref($spec) eq 'CODE';
-  my $proto = prototype $spec;
-  my $parser = $class->_build_dispatch_parser;
-  my $matcher = (
-    defined($proto) && length($proto)
-      ? $parser->parse($proto)
-      : sub { ({}, $_[1]) }
-  );
-  return $class->_build_dispatcher({
-    match => $matcher,
-    call => sub { shift;
-      shift->_run_with_self($spec, @_)
-    },
-  });
-}
-
-sub _build_dispatch_chain {
-  my ($class, $dispatch_specs) = @_;
-  my ($root, $last);
-  foreach my $dispatch_spec (@$dispatch_specs) {
-    my $new = $class->_build_dispatcher_from_spec($dispatch_spec);
-    $root ||= $new;
-    $last = $last ? $last->next($new) : $new;
+    *{"${class}::dispatch_request"} = $dispatcher;
   }
-  return $root;
-}
-
-sub _build_dispatcher {
-  bless($_[1], 'Web::Simple::Dispatcher');
 }
 
 sub _build_final_dispatcher {
-  shift->_build_dispatcher({
-    call => sub {
-      [
-        404, [ 'Content-type', 'text/plain' ],
-        [ 'Not found' ]
-      ]
-    }
-  })
-}
-
-sub _dispatch {
-  my ($self, $env) = @_;
-  $self->_dispatcher->dispatch($env, $self);
+  [ 404, [ 'Content-type', 'text/plain' ], [ 'Not found' ] ]
 }
 
 sub _run_with_self {
@@ -264,7 +134,14 @@ sub _run_fcgi {
 
 sub as_psgi_app {
   my $self = ref($_[0]) ? $_[0] : $_[0]->new;
-  sub { $self->_dispatch(@_) };
+  require Web::Dispatch;
+  require Web::Simple::DispatchNode;
+  my $final = $self->_build_final_dispatcher;
+  Web::Dispatch->new(
+    app => sub { $self->dispatch_request(@_), $final },
+    node_class => 'Web::Simple::DispatchNode',
+    node_args => { app_object => $self }
+  )->to_app;
 }
 
 sub run {
diff --git a/lib/Web/Simple/DispatchNode.pm b/lib/Web/Simple/DispatchNode.pm
new file mode 100644 (file)
index 0000000..e00da02
--- /dev/null
@@ -0,0 +1,21 @@
+package Web::Simple::DispatchNode;
+
+use Moo;
+
+extends 'Web::Dispatch::Node';
+
+has _app_object => (is => 'ro', init_arg => 'app_object', required => 1);
+
+around _curry => sub {
+  my ($orig, $self) = (shift, shift);
+  my $app = $self->_app_object;
+  my $class = ref($app);
+  my $inner = $self->$orig($app, @_);
+  sub {
+    no strict 'refs';
+    local *{"${class}::self"} = \$app;
+    $inner->(@_);
+  }
+};
+
+1;
index 14f38d7..8aa35f6 100644 (file)
@@ -6,12 +6,12 @@ use Test::More qw(no_plan);
 require_ok 'examples/bloggery/bloggery.cgi';
 
 __END__
-use Test::More (
-  eval { require HTTP::Request::AsCGI }
-    ? 'no_plan'
-    : (skip_all => 'No HTTP::Request::AsCGI')
-);
-  
+#use Test::More (
+#  eval { require HTTP::Request::AsCGI }
+#    ? 'no_plan'
+##    : (skip_all => 'No HTTP::Request::AsCGI')
+#);
+use HTTP::Request::AsCGI;  
 
 use HTTP::Request::Common qw(GET POST);
 
@@ -23,7 +23,7 @@ my $app = Bloggery->new(
 
 sub run_request {
   my $request = shift;
-  my $c = HTTP::Request::AsCGI->new($request)->setup;
+  my $c = HTTP::Request::AsCGI->new($request, SCRIPT_NAME=> $0)->setup;
   $app->run;
   $c->restore;
   return $c->response;
diff --git a/t/sub-dispatch-args.t b/t/sub-dispatch-args.t
new file mode 100644 (file)
index 0000000..ac5128b
--- /dev/null
@@ -0,0 +1,134 @@
+use strict;
+use warnings FATAL => 'all';
+
+use Data::Dump qw(dump);
+use Test::More (
+  eval { require HTTP::Request::AsCGI }
+    ? 'no_plan'
+    : (skip_all => 'No HTTP::Request::AsCGI')
+);
+
+{
+    use Web::Simple 't::Web::Simple::SubDispatchArgs';
+    package t::Web::Simple::SubDispatchArgs;
+
+    sub dispatch_request {
+        sub (/) {
+            $self->show_landing(@_);
+        },
+        sub(/...) {
+            sub (GET + /user) {
+                $self->show_users(@_);
+            },
+            sub (/user/*) {
+                sub (GET) {
+                    $self->show_user(@_);
+                },
+                sub (POST + %:id=&:@roles~) {
+                    $self->process_post(@_);
+                }
+            },
+        }
+    };
+
+    sub show_landing {
+        my ($self, @args) = @_;
+        return [
+            200, ['Content-Type' => 'application/perl' ],
+            [Data::Dump::dump @args],
+        ];
+    }
+    sub show_users {
+        my ($self, @args) = @_;
+        return [
+            200, ['Content-Type' => 'application/perl' ],
+            [Data::Dump::dump @args],
+        ];
+    }
+    sub show_user {
+        my ($self, @args) = @_;
+        return [
+            200, ['Content-Type' => 'application/perl' ],
+            [Data::Dump::dump @args],
+        ];
+    }
+    sub process_post {
+        my ($self, @args) = @_;
+        return [
+            200, ['Content-Type' => 'application/perl' ],
+            [Data::Dump::dump @args],
+        ];
+    }
+}
+
+ok my $app = t::Web::Simple::SubDispatchArgs->new,
+  'made app';
+
+sub run_request {
+  my @args = (shift, SCRIPT_NAME=> $0);
+  my $c = HTTP::Request::AsCGI->new(@args)->setup;
+  $app->run;
+  $c->restore;
+  return $c->response;
+}
+
+use HTTP::Request::Common qw(GET POST);
+
+ok my $get_landing = run_request(GET 'http://localhost/' ),
+  'got landing';
+
+cmp_ok $get_landing->code, '==', 200, 
+  '200 on GET';
+
+{
+    my ($self, $env, @noextra) = eval $get_landing->content;
+    is scalar(@noextra), 0, 'No extra stuff';
+    is ref($self), 't::Web::Simple::SubDispatchArgs', 'got object';
+    is ref($env), 'HASH', 'Got hashref';
+    is $env->{SCRIPT_NAME}, $0, 'correct scriptname';
+}
+
+ok my $get_users = run_request(GET 'http://localhost/user'),
+  'got user';
+
+cmp_ok $get_users->code, '==', 200, 
+  '200 on GET';
+
+{
+    my ($self, $env, @noextra) = eval $get_users->content;
+    is scalar(@noextra), 0, 'No extra stuff';
+    is ref($self), 't::Web::Simple::SubDispatchArgs', 'got object';
+    is ref($env), 'HASH', 'Got hashref';
+    is $env->{SCRIPT_NAME}, $0, 'correct scriptname';
+}
+
+ok my $get_user = run_request(GET 'http://localhost/user/42'),
+  'got user';
+
+cmp_ok $get_user->code, '==', 200, 
+  '200 on GET';
+
+{
+    my ($self, $env, @noextra) = eval $get_user->content;
+    is scalar(@noextra), 0, 'No extra stuff';
+    is ref($self), 't::Web::Simple::SubDispatchArgs', 'got object';
+    is ref($env), 'HASH', 'Got hashref';
+    is $env->{SCRIPT_NAME}, $0, 'correct scriptname';
+}
+
+ok my $post_user = run_request(POST 'http://localhost/user/42', [id => '99'] ),
+  'post user';
+
+cmp_ok $post_user->code, '==', 200, 
+  '200 on POST';
+
+{
+    my ($self, $params, $env, @noextra) = eval $post_user->content;
+    is scalar(@noextra), 0, 'No extra stuff';
+    is ref($self), 't::Web::Simple::SubDispatchArgs', 'got object';
+    is ref($params), 'HASH', 'Got POST hashref';
+    is $params->{id}, 99, 'got expected value for id';
+    is ref($env), 'HASH', 'Got hashref';
+    is $env->{SCRIPT_NAME}, $0, 'correct scriptname';
+}
+