/
Cookbook.pod
1924 lines (1375 loc) · 66.5 KB
/
Cookbook.pod
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
=encoding utf8
=head1 NAME
Mojolicious::Guides::Cookbook - Cooking with Mojolicious
=head1 OVERVIEW
This document contains many fun recipes for cooking with L<Mojolicious>.
=head1 CONCEPTS
Essentials every L<Mojolicious> developer should know.
=head2 Blocking and non-blocking operations
A I<blocking> operation is a subroutine that blocks the execution of the calling subroutine until the subroutine is
finished.
sub foo {
my $result = blocking_subroutine();
...
}
A I<non-blocking> operation on the other hand lets the calling subroutine continue execution even though the subroutine
is not yet finished. Instead of waiting, the calling subroutine passes along a callback to be executed once the
subroutine is finished, this is called continuation-passing style.
sub foo {
non_blocking_subroutine(sub ($result) {
...
});
...
}
While L<Mojolicious> has been designed from the ground up for non-blocking I/O and event loops, it is not possible to
magically make Perl code non-blocking. You have to use specialized non-blocking code available through modules like
L<Mojo::IOLoop> and L<Mojo::UserAgent>, or third-party event loops. You can wrap your blocking code in
L<subprocesses|Mojo::IOLoop/"subprocess"> though to prevent it from interfering with your non-blocking code.
=head2 Event loops
An event loop is basically a loop that continually tests for external events and executes the appropriate callbacks to
handle them, it is often the main loop in a program. Non-blocking tests for readability/writability of file descriptors
and timers are commonly used events for highly scalable network servers, because they allow a single process to handle
thousands of client connections concurrently.
while (1) {
my @readable = test_fds_for_readability();
handle_readable_fds(@readable);
my @writable = test_fds_for_writability();
handle_writable_fds(@writable);
my @expired = test_timers();
handle_timers(@expired);
}
In L<Mojolicious> this event loop is L<Mojo::IOLoop>.
=head2 Reverse proxy
A reverse proxy architecture is a deployment technique used in many production environments, where a I<reverse proxy>
server is put in front of your application to act as the endpoint accessible by external clients. It can provide a lot
of benefits, like terminating SSL connections from the outside, limiting the number of concurrent open sockets towards
the Mojolicious application (or even using Unix sockets), balancing load across multiple instances, or supporting
several applications through the same IP/port.
..........................................
: :
+--------+ : +-----------+ +---------------+ :
| |-------->| | | | :
| client | : | reverse |----->| Mojolicious | :
| |<--------| proxy | | application | :
+--------+ : | |<-----| | :
: +-----------+ +---------------+ :
: :
.. system boundary (e.g. same host) ......
This setup introduces some problems, though: the application will receive requests from the reverse proxy instead of
the original client; the address/hostname where your application lives internally will be different from the one
visible from the outside; and if terminating SSL, the reverse proxy exposes services via HTTPS while using HTTP towards
the Mojolicious application.
As an example, compare a sample request from the client and what the Mojolicious application receives:
client reverse proxy Mojolicious app
__|__ _______________|______________ ____|____
/ \ / \ / \
1.2.3.4 --HTTPS--> api.example.com 10.20.30.39 --HTTP--> 10.20.30.40
GET /foo/1 HTTP/1.1 | GET /foo/1 HTTP/1.1
Host: api.example.com | Host: 10.20.30.40
User-Agent: Firefox | User-Agent: ShinyProxy/1.2
... | ...
However, now the client address is no longer available (which might be useful for analytics, or Geo-IP) and URLs
generated via L<Mojolicious::Controller/"url_for"> will look like this:
http://10.20.30.40/bar/2
instead of something meaningful for the client, like this:
https://api.example.com/bar/2
To solve these problems, you can configure your reverse proxy to send the missing data (see L</Nginx> and
L</"Apache/mod_proxy">) and tell your application about it by setting the environment variable C<MOJO_REVERSE_PROXY>.
In more complex situations, usually involving multiple proxies or proxies that live outside your network, it can be
necessary to tell the application from which ip addresses to expect proxy requests by setting C<MOJO_TRUSTED_PROXIES>
to a list of comma separated addresses or CIDR networks. For even finer control, L</Rewriting> includes examples of how
the changes could be implemented manually.
=head1 DEPLOYMENT
Getting L<Mojolicious> and L<Mojolicious::Lite> applications running on different platforms. Note that many real-time
web features are based on the L<Mojo::IOLoop> event loop, and therefore require one of the built-in web servers to be
able to use them to their full potential.
=head2 Built-in web server
L<Mojolicious> contains a very portable non-blocking I/O HTTP and WebSocket server with L<Mojo::Server::Daemon>. It is
usually used during development and in the construction of more advanced web servers, but is solid and fast enough for
small to mid sized applications.
$ ./script/my_app daemon
Web application available at http://127.0.0.1:3000
It is available to every application through the command L<Mojolicious::Command::daemon>, which has many configuration
options and is known to work on every platform Perl works on with its single-process architecture.
$ ./script/my_app daemon -h
...List of available options...
Another huge advantage is that it supports TLS and WebSockets out of the box, a development certificate for testing
purposes is built right in, so it just works, but you can specify all listen locations supported by
L<Mojo::Server::Daemon/"listen">.
$ ./script/my_app daemon -l https://[::]:3000
Web application available at https://[::]:3000
To manage the web server with systemd, you can use a unit configuration file like this.
[Unit]
Description=My Mojolicious application
After=network.target
[Service]
Type=simple
User=sri
ExecStart=/home/sri/myapp/script/my_app daemon -m production -l http://*:8080
[Install]
WantedBy=multi-user.target
=head2 Pre-forking
For bigger applications L<Mojolicious> contains the UNIX optimized pre-forking web server L<Mojo::Server::Prefork>,
which can take advantage of multiple CPU cores and copy-on-write memory management to scale up to thousands of
concurrent client connections.
Mojo::Server::Prefork
|- Mojo::Server::Daemon [1]
|- Mojo::Server::Daemon [2]
|- Mojo::Server::Daemon [3]
+- Mojo::Server::Daemon [4]
It is based on L<Mojo::Server::Daemon> and available to every application through the command
L<Mojolicious::Command::prefork>.
$ ./script/my_app prefork
Web application available at http://127.0.0.1:3000
Since all built-in web servers are based on the L<Mojo::IOLoop> event loop, they scale best with non-blocking
operations. But if your application for some reason needs to perform many blocking operations, you can improve
performance by increasing the number of worker processes and decreasing the number of concurrent connections each
worker is allowed to handle (often as low as C<1>).
$ ./script/my_app prefork -m production -w 10 -c 1
Web application available at http://127.0.0.1:3000
During startup your application is preloaded in the manager process, which does not run an event loop, so you can use
L<Mojo::IOLoop/"next_tick"> to run code whenever a new worker process has been forked and its event loop gets started.
use Mojolicious::Lite;
Mojo::IOLoop->next_tick(sub ($ioloop) {
app->log->info("Worker $$ star...ALL GLORY TO THE HYPNOTOAD!");
});
get '/' => {text => 'Hello Wor...ALL GLORY TO THE HYPNOTOAD!'};
app->start;
And to manage the pre-forking web server with systemd, you can use a unit configuration file like this.
[Unit]
Description=My Mojolicious application
After=network.target
[Service]
Type=simple
User=sri
ExecStart=/home/sri/myapp/script/my_app prefork -m production -l http://*:8080
[Install]
WantedBy=multi-user.target
=head2 Morbo
After reading the L<Mojolicious::Guides::Tutorial>, you should already be familiar with L<Mojo::Server::Morbo>.
Mojo::Server::Morbo
+- Mojo::Server::Daemon
It is basically a restarter that forks a new L<Mojo::Server::Daemon> web server whenever a file in your project
changes, and should therefore only be used during development. To start applications with it you can use the L<morbo>
script.
$ morbo ./script/my_app
Web application available at http://127.0.0.1:3000
=head2 Containers
There are many ways to go cloud-native with L<Mojolicious>. To get you started with containerizing your web applications
we will explore one of them in this recipe. First, you will need to declare the CPAN dependencies of your application,
for example in a C<Makefile.PL> file. This should always include at the very least L<Mojolicious> itself.
use strict;
use warnings;
use ExtUtils::MakeMaker;
WriteMakefile(
VERSION => '0.01',
PREREQ_PM => {
'Mojolicious' => '8.65',
'Mojolicious::Plugin::Status' => '1.12'
},
test => {TESTS => 't/*.t'}
);
The helper command L<Mojolicious::Command::Author::generate::makefile> can also generate a minimal C<Makefile.PL> for
you.
$ ./myapp.pl generate makefile
...
And then we are going to need a C<Dockerfile> describing the container. A very simple one will do for now.
FROM perl
WORKDIR /opt/myapp
COPY . .
RUN cpanm --installdeps -n .
EXPOSE 3000
CMD ./myapp.pl prefork
It uses the latest L<Perl container|https://hub.docker.com/_/perl> from Docker Hub, copies all the contents of your
application directory into the container, installs CPAN dependencies with L<App::cpanminus>, and then starts the
application on port C<3000> with the pre-forking web server. With L<Mojolicious::Command::Author::generate::dockerfile>
there is also a helper command to generate a minimal C<Dockerfile> for you.
$ ./myapp.pl generate dockerfile
...
To build and deploy our container there are also many options available, here we will simply use Docker.
$ docker build -t myapp_image .
...
$ docker run -d -p 3000:3000 --name myapp_container myapp_image
...
And now your web application should be deployed as a container under C<http://127.0.0.1:3000>. For more information and
many more container deployment options we recommend the L<Docker|https://docs.docker.com/> and
L<Kubernetes|https://kubernetes.io/docs/> documentation.
=head2 Hypnotoad
L<Hypnotoad|Mojo::Server::Hypnotoad> is based on the L<Mojo::Server::Prefork> web server, and adds some features
especially optimized for high availability non-containerized production environments. To start applications with it you
can use the L<hypnotoad> script, which listens on port C<8080>, automatically daemonizes the server process and defaults
to C<production> mode for L<Mojolicious> and L<Mojolicious::Lite> applications.
$ hypnotoad ./script/my_app
Many configuration settings can be tweaked right from within your application with L<Mojolicious/"config">, for a full
list see L<Mojo::Server::Hypnotoad/"SETTINGS">.
use Mojolicious::Lite;
app->config(hypnotoad => {listen => ['http://*:80']});
get '/' => {text => 'Hello Wor...ALL GLORY TO THE HYPNOTOAD!'};
app->start;
Or just add a C<hypnotoad> section to your L<Mojolicious::Plugin::Config>, L<Mojolicious::Plugin::JSONConfig> or
L<Mojolicious::Plugin::NotYAMLConfig> configuration file.
# myapp.conf
{
hypnotoad => {
listen => ['https://*:443?cert=/etc/server.crt&key=/etc/server.key'],
workers => 10
}
};
But one of its biggest advantages is the support for effortless zero downtime software upgrades (hot deployment). That
means you can upgrade L<Mojolicious>, Perl or even system libraries at runtime without ever stopping the server or
losing a single incoming connection, just by running the command above again.
$ hypnotoad ./script/my_app
Starting hot deployment for Hypnotoad server 31841.
You might also want to enable proxy support if you're using L<Hypnotoad|Mojo::Server::Hypnotoad> behind a reverse
proxy. This allows L<Mojolicious> to automatically pick up the C<X-Forwarded-For> and C<X-Forwarded-Proto> headers.
# myapp.conf
{hypnotoad => {proxy => 1}};
To manage L<Hypnotoad|Mojo::Server::Hypnotoad> with systemd, you can use a unit configuration file like this.
[Unit]
Description=My Mojolicious application
After=network.target
[Service]
Type=forking
User=sri
PIDFile=/home/sri/myapp/script/hypnotoad.pid
ExecStart=/path/to/hypnotoad /home/sri/myapp/script/my_app
ExecReload=/path/to/hypnotoad /home/sri/myapp/script/my_app
KillMode=process
[Install]
WantedBy=multi-user.target
=head2 Zero downtime software upgrades
L<Hypnotoad|Mojo::Server::Hypnotoad> makes zero downtime software upgrades (hot deployment) very simple, as you can see
above, but on modern operating systems that support the C<SO_REUSEPORT> socket option, there is also another method
available that works with all built-in web servers.
$ ./script/my_app prefork -P /tmp/first.pid -l http://*:8080?reuse=1
Web application available at http://127.0.0.1:8080
All you have to do, is to start a second web server listening to the same port, and stop the first web server
gracefully afterwards.
$ ./script/my_app prefork -P /tmp/second.pid -l http://*:8080?reuse=1
Web application available at http://127.0.0.1:8080
$ kill -s TERM `cat /tmp/first.pid`
Just remember that both web servers need to be started with the C<reuse> parameter.
=head2 Nginx
One of the most popular setups these days is L<Hypnotoad|Mojo::Server::Hypnotoad> behind an L<Nginx|https://nginx.org>
reverse proxy, which even supports WebSockets in newer versions.
upstream myapp {
server 127.0.0.1:8080;
}
server {
listen 80;
server_name localhost;
location / {
proxy_pass http://myapp;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
=head2 Apache/mod_proxy
Another good reverse proxy is L<Apache|https://httpd.apache.org> with C<mod_proxy>, the configuration looks quite
similar to the Nginx one above. And if you need WebSocket support, newer versions come with C<mod_proxy_wstunnel>.
<VirtualHost *:80>
ServerName localhost
<Proxy *>
Require all granted
</Proxy>
ProxyRequests Off
ProxyPreserveHost On
ProxyPass /echo ws://localhost:8080/echo
ProxyPass / http://localhost:8080/ keepalive=On
ProxyPassReverse / http://localhost:8080/
RequestHeader set X-Forwarded-Proto "http"
</VirtualHost>
=head2 Apache/CGI
C<CGI> is supported out of the box and your L<Mojolicious> application will automatically detect that it is executed as
a C<CGI> script. Its use in production environments is discouraged though, because as a result of how C<CGI> works, it
is very slow and many web servers are making it exceptionally hard to configure properly. Additionally, many real-time
web features, such as WebSockets, are not available.
ScriptAlias / /home/sri/my_app/script/my_app/
=head2 Envoy
L<Mojolicious> applications can be deployed on cloud-native environments that use L<Envoy|https://www.envoyproxy.io>,
such as with this reverse proxy configuration similar to the Apache and Nginx ones above.
static_resources:
listeners:
- name: listener_0
address:
socket_address: { address: 0.0.0.0, port_value: 80 }
filter_chains:
- filters:
- name: envoy.filters.network.http_connection_manager
typed_config:
"@type": type.googleapis.com/envoy.extensions.filters.network.http_connection_manager.v3.HttpConnectionManager
codec_type: auto
stat_prefix: index_http
route_config:
name: local_route
virtual_hosts:
- name: service
domains: ["*"]
routes:
- match:
prefix: "/"
route:
cluster: local_service
upgrade_configs:
- upgrade_type: websocket
http_filters:
- name: envoy.filters.http.router
typed_config:
clusters:
- name: local_service
connect_timeout: 0.25s
type: strict_dns
lb_policy: round_robin
load_assignment:
cluster_name: local_service
endpoints:
- lb_endpoints:
- endpoint:
address:
socket_address: { address: mojo, port_value: 8080 }
While this configuration works for simple applications, Envoy's typical use case is for implementing proxies of
applications as a "service mesh" providing advanced filtering, load balancing, and observability features, such as
seen in L<Istio|https://istio.io/latest/docs/ops/deployment/architecture/>. For more examples, visit the
L<Envoy documentation|https://www.envoyproxy.io/docs/envoy/latest/start/start>.
=head2 PSGI/Plack
L<PSGI> is an interface between Perl web frameworks and web servers, and L<Plack> is a Perl module and toolkit that
contains L<PSGI> middleware, helpers and adapters to web servers. L<PSGI> and L<Plack> are inspired by Python's WSGI
and Ruby's Rack. L<Mojolicious> applications are ridiculously simple to deploy with L<Plack>, but be aware that many
real-time web features, such as WebSockets, are not available.
$ plackup ./script/my_app
L<Plack> provides many server and protocol adapters for you to choose from, such as C<FCGI>, C<uWSGI> and C<mod_perl>.
$ plackup ./script/my_app -s FCGI -l /tmp/myapp.sock
The C<MOJO_REVERSE_PROXY> environment variable can be used to enable proxy support, this allows L<Mojolicious> to
automatically pick up the C<X-Forwarded-For> and C<X-Forwarded-Proto> headers.
$ MOJO_REVERSE_PROXY=1 plackup ./script/my_app
If an older server adapter is unable to correctly detect the application home directory, you can simply use the
C<MOJO_HOME> environment variable.
$ MOJO_HOME=/home/sri/my_app plackup ./script/my_app
There is no need for a C<.psgi> file, just point the server adapter at your application script, it will automatically
act like one if it detects the presence of a C<PLACK_ENV> environment variable.
=head2 Plack middleware
Wrapper scripts like C<myapp.fcgi> are a great way to separate deployment and application logic.
#!/usr/bin/env plackup -s FCGI
use Plack::Builder;
builder {
enable 'Deflater';
require './script/my_app';
};
L<Mojo::Server::PSGI> can be used directly to load and customize applications in the wrapper script.
#!/usr/bin/env plackup -s FCGI
use Mojo::Server::PSGI;
use Plack::Builder;
builder {
enable 'Deflater';
my $server = Mojo::Server::PSGI->new;
$server->load_app('./script/my_app');
$server->app->config(foo => 'bar');
$server->to_psgi_app;
};
But you could even use middleware right in your application.
use Mojolicious::Lite -signatures;
use Plack::Builder;
get '/welcome' => sub ($c) {
$c->render(text => 'Hello Mojo!');
};
builder {
enable 'Deflater';
app->start;
};
=head2 Rewriting
Sometimes you might have to deploy your application in a blackbox environment where you can't just change the server
configuration or behind a reverse proxy that passes along additional information with C<X-Forwarded-*> headers. In such
cases you can use the hook L<Mojolicious/"before_dispatch"> to rewrite incoming requests.
# Change scheme if "X-Forwarded-HTTPS" header is set
$app->hook(before_dispatch => sub ($c) {
$c->req->url->base->scheme('https')
if $c->req->headers->header('X-Forwarded-HTTPS');
});
Since reverse proxies generally don't pass along information about path prefixes your application might be deployed
under, rewriting the base path of incoming requests is also quite common. This allows
L<Mojolicious::Controller/"url_for"> for example, to generate portable URLs based on the current environment.
# Move first part and slash from path to base path in production mode
$app->hook(before_dispatch => sub ($c) {
push @{$c->req->url->base->path->trailing_slash(1)},
shift @{$c->req->url->path->leading_slash(0)};
}) if $app->mode eq 'production';
L<Mojo::URL> objects are very easy to manipulate, just make sure that the URL (C<foo/bar?baz=yada>), which represents
the routing destination, is always relative to the base URL (C<http://example.com/myapp/>), which represents the
deployment location of your application.
=head2 Deployment specific plugins
Deployment specific 3rd party plugins such as L<Mojolicious::Plugin::SetUserGroup> do not need to be included in your
application code. They can also be loaded later on via the reserved C<plugins> value for L<Mojolicious> applications
that are using any one of the built-in configuration plugins L<Mojolicious::Plugin::Config>,
L<Mojolicious::Plugin::JSONConfig> or L<Mojolicious::Plugin::NotYAMLConfig>.
# myapp.conf
{
plugins => [
{SetUserGroup => {user => 'sri', group => 'staff'}}
]
};
=head2 Application embedding
From time to time you might want to reuse parts of L<Mojolicious> applications like configuration files, database
connection or helpers for other scripts, with this little L<Mojo::Server> based mock server you can just embed them.
use Mojo::Server;
# Load application with mock server
my $server = Mojo::Server->new;
my $app = $server->load_app('./myapp.pl');
# Access fully initialized application
say for @{$app->static->paths};
say $app->config->{secret_identity};
say $app->dumper({just => 'a helper test'});
say $app->build_controller->render_to_string(template => 'foo');
The plugin L<Mojolicious::Plugin::Mount> uses this functionality to allow you to combine multiple applications into one
and deploy them together.
use Mojolicious::Lite;
app->config(hypnotoad => {listen => ['http://*:80']});
plugin Mount => {'test1.example.com' => '/home/sri/myapp1.pl'};
plugin Mount => {'test2.example.com' => '/home/sri/myapp2.pl'};
app->start;
=head2 Web server embedding
You can also use L<Mojo::IOLoop/"one_tick"> to embed the built-in web server L<Mojo::Server::Daemon> into alien
environments like foreign event loops that for some reason can't just be integrated with a new reactor backend.
use Mojolicious::Lite;
use Mojo::IOLoop;
use Mojo::Server::Daemon;
# Normal action
get '/' => {text => 'Hello World!'};
# Connect application with web server and start accepting connections
my $daemon = Mojo::Server::Daemon->new(app => app, listen => ['http://*:8080']);
$daemon->start;
# Call "one_tick" repeatedly from the alien environment
Mojo::IOLoop->one_tick while 1;
=head1 REAL-TIME WEB
The real-time web is a collection of technologies that include Comet (long polling), EventSource and WebSockets, which
allow content to be pushed to consumers with long-lived connections as soon as it is generated, instead of relying on
the more traditional pull model. All built-in web servers use non-blocking I/O and are based on the L<Mojo::IOLoop>
event loop, which provides many very powerful features that allow real-time web applications to scale up to thousands
of concurrent client connections.
=head2 Backend web services
Since L<Mojo::UserAgent> is also based on the L<Mojo::IOLoop> event loop, it won't block the built-in web servers when
used non-blocking, even for high latency backend web services.
use Mojolicious::Lite -signatures;
# Search MetaCPAN for "mojolicious"
get '/' => sub ($c) {
$c->ua->get('fastapi.metacpan.org/v1/module/_search?q=mojolicious' => sub ($ua, $tx) {
$c->render('metacpan', hits => $tx->result->json->{hits}{hits});
});
};
app->start;
__DATA__
@@ metacpan.html.ep
<!DOCTYPE html>
<html>
<head><title>MetaCPAN results for "mojolicious"</title></head>
<body>
% for my $hit (@$hits) {
<p><%= $hit->{_source}{release} %></p>
% }
</body>
</html>
The callback passed to L<Mojo::UserAgent/"get"> will be executed once the request to the backend web service has been
finished, this is called continuation-passing style.
=head2 Synchronizing non-blocking operations
Multiple non-blocking operations, such as concurrent requests, can be easily synchronized with promises and
L<Mojo::Promise/"all">. You create L<Mojo::Promise> objects manually or use methods like L<Mojo::UserAgent/"get_p">
that create them for you.
use Mojolicious::Lite -signatures;
use Mojo::Promise;
use Mojo::URL;
# Search MetaCPAN for "mojo" and "minion"
get '/' => sub ($c) {
# Create two promises
my $url = Mojo::URL->new('http://fastapi.metacpan.org/v1/module/_search');
my $mojo = $c->ua->get_p($url->clone->query({q => 'mojo'}));
my $minion = $c->ua->get_p($url->clone->query({q => 'minion'}));
# Render a response once both promises have been resolved
Mojo::Promise->all($mojo, $minion)->then(sub ($mojo, $minion) {
$c->render(json => {
mojo => $mojo->[0]->result->json('/hits/hits/0/_source/release'),
minion => $minion->[0]->result->json('/hits/hits/0/_source/release')
});
})->catch(sub ($err) {
$c->reply->exception($err);
})->wait;
};
app->start;
To create promises manually you just wrap your continuation-passing style APIs in functions that return promises.
Here's an example for how L<Mojo::UserAgent/"get_p"> works internally.
use Mojo::UserAgent;
use Mojo::Promise;
# Wrap a user agent method with a promise
my $ua = Mojo::UserAgent->new;
sub get_p {
my $promise = Mojo::Promise->new;
$ua->get(@_ => sub ($ua, $tx) {
my $err = $tx->error;
$promise->resolve($tx) if !$err || $err->{code};
$promise->reject($err->{message});
});
return $promise;
}
# Use our new promise generating function
get_p('https://mojolicious.org')->then(sub ($tx) {
say $tx->result->dom->at('title')->text;
})->wait;
Promises have three states, they start out as C<pending> and you call L<Mojo::Promise/"resolve"> to transition them to
C<fulfilled>, or L<Mojo::Promise/"reject"> to transition them to C<rejected>.
=head2 async/await
And if you have L<Future::AsyncAwait> installed you can make using promises even easier. The C<async> and C<await>
keywords are enabled with the C<-async_await> flag of L<Mojo::Base>, and make the use of closures with promises
completely optional.
use Mojo::Base -strict, -async_await;
The C<async> keyword is placed before the C<sub> keyword, and means that this function always returns a promise.
Returned values that are not L<Mojo::Promise> objects will be wrapped in a resolved promise automatically. And if an
exception gets thrown in the function it will result in a rejected promise.
use Mojo::Base -strict, -async_await;
async sub hello_p {
return 'Hello Mojo!';
}
hello_p()->then(sub { say @_ })->wait;
The C<await> keyword on the other hand makes Perl wait for the promise to be settled. It then returns the fulfillment
values or throws an exception with the rejection reason. While waiting, the event loop is free to perform other tasks
however, so no resources are wasted.
use Mojo::Base -strict, -signatures, -async_await;
use Mojo::UserAgent;
use Mojo::URL;
my $ua = Mojo::UserAgent->new;
# Search MetaCPAN non-blocking for multiple terms sequentially
async sub search_cpan_p ($terms) {
my $cpan = Mojo::URL->new('http://fastapi.metacpan.org/v1/module/_search');
my @urls = map { $cpan->clone->query(q => $_) } @$terms;
for my $url (@urls) {
my $tx = await $ua->get_p($url);
say $tx->result->json('/hits/hits/0/_source/release');
}
}
search_cpan_p(['mojo', 'minion'])->wait;
The loop above performs all requests sequentially, awaiting a result before sending the next request. But you can also
perform those requests concurrently instead, by using methods like L<Mojo::Promise/"all"> to combine multiple promises
before awaiting the results.
use Mojo::Base -strict, -signatures, -async_await;
use Mojo::Promise;
use Mojo::UserAgent;
use Mojo::URL;
my $ua = Mojo::UserAgent->new;
# Search MetaCPAN non-blocking for multiple terms concurrently
async sub search_cpan_p ($terms) {
my $cpan = Mojo::URL->new('http://fastapi.metacpan.org/v1/module/_search');
my @urls = map { $cpan->clone->query(q => $_) } @$terms;
my @promises = map { $ua->get_p($_) } @urls;
my @results = await Mojo::Promise->all(@promises);
for my $result (@results) {
say $result->[0]->result->json('/hits/hits/0/_source/release');
}
}
search_cpan_p(['mojo', 'minion'])->wait;
All of this also means that you can use normal Perl exception handling again. Even many 3rd party exception handling
modules from CPAN work just fine.
use Mojo::Base -strict, -async_await;
use Mojo::Promise;
# Catch a non-blocking exception
async sub hello_p {
eval { await Mojo::Promise->reject('This is an exception') };
if (my $err = $@) { warn "Error: $err" }
}
hello_p()->wait;
And it works just the same in L<Mojolicious> and L<Mojolicious::Lite> applications. Just declare your actions with the
C<async> keyword and use C<await> to wait for promises to be C<fulfilled> or C<rejected>.
use Mojolicious::Lite -signatures, -async_await;
# Request HTML titles from two sites non-blocking
get '/' => async sub ($c) {
my $mojo_tx = await $c->ua->get_p('https://mojolicious.org');
my $mojo_title = $mojo_tx->result->dom->at('title')->text;
my $cpan_tx = await $c->ua->get_p('https://metacpan.org');
my $cpan_title = $cpan_tx->result->dom->at('title')->text;
$c->render(json => {mojo => $mojo_title, cpan => $cpan_title});
};
app->start;
Promises returned by actions will automatically get the default L<Mojolicious> exception handler attached. Making it
much harder to ever miss a non-blocking exception again, even if you forgot to handle it yourself.
=head2 Timers
Timers, another primary feature of the event loop, are created with L<Mojo::IOLoop/"timer"> and can, for example, be
used to delay rendering of a response, and unlike C<sleep>, won't block any other requests that might be processed
concurrently.
use Mojolicious::Lite -signatures;
use Mojo::IOLoop;
# Wait 3 seconds before rendering a response
get '/' => sub ($c) {
Mojo::IOLoop->timer(3 => sub ($ioloop) {
$c->render(text => 'Delayed by 3 seconds!');
});
};
app->start;
Recurring timers created with L<Mojo::IOLoop/"recurring"> are slightly more powerful, but need to be stopped manually,
or they would just keep getting emitted.
use Mojolicious::Lite -signatures;
use Mojo::IOLoop;
# Count to 5 in 1 second steps
get '/' => sub ($c) {
# Start recurring timer
my $i = 1;
my $id = Mojo::IOLoop->recurring(1 => sub ($ioloop) {
$c->write_chunk($i);
$c->finish if $i++ == 5;
});
# Stop recurring timer
$c->on(finish => sub ($c) { Mojo::IOLoop->remove($id) });
};
app->start;
Timers are not tied to a specific request or connection, and can even be created at startup time.
use Mojolicious::Lite -signatures;
use Mojo::IOLoop;
# Check title in the background every 10 seconds
my $title = 'Got no title yet.';
Mojo::IOLoop->recurring(10 => sub ($ioloop) {
app->ua->get('https://mojolicious.org' => sub ($ua, $tx) {
$title = $tx->result->dom->at('title')->text;
});
});
# Show current title
get '/' => sub ($c) {
$c->render(json => {title => $title});
};
app->start;
Just remember that all these non-blocking operations are processed cooperatively, so your callbacks shouldn't block for
too long.
=head2 Subprocesses
You can also use subprocesses, created with L<Mojo::IOLoop/"subprocess">, to perform computationally expensive
operations without blocking the event loop.
use Mojolicious::Lite -signatures;
use Mojo::IOLoop;
# Operation that would block the event loop for 5 seconds
get '/' => sub ($c) {
Mojo::IOLoop->subprocess->run_p(sub {
sleep 5;
return '♥', 'Mojolicious';
})->then(sub (@results) {
$c->render(text => "I $results[0] $results[1]!");
})->catch(sub ($err) {
$c->reply->exception($err);
});
};
app->start;
The callback passed to L<Mojo::IOLoop::Subprocess/"run_p"> will be executed in a child process, without blocking the
event loop of the parent process. The results of the callback will then be shared between both processes, and the
promise fulfilled or rejected in the parent process.
=head2 Exceptions in non-blocking operations
Since timers and other non-blocking operations are running solely in the event loop, outside of the application,
exceptions that get thrown in callbacks can't get caught and handled automatically. But you can handle them manually by
subscribing to the event L<Mojo::Reactor/"error"> or catching them inside the callback.
use Mojolicious::Lite -signatures;
use Mojo::IOLoop;
# Forward error messages to the application log
Mojo::IOLoop->singleton->reactor->on(error => sub ($reactor, $err) {
app->log->error($err);
});
# Exception only gets logged (and connection times out)
get '/connection_times_out' => sub ($c) {
Mojo::IOLoop->timer(2 => sub ($ioloop) {
die 'This request will not be getting a response';
});
};
# Exception gets caught and handled
get '/catch_exception' => sub ($c) {
Mojo::IOLoop->timer(2 => sub ($ioloop) {
eval { die 'This request will be getting a response' };
$c->reply->exception($@) if $@;
});
};
app->start;
A default subscriber that turns all errors into warnings will usually be added by L<Mojo::IOLoop> as a fallback.
Mojo::IOLoop->singleton->reactor->unsubscribe('error');
During development or for applications where crashing is simply preferable, you can also make every exception that gets
thrown in a callback fatal by removing all of its subscribers.
=head2 WebSocket web service
The WebSocket protocol offers full bi-directional low-latency communication channels between clients and servers.
Receive messages just by subscribing to events such as L<Mojo::Transaction::WebSocket/"message"> with
L<Mojolicious::Controller/"on"> and return them with L<Mojolicious::Controller/"send">.
use Mojolicious::Lite -signatures;
# Template with browser-side code
get '/' => 'index';
# WebSocket echo service
websocket '/echo' => sub ($c) {
# Opened
$c->app->log->debug('WebSocket opened');
# Increase inactivity timeout for connection a bit
$c->inactivity_timeout(300);
# Incoming message
$c->on(message => sub ($c, $msg) {
$c->send("echo: $msg");
});
# Closed
$c->on(finish => sub ($c, $code, $reason = undef) {
$c->app->log->debug("WebSocket closed with status $code");
});
};
app->start;
__DATA__
@@ index.html.ep
<!DOCTYPE html>
<html>
<head><title>Echo</title></head>
<body>
<script>
const ws = new WebSocket('<%= url_for('echo')->to_abs %>');
// Incoming messages
ws.onmessage = function (event) {
document.body.innerHTML += event.data + '<br/>';
};
// Outgoing messages
ws.onopen = function (event) {
window.setInterval(function () { ws.send('Hello Mojo!') }, 1000);
};
</script>
</body>
</html>
The event L<Mojo::Transaction::WebSocket/"finish"> will be emitted right after the WebSocket connection has been
closed.
$c->tx->with_compression;
You can activate C<permessage-deflate> compression with L<Mojo::Transaction::WebSocket/"with_compression">, this can
result in much better performance, but also increases memory usage by up to 300KiB per connection.
my $proto = $c->tx->with_protocols('v2.proto', 'v1.proto');
You can also use L<Mojo::Transaction::WebSocket/"with_protocols"> to negotiate a subprotocol.