/[Frey]/trunk/lib/Frey/Server.pm
This is repository of my old source code which isn't updated any more. Go to git.rot13.org for current projects!
ViewVC logotype

Diff of /trunk/lib/Frey/Server.pm

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

trunk/server.pl revision 9 by dpavlin, Sat Jun 28 18:49:47 2008 UTC trunk/lib/Frey/Server.pm revision 1158 by dpavlin, Thu Jul 2 15:30:30 2009 UTC
# Line 1  Line 1 
1  #!/usr/bin/perl  package Frey::Server;
2    
3  # "HTTP Push" is not readily attainable, so instead we will simulate it using a  use Moose;
4  # long-pull, aka "Comet". The client browser simply opens an HTTP connection to  extends 'Frey::Editor';
5  # the server and waits for a response. The server doesn't respond until there  with 'Frey::Config';
 # is some event (here a new message), giving the appearance of HTTP-push.  
 #  
 # Each user gets three continuations for these three cases:  
 #  
 #   - Initial load or reload of the page  
 #   - Sending a message (uses AJAX on the client)  
 #   - Recieving messages (uses COMET on the client)  
6    
 use strict;  
 use lib 'lib';  
 use Continuity;  
 use Continuity::REPL;  
7  use Data::Dump qw/dump/;  use Data::Dump qw/dump/;
8    
9  use View;  #use Carp::REPL; # 'nodie';
10    
11    use lib 'lib';
12    use Frey::Run;
13    
14    has 'port' => (
15            documentation => 'port on which server listen',
16            is => 'ro',
17            isa => 'Int',
18            default => sub {
19                    my $self = shift;
20                    $ENV{FREY_PORT} || $self->config->{port} || 16001
21            },
22    );
23    
24  use Template::Declare;  has 'editor' => (
25  use Template::Declare::Tags; # defaults to 'HTML'          is => 'ro',
26  Template::Declare->init( roots => ['View']);          isa => 'Frey::Editor',
27  warn "templates = ",dump( Template::Declare->templates );          lazy => 1,
28            default => sub {
29  my @messages;    # Global (shared) list of messages                  Frey::Editor->new;
30  my $got_message; # Flag to indicate that there is a new message to display          },
   
 use vars qw( $repl $server @messages );  
 $repl = Continuity::REPL->new;  
   
 $server = Continuity->new(  
   port => 16001,  
   path_session => 1,  
   cookie_session => 'sid',  
31  );  );
 $server->debug_level( 2 );  
32    
33  $server->loop;  =head2 request
34    
35  # This is the main entrypoint. We are looking for one of three things -- a  This is simple dispatcher for our server. Currently it's in flux and
36  # pushstream, a sent message, or a request for the main HTML. We delegate each  documented only in source code.
 # of these cases, none of which will return (they all loop forever).  
 sub main {  
   my ($req) = @_;  
     
   my $path = $req->request->url->path;  
   print STDERR "Path: '$path'\n";  
   
         warn $req->request->header('User_Agent');  
 #warn dump( $req );  
   
   # If this is a request for the pushtream, then give them that  
   if($path =~ /pushstream/) {  
     pushstream($req);  
   }  
     
   # If they are sending us a message, we give them a thread for that too  
   if($path =~ /sendmessage/) {  
     send_message($req);  
   }  
37    
38    # Otherwise, lets give them the base page    my $content_type = $self->request( $url, $params );
   send_base_page($req);  
 }  
39    
40  # Here we accept a connection to the browser, and keep it open. Meanwhile we  =cut
41  # watch the global $got_message variable, and when it gets touched we send off  
42  # the list of messages through the held-open connection. Then we let the  sub print {
43  # browser open a new connection and begin again.          my $self = shift;
44  sub pushstream {          warn "# print ", join(' ', map { length $_ } @_ );
45    my ($req) = @_;          $self->{_print}->( @_ );
   # Set up watch event -- this will be triggered when $got_message is written  
   my $w = Coro::Event->var(var => \$got_message, poll => 'w');  
   while(1) {  
     print STDERR "**** GOT MESSAGE, SENDING ****\n";  
     my $log = join "<br>", @messages;  
     $req->print($log);  
     $req->next;  
     print STDERR "**** Waiting for got_message indicator ****\n";  
     $w->next;  
   }  
46  }  }
47    
48    sub request {
49            my ( $self, $url, $params ) = @_;
50    
51            if ( my $ref = ref($url) ) {
52                    die "url not URI but ", dump( $url ) unless $ref =~ m{^URI};
53            } else {
54                    $url = URI->new($url);
55            }
56    
57            my $path = $url->path;
58    
59            if ( $path =~ m{^/(favicon.ico|__history__.html)$} ) {
60                    warn "INFO: $path ignored";
61                    return { code => 404, content_type => 'text/plain' };
62            }
63    
64            my $request = {
65                    content_type => 'text/html',
66                    code => 200,
67            };
68    
69            eval {
70    
71                    if ( $path =~ m{/reload(.*)} ) {
72    
73                            $ENV{FREY_NO_LOG} = 1;
74                            my $cmd = "perl -c $0";
75                            warn "# check syntax with $cmd";
76                            if ( system($cmd) == 0 ) {
77                                    my $server = Frey::Server->new;
78                                    $self->load_config;
79    #                               Module::Reload->check;
80                                    warn "# reload done";
81                                    $self->print( refresh( $1, 0 ) );
82                                    return;
83                            } else {
84                                    warn "ERROR: $?";
85                            }
86                            $ENV{FREY_NO_LOG} = 0;
87            
88                    } elsif ( $path =~ m{/exit(.*)} ) {
89                            # FIXME do we need some kind of check here for production? :-)
90                            # ./bin/dev.sh will restart us during development
91                            $self->print( refresh( $1, 2 ) );
92                            exit;
93                    }
94    
95                    my $html;
96    
97                    sub rest2class {
98                            my $class = shift;
99                            $class =~ s/-/::/; # sigh!
100                            return $class;
101                    }
102    
103                    my $f;
104    
105                    # shared run params
106                    my $run = {
107                            request_url => $url,
108    #                       debug => 1,
109                    };
110    
111                    if (
112                            $path =~ m{/Frey[:-]+ObjectBrowser}
113                    ) {
114                            $f = Frey::ObjectBrowser->new( fey_class => $params->{class} );
115    #                       $f->request( $req );
116                    } elsif (
117                            $path =~ m{/Frey[:-]+ObjectDesigner}
118                    ) {
119                            $f = Frey::ObjectDesigner->new( fey_class => $params->{class} );
120    #                       $f->request( $req );
121                    } elsif ( $path =~ $self->editor->url_regex ) {
122                            $self->print( $self->editor->command( $path ) );
123                            return;
124                    } elsif (
125                            $path =~ m{/([^/]+)/(\w+)/?([^/]+)?}
126                    ) {
127                            my $class = rest2class $1;
128                            warn "# run $path -> $class $2";
129                            $run->{format} = $3 if $3;
130                            foreach my $p ( keys %$params ) {
131                                    $run->{$p} = $params->{$p} if defined $params->{$p} && $params->{$p} ne '';
132                            }
133                            $f = Frey::Run->new( class => $class, params => $run, run => $2 );
134                    } elsif (
135                            $path =~ m{/([^/]+)/?$}
136                    ) {
137                            my $class = rest2class $1;
138                            warn "# introspect $class";
139                            $run->{class} ||= $class;
140                            $f = Frey::Run->new( class => 'Frey::Introspect', params => $run );
141                    } else {
142                            $f = Frey::Run->new( class => 'Frey::Class::Browser', params => $run );
143                    }
144    
145                    if ( $f ) {
146                            $f->setup_request;
147    #                       $f->add_status( { request => $req } );
148                            $f->status_parts;
149                            if ( my $html = $f->html ) {
150                                    warn "## html ",length($html)," bytes";
151                                    $self->print( $html );
152                            } else {
153                                    confess "no output from $f";
154                            }
155                    } else {
156                            confess "# can't call request on nothing!";
157                    }
158    
159                    $request->{content_type} = $f->content_type;
160            };
161    
162            if ( $@ ) {
163                    warn "SERVER ERROR: $@";
164                    $self->print( qq|<pre class="frey-error">$@<pre>| );
165    #               Carp::REPL::repl;
166                    return {
167                            content_type => 'text/html',
168                            code => 404,
169                    }
170            }
171    
172  # Watch for the user to send us a message. As soon as we get it, we add it to          return $request;
 # our list of messages and touch the $got_message flag to let all the  
 # pushstreams know.  
 sub send_message {  
   my ($req) = @_;  
   while(1) {  
     my $msg = $req->param('message');  
     my $name = $req->param('username');  
     if($msg) {  
       unshift @messages, "$name: $msg";  
       pop @messages if $#messages > 15; # Only keep the recent 15 messages  
     }  
     $got_message = 1;  
     $req->print("Got it!");  
     $req->next;  
   }  
173  }  }
174    
175  # This isn't a pushstream, nor a new message. It is just the main page. We loop  sub refresh {
176  # in case they ask for it multiple times :)          my ( $url, $time ) = @_;
177  sub send_base_page {          $url  ||= '/';
178    my ($req) = @_;          $time ||= 0;
179    while(1) {          warn "# refresh $url";
180          warn "base page";          qq|
181          $req->print( Template::Declare->show( 'user' ) );                  <html>
182  =for later                  <head>
183      $req->print(qq{                          <META HTTP-EQUIV="Refresh" CONTENT="$time; URL=$url"></META>
184        <html>                  </head>
185          <head>                  <body>
186            <title>Chat!</title>                          Refresh <a href="$url"><tt>$url</tt></a> in $time sec
187            <script src="jquery.js" type="text/javascript"></script>                  </body>
188            <script src="chat-ajax-push.js" type="text/javascript"></script>                  </html>
189          </head>                  \n\r\n\r
190          <body>          |; # XXX newlines at end are important to flush content to browser
           <form id=f>  
           <input type=text id=username name=usernamename size=10>  
           <input type=text id=message name=message size=50>  
           <input type=submit name="sendbutton" value="Send" id="sendbutton">  
           <span id=status></span>  
           </form>  
           <br>  
           <div id=log>-- no messages yet --</div>  
         </body>  
       </html>  
     });  
 =cut  
     $req->next;  
   }  
191  }  }
192    
193    __PACKAGE__->meta->make_immutable;
194    no Moose;
195    
196    my $timestamp_interval = 3;
197    my $output_tell = 0;
198    
199    $SIG{ALRM} = sub {
200            if ( tell(STDERR) != $output_tell ) {
201                    warn "\nTIMESTAMP: " . localtime() . "\n\n";
202                    $output_tell = tell(STDERR);
203            }
204            alarm $timestamp_interval;
205    };
206    alarm $timestamp_interval;
207    
208    1;

Legend:
Removed from v.9  
changed lines
  Added in v.1158

  ViewVC Help
Powered by ViewVC 1.1.26