Pre-compress static assets

This compresses the static assets with gzip on server startup, and then
serves them up compressed to clients.

The compression is done at server startup because some boards have very
anemic CPUs and slow "disks", so loading from disk pre-compressed and
avoiding CPU usage is a big win.
This commit is contained in:
Flaviu Tamas committed 2020-03-29 09:47:10 -04:00
1 parent 6232a04e52
commit 851539cc6f
3 files changed
+58 -11

No files matched your search

+8 -6
View File
@@ -686,7 +686,8 @@ class Server(object):
as_attachment=True),
camera_permission_validator)),
# generated webassets
(r"/static/webassets/(.*)", util.tornado.LargeResponseHandler, dict(path=os.path.join(self._settings.getBaseFolder("generated"), "webassets"))),
(r"/static/webassets/(.*)", util.tornado.LargeResponseHandler, dict(path=os.path.join(self._settings.getBaseFolder("generated"), "webassets"),
is_pre_compressed=True)),
# online indicators - text file with "online" as content and a transparent gif
(r"/online.txt", util.tornado.StaticDataHandler, dict(data="online\n")),
@@ -1568,13 +1569,14 @@ class Server(object):
# a couple of custom filters
from octoprint.server.util.webassets import LessImportRewrite, JsDelimiterBundler, \
SourceMapRewrite, SourceMapRemove, JsPluginBundle
SourceMapRewrite, SourceMapRemove, JsPluginBundle, GzipFile
from webassets.filter import register_filter
register_filter(LessImportRewrite)
register_filter(SourceMapRewrite)
register_filter(SourceMapRemove)
register_filter(JsDelimiterBundler)
register_filter(GzipFile)
def all_assets_for_plugins(collection):
"""Gets all plugin assets for a dict of plugin->assets"""
@@ -1585,8 +1587,8 @@ class Server(object):
# -- JS --------------------------------------------------------------------------------------------------------
js_filters = ["sourcemap_remove", "js_delimiter_bundler"]
js_plugin_filters = ["sourcemap_remove", "js_delimiter_bundler"]
js_filters = ["sourcemap_remove", "js_delimiter_bundler", "gzip"]
js_plugin_filters = ["sourcemap_remove", "js_delimiter_bundler", "gzip"]
def js_bundles_for_plugins(collection, filters=None):
"""Produces JsPluginBundle instances that output IIFE wrapped assets"""
@@ -1645,7 +1647,7 @@ class Server(object):
# -- CSS -------------------------------------------------------------------------------------------------------
css_filters = ["cssrewrite"]
css_filters = ["cssrewrite", "gzip"]
css_core = list(dynamic_core_assets["css"]) \
+ all_assets_for_plugins(dynamic_plugin_assets["bundled"]["css"])
@@ -1675,7 +1677,7 @@ class Server(object):
# -- LESS ------------------------------------------------------------------------------------------------------
less_filters = ["cssrewrite", "less_importrewrite"]
less_filters = ["cssrewrite", "less_importrewrite", "gzip"]
less_core = list(dynamic_core_assets["less"]) \
+ all_assets_for_plugins(dynamic_plugin_assets["bundled"]["less"])
+29 -5
View File
@@ -949,11 +949,13 @@ class LargeResponseHandler(RequestlessExceptionLoggingMixin,
called with the response handler as parameter. May return ``None`` to prevent the ETag response header
from being set. If not provided the last modified time of the file in question will be used as returned
by ``get_content_version``.
is_pre_compressed (bool): if the file is expected to be pre-compressed, i.e, if there is a file in the same
directory with the same name, but with '.gz' appended and gzip-encoded
"""
def initialize(self, path, default_filename=None, as_attachment=False, allow_client_caching=True,
access_validation=None, path_validation=None, etag_generator=None, name_generator=None,
mime_type_guesser=None):
mime_type_guesser=None, is_pre_compressed=False):
tornado.web.StaticFileHandler.initialize(self, os.path.abspath(path), default_filename)
self._as_attachment = as_attachment
self._allow_client_caching = allow_client_caching
@@ -962,6 +964,11 @@ class LargeResponseHandler(RequestlessExceptionLoggingMixin,
self._etag_generator = etag_generator
self._name_generator = name_generator
self._mime_type_guesser = mime_type_guesser
self._is_pre_compressed = is_pre_compressed
def should_use_precompressed(self):
return (self._is_pre_compressed and
"gzip" in self.request.headers.get("Accept-Encoding"))
def get(self, path, include_body=True):
if self._access_validation is not None:
@@ -972,8 +979,11 @@ class LargeResponseHandler(RequestlessExceptionLoggingMixin,
if "cookie" in self.request.arguments:
self.set_cookie(self.request.arguments["cookie"][0], "true", path="/")
result = tornado.web.StaticFileHandler.get(self, path, include_body=include_body)
return result
if self.should_use_precompressed():
self.set_header("Content-Encoding", "gzip")
path = path + ".gz"
return tornado.web.StaticFileHandler.get(self, path, include_body=include_body)
def set_extra_headers(self, path):
if self._as_attachment:
@@ -991,6 +1001,12 @@ class LargeResponseHandler(RequestlessExceptionLoggingMixin,
self.set_header("Cache-Control", "max-age=0, must-revalidate, private")
self.set_header("Expires", "-1")
def original_absolute_path(self):
"""The path of the uncompressed file corresponding to the compressed file"""
if self._is_pre_compressed:
return self.absolute_path.rstrip('.gz')
return self.absolute_path
def compute_etag(self):
if self._etag_generator is not None:
return self._etag_generator(self)
@@ -999,11 +1015,19 @@ class LargeResponseHandler(RequestlessExceptionLoggingMixin,
def get_content_type(self):
if self._mime_type_guesser is not None:
type = self._mime_type_guesser(self.absolute_path)
type = self._mime_type_guesser(self.original_absolute_path)
if type is not None:
return type
return tornado.web.StaticFileHandler.get_content_type(self)
correct_absolute_path = None
try:
if self.should_use_precompressed():
correct_absolute_path = self.absolute_path
self.absolute_path = self.original_absolute_path()
return tornado.web.StaticFileHandler.get_content_type(self)
finally:
if self.should_use_precompressed() and correct_absolute_path is not None:
self.absolute_path = correct_absolute_path
@classmethod
def get_content_version(cls, abspath):
+21
View File
@@ -5,6 +5,8 @@ __author__ = "Gina Häußge <gina@octoprint.org>"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2017 The OctoPrint Project - Released under terms of the AGPLv3 License"
import gzip
import os
import re
try:
@@ -105,6 +107,25 @@ class JsDelimiterBundler(Filter):
out.write("\n;\n")
class GzipFile(Filter):
name = "gzip"
options = {}
def output(self, _in, out, **kwargs):
data = _in.read()
out.write(data)
# webassets requires us to output a "str", but we can't do that since gzip
# provides binary outputs.
#
# We work around that by outputting the gziped file to another path
if kwargs.get("output_path", None):
output_path = kwargs["output_path"]
gziped_output_path = output_path + ".gz"
with open(gziped_output_path, "wb") as gziped_output:
gziped_output.write(gzip.compress(data.encode("utf8"), compresslevel=9))
class ChainedHunk(BaseHunk):
def __init__(self, *hunks):
self._hunks = hunks