@@ -2,21 +2,30 @@ local cjson = require "cjson.safe"
2
2
3
3
local _M = {}
4
4
5
+ local function parseDuration (str )
6
+ -- TODO: parse inputs like "1h", "2d", "10m" and return them as seconds
7
+ return 5 * 60
8
+ end
9
+
5
10
function _M .init ()
6
11
local npmConfig = ngx .shared .npmConfig
7
- local registry = os.getenv (" npm_config_registry" ):gsub (" /+$" , " " )
8
- local pattern = registry :gsub (" %." , " %%." ):gsub (" %-" , " %%-" )
12
+ _M .registry = os.getenv (" npm_config_registry" ):gsub (" /+$" , " " )
13
+ _M .hostPattern = _M .registry :gsub (" %." , " %%." ):gsub (" %-" , " %%-" )
14
+ _M .MAXAGE = parseDuration (os.getenv (" MAXAGE" ) or " 5m" )
9
15
-- escape . and - which have special meaning in Lua patterns
10
- npmConfig :set (' npm_config_registry' , registry )
11
- npmConfig :set (' npm_upstream_pattern' , pattern )
16
+ npmConfig :set (' npm_config_registry' , _M .registry )
17
+ npmConfig :set (' npm_upstream_pattern' , _M .hostPattern )
18
+ npmConfig :set (' MAXAGE' , _M .MAXAGE )
12
19
end
13
20
14
21
function _M .getPackage ()
15
22
local uri = ngx .var .uri
16
23
local meta = ngx .shared .npmMeta
17
24
local body = meta :get (uri )
25
+ local base = ngx .var .scheme .. ' ://' .. ngx .var .http_host
18
26
-- yep, our own shared memory cache implementation :-/
19
27
if body == nil then
28
+ ngx .var .ephemeralCacheStatus = ' MISS'
20
29
local res = ngx .location .capture (' /-@-' .. uri ,
21
30
{ copy_all_vars = true })
22
31
body = res .body
@@ -27,19 +36,13 @@ function _M.getPackage()
27
36
-- next time
28
37
return ngx .redirect (uri , ngx .HTTP_MOVED_TEMPORARILY )
29
38
end
30
- meta :set (uri , body )
39
+ meta :set (uri , body , _M .MAXAGE )
40
+ else
41
+ ngx .var .ephemeralCacheStatus = ' HIT'
31
42
end
43
+ body = string.gsub (body , _M .hostPattern , base )
32
44
ngx .header [" Content-Length" ] = # body
33
45
ngx .print (body )
34
46
end
35
47
36
- function _M .filterPackageBody ()
37
- local npmConfig = ngx .shared .npmConfig
38
- local upstream = npmConfig :get (' npm_upstream_pattern' )
39
- -- need to construct URL because we may be proxying http<->https
40
- local base = ngx .var .scheme .. ' ://' .. ngx .var .http_host
41
- -- ngx.log(ngx.ERR, "Modifying JSON of " .. ngx.var.uri .. " to replace '" .. upstream .. "' with '" .. base .. "'")
42
- ngx .arg [1 ] = string.gsub (ngx .arg [1 ], upstream , base )
43
- end
44
-
45
48
return _M
0 commit comments