Skip to content

Commit

Permalink
pre-cache related packages when caching
Browse files Browse the repository at this point in the history
This results in the registry pre-warm itself in response to the first
request.
  • Loading branch information
rmg committed May 11, 2017
1 parent 34d4468 commit 63b6542
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 2 deletions.
3 changes: 2 additions & 1 deletion Dockerfile
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
FROM openresty/openresty:alpine
MAINTAINER Ryan Graham <[email protected]>

RUN apk --no-cache add dnsmasq
RUN apk --no-cache add dnsmasq perl curl \
&& opm get pintsized/lua-resty-http

ADD entrypoint.sh nginx.conf ephemeral-npm.lua /

Expand Down
45 changes: 44 additions & 1 deletion ephemeral-npm.lua
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
local cjson = require "cjson.safe"
local http = require "resty.http"

local _M = {}

Expand All @@ -18,6 +19,44 @@ function _M.init()
npmConfig:set('MAXAGE', _M.MAXAGE)
end

function _M.prefetchRelatedPackages(premature, selfHost, pkg)
local httpc = http.new()
httpc:connect('127.0.0.1', 4873)
local distTags = pkg['dist-tags'] or {}
local versions = pkg.versions or {}
local latestVersion = distTags.latest
local latest = versions[latestVersion] or {}
local deps = latest.dependencies or {}
local reqs = {}
-- find any deps that we haven't already seen and queue them for fetching
for k, v in pairs(deps) do
if meta:get('/' .. k) == nil then
table.insert(reqs, {
path = '/' .. k,
method = 'GET',
headers = {
["Host"] = selfHost,
},
})
end
end
-- extract all the tarball URLs and fetch them to force them to be cached
for v,p in pairs(versions) do
local scheme, host, port, path, query = unpack(httpc:parse_uri(p.dist.tarball))
table.insert(reqs, {
path = path,
method = 'GET',
})
end
local responses, err = httpc:request_pipeline(reqs)
for i,r in ipairs(responses) do
if r.status then
r:read_body() -- to oblivion!
end
end
httpc:close()
end

function _M.getPackage()
local uri = ngx.var.uri
local meta = ngx.shared.npmMeta
Expand All @@ -37,10 +76,14 @@ function _M.getPackage()
return ngx.redirect(uri, ngx.HTTP_MOVED_TEMPORARILY)
end
meta:set(uri, body, _M.MAXAGE)
-- We rewrite the URLs AFTER caching so that we can be accessed by
-- any hostname that is pointed at us.
body = string.gsub(body, _M.hostPattern, base)
ngx.timer.at(0.1, _M.prefetchRelatedPackages, ngx.var.http_host, pkgJSON)
else
body = string.gsub(body, _M.hostPattern, base)
ngx.var.ephemeralCacheStatus = 'HIT'
end
body = string.gsub(body, _M.hostPattern, base)
ngx.header["Content-Length"] = #body
ngx.print(body)
end
Expand Down

0 comments on commit 63b6542

Please sign in to comment.