Web/MREST.pm

filter: Statementstmt 64.6% 42 / 65 Branchbran 15.0% 3 / 20 Conditioncond 0.0% 0 / 6 MC/DCmcdc 0.0% 0 / 4 Subroutinesub 100% 12 / 12 Podpod 100% 2 / 2 totaltotal 54.1% 59 / 109 CC 14 SCAR 41.0
CC
14
Cov
49%
init
106.9
BEGIN
1.0
BEGIN
1.0
CRAP 60.3
↑ Summary Web/MREST/Dispatch.pm »
1 # *************************************************************************
2 # Copyright (c) 2014-2022, SUSE LLC
3 #
4 # All rights reserved.
5 #
6 # Redistribution and use in source and binary forms, with or without
7 # modification, are permitted provided that the following conditions are met:
8 #
9 # 1. Redistributions of source code must retain the above copyright notice,
10 # this list of conditions and the following disclaimer.
11 #
12 # 2. Redistributions in binary form must reproduce the above copyright
13 # notice, this list of conditions and the following disclaimer in the
14 # documentation and/or other materials provided with the distribution.
15 #
16 # 3. Neither the name of SUSE LLC nor the names of its contributors may be
17 # used to endorse or promote products derived from this software without
18 # specific prior written permission.
19 #
20 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
21 # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22 # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23 # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
24 # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
25 # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
26 # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
27 # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
28 # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
29 # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
30 # POSSIBILITY OF SUCH DAMAGE.
31 # *************************************************************************
32  
33 package Web::MREST;
34  
35 22 ▶use 5.012;
Subroutine BEGIN: called CC=1 SCAR=0.0
36 22 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
37 22 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
38  
39 22 ▶use App::CELL qw( $CELL $log $meta $core $site );
Subroutine BEGIN: called CC=1 SCAR=0.0
40 22 ▶use App::CELL::Test qw( _touch );
Subroutine BEGIN: called CC=1 SCAR=0.0
41 22 ▶use Data::Dumper;
Subroutine BEGIN: called CC=1 SCAR=0.0
42 22 ▶use File::ShareDir;
Subroutine BEGIN: called CC=1 SCAR=0.0
43 22 ▶use Log::Any::Adapter;
Subroutine BEGIN: called CC=1 SCAR=0.0
44 22 ▶use Params::Validate qw( :all );
Subroutine BEGIN: called CC=1 SCAR=0.0
45 #use Try::Tiny;
46 22 ▶use Web::Machine;
Subroutine BEGIN: called CC=1 SCAR=0.0
47  
48  
49  
50  
51 =head1 NAME
52  
53 Web::MREST - Minimalistic REST server
54  
55  
56  
57  
58 =head1 VERSION
59  
60 Version 0.290
61  
62 =cut
63  
64 22 our $VERSION = '0.290';
65  
66  
67 =head2 Development status
68  
69 L<Web::MREST> is currently in "Alpha - feature freeze". There are almost
70 certainly bugs lurking in the code, but all features have been implemented.
71  
72  
73  
74  
75 =head1 SYNOPSIS
76  
77 To take this module for a spin, execute this command:
78  
79 $ mrest-standalone
80  
81 Leave this running, and from another console start the command-line client:
82  
83 $ mrest-cli
84  
85 In the CLI client, type e.g.
86  
87 Web::MREST::CLI::Parser> get /
88  
89 A 'GET' request will be sent for the root resource and the CLI client
90 will display a representation of the response.
91  
92 A similar result can be obtained using C<curl>:
93  
94 curl -v http://localhost:5000/ -X GET -H "Content-Type: application/json"
95  
96 For more information on using the CLI client, see L<Web::MREST::CLI>.
97  
98  
99  
100 =head1 DESCRIPTION
101  
102 MREST stands for "minimalistic" or "mechanical" REST server. (Mechanical because
103 it relies on L<Web::Machine>.)
104  
105 L<Web::MREST> provides a fully functional REST server that can be started
106 with a simple command. Without modification, the server provides a set of
107 generalized resources that can be used to demonstrate how the REST server
108 works, or for testing.
109  
110 Developers can use L<Web::MREST> as a platform for implementing their own
111 REST servers, as described below. L<App::Dochazka::REST> is a "real-world"
112 example of such a server.
113  
114 For an introduction to REST and Web Services, see
115 L<Web::MREST::WebServicesIntro>.
116  
117  
118  
119 =head1 RFC2616 AS A STATE MACHINE
120  
121 RFC2616 is, of course, the HTTP 1.1 standard - not a state machine. But
122 the authors of "Web Machine" (which was originally implemented in Erlang) had a
123 neat idea to represent it as a state machine and use this to implement a server
124 for providing web services.
125  
126 L<Web::Machine> is, of course, the Perl port of Web Machine.
127  
128 L<Web::MREST> relies on L<Web::Machine> to implement RFC2616. L<Web::MREST>
129 can be thought of as an additional abstraction layer over L<Web::Machine>.
130  
131 By itself, L<Web::Machine> is not a server. It does not listen on a port, for
132 example. Instead, it is designed to work (via L<Plack>) with a
133 L<PSGI>-compliant web server.
134  
135 The web server hands incoming requests over to L<Web::Machine>, which runs the
136 requests through its state machine. (The L<Web::Machine> authors refer to the
137 state machine as "the FSM.") The best way to grasp the state machine is to
138 envision it as a flow-chart. At each "decision node" of the flow-chart - where
139 flow can go in one of two directions - L<Web::Machine> calls the method
140 corresponding to that node. Each node is designated by a letter and a number:
141 e.g. F7, O18, etc.
142  
143 The flow-chart implemented by the FSM can be found L<here|http://...> - you are
144 encouraged to have that open for reference while reading this documentation
145 and implementing your REST server.
146  
147  
148  
149  
150 =head1 SERVER STARTUP AND INHERITANCE SCHEME
151  
152  
153 =head2 Standalone mode
154  
155 As stated above, L<Web::MREST> is capable of operating independently. To try
156 it out, start up the server like this:
157  
158 $ mrest-standalone
159  
160 And then point your browser to
161  
162 http://localhost:5000
163  
164 If you look inside the C<mrest-standlone> script, you will see that it is
165 just a wrapper for the C<mrest> script, which takes two mandatory options. The
166 first, C<--distro>, is the name of the distribution in whose sharedir it should
167 look for configuration files. The second, C<--module>, is the name of the
168 application's resource module, i.e. the ultimate module in the chain of
169 inheritance.
170  
171 In standalone mode, the actual command that is run is:
172  
173 mrest --distro=Web::MREST --module=Web::MREST::Dispatch
174  
175 which causes the chain of inheritance to be built up as follows:
176  
177 =over
178  
179 =item C<bin/mrest>
180  
181 calls C<< Web::Machine->new >>; the L<Web::Machine> object is blessed into L<Web::MREST::Dispatch>
182  
183 =item L<Web::MREST::Dispatch>
184  
185 inherits from L<Web::MREST::Entity>
186  
187 =item L<Web::MREST::Entity>
188  
189 inherits from L<Web::MREST::Resource>
190  
191 =item L<Web::MREST::Resource>
192  
193 inherits from L<Web::Machine::Resource>
194  
195 =back
196  
197 When you browse to C<http://0:5000> in standalone mode, you get a list of the
198 sample REST resources that are available. For more information on these, see
199 C<config/dispatch_Config.pm>.
200  
201  
202 =head2 With your application
203  
204 Starting the server with your application is the same as described in
205 L<"Standalone mode">, above, except that you replace C<Web-MREST> with the name
206 of your distribution and C<Web::MREST::Dispatch> with the name of your ultimate
207 resource module.
208  
209 $ mrest YourApp-MREST YourApp::MREST::Dispatch
210  
211 For example, here we are starting the server with the distribution
212 C<YourApp-MREST>, which is presumed to implement a chain of inheritance
213 similar to L<Web::MREST>'s, i.e.:
214  
215 Web::MREST -> YourApp::MREST::Resource -> YourApp::MREST::Dispatch
216  
217 Thanks to this arrangement, the application developer can customize
218 L<Web::MREST> - i.e., not only providing her own resources and handlers,
219 but even altering how the state machine operates, if necessary - by providing
220 her own chain of inheritance and overriding various methods within it.
221  
222  
223 =head3 Recapitulation
224  
225 Since the above is quite important, let's go over it again:
226  
227 The L<Web::MREST> documentation will always refer to your application either
228 as the "application" or as C<YourApp>. The application should take the form
229 of a Perl distribution, which should have:
230  
231 =over
232  
233 =item * a distribution sharedir
234  
235 =item * a resource module, C<YourApp::Resource>.
236  
237 =item * a dispatch module, C<YourApp::Dispatch>
238  
239 =back
240  
241 For now, just think of these three components as "black boxes". We will
242 cover their contents later.
243  
244 The server (i.e. your application), is started by executing the C<mrest>
245 executable with the name of your application's distribution and the name of its
246 dispatch module, which should be the ultimate module in the chain of
247 inheritance.
248  
249 $ mrest --distro YourApp --module YourApp::Dispatch
250  
251 Under the hood the startup script, which can be reviewed at C<bin/mrest>,
252 does essentially this:
253  
254 use Web::Machine;
255  
256 Web::Machine->new(
257 resource => 'YourApp::Dispatch',
258 )->to_app;
259  
260 There are two key points concerning the L<Web::Machine> object constructed by
261 call to C<< Web::Machine->new >>:
262  
263 =over
264  
265 =item 1. the object is blessed into C<YourApp::Dispatch>
266  
267 =item 2. the object is a L<Plack> application
268  
269 =back
270  
271  
272  
273 =head1 INHERITANCE SCHEME
274  
275 As seen in the previous section, C<YourApp> inherits from
276 L<Web::MREST> via a chain of inheritance. Here is the chain implemented by L<Web::MREST>:
277  
278
279 -> Web::MREST::Dispatch
280 -> Web::MREST::Entity
281 -> Web::MREST::Resource
282 -> Web::Machine::Resource
283 -> Plack::Component
284  
285 Assuming L<YourApp> has its authentication and authorization routines
286 in L<YourApp::Resource> and its resource definitions and handlers in
287 L<YourApp::Dispatch>, the chain for L<YourApp> would look like this:
288  
289 -> YourApp::Dispatch
290 -> YourApp::Resource
291 -> Web::MREST::Entity
292 -> Web::MREST::Resource
293 -> Web::Machine::Resource
294 -> Plack::Component
295  
296 (In other words, L<YourApp::Dispatch> and L<YourApp::Resource> replace
297 L<Web::MREST::Dispatch>, which is just a demo.)
298  
299 When L<Web::Machine> reaches a given node in the FSM, it calls the
300 corresponding method on that L<Web::Machine> object. Since the object is
301 blessed into C<YourApp::Dispatch>, that module is where Perl will
302 start to look for the method.
303  
304 If the method is not found at the lowest level, Perl follows the chain of
305 inheritance "upward". The highest level, L<Plack::Component>, is shown only for
306 completeness - L<Web::MREST::Resource> and L<Web::MREST::Entity> implement
307 all the methods that your resource module might (or should) want to override.
308  
309 Readers who are not well-versed in writing Perl applications that use
310 inheritance are referred to the fine Perl manuals such as C<perlootut>.
311  
312  
313  
314 =head1 STATE MACHINE INTRODUCTION
315  
316 At this point we have enough background information to begin to grasp the state
317 machine. (Instead of writing "state machine" we will follow the L<Web::Machine>
318 convention of referring to it as the "FSM".) This section presents selected
319 features and nodes of the FSM, how L<Web::MREST> implements them, and how to
320 use them. The discourse proceeds in the order in which the methods are called
321 when an HTTP request enters the FSM. We can envision these method calls as
322 decision nodes of a flow-chart, or "cogs" of the FSM.
323  
324 And we needn't just imagine the flow-chart - it actually exists and can be
325 downloaded from L<...>. If you want to understand how L<Web::Machine> and
326 L<Web::MREST> work, this document is of fundamental importance. Hereinafter
327 it will be referred to as "the FSM diagram".
328  
329 As you can see in the FSM diagram, each FSM cog has a code like C<B6>, for ease
330 of reference.
331  
332  
333  
334 =head1 POLICIES AND FEATURES
335  
336 L<Web::Machine> implements the FSM, and that's all it does. In particular, it
337 imposes no policies on distributions that use it. By taking this approach,
338 L<Web::Machine> maximizes its range of potential uses.
339  
340 Powerful as it is, L<Web::Machine> can be confusing to use. When I started
341 writing my first application based on it, I found myself wanting an
342 intermediate module between my application and L<Web::Machine> - something that
343 would make L<Web::Machine> a little more friendly.
344  
345 L<Web::MREST> is that module. It builds on L<Web::Machine> in an effort to
346 provide certain additional features. Inevitably, this means imposing some
347 policies (i.e., limitations) on users. To me that seems like an acceptable
348 trade-off.
349  
350  
351 =head2 Path dispatch
352  
353 A key part of any web application is "path dispatch" (i.e. URI translation),
354 which answers the question: "how are URIs mapped to resources?"
355  
356 Although L<Web::Machine> provides a way to specify handlers for various media
357 types that may appear in request and response entities, it provides no
358 way of getting from the URI to the handler. L<Web::MREST> bridges this gap
359 by providing a system of resource definitions (see L<"Resource definitions">,
360 below).
361  
362 The definition of each resource specifies the URI-to-resource mapping and
363 provides the name of the resource's handler method. Internally, L<Web::MREST>
364 uses a single L<Path::Router> object to parse URIs.
365  
366 Before any URIs can be parsed, this L<Path::Router> object must be initialized.
367 This is done in L<Web::MREST::Resource>, in the C<service_available> method.
368 That method checks the scalar variable that is supposed to contain the
369 L<Path::Router> object and, if needed, calls the C<init_router> method to
370 initialize it.
371  
372 In the L<Web::MREST> demo application, C<init_router> is implemented in
373 L<Web::MREST::Dispatch>.
374  
375  
376 =head2 Resource handlers
377  
378 The L<Web::Machine> documentation mentions "handlers" but doesn't go into
379 any detail on how to write them. L<Web::MREST> not only provides some working
380 resource handlers, but also implements a paradigm for writing them.
381  
382 In this paradigm, the handler is called as a method, just like any of the other
383 methods in the chain of inheritance. (To avoid namespace issues, it is
384 recommended that handler method names start with C<handler_>.) The name of the
385 method is specified in the resource definition.
386  
387 The handler method is called twice - in other words, there are two passes. In
388 the first pass, the handler is called with the argument C<1> (scalar value) and
389 is expected to return a boolean value indicating whether the resource exists.
390  
391 In the second pass, indicated by the argument C<2> (scalar value), the handler
392 is expected to return a C<App::CELL::Status> object. This object (rendered in
393 JSON) becomes the response entity unless overrided by a declared status (see
394 C<mrest_declare_status> in L<Web::MREST::Resource>.
395  
396 B<N.B.:> The request entity is not available to the handler (via
397 C<$self->context->{request_entity}> until the second pass!
398  
399  
400 =head2 Status objects
401  
402 As mentioned in the previous section, L<App::CELL::Status> objects are returned
403 by resource handlers. Not only that - L<Web::MREST> tries its best to I<always>
404 return an L<App::CELL::Status> object in the response entity.
405  
406 Actually, it is not the object itself that is returned, but a JSON
407 representation of its underlying data structure. From this, the object can
408 easily be reconstituted on the client side by doing
409  
410 my $status = $JSON->decode( $response_entity );
411 bless $status, 'App::CELL::Status';
412  
413 For more on what status objects can do, see L<App::CELL::Status>, L<App::CELL>,
414 and L<App::CELL::Guide>.
415  
416  
417 =head2 Error statuses
418  
419 L<Web::Machine> always tries to return the proper HTTP status code in the
420 response. The application developer will likely need to "force" a code in
421 certain cases. For example, the request may be "malformed" in a way that is
422 not discoverable until the handler runs. Or, caught exceptions may need to be
423 exposed to the client with C<500 - Internal Error>.
424  
425 Also, the RFC says
426  
427 . . . the server SHOULD include an entity containing an explanation of the
428 error situation, and whether it is a temporary or permanent condition.
429  
430 Clearly, then, a mechanism is needed for providing such explanations and
431 indicating whether the error is temporary or permanent. And that mechanism
432 should enable an arbitrary status code to be declared.
433  
434 By itself, L<Web::Machine> does not really provide such a mechanism. What it
435 does provide is a mechanism for "forcing" an arbitrary status code (e.g. C<404
436 - Not Found>) by returning a scalar reference. This mechanism has two
437 disadvantages:
438  
439 =over
440  
441 =item it is only available at certain junctions of the FSM
442  
443 I wanted a way to "declare" a status code at any point and be certain that
444 L<Web::Machine> won't change it later on.
445  
446 =item there is no obvious way to provide an explanation of the error
447  
448 L<Web::Machine> considers this an implementation detail.
449  
450 =back
451  
452 Hence, L<Web::MREST> provides the C<mrest_declare_status> method. To learn
453 how to call it and how it works, see L<Web::MREST::Resource>.
454  
455  
456  
457 =head1 THE FINE STATE MACHINE
458  
459 In this section we take a detailed look at the FSM by considering some common
460 scenarios. For our purposes these are C<GET>, C<POST>, C<PUT>, and C<DELETE>
461 requests. Handling can differ according to whether or not a C<POST> creates a
462 new resource and whether or not the resource is determined to exist.
463  
464 =head2 Part One (sanity checks and information gathering)
465  
466 The first few cogs are executed, in the same order, on all requests regardless
467 of method. They can be thought of both as a set of sanity checks and as an
468 information-gathering process.
469  
470  
471 =head3 C<service_available> (B13)
472  
473 The first method call is C<service_available>, which is implemented by
474 L<Web::MREST::Resource> and should I<not> be implemented by your application,
475 because it calls C<init_router> to ensure that all the resource definitions are
476 loaded and the L<Path::Router> singleton is properly initialized.
477  
478 This is not really a limitation, however. Whatever code you need to run here
479 can be placed in a method called C<mrest_service_available>, which should
480 return a boolean value (i.e. 1 or 0), which determines the return value from
481 the method.
482  
483 If the service really isn't available, you can return false, which will trigger
484 a C<503 Service Not Available> response. Before returning you should do:
485  
486 $self->mrest_declare_status( explanation => '...', permanent => 0 );
487  
488 to provide an explanation of what is going on.
489  
490 For details, see the C<t/503-Service-Unavailable.t> unit test.
491  
492  
493 =head3 C<known_methods> (B12)
494  
495 Returns the list of supported ("known") methods in
496 C<< $site->MREST_SUPPORTED_HTTP_METHODS >>. If the request method is not
497 in that list, a C<501 Not Implemented> response is returned along with
498 an explanation that the method requested is not supported.
499  
500 If this behavior is not appropriate, the method can be implemented by the
501 application.
502  
503  
504 =head3 C<uri_too_long> (B11)
505  
506 If the request URI is longer than the value set in the C<MREST_MAX_LENGTH_URI> site parameter,
507 the client will receive a C<414 Request URI Too Long> response.
508  
509 To override this behavior, provide your own C<uri_too_long> routine in your
510 resource module.
511  
512 This functionality is demonstrated by the C<t/414-Request-URI-Too-Long.t> unit.
513  
514  
515 =head3 C<allowed_methods> (B10)
516  
517 "Is the method allowed on this resource?"
518  
519 This next routine is where things start to get complicated. According to the
520 L<Web::Machine::Resource
521 documentation|https://metacpan.org/pod/Web::Machine::Resource#allowed_methods>,
522 we are expected to respond with a list of methods allowed on the resource. To
523 assemble such a list, we must first answer two questions:
524  
525 =over
526  
527 =item 1. Have the resource definitions been loaded?
528  
529 =item 2. Does the URI match a known resource?
530  
531 =back
532  
533 After the server starts, the first time this method is called triggers a
534 call to the C<init_router> method, which populates the C<$resources> package
535 variable in C<Web::MREST::InitRouter> with all the resource definitions.
536 This is explained in detail in L<"Resource definitions">. This takes care of
537 the first question.
538  
539 The second question is answered by C<Path::Router>. Once the request has
540 been associated with a known resource, completing our task becomes a matter of
541 getting and returning the set of methods for which the resource is defined.
542  
543  
544 =head3 C<malformed_request> (B9)
545  
546 A true return value from this method triggers a "400 Bad Request" response
547 status. RFC2616 does not stipulate exactly what constitutes a bad request.
548 We already (in allowed_methods) took care of the case when the URI
549 fails to match a known resource, and that includes applying any C<validations>
550 properties from the resource definition.
551  
552 So, in this method (or your overlay) we take the "next step" (whatever that is)
553 in vetting the request. Keep in mind that this method is called before
554 the resource handler. If you have any sanity checks you wish to apply _after_
555 the URI is matched to a resource but _before_ the resource handler fires, this
556 is the place to put them.
557  
558 If you would like to keep L<Web::MREST>'s implementation of this method
559 (which, for example, pushes the Content-Length and Content-Type information
560 onto the context) and add your own logic, you can put it in
561 C<mrest_malformed_request> instead of overriding C<malformed_request> itself.
562  
563 If you intend to return false from this method you should first do this:
564  
565 $self->mrest_declare_status( explanation => '...' );
566  
567 to ensure that an explanation is included with the 400 response.
568  
569  
570 =head3 C<is_authorized> (B8)
571  
572 In my mind, "authentication" is the process of determining who the user
573 is, and "authorization" determines if the user is allowed to do what she
574 is asking to do. However, RFC2616 does not make such a clear distinction.
575  
576 For that reason, it is left to the application to implement this method
577 if needed.
578  
579  
580 =head3 C<forbidden> (B7)
581  
582 The same thoughts as expressed under C<is_authorized>, above, apply to
583 this method as well.
584  
585  
586 =head3 C<valid_content_headers> (B6)
587  
588 This is where you vet the C<Content-*> headers in the request. If the
589 request contains any invalid C<Content-*> headers (i.e., if the '*' part
590 does not appear in << $site->MREST_VALID_CONTENT_HEADERS >>),
591 a 501 will be generated.
592  
593 The content headers are passed to the method in a L<Hash::MultiValue>
594 object.
595  
596  
597 =head3 C<known_content_type> (B5)
598  
599 If the C<Content-Type> header is relevant - i.e., if this is a PUT or
600 POST request and if there is a request entity - check it against
601 << $site->MREST_SUPPORTED_CONTENT_TYPES >>.
602  
603  
604 =head3 C<valid_entity_length> (B4)
605  
606 A simple routine that compares the entity length (in bytes) with the
607 maximum set in C<< $site->MREST_MAX_LENGTH_REQUEST_BODY >>.
608  
609  
610 =head3 C<options> (B3)
611  
612 If your application needs to support the C<OPTIONS> method, you should
613 implement this yourself - otherwise, ignore it.
614  
615  
616 =head2 Part Two (content negotioation)
617  
618 The HTTP standard provides some complicated logic to enable clients
619 and servers to "negotiate" the format (media type), language, encoding,
620 etc. in which content will be passed back and forth. Here in the L<Web::MREST>
621 documentation we gloss over this complexity and focus only on the media type.
622 However, L<Web::Machine> includes methods for handling all the content
623 negotiation decision nodes and the application developer is free to take
624 advantage of them.
625  
626 That said, L<Web::MREST> itself provides JSON handlers for both the request and
627 the response entities, and should be fully UTF-8 clean. Hopefully, this will
628 save application developers some work. (For more information, see L<"STATUS
629 OBJECTS AND ERROR HANDLING">.)
630  
631 The following subsections detail the principal content negotiation methods.
632  
633 =head3 C<content_types_provided>
634  
635 As the L<Web::Machine::Resource> documentation states, this method must be
636 implemented (i.e., by the application) - otherwise, "your resource will not be
637 able to return any useful content".
638  
639 Quoting further: "This should return an ARRAY of HASH ref pairs where the key
640 is the name of the media type and the value is a CODE ref (or name of a method)
641 which can provide a resource representation in that media type."
642  
643 The implementation provided by L<Web::MREST> allows clients to specify (via
644 an C<Accept> header) one of two media types:
645  
646 =over
647  
648 =item C<text/html>
649  
650 Since it is the first hashref pair of the two, it is the default. That means
651 if the incoming request does not have an C<Accept> header, the handler
652 specified for C<text/html> will be called to generate the response entity.
653  
654 =item C<application/json>
655  
656 This is the media type that L<Web::MREST> was written to support, both in
657 request entities and in response entities. However, there is nothing preventing
658 you as the application developer from specifying handlers for other media types.
659  
660 =back
661  
662 If the request includes an C<Accept> header, but none of the media types
663 specified in it are found in C<content_types_provided>, L<Web::Machine> will
664 generate a C<406 Not Acceptable> response. (Unfortunately, there is no easy way
665 for L<Web::MREST> or the application to know in advance that this error will be
666 triggered, so it will be returned "bare" - i.e., without any explanatory
667 response entity.)
668  
669 In the normal case when an acceptable handler exists, it will be called to
670 generate the response - in other words, whatever is returned by the chosen
671 handler becomes the response entity, unless an error occurs inside the handler.
672 In that case, the handler should return a reference to a scalar value
673 (e.g., \400), which L<Web::Machine> will interpret as an HTTP response code.
674 See L<"STATUS OBJECTS AND ERROR HANDLING">.
675  
676 For more on response entity generation, see the sections dedicated to the
677 various HTTP methods (L<"GET">, L<"PUT">, L<"POST">, L<"DELETE">), below.
678  
679  
680 =head3 C<content_types_accepted>
681  
682 When the client sends C<PUT> or C<POST> requests, it will typically provide a
683 'Content-Type' header specifying the media type of the bytes it is sending in
684 the request body. This content type is compared with the media types returned
685 by this method. If there is no match, L<Web::Machine> returns a C<415
686 Unsupported Media Type> error response. (Unfortunately, there is no easy way
687 for L<Web::MREST> or the application to know in advance that this error will be
688 triggered, so it will be returned "bare" - i.e., without any explanatory
689 response entity.)
690  
691  
692 =head3 Other methods
693  
694 For handling character sets, encodings, and languages, L<Web::Machine> provides
695 a number of other content negotiation methods:
696  
697 =over
698  
699 =item C<charsets_provided>
700  
701 =item C<default_charset>
702  
703 =item C<languages_provided>
704  
705 =item C<encodings_provided>
706  
707 =item C<variances>
708  
709 =back
710  
711 However, they are only needed if the application does complex content
712 negotiation.
713  
714  
715 =head2 Part Three (resource existence)
716  
717 When we have made it past content negotiation, we know more than just which
718 routines will be used to process the request entity (if any) and generate the
719 response. We have gathered quite a bit of information about the request. All
720 this information has been pushed onto the context, so it is available to all
721 our resource methods, including the resource handler which we will get to
722 presently. This information includes:
723  
724 (FIXME: verify this list as it is outdated)
725  
726 =over
727  
728 =item C<method>
729  
730 The request method
731  
732 =item C<resource_name>
733  
734 The resource name, which can be used as a key to look up the full resource
735 definition in the C<< $Web::MREST::InitRouter::resources >>
736  
737 =item C<handler_name>
738  
739 The name of the resource handler, e.g. C<handler_bugreport>. In L<Web::MREST>,
740 the resource handlers reside in the L<Web::MREST::Dispatch> module.
741  
742 =item C<uri>
743  
744 The full URI provided with the request
745  
746 =item C<uri_base>
747  
748 The base part of the URI (e.g. "http://localhost:5000/" )
749  
750 =item C<uri_path>
751  
752 The relative path to the resource (e.g. "/bugreport")
753  
754 =item C<components>
755  
756 Reference to an array the elements of which are the individual 'components'
757 (i.e., everything between the '/' characters) of the C<uri_path>
758  
759 =item C<mapping>
760  
761 A hashref mapping resource parameter names (if any) to their values
762  
763 =item C<content-length>
764  
765 The content-length header.
766  
767 =item C<content-type>
768  
769 The content-type header.
770  
771 =back
772  
773 One major piece of information is missing, however: whether the resource exists
774 or not. For that, we have to actually call the resource handler.
775  
776  
777 =head3 C<resource_exists> (G7)
778  
779 The term "resource" is not precisely defined. It can refer to the resource
780 definition (a data structure), the resource handler (a Perl subroutine called
781 as an object method), or an object (set of records) in an underlying database.
782 Or it can refer to all of the above, or to something else. The following
783 paragraphs describe L<Web::MREST>'s approach.
784  
785 By the time control reaches this method, the request URI has already been
786 matched to a resource definition. So the resource handler is known. Since we
787 have no other way of knowing, we ask the resource itself, by calling the
788 handler with the scalar value C<1> (i.e. the numeral 1) as the sole argument.
789 This handler call is referred to as the "first pass".
790  
791 How the handler is implemented does not concern us. We only ask that it return
792 a boolean value (true or false) when called with this argument. If the return
793 value from the handler is true, we can assume that the handler will be called
794 again (second pass) in the response generation phase - read on.
795  
796  
797 =head2 Part Four (generation of response entity)
798  
799 At this point we have
800  
801 =over
802  
803 =item gathered information about the request and placed it on the context
804  
805 =item run the resource handler (first pass) to determine resource existence
806  
807 =back
808  
809 Up until now (i.e., through determination of resource existence), the FSM
810 has been a series of steps applied, in the same order, regardless of the
811 HTTP method.
812  
813 In the sections below, we examine how responses are generated for each of
814 four HTTP methods (C<GET>, C<PUT>, C<POST>, and C<DELETE>) when the resource
815 exists and when it doesn't exist.
816  
817 =head3 Resource exists
818  
819 =head4 C<GET>
820  
821 =over
822  
823 =item 1. C<content_types_provided> method call
824  
825 First, C<content_types_provided> is called to determine the name of the
826 method that is capable of generating the response in the required format.
827 This method is the one we mean when we refer to the "response generator".
828  
829 =item 2. Response generator method call
830  
831 Second, the response generator is called (from C<o18> in
832 L<Web::Machine::FSM::States>). It is expected to always return an
833 L<App::CELL::Status> object. If an error condition is detected, the
834 handler should declare it using C<< $self->mrest_declare_status >>
835 and then return a "non_ok" status.
836  
837 =back
838  
839 C<GET> is the only request method that demands a response entity
840 in the format specified by the C<Accept> header. For the other methods,
841 response entities are optional, but recommended. In practice, this
842 means that we have to create them ourselves.
843  
844  
845 =head4 C<POST>
846  
847 Here we have two possible paths, depending on the value returned by
848 C<post_is_create>:
849  
850 =over
851  
852 =item C<post_is_create> true
853  
854 =over
855  
856 =item C<create_path> and C<create_path_after_handler>
857  
858 If, and only if, C<post_is_create> is true, processing continues via
859 C<create_path> and C<create_path_after_handler>. Depending on the value of the
860 latter, the request handler (determined by consulting
861 C<content_types_accepted>) is called either before or after C<create_path>.
862  
863 The request handler should stage the response entity in preparation for
864 finalization. The content type can be inferred from
865 C<< $request->env->{'web.machine.context'} >>.
866  
867 =item Finalization
868  
869 Request is finalized by a call to C<finish_request>.
870  
871 =back
872  
873 =item C<post_is_create> false
874  
875 If C<post_is_create> returns false, all bets are off. For reasons I do not
876 understand, L<Web::Machine> does not consult C<content_types_provided> or
877 C<content_types_accepted> on this type of request. The only thing it does is
878 call C<process_post>, and so it is up to this method to do whatever needs to be
879 done to generate an entity and get it into the response.
880  
881 L<Web::MREST> helps by making sure that the content type is stored in the
882 context (in the C<'content_type'> property), so C<process_post> can look
883 there for it and generate the response entity accordingly.
884  
885 =back
886  
887  
888 =head4 C<PUT>
889  
890 On all C<PUT> requests, and those C<POST> requests that are handled as
891 C<PUT> requests (see above), L<Web::Machine> uses the following process:
892  
893 =over
894  
895 =item C<content_types_accepted>
896  
897 This method is called to determine the name of the method that can process
898 the request body. This method is expected not only to process the request
899 body, but also to generate the response. Therefore, we refer to this
900 method as the "response generator" for C<PUT> requests.
901  
902 =item Response generator method call
903  
904 Next, the response generator is called. For C<PUT> requests, the response
905 generator is determined from C<content_types_accepted> based on the Here again, the method referred
906 to by C<content_types_provided> is not called by L<Web::Machine>, but the
907 response generator is free to call C<content_types_provided> and find
908 out the method itself, and call it. Or do something else.
909  
910 When C<resource_exists> is true, the response generator is called from C<o14>
911 in L<Web::Machine::FSM::States>.
912  
913 =back
914  
915 Whenever a new resource is created, a C<Location> header is added to
916 the response with the URI path of the new resource.
917  
918 In general, we understand C<PUT> to be a request to write to a resource.
919 Typically, this will involve either creating (INSERT) or modifying (UPDATE) one
920 or more database records/objects.
921  
922 Therefore, it has to be possible for a URI to resolve to a resource that
923 does not yet exist. For example:
924  
925 PUT employee/nick/Bubba
926  
927 There may or may not be an employee by the name of Bubba in the database,
928 but if we have a resource called 'employee/nick/:nick', Path::Router will
929 match it in C<allowed_methods> and the resource handler will be called in
930 C<resource_exists> - up until this point, the same sequence of method
931 calls is used for C<GET>, C<POST>, C<PUT>, and C<DELETE>.
932  
933 L<Web::MREST> has no way of knowing whether there is an employee named Bubba.
934 It is up to the handler to determine this, and then do an INSERT or UPDATE
935 operation as appropriate. This operation is not expected to fail, but if it
936 does fail the handler should force a 4xx or 5xx status code (and provide an
937 explanation) by calling C<< $self->mrest_declare_status >>.
938  
939 If the request causes a new object - and, hence, a new resource - to be
940 created, the handler should cause a C<Location> header with the URI of the
941 new resource to be added to the response. This tells L<Web::Machine> to
942 set the response status to C<201 Created>.
943  
944 If the request only modifies an existing object/resource, simply do not
945 add a C<Location> header to the response. This will cause L<Web::Machine>
946 to return a C<200 OK> status in the response.
947  
948  
949 =head4 C<DELETE>
950  
951 For C<DELETE>, two methods are called: C<delete_resource> and
952 C<delete_completed>. The C<delete_resource> method should enact the delete
953 operation and generate the response entity. The second method, C<delete_completed>,
954 is for cases when the delete operation cannot be guaranteed to have completed -
955 this method defaults to false, but if it returns true L<Web::Machine> will
956 trigger a C<...> response.
957  
958  
959 =head3 Resource does not exist
960  
961 =head4 C<GET>
962  
963 Request goes to finalization with 404 status.
964  
965 =head4 C<POST>
966  
967 Request goes to C<allow_missing_post>, which always returns false in
968 L<Web::MREST>'s implementation.
969  
970 After that, the request goes to finalization with 404 status.
971  
972 If the
973  
974 =head4 C<PUT>
975  
976  
977  
978 =head2 C<finish_request>
979  
980 The previous sections should suffice for the reader to gain a degree of
981 understanding of how the state machine works for various types of requests, and
982 how L<Web::MREST> interfaces with the response handlers.
983  
984 The last cog of the FSM is C<finish_request>.
985  
986  
987  
988 =head1 IN-DEPTH DISCUSSIONS OF VARIOUS TOPICS
989  
990 =head2 Resource definitions
991  
992 As we read in the "crash course" above, resources are central to what a REST
993 server is and does: the server processes incoming requests. Each request has
994 a URI which resolves (or does not resolve) to a resource. Resources are
995 defined as module variables: each module that contains resource handlers
996 should also define a module variable (via C<our $resource_defs = { ... };>)
997 containing the definitions of the resources covered by that module.
998  
999 The top-level dispatch module, L<Web::MREST::Dispatch>, should implement
1000 a method called C<init_router> which calls the function
1001  
1002 Web::MREST::InitRouter::load_resource_defs
1003  
1004 for all the resource-defining modules. When the first HTTP request comes in,
1005 L<Web::MREST::Resource> calls the C<init_router> method. This only happens
1006 once, ensuring that the resource definitions are fully loaded for the first -
1007 and all subsequent - requests.
1008  
1009 Each resource definition is a hashref consisting of a number of properties.
1010 This definition hashref is itself included in the C<$resources> package
1011 hashref, which essentially looks like this:
1012  
1013 {
1014 RESOURCE_NAME => RESOURCE_DEFINTION,
1015 RESOURCE_NAME => RESOURCE_DEFINTION,
1016 RESOURCE_NAME => RESOURCE_DEFINTION,
1017 }
1018  
1019 where C<RESOURCE_NAME> is a resource name (a string like C<'/'> or
1020 C<'docu/text'>) and C<RESOURCE_DEFINITION> is that resource's definition
1021 hashref.
1022  
1023 The root resource should be defined under the name C<'/'> and top-level
1024 resources should have a C<parent> property set to this string.
1025  
1026 In the resource definition, properties can be specified either as a
1027 scalar value, in which case the definition applies to all the methods
1028 specified in C<< $site->MREST_SUPPORTED_HTTP_METHODS >>, or as a
1029 hashref in case the given resource is only defined for certain methods.
1030  
1031 In the latter case, it is not necessary to define all properties as
1032 hashrefs. The set of permitted methods will always be taken from the
1033 'handler' property. For example in this snippet whizzo_resource is only
1034 defined for the GET method, and that will be applied to 'foo' (and the
1035 rest of this resource's properties) as well.
1036  
1037 'whizzo_resource' => {
1038 'handler' => {
1039 'GET' => 'some_method',
1040 },
1041 'foo' => 'barbazbat',
1042 ...
1043 }
1044  
1045 So 'foo' will only be defined for the GET method.
1046  
1047 Examples:
1048  
1049 'foo_prop' => 'value applied to all available methods',
1050  
1051 'bar_prop' => {
1052 'GET' => 'value applied to GET requests',
1053 'POST' => 'value applied to POST requests',
1054 },
1055  
1056 There is one required property, 'handler', which is used to specify the
1057 handler(s) for the resource (see the examples below). The value of this
1058 property is taken to be the name of a method. This method call looks
1059 like this:
1060  
1061 $self->$handler
1062  
1063 and is located in Web::MREST::Resource->resource_exists
1064  
1065 (The inheritance chain is set up in C<bin/mrest> - the server startup script -
1066 and via C<use parent> statements in the various modules that make up the
1067 inheritance chain.)
1068  
1069 In addition, each resource may have any properties you, the application
1070 developer, wish to invest in it. For our 'docu' methods we use the
1071 properties 'description' and 'documentation', for example.
1072  
1073 Two properties - 'parent' and 'validations' - are
1074 exceptions to the above and should never be defined on a per-method
1075 basis:
1076  
1077 - 'validations' contains validation checks to be applied when matching
1078 URI to resource (for more information, see the Path::Router
1079 documentation).
1080
1081 - 'parent' contains the name of the resource's parent resource
1082 (defaults to '' - the root resource)
1083  
1084 - 'documentation' is reserved for the self-documentation feature
1085  
1086  
1087  
1088 =head3 C<Path::Router> object initialization
1089  
1090 When the server starts, the C<MREST_RESOURCE_DEFINITIONS> and
1091 C<MREST_ROOT_RESOURCE> meta parameters are initialized from the configuration
1092 file C<config/dispatch_MetaConfig.pm> in the L<Web::MREST> distribution.
1093  
1094 The application developer will of course want to define her own set of
1095 resources. This should be done by manipulating the meta parameters
1096 C<MREST_RESOURCE_DEFINITIONS> and C<MREST_ROOT_RESOURCE>. A good place
1097 to do this is in the application's C<mrest_init_router> routine.
1098  
1099 Here are two approaches to defining the application's resources, depending on
1100 whether the application wishes to retain the L<Web::MREST> resources.
1101  
1102 =over
1103  
1104 =item 1. retain
1105  
1106 package MyApp::Resource;
1107  
1108 use Clone 'clone';
1109 use parent 'Web::MREST::Resource';
1110  
1111 # We assume that the application somehow loads its resource definitions
1112 # (including the root resource) into a package variable $r_defs -- for
1113 # example by hard-coding them like this
1114 my $r_defs = { ... };
1115  
1116 # ----------------------------------------
1117 # mrest_init_router - called by Web::MREST
1118 # ----------------------------------------
1119 sub mrest_init_router {
1120 my $self = shift;
1121  
1122 # set up the root resource
1123 $meta->set( 'MREST_ROOT_RESOURCE', $r_defs->{''} );
1124 delete $r_defs->{''};
1125  
1126 # set up the remaining resources, retaining (but possibly
1127 # overwriting) the Web::MREST default resources
1128 my $mrest_defs = clone( $meta->MREST_RESOURCE_DEFINITIONS );
1129 foreach my $r_name ( keys %$r_defs ) {
1130 $mrest_defs->{$r_name} = $r_defs->{$r_name};
1131 }
1132 $meta->set( 'MREST_RESOURCE_DEFINITIONS', $mrest_defs );
1133 }
1134  
1135 =item 2. do not retain
1136  
1137 This approach is more simple because no C<mrest_init_router> need be written.
1138 The application should have its own distro sharedir C<config/> and therein a
1139 file C<dispatch_MetaConfig.pm>. Inside that file, the application puts its own
1140 resource definitions in the C<MREST_RESOURCE_DEFINITIONS> and
1141 C<MREST_ROOT_RESOURCE> parameters (refer to C<config/dispatch_MetaConfig.pm> in
1142 the L<Web::MREST> distribution for syntax and semantics).
1143  
1144 The application's definitions will overlay (i.e. replace) those of
1145 L<Web::MREST>. Even in this scenario, some or all of L<Web::MREST>'s resources
1146 could be used in the application, but only by copy-pasting the definitions and
1147 their respective handlers into the application's source code.
1148  
1149 =back
1150  
1151  
1152 =head3 Tree structure
1153  
1154 L<Web::MFILE> allows resources to be defined in a tree structure. It is
1155 designed to allow a tree structure to be described in a flat configuration
1156 file. The C<MREST_RESOURCE_DEFINITIONS> hash is keyed on the resource name.
1157 Child resources are indicated by including a C<parent> property with the name
1158 of the parent resource. Care should be exercised not to introduce any circular
1159 references.
1160  
1161 If a flat structure is desired, simply do not include any C<parent> properties
1162 in your resource definitions.
1163  
1164 The format of C<MREST_RESOURCE_DEFINITIONS> hash is documented in
1165 C<config/dispatch_MetaConfig.pm>.
1166  
1167  
1168 =head3 C<< $Web::MREST::InitRouter::resources >>
1169  
1170 The resource definition hashrefs in the dispatch modules are designed to be
1171 written and maintained by humans. When the C<init_router> method runs, it loops
1172 over all the resource definitions and builds up a second hash,
1173 C<< $Web::MREST::InitRouter::resources >>, which contains the same information
1174 in a format that is more convenient for automated processing.
1175  
1176 Since the resource definitions are a potential source of typographical and
1177 semantic errors, you should dump this package variable to the log and examine
1178 it to make sure your resource definitions are being processed correctly.
1179  
1180  
1181 =head2 Errors
1182  
1183 As we move through the state machine (i.e. the chain of method calls driven
1184 by L<Web::Machine>), we build up a "context" from which we generate the HTTP
1185 response. Stated very simply, the response code can either be 'OK' (200) or
1186 "something else" - i.e., an error of some kind.
1187  
1188 And, indeed, checking for errors accounts for a large portion of what our
1189 resource modules do. As RFC2616 explains, errors can be divided into two
1190 brought classes: client errors and server errors.
1191  
1192 =over
1193  
1194 =item Client errors (4xx)
1195  
1196 Client errors have status codes that start with 4 (e.g. 400, 401, 404).
1197  
1198 RFC2616 has this to say about them:
1199  
1200 The 4xx class of status code is intended for cases in which the client
1201 seems to have erred. Except when responding to a HEAD request, the server
1202 SHOULD include an entity containing an explanation of the error situation, and
1203 whether it is a temporary or permanent condition. These status codes are
1204 applicable to any request method. User agents SHOULD display any included
1205 entity to the user.
1206  
1207 =item Server errors (5xx)
1208  
1209 Server errors have codes beginning with th digit "5". According to RFC2616,
1210 they
1211  
1212 indicate cases in which the server is aware that it has erred or is
1213 incapable of performing the request. Except when responding to a HEAD
1214 request, the server SHOULD include an entity containing an explanation of
1215 the error situation, and whether it is a temporary or permanent condition.
1216 User agents SHOULD display any included entity to the user. These response
1217 codes are applicable to any request method.
1218  
1219 =back
1220  
1221 The key point here is that it is not sufficient to return a bare 4xx or 5xx
1222 response status code. The response should include an entity body with an
1223 explanation of the error condition.
1224  
1225 =head3 How to provide explanation in response entity
1226  
1227 L<Web::MREST> provides a mechanism for adding the explanation to the entity
1228 body as called for by RFC2616. At the exact place in your resource module
1229 where you discover the error, do something like this:
1230  
1231 $self->mrest_declare_status( code => '400', explanation => 'You messed up' );
1232  
1233 This will be converted into the respective L<App::CELL::Status> object and
1234 returned in the response entity. The object will have properties like this:
1235  
1236 {
1237 level => 'ERR',
1238 code => 'You messed up',
1239 payload => {
1240 http_code => '500',
1241 uri_path => ... (taken from the context),
1242 resource_name => ... (taken from the context),
1243 found_in => ... (taken from 'caller'),
1244 permanent => JSON::true (the default),
1245 },
1246 }
1247  
1248 Alternatively, you can pass in your own arbitary L<App::CELL::Status> object.
1249  
1250 To see how the L<App::CELL::Status> object becomes the response entity, see
1251 the C<finish_request> method in L<Web::MREST::Resource>.
1252  
1253  
1254 =head2 Context
1255  
1256 Typically referred to as C<$context>, the "MREST context" is a hashref that is
1257 built up during the course of request processing. In addition to being used
1258 within L<Web::MREST::Resource>, it is always sent as an argument whenever
1259 L<Web::MREST::Resource> calls a hook, so the developer can modify it in her
1260 implementations of the various hook routines.
1261  
1262  
1263 =head2 Authentication
1264  
1265 Ever since the Big Bad Wolf ate Granny, authentication mechanisms have been
1266 prone to abuse by individuals who are willing to lie about their identity.
1267  
1268 Humans are good at distinguishing one human from another, provided they can
1269 apply all their senses to the task. Computers lack proper senses and are
1270 downright awful at this task. Computerized authentication schemes typically
1271 operate by presenting the user with one or more hoops to jump through. Whoever
1272 succeeds at this task is deemed to be the user. What could go wrong?
1273  
1274 Passwords (or passphrases) are the "hoop" most frequently used to authenticate
1275 users and keep would-be intruders out. Therefore, a system's security is often
1276 gauged by how well it protects user credentials from disclosure. Since
1277 usernames are public, the only thing keeping a determined intruder at bay are
1278 the passwords, and various measures are taken to protect them.
1279  
1280 From the perspective of L<Web::Machine>, authentication is a matter of
1281 calling the L<is_authorized> method. If the return value is false, the response
1282 will be C<401 Unauthorized>. If it is true, request processing continues.
1283 Whatever authentication measures the application developer decides to implement
1284 should be triggered by this method call.
1285  
1286 For more about L<is_authorized>, see the L<Web::Machine::Resource documentation|https://metacpan.org/pod/Web::Machine::Resource#is_authorized-authorization_header>
1287  
1288  
1289  
1290 =head2 Authorization
1291  
1292 Once authentication has determined the user's identity, a related task,
1293 authorization, begins. As the name would imply (and the RFC's vague
1294 use of the term "authorization" notwithstanding), authorization answers
1295 the question:
1296  
1297 Is this specific user authorized to make this request?
1298  
1299 Compare this with authentication, which answers a different question:
1300  
1301 Is this user really who they are purporting to be?
1302  
1303 Or, even more pithily:
1304  
1305 Who is this user?
1306  
1307 Authorization implies a boolean "function" (in both the mathematical and
1308 computer science sense) that takes three arguments: the username, the HTTP
1309 method, and the resource. Implementation of this function is left to the
1310 application developer.
1311  
1312 It is worth noting here that L<Web::Machine> provides a C<forbidden> method.
1313 Since C<is_authorized> is already taken for authentication, we can use
1314 C<forbidden> for authorization. Just be sure to understand thoroughly that
1315 a true return value from C<forbidden> means "not authorized".
1316  
1317  
1318 =head2 Customized URI parsing
1319  
1320 While L<Web::MREST> provides for URI parsing using L<Path::Router>, if this is
1321 not desired the application developer can parse URIs herself by simply
1322 substituting her own C<init_router> and C<match> methods for the ones provided
1323 by L<Path::Router> and L<Path::Router::Route::Match>, respectively.
1324  
1325 When request processing enters C<resource_exists>,
1326 Alternatively, the application developer can overlay the C<init_router> routine
1327 with one that returns an arbitrary object (stored in C<$router>) that has a
1328 C<match> method. After that, L<Web::MREST> does
1329  
1330 my $match = $router->match( $path );
1331  
1332 where C<$path> is the relative portion of the URI (i.e. everything left after
1333 the C<http://myapp.example.com/> part is cut off).
1334  
1335 The C<$match> object should provide a C<route> method, which should return the
1336 definition of the matched resource. See L<"RESOURCE DEFINITIONS">.
1337  
1338  
1339 =head1 FUNCTIONS IN THIS MODULE
1340  
1341 =head2 init
1342  
1343 Do initialization-like things, such as loading configuration parameters.
1344 Takes a PARAMHASH which can contain one of the following:
1345  
1346 =over
1347  
1348 =item C<distro>
1349  
1350 The name of the application distribution from which the distro sharedir will be
1351 loaded.
1352  
1353 =item C<path>
1354  
1355 The name (full path) of a directory containing the application's configuration
1356 files.
1357  
1358 =item C<hashref>
1359  
1360 A reference to a hash containing meta parameters to be loaded.
1361  
1362 =back
1363  
1364 =cut
1365  
1366 22 ▶sub init {
Subroutine init: called CC=14 SCAR=46.7
Pod documented
1367 22 my %ARGS = validate( @_, {
1368 distro => { type => SCALAR, optional => 1 },
1369 sitedir => { type => SCALAR, optional => 1 },
1370 hashref => { type => HASHREF, optional => 1 },
1371 early_debug => { type => SCALAR, optional => 1 },
1372 } );
1373
1374 22 my $tf = $ARGS{'early_debug'};
1375 22 ▶ if ( $tf ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($tf) 0 22 22
1376 0 _touch $tf;
1377 0 ▶ if ( -r $tf and -w $tf ) {
Branch: 1 branch
BranchTrueFalseTotal
if (-r $tf and -w $tf) { } 0 0 0
Condition0%0/3
-r $tf and -w $tf
!ll&&!rl&&r
000
MC/DC0%0/2
-r $tf and -w $tf
-r $tf -w $tf
Truth table0%0/3
A and B
A= -r $tfB= -w $tf
ABresult
0X0
100
111
1378 0 unlink $tf;
1379 0 Log::Any::Adapter->set( 'File', $tf );
1380 0 $log->debug( __PACKAGE__ . "::init activating early debug logging to $tf" );
1381 } else {
1382 0 print "Given unreadable/unwritable early debugging filespec $tf\n";
1383 }
1384 }
1385  
1386 # always load Web::MREST's configuration parameters
1387 22 my $target = File::ShareDir::dist_dir('Web-MREST');
1388 22 $log->debug( "About to load Web::MREST configuration parameters from $target" );
1389 22 my $status = $CELL->load( sitedir => $target, verbose => 1 );
1390 22 ▶ return $status if $status->not_ok;
Branch: 1 branch
BranchTrueFalseTotal
if $status->not_ok 0 22 22
1391  
1392 22 $meta->set( 'MREST_EARLY_DEBUGGING', $tf );
1393  
1394 # if argument provided, load that, too
1395 22 ▶ if ( %ARGS ) {
Branch: 1 branch
BranchTrueFalseTotal
if (%ARGS) 0 22 22
1396 0 $target = undef;
1397 0 ▶ if ( $ARGS{'distro'} and $ARGS{'distro'} ne 'Web-MREST' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($ARGS{"distro"} and $ARGS{"distro"} ne "Web-MREST") 0 0 0
Condition0%0/3
$ARGS{"distro"} and $ARGS{"distro"} ne "Web-MREST"
!ll&&!rl&&r
000
MC/DC0%0/2
$ARGS{"distro"} and $ARGS{"distro"} ne "Web-MREST"
$ARGS{"distro"} $ARGS{"distro"} ne "Web-MREST"
Truth table0%0/3
A and B
A= $ARGS{"distro"}B= $ARGS{"distro"} ne "Web-MREST"
ABresult
0X0
100
111
1398 # distro must be given as "MyApp-Foo", not "MyApp::Foo"
1399 0 $target = File::ShareDir::dist_dir( $ARGS{'distro'} );
1400 0 $status = $CELL->load( sitedir => $target );
1401 0 ▶ return $status if $status->not_ok;
Branch: 1 branch
BranchTrueFalseTotal
if $status->not_ok 0 0 0
1402 }
1403 0 ▶ if ( my $sitedir_target = $ARGS{'sitedir'} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $sitedir_target = $ARGS{"sitedir"}) 0 0 0
1404 0 ▶ if ( -d $sitedir_target ) {
Branch: 1 branch
BranchTrueFalseTotal
if (-d $sitedir_target) { } 0 0 0
1405 0 $status = $CELL->load( sitedir => $sitedir_target );
1406 0 ▶ return $status if $status->not_ok;
Branch: 1 branch
BranchTrueFalseTotal
if $status->not_ok 0 0 0
1407 } else {
1408 0 $log->warn( 'Web::MREST::init() says sitedir argument given, but it is not a directory: ' .
1409 Dumper( $sitedir_target ) );
1410 }
1411 }
1412 0 ▶ if ( $ARGS{'hashref'} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($ARGS{"hashref"}) 0 0 0
1413 0 my $count = 0;
1414 0 foreach my $key ( keys %{ $ARGS{'hashref'} } ) {
1415 0 $meta->set( $key, $ARGS{'hashref'}->{$key} );
1416 0 $count += 1;
1417 }
1418 0 $log->notice( "Web::MREST::init loaded $count meta parameters from a hashref" );
1419 }
1420 }
1421  
1422 22 return $CELL->status_ok;
1423 }
1424  
1425  
1426 =head2 version
1427  
1428 Accessor method (to be called like a constructor) providing access to C<$VERSION> variable
1429  
1430 =cut
1431  
1432 2 ▶sub version { $VERSION; }
Subroutine version: called CC=1 SCAR=0.0
Pod documented
1433  
1434 22 1;
↑ Summary Web/MREST/Dispatch.pm »