remote.js 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121
  1. const Minipass = require('minipass')
  2. const fetch = require('minipass-fetch')
  3. const promiseRetry = require('promise-retry')
  4. const ssri = require('ssri')
  5. const CachingMinipassPipeline = require('./pipeline.js')
  6. const getAgent = require('./agent.js')
  7. const pkg = require('../package.json')
  8. const USER_AGENT = `${pkg.name}/${pkg.version} (+https://npm.im/${pkg.name})`
  9. const RETRY_ERRORS = [
  10. 'ECONNRESET', // remote socket closed on us
  11. 'ECONNREFUSED', // remote host refused to open connection
  12. 'EADDRINUSE', // failed to bind to a local port (proxy?)
  13. 'ETIMEDOUT', // someone in the transaction is WAY TOO SLOW
  14. 'ERR_SOCKET_TIMEOUT', // same as above, but this one comes from agentkeepalive
  15. // Known codes we do NOT retry on:
  16. // ENOTFOUND (getaddrinfo failure. Either bad hostname, or offline)
  17. ]
  18. const RETRY_TYPES = [
  19. 'request-timeout',
  20. ]
  21. // make a request directly to the remote source,
  22. // retrying certain classes of errors as well as
  23. // following redirects (through the cache if necessary)
  24. // and verifying response integrity
  25. const remoteFetch = (request, options) => {
  26. const agent = getAgent(request.url, options)
  27. if (!request.headers.has('connection')) {
  28. request.headers.set('connection', agent ? 'keep-alive' : 'close')
  29. }
  30. if (!request.headers.has('user-agent')) {
  31. request.headers.set('user-agent', USER_AGENT)
  32. }
  33. // keep our own options since we're overriding the agent
  34. // and the redirect mode
  35. const _opts = {
  36. ...options,
  37. agent,
  38. redirect: 'manual',
  39. }
  40. return promiseRetry(async (retryHandler, attemptNum) => {
  41. const req = new fetch.Request(request, _opts)
  42. try {
  43. let res = await fetch(req, _opts)
  44. if (_opts.integrity && res.status === 200) {
  45. // we got a 200 response and the user has specified an expected
  46. // integrity value, so wrap the response in an ssri stream to verify it
  47. const integrityStream = ssri.integrityStream({
  48. algorithms: _opts.algorithms,
  49. integrity: _opts.integrity,
  50. size: _opts.size,
  51. })
  52. const pipeline = new CachingMinipassPipeline({
  53. events: ['integrity', 'size'],
  54. }, res.body, integrityStream)
  55. // we also propagate the integrity and size events out to the pipeline so we can use
  56. // this new response body as an integrityEmitter for cacache
  57. integrityStream.on('integrity', i => pipeline.emit('integrity', i))
  58. integrityStream.on('size', s => pipeline.emit('size', s))
  59. res = new fetch.Response(pipeline, res)
  60. // set an explicit flag so we know if our response body will emit integrity and size
  61. res.body.hasIntegrityEmitter = true
  62. }
  63. res.headers.set('x-fetch-attempts', attemptNum)
  64. // do not retry POST requests, or requests with a streaming body
  65. // do retry requests with a 408, 420, 429 or 500+ status in the response
  66. const isStream = Minipass.isStream(req.body)
  67. const isRetriable = req.method !== 'POST' &&
  68. !isStream &&
  69. ([408, 420, 429].includes(res.status) || res.status >= 500)
  70. if (isRetriable) {
  71. if (typeof options.onRetry === 'function') {
  72. options.onRetry(res)
  73. }
  74. return retryHandler(res)
  75. }
  76. return res
  77. } catch (err) {
  78. const code = (err.code === 'EPROMISERETRY')
  79. ? err.retried.code
  80. : err.code
  81. // err.retried will be the thing that was thrown from above
  82. // if it's a response, we just got a bad status code and we
  83. // can re-throw to allow the retry
  84. const isRetryError = err.retried instanceof fetch.Response ||
  85. (RETRY_ERRORS.includes(code) && RETRY_TYPES.includes(err.type))
  86. if (req.method === 'POST' || isRetryError) {
  87. throw err
  88. }
  89. if (typeof options.onRetry === 'function') {
  90. options.onRetry(err)
  91. }
  92. return retryHandler(err)
  93. }
  94. }, options.retry).catch((err) => {
  95. // don't reject for http errors, just return them
  96. if (err.status >= 400 && err.type !== 'system') {
  97. return err
  98. }
  99. throw err
  100. })
  101. }
  102. module.exports = remoteFetch