This repository has been archived by the owner on Nov 16, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5
/
server.js
70 lines (59 loc) · 1.81 KB
/
server.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
// Pre-emptive purging of the fastly cache fronting registry.npmjs.org.
// Clear out user and packages as they change.
process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0'
var conf = require('./config.js')
var follow = require('follow')
var fastly = require('fastly')(conf.fastlykey)
var path = require('path')
var fs = require('fs')
var SF = require('seq-file')
var regSeq = new SF(path.resolve(__dirname, 'registry.seq'))
var uSeq = new SF(path.resolve(__dirname, '_users.seq'))
// /registry/:pkg -> invalidate /:pkg
// /_users/:user -> invalidate /-/user/:user
// For views and such, just let the TTL and ETags do their thing
follow({
db: conf.registry,
include_docs: true,
inactivity_ms: conf.inactivity_ms,
since: regSeq.readSync()
}, function onchange (er, change) {
if (er)
throw er
// Make sure that we're at least c.lag ms behind the db
var doc = change.doc
if (doc && doc.time && doc.time.modified) {
var modified = Date.parse(doc.time.modified)
var now = Date.now()
var age = now - modified
if (age < conf.lag) {
return setTimeout(function() {
purge.call(this, '/' + change.id, regSeq, change.seq)
}.bind(this), conf.lag - age)
}
}
// Otherwise, if old enough, or no time info, just do it now.
purge.call(this, '/' + change.id, regSeq, change.seq)
})
follow({
db: conf._users,
include_docs: false,
inactivity_ms: conf.inactivity_ms,
since: uSeq.readSync()
}, userPurge)
function userPurge (er, change) {
if (er)
throw er
purge.call(this, '/-/user/' + change.id, uSeq, change.seq)
}
function purge(url, seqFile, seq) {
console.log('PURGE %s', url)
this.pause()
fastly.purge(conf.host, url, onpurge.bind(this, seqFile, seq))
}
function onpurge(seqFile, seq, er) {
if (er && er.statusCode !== 404)
throw er
seqFile.save(seq)
this.resume()
}