NAME

Plack::App::MCCS - Minify, Compress, Cache-control and Serve static files from Plack applications

EXTENDS

Plack::Component

SYNOPSIS

    # in your app.psgi:
    use Plack::Builder;
    use Plack::App::MCCS;

    my $app = sub { ... };

    # be happy with the defaults:
    builder {
            mount '/static' => Plack::App::MCCS->new(root => '/path/to/static_files')->to_app;
            mount '/' => $app;
    };

    # or tweak the app to suit your needs:
    builder {
            mount '/static' => Plack::App::MCCS->new(
                    root => '/path/to/static_files',
                    min_cache_dir => 'min_cache',
                    defaults => {
                            valid_for => 86400,
                            cache_control => ['private'],
                    },
                    types => {
                            '.htc' => {
                                    content_type => 'text/x-component',
                                    valid_for => 360,
                                    cache_control => ['no-cache', 'must-revalidate'],
                            },
                    },
            )->to_app;
            mount '/' => $app;
    };

    # or use the supplied middleware
    builder {
            enable 'Plack::Middleware::MCCS',
                    path => qr{^/static/},
                    root => '/path/to/static_files'; # all other options are supported
            $app;
    };

DESCRIPTION

Plack::App::MCCS is a Plack application that serves static files from a directory. It will prefer serving precompressed versions of files if they exist and the client supports it, and also prefer minified versions of CSS/JS files if they exist.

If IO::Compress::Gzip is installed, MCCS will also automatically compress files that do not have a precompressed version and save the compressed versions to disk (so it only happens once and not on every request to the same file).

If CSS::Minifier::XS and/or JavaScript::Minifier::XS are installed, it will also automatically minify CSS/JS files that do not have a preminified version and save them to disk (once again, will only happen once per file).

This means MCCS needs to have write privileges to the static files directory. It would be better if files are preminified and precompressed, say automatically in your build process (if such a process exists). However, at some projects where you don't have an automatic build process, it is not uncommon to forget to minify/precompress. That's where automatic minification/compression is useful.

Most importantly, MCCS will generate proper Cache Control headers for every file served, including Last-Modified, Expires, Cache-Control and even ETag (ETags are created automatically, once per file, and saved to disk for future requests). It will appropriately respond with 304 Not Modified for requests with headers If-Modified-Since or If-None-Match when these cache validations are fulfilled, without actually having to read the files' contents again.

MCCS is active by default, which means that if there are some things you don't want it to do, you have to tell it not to. This is on purpose, because doing these actions is the whole point of MCCS.

WAIT, AREN'T THERE EXISTING PLACK MIDDLEWARES FOR THAT?

Yes and no. A similar functionality can be added to an application by using the following Plack middlewares:

So why wouldn't I just use these middlewares? Here are my reasons:

Plack::App::MCCS attempts to perform all of this faster and better. Read the next section for more info.

HOW DOES MCCS HANDLE REQUESTS?

When a request is handed to Plack::App::MCCS, the following process is performed:

HOW DO WEB CACHES WORK ANYWAY?

If you need more information on how caches work and cache control headers, read this great article.

CLASS METHODS

new( %opts )

Creates a new instance of this module. %opts must have the following keys:

root - the path to the root directory where static files reside.

%opts may have the following keys:

encoding - the character set to append to content-type headers when text files are returned. Defaults to UTF-8.

defaults - a hash-ref with some global defaults, the following options are supported:

min_cache_dir - For unminified files, by default minified files are generated in the same directory as the original file. If this attribute is specified they are instead generated within root/$min_cache_dir, and minified files outside that directory are ignored, unless requested directly. This can make it easier to filter out generated files when validating a deployment.

Giving minify, compress and etag false values is useful during development, when you don't want your project to be "polluted" with all those .gz, .min and .etag files.

types - a hash-ref with file extensions that may be served (keys must begin with a dot, so give '.css' and not 'css'). Every extension takes a hash-ref that might have valid_for and cache_control as with the defaults option, but also content_type with the content type to return for files with this extension (useful when Plack::MIME doesn't know the content type of a file).

If you don't want something to be cached, you need to give the valid_for option (either in defaults or for a specific file type) a value of either zero, or preferably any number lower than zero, which will cause MCCS to set an Expires header way in the past. You should also pass the cache_control option no_store and probably no_cache. When MCCS encounteres the no_store option, it does not automatically add the max-age option to the Cache-Control header.

OBJECT METHODS

call( \%env )

Plack automatically calls this method to handle a request. This is where the magic (or disaster) happens.

CAVEATS AND THINGS TO CONSIDER

DIAGNOSTICS

This module doesn't throw any exceptions, instead returning HTTP errors for the client and possibly issuing some warns. The following list should help you to determine some potential problems with MCCS:

CONFIGURATION AND ENVIRONMENT

Plack::App::MCCS requires no configuration files or environment variables.

DEPENDENCIES

Plack::App::MCCS depends on the following CPAN modules:

Plack::App::MCCS will use the following modules if they exist, in order to minify/compress files (if they are not installed, MCCS will not be able to minify/compress on its own):

INCOMPATIBILITIES WITH OTHER MODULES

None reported.

BUGS AND LIMITATIONS

No bugs have been reported.

Please report any bugs or feature requests to bug-Plack-App-MCCS@rt.cpan.org, or through the web interface at http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Plack-App-MCCS.

SEE ALSO

Plack::Middleware::MCCS, Plack::Middleware::Static, Plack::App::File, Plack::Builder.

AUTHOR

Ido Perlmuter ido@ido50.net

ACKNOWLEDGMENTS

Some of this module's code is based on Plack::App::File by Tatsuhiko Miyagawa and Plack::Middleware::ETag by Franck Cuny.

Christian Walde contributed new features and fixes for the 1.0.0 release.

LICENSE AND COPYRIGHT

Copyright (c) 2011-2016, Ido Perlmuter ido@ido50.net.

This module is free software; you can redistribute it and/or modify it under the same terms as Perl itself, either version 5.8.1 or any later version. See perlartistic and perlgpl.

The full text of the license can be found in the LICENSE file included with this module.

DISCLAIMER OF WARRANTY

BECAUSE THIS SOFTWARE IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE SOFTWARE, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE SOFTWARE "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE SOFTWARE IS WITH YOU. SHOULD THE SOFTWARE PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR, OR CORRECTION.

IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE SOFTWARE AS PERMITTED BY THE ABOVE LICENCE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE SOFTWARE (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE SOFTWARE TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.