そろそろやることなくなったので minify などをやることにしました。

ただ、ブログシステムの出力の最後ほうでページごとに全体を minify すると、全体としてどうしても処理に時間がかかってしまいます。要求として、キャッシュなしの状態からでも1エントリあたり0.1秒ぐらいでは処理したいので、これだと厳しい感じでした。(約7900エントリぐらいあるので、0.1s で処理しても全体のキャッシュ再構築に13分かかる計算です)

いろいろ考えたのですが (そもそも minify しないとかも)、以下のようにしました

  • エントリ本文はエントリ保存時に minify しておく (本文はDB に格納)
  • テンプレートをテンプレートの段階で minify してキャッシュしておく

minify には html-minifier を使っています。html-minifier はテンプレートを対象にした minify も一応サポートしていて、ある程度妥協すればテンプレート対象でも十分に minify できます。

テンプレートとエントリが前もってをminifyされていれば、あとは繋げて出すだけです。

テンプレートの minify

このブログシステムのテンプレートは Text::Xslate::Syntax::TTerse です。

まず、Xslate のビュー読みこみをフックして、テンプレートを動的に minify するようにしました。

{
	no warnings 'redefine';
	*Text::Xslate::slurp_template = sub {
		my ($self, $input_layer, $fullpath) = @_;
		my $source = sub {
			if (ref $fullpath eq 'SCALAR') {
				return $$fullpath;
			} else {
				open my($source), '<' . $input_layer, $fullpath
					or $self->_error("LoadError: Cannot open $fullpath for reading: $!");
				local $/;
				return scalar <$source>;
			}
		}->();
		if ($fullpath =~ /\.html$/) {
			$source = Nogag::Utils->minify($source);
			return $source;
		} else {
			return $source;
		}
	};
	$XSLATE->load_file($_) for qw{
		index.html
		_article.html
		_adsense.html
		_images.html
	};
};

Xslate には pre_process_handler というのがあって、 読みこまれたテンプレートにフィルタをかけることができます。が、この機能だとファイル名がわからないので使っておらず、slurp_template を上書きしています。

(明示的に load_file しているのは、エラーが起きるなら起動時にしたいというのと、fork 前にロードすることでメモリの節約になるからで、本題とは関係ありません)

TTerse なテンプレートに対して html-minifier を使う場合、配慮する点がいくつかあります。

全体的にHTMLとしてパースできること

TTerse の場合以下のようにも書けますが、ダブルクオートの入れ子が HTML として見ると syntax error なので html-minifier で Parse Error になります。

<meta content="[% "foo" _ "bar" %]">

属性を出しわけるとき個別に条件をつける

テンプレートの構文をタグに混ぜるには html-minifier 側にオプションを設定します (customAttrSurround)。

ただ、複数属性を囲うとうまく属性を分解できなくて死ぬっぽいので、個別に囲う必要がありました。

<!-- ダメ -->
<article
   [% IF xxx %]
   itemscope
   itemprop="blogPosts"
   [% END %]
   >
<!-- よろしい -->
<article
   [% IF xxx %]itemscope[% END %]
   [% IF xxx %]itemprop="blogPosts"[% END %]
   >

sortClassName は false にする

クラスをテンプレートで出しわけしていると死にます

実際の html-minifier へのオプション

TTerse 対応のためオプションは以下のようになりました。customAttrSurround が適切に設定されていれば、sortAttributes は true にしても問題ないようです。

function processMinify (html) {
	return Promise.resolve(minify(html, {
		html5: true,
		customAttrSurround: [
			[/\[%\s*(?:IF|UNLESS)\s+.+?\s*%\]/, /\[%\s*END\s*%\]/]
		],
		decodeEntities: true,
		collapseBooleanAttributes: true,
		collapseInlineTagWhitespace: true,
		collapseWhitespace: true,
		conservativeCollapse: true,
		preserveLineBreaks: false,
		minifyCSS: true,
		minifyJS: true,
		removeAttributeQuotes: true,
		removeOptionalTags: true,
		removeRedundantAttributes: true,
		removeScriptTypeAttributes: true,
		removeStyleLinkTypeAttributes: true,
		processConditionalComments: true,
		removeComments: true,
		sortAttributes: true,
		sortClassName: false,
		useShortDoctype: true
	}));
}

エントリ本文のポストプロセス

エントリ保存時には、minify もそうですが、ほかにも修正を加えたいことが多々あります。例えば画像を強制的に https 化して mixed content を防ぎたいとか、コードハイライトを行いたいとかです。

コードハイライトは今まで highlight.js を使い、クライアントサイドでやっていました。これも本来ダイナミックにやる必要はなくポストプロセスでできることなので、そのように変えることにしました。highlight.js をサーバサイドで行うと、付与されるマークアップ分 HTML の転送量が増えますが、highlight.js 自体が結構大きいので、かなり長いコードをハイライトしない限り、サーバサイドでやったほうが得そうです。

以前サーバサイドでMathJaxを処理するようにしましたが、この node.js の内部向けサーバをさらに拡張して、JS でいろいろなポストプロセスの処理を書けるようにしました。

これにより、クライアントサイドでやってたことをそのままサーバサイドできるようになりました。すなわち、hightlight.js をそのままサーバサイドでも動かしていますし、jsdom を使って細かいHTMLの書きかえを querySelector など標準の DOM 操作でできるようにしています。

ポストプロセス用のデーモン

前述のように node.js で動くデーモンで、ブログシステム(Perl)とは別のプロセスで動き、APIサーバになっています。

全体的には以下のようなコードです。なお書き換え部分は変な挙動をするとやっかいなので、テストを書けるようにしてあります

#!/usr/bin/env node


const jsdom = require("jsdom").jsdom;
const mjAPI = require("mathjax-node/lib/mj-page.js");
const hljs = require('highlight.js');


const minify = require('html-minifier').minify;
const http = require('http');
const https = require('https');
const url = require('url');
const vm = require('vm');


const HTTPS = {
	GET : function (url) {
		var body = '';
		return new Promise( (resolve, reject) => {
			https.get(
				url,
				(res) => {
					res.on('data', function (chunk) {
						body += chunk;
					});
					res.on('end', function() {
						res.body = body;
						resolve(res);
					})
				}
			).on('error', reject);
		});
	}
};


mjAPI.start();
mjAPI.config({
	tex2jax: {
		inlineMath: [["\\(","\\)"]],
		displayMath: [ ["$$", "$$"] ]
	},
	extensions: ["tex2jax.js"]
});


function processWithString (html) {
	console.log('processWithString');
	return Promise.resolve(html).
		then(processMathJax).
		then(processMinify);
}


function processWithDOM (html) {
	console.log('processWithDOM');
	var document = jsdom(undefined, {
		features: {
			FetchExternalResources: false,
			ProcessExternalResources: false,
			SkipExternalResources: /./
		}
	});
	document.body.innerHTML = html;
	var dom = document.body;
	return Promise.resolve(dom).
		then(processHighlight).
		then(processImages).
		then(processWidgets).
		then( (dom) => dom.innerHTML );
}




function processHighlight (node) {
	console.log('processHighlight');
	var codes = node.querySelectorAll('pre.code');
	for (var i = 0, it; (it = codes[i]); i++) {
		if (/lang-(\S+)/.test(it.className)) {
			console.log('highlightBlock', it);
			hljs.highlightBlock(it);
		}
	}
	return Promise.resolve(node);
}


function processImages (node) {
	console.log('processImages');
	{
		var imgs = node.querySelectorAll('img[src*="googleusercontent"], img[src*="ggpht"]');
		for (var i = 0, img; (img = imgs[i]); i++) {
			img.src = img.src.
				replace(/^http:/, 'https:').
				replace(/\/s\d+\//g, '/s2048/');
		}
	}
	{
		var imgs = node.querySelectorAll('img[src*="cdn-ak.f.st-hatena.com"]');
		for (var i = 0, img; (img = imgs[i]); i++) {
			img.src = img.src.
				replace(/^http:/, 'https:');
		}
	}
	{
		var imgs = node.querySelectorAll('img[src*="ecx.images-amazon.com"]');
		for (var i = 0, img; (img = imgs[i]); i++) {
			img.src = img.src.
				replace(/^http:\/\/ecx\.images-amazon\.com/, 'https://images-na.ssl-images-amazon.com');
		}
	}
	return Promise.resolve(node);
}


function processWidgets (node) {
	var promises = [];


	console.log('processWidgets');
	var iframes = node.querySelectorAll('iframe[src*="www.youtube.com"]');
	for (var i = 0, iframe; (iframe = iframes[i]); i++) {
		iframe.src = iframe.src.replace(/^http:/, 'https:');
	}


	var scripts = node.getElementsByTagName('script');
	for (var i = 0, it; (it = scripts[i]); i++) (function (it) {
		if (!it.src) return;
		if (it.src.match(new RegExp('https://gist.github.com/[^.]+?.js'))) {
			var promise = HTTPS.GET(it.src).
				then( (res) => {
					var written = '';
					vm.runInNewContext(res.body, {
						document : {
							write : function (str) {
								written += str;
							}
						}
					});
					var div = node.ownerDocument.createElement('div');
					div.innerHTML = written;
					div.className = 'gist-github-com-js';
					it.parentNode.replaceChild(div, it);
				}).
				catch( (e) => {
					console.log(e);
				});


			promises.push(promise);
		}
	})(it);


	return Promise.all(promises).then( () => {
		return node;
	});
}


function processMathJax (html) {
	console.log('processMathJax');
	if (!html.match(/\\\(|\$\$/)) {
		return Promise.resolve(html);
	}
	return new Promise( (resolve, reject) => {
		mjAPI.typeset({
			html: html,
			renderer: "SVG",
			inputs: ["TeX"],
			ex: 6,
			width: 40
		}, function (result) {
			console.log('typeset done');
			console.log(result);


			resolve(result.html);
		});
	});
}


function processMinify (html) {
	return Promise.resolve(minify(html, {
		html5: true,
		customAttrSurround: [
			[/\[%\s*(?:IF|UNLESS)\s+.+?\s*%\]/, /\[%\s*END\s*%\]/]
		],
		decodeEntities: true,
		collapseBooleanAttributes: true,
		collapseInlineTagWhitespace: true,
		collapseWhitespace: true,
		conservativeCollapse: true,
		preserveLineBreaks: false,
		minifyCSS: true,
		minifyJS: true,
		removeAttributeQuotes: true,
		removeOptionalTags: true,
		removeRedundantAttributes: true,
		removeScriptTypeAttributes: true,
		removeStyleLinkTypeAttributes: true,
		processConditionalComments: true,
		removeComments: true,
		sortAttributes: true,
		sortClassName: false,
		useShortDoctype: true
	}));
}
const port = process.env['PORT'] || 13370


http.createServer(function (req, res) {
	var html = '';
	var location = url.parse(req.url, true);
	req.on('readable', function () {
		var chunk = req.read();
		console.log('readable');
		if (chunk) html += chunk.toString('utf8');
	});
	req.on('end', function() {
		console.log('end');


		if (location.query.minifyOnly) {
			Promise.resolve(html).
				then(processMinify).
				then( (html) => {
					console.log('done');
					res.writeHead(200, {'Content-Type': 'text/plain; charset=utf-8'});
					res.end(html);
				}).
				catch( (e) => {
					console.log(e);
					console.log(e.stack);
					res.writeHead(500, {'Content-Type': 'text/plain; charset=utf-8'});
					res.end(html);
				});
		} else {
			Promise.resolve(html).
				then(processWithDOM).
				then(processWithString).
				then( (html) => {
					console.log('done');
					res.writeHead(200, {'Content-Type': 'text/plain; charset=utf-8'});
					res.end(html);
				}).
				catch( (e) => {
					console.log(e);
					console.log(e.stack);
					res.writeHead(500, {'Content-Type': 'text/plain; charset=utf-8'});
					res.end(html);
				});
		}
	});
}).listen(port, '127.0.0.1');
console.log('Server running at http://127.0.0.1:' + port);

デーモン利用側

利用側は単純に http リクエストを送っているだけです。ときどきパースエラーで失敗したりするので、そういう場合は元々の HTML をそのまま使うようにしています。

運用

  1. エントリ保存時にはてな記法→HTMLと上記のような処理をしてDBに保存する(キャッシュ)
  2. レンダリング結果をページキャッシュ

という2段階のキャッシュがあります。テンプレートを変更しただけの場合、レンダリング結果のキャッシュを作りなおします。これは冒頭の通り約13分程度かかります。このページ単位のキャッシュはエントリを保存すると関連するキャッシュが自動的に無効になるようになっています。この場合、次回アクセス時に再生成になります。

記法フォーマッターのコード変更や、ポストプロセス処理に変更を入れた場合には、エントリのリフォーマットが必要です。これは全てやると約10分ぐらいかかります。ただ一部エントリだけにリフォーマットをかけるようなこともできるようにしています。

  1. トップ
  2. tech
  3. ブログシステムの HTML 生成を効率化

Default と Dark テーマの違い。お分かりいただけるだろうか……?

よく見ると Default のほうは、リソースの Timeline に DOMContentLoaded の線(青い線)がない。

今まで、なぜ表示されないんだろう? と疑問だったけど、Dark にしないと表示されないとは…… (バグじゃないか)

  1. トップ
  2. tech
  3. Chrome の Developer Tools でテーマが Dark のときだけ分かる情報

ほとんどのブラウザで、通常リロードは Cache-Control: max-age=0、スーパーリロードで Cache-Control: no-cache がリクエストヘッダとして送られてくるみたいなのですが、実際の挙動はともかく意味の違いがよくわかりませんでした。

RFC7234 によると max-age は

The "max-age" request directive indicates that the client is unwilling to accept a response whose age is greater than the specified number of seconds. Unless the max-stale request directive is also present, the client is not willing to accept a stale response.

https://tools.ietf.org/html/rfc7234

no-cache は

The "no-cache" request directive indicates that a cache MUST NOT use a stored response to satisfy the request without successful validation on the origin server.

https://tools.ietf.org/html/rfc7234

となっています。読んでも違いがよくわかりません。検索するとWhat's the difference between Cache-Control: max-age=0 and no-cache? あたりがヒットして、古いほうのRFC HTTP/1.1: Caching in HTTPが示されています。

max-age=0 は validate した結果最新とわかったならキャッシュを返すことを許しているが、no-cache はそもそも cache を使うことを許していない、という違いがあるようです。

もっというと、max-age=0 のときは validate して最新なら 304 を返してくれてもいいが、no-cache のときは validate すらせず全て 200 で転送しなおせという意味のようです。

余談:レスポンス時の Cache-Control: no-cache

レスポンス時の Cache-Control: no-cache が語感に反してキャッシュの利用を許可しているというのは良く知られている(?)と思いますが (キャッシュの利用を許可しないのは no-store)、これも max-age=0 との違いがよくわかってませんでした。

これについても上記の stackoverflow でわかりやすい解説があって、Cache-Control: no-cache は実質 Cache-Control: max-age=0, must-revalidate 相当だろうとのことでした。単純な max-age=0 はクライアント側が validate できなければ期限切れのキャッシュ利用を許しているという違いがあるようです。

  1. トップ
  2. tech
  3. リクエスト時の Cache-Control、max-age=0 と no-cache の違い

Hardware IO Tools for Xcode をダウンロードすると Network Link Conditioner という環境設定が含まれていて、インストールするとそこそこ細かくネットワーク環境を再現できます。Xcode → Open Developer Tools → More Developer Tools… とたどるといろんなツールを検索できるページにいくので、そこからダウンロードしてこれます。

プリセットだと LTE っぽいプロファイルがないので、適当にカスタムプロファイルを作ってみました。Downlink/Uplink で別々に設定できることから、Delay はおそらく片道っぽいので、RTT / 2 を設定します。Bandwidth は各社の実効速度データのうち、下限付近を参考に設定しました。

当然ながらテスト環境の回線品質が良くないとテストにならないので、平均とか25%値でテストしようと思うなら無線LANでテストしてたらダメそうです。

また、システム全体に効いてしまうので、他のアプリケーションで通信が発生しまくっているとかなり影響してきます。

throttling しつつ nghttp

なお Chrome の場合は開発者ツールの Network タブで速度と Latency を設定して throttling できます。

ref.

  1. トップ
  2. tech
  3. OS X でのネットワークの throttling を簡単に設定する

h2o は mruby ハンドラで link ヘッダを使って push を指示すると、バックエンドへの問合せと非同期で静的ファイルを push してくれます。

もしバックエンドアプリケーションで link ヘッダを吐いて push する場合、バックエンドアプリケーションの処理が終わったあとから push が始まることになるので、アプリケーションの実行時間分、push できる時間を失うことになります。

server-push の指示をテンプレートに書きたい病

自分はプリロード指示をバックエンド側のテンプレートに書きたい病にかかっており、現状で以下のようなテンプレートコードを書いて、バックエンドから preload ヘッダを吐いています。

r.preload() は link ヘッダを追加するメソッドになっており、これを実際に読みこんでいるHTMLの部分の近くに置くことでリソース管理を簡略化しています。

しかし、これだとバックエンドから h2o へ server-push を指示する形になるので、前述のようにアプリケーションの実行時間分、push できる時間を無駄にします。

バックエンドから server-push するリストをあらかじめ取得する

できれば無駄をなくしたいので、やはり h2o の mruby ハンドラでも link ヘッダを吐くことにします。

ただ、二重に設定を書きたくはないので、バックエンドの吐く link ヘッダを、h2o 起動時に取得しておき、以降のリクエストではそれを元に server-push させるようにします。

まずバックエンドのヘッダをファイルに保存しておきます。ここでは適当に curl を使ってます。

curl -s --head -H 'Cache-Control: no-cache' https://lowreal.net > /srv/www/lowreal.net.link.txt

そして、起動時に read して push する分の link ヘッダを作っておき、ハンドラでそれを送るように設定します。

        mruby.handler: |
          LINK = File.read("/srv/www/lowreal.net.link.txt").
            split(/\r?\n/).select{|l| l.sub!(/^link: /, "") and l.match(/rel=preload/) and !l.match(/nopush/) }.
            join("\n")


          $stderr.puts LINK.inspect


          lambda do |env|
            [ 399, { "link" => LINK }, [] ]
         end

運用上は、適当なタイミング(デプロイタイミング)で curl を打って再度ヘッダを保存して h2o を再起動するようにします。

余談ですが curl を使わずとも mruby ハンドラ内で使える http_request() があるので h2o で完結しそうと思いきや、起動中のコンテキストでは使えないみたいです。

効果

mruby ハンドラで server-push を指示しない場合

mruby ハンドラで server-push を指示する場合

見るべきは、各リソースの responseEnd の時間と、 / に対する requestStart の時間の差です。ただ requestStart はいずれも 1ms 程度なので、注目するのは responseEnd だけで良さそうです。

mruby ハンドラで指示しない場合各リソースの responseEnd は100ms以上になっています。これはバックエンドの処理に約100msほどかかっているからです。一方 mruby ハンドラで指示する場合、responseEnd は 22ms ぐらいになっています。

この例だと、静的ファイルの responseEnd から、バックエンドのレスポンス開始までまだ時間があるので、もっと静的ファイルを server-push する余地がありそうです。

('cache-control: no-cache' をつけているのはバックエンド側のキャッシュを無効にして処理時間を作って差をわかりやすくしているだけです)

  1. トップ
  2. tech
  3. h2o での server-push タイミングの最適化

h2o の casper (cache-aware server-push) を有効にしていると、force reload したときでも push されなくなってしまって、だんだん混乱してきます。YAML を一時的に変えて再起動したりしていたのですが、自分以外にも影響が及ぶのでちょっとなんとかしました。

JS で h2o_casper クッキーを削除してからリロードする

最初に思いつく方法で手軽なやつです。以下のようなブックマークレットでリロードすると cookie がない状態からのリロードになります。

javascript:document.cookie="h2o_casper=; max-age=-1; path=/";location.reload(true);

h2o へパッチをあてて、force reload 時は常に h2o_casper を無視してプッシュさせる

force reload 時にブラウザはリクエストヘッダに Cache-Control: no-cache をつけるので (全てのブラウザかどうかわかりませんが)、その場合にはクッキーを無視して push します (set-cookie は吐かれます)

Cache-Control: no-cache とクライアントが宣言しているなら、casper も無効になっているのは正当ではないか?と思い実装しましたが、ほんとにそうか自信がないので、ひとまず自分のところでテストしています (このサーバには適用済み)。

diff --git a/lib/http2/connection.c b/lib/http2/connection.c
index 4395728..bc83829 100644
--- a/lib/http2/connection.c
+++ b/lib/http2/connection.c
@@ -1185,6 +1185,19 @@ static void push_path(h2o_req_t *src_req, const char *abspath, size_t abspath_le
                 src_stream->pull.casper_state = H2O_HTTP2_STREAM_CASPER_DISABLED;
                 return;
             }
+
+            /* disable casper (always push) when super-reloaded (cache-control is exactly matched to no-cache) */
+            if ( (header_index = h2o_find_header(&src_stream->req.headers, H2O_TOKEN_CACHE_CONTROL, -1)) != -1) {
+                h2o_header_t *header = src_stream->req.headers.entries + header_index;
+                if (h2o_lcstris(header->value.base, header->value.len, H2O_STRLIT("no-cache"))) {
+                    /* casper enabled for this request but ignore cookie */
+                    if (conn->casper == NULL)
+                        h2o_http2_conn_init_casper(conn, src_stream->req.hostconf->http2.casper.capacity_bits);
+                    src_stream->pull.casper_state = H2O_HTTP2_STREAM_CASPER_READY;
+                    break;
+                }
+            }
+
             /* casper enabled for this request */
             if (conn->casper == NULL)
                 h2o_http2_conn_init_casper(conn, src_stream->req.hostconf->http2.casper.capacity_bits);

mruby.handler でなんとかできないかと思いましたが、mruby 側の env に渡ってくる HTTP_COOKIE とかを書きかえても h2o 内部の処理には影響しないみたいなので無理そうでした。

  1. トップ
  2. tech
  3. h2o の casper を一時的に無効にする