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 10, 2017
1 parent 82ce02f commit 1438f76
Show file tree
Hide file tree
Showing 2 changed files with 43 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
42 changes: 41 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 @@ -11,6 +12,44 @@ function _M.init()
npmConfig:set('npm_upstream_pattern', pattern)
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 @@ -27,7 +66,8 @@ function _M.getPackage()
-- next time
return ngx.redirect(uri, ngx.HTTP_MOVED_TEMPORARILY)
end
meta:set(uri, body)
local succ, err, forcible = meta:set(uri, body)
ngx.timer.at(0.1, _M.prefetchRelatedPackages, ngx.var.http_host, pkgJSON)
end
ngx.header["Content-Length"] = #body
ngx.print(body)
Expand Down

0 comments on commit 1438f76

Please sign in to comment.