read.js 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  1. 'use strict'
  2. const fs = require('fs/promises')
  3. const fsm = require('fs-minipass')
  4. const ssri = require('ssri')
  5. const contentPath = require('./path')
  6. const Pipeline = require('minipass-pipeline')
  7. module.exports = read
  8. const MAX_SINGLE_READ_SIZE = 64 * 1024 * 1024
  9. async function read (cache, integrity, opts = {}) {
  10. const { size } = opts
  11. const { stat, cpath, sri } = await withContentSri(cache, integrity, async (cpath, sri) => {
  12. // get size
  13. const stat = size ? { size } : await fs.stat(cpath)
  14. return { stat, cpath, sri }
  15. })
  16. if (stat.size > MAX_SINGLE_READ_SIZE) {
  17. return readPipeline(cpath, stat.size, sri, new Pipeline()).concat()
  18. }
  19. const data = await fs.readFile(cpath, { encoding: null })
  20. if (stat.size !== data.length) {
  21. throw sizeError(stat.size, data.length)
  22. }
  23. if (!ssri.checkData(data, sri)) {
  24. throw integrityError(sri, cpath)
  25. }
  26. return data
  27. }
  28. const readPipeline = (cpath, size, sri, stream) => {
  29. stream.push(
  30. new fsm.ReadStream(cpath, {
  31. size,
  32. readSize: MAX_SINGLE_READ_SIZE,
  33. }),
  34. ssri.integrityStream({
  35. integrity: sri,
  36. size,
  37. })
  38. )
  39. return stream
  40. }
  41. module.exports.stream = readStream
  42. module.exports.readStream = readStream
  43. function readStream (cache, integrity, opts = {}) {
  44. const { size } = opts
  45. const stream = new Pipeline()
  46. // Set all this up to run on the stream and then just return the stream
  47. Promise.resolve().then(async () => {
  48. const { stat, cpath, sri } = await withContentSri(cache, integrity, async (cpath, sri) => {
  49. // get size
  50. const stat = size ? { size } : await fs.stat(cpath)
  51. return { stat, cpath, sri }
  52. })
  53. return readPipeline(cpath, stat.size, sri, stream)
  54. }).catch(err => stream.emit('error', err))
  55. return stream
  56. }
  57. module.exports.copy = copy
  58. function copy (cache, integrity, dest) {
  59. return withContentSri(cache, integrity, (cpath) => {
  60. return fs.copyFile(cpath, dest)
  61. })
  62. }
  63. module.exports.hasContent = hasContent
  64. async function hasContent (cache, integrity) {
  65. if (!integrity) {
  66. return false
  67. }
  68. try {
  69. return await withContentSri(cache, integrity, async (cpath, sri) => {
  70. const stat = await fs.stat(cpath)
  71. return { size: stat.size, sri, stat }
  72. })
  73. } catch (err) {
  74. if (err.code === 'ENOENT') {
  75. return false
  76. }
  77. if (err.code === 'EPERM') {
  78. /* istanbul ignore else */
  79. if (process.platform !== 'win32') {
  80. throw err
  81. } else {
  82. return false
  83. }
  84. }
  85. }
  86. }
  87. async function withContentSri (cache, integrity, fn) {
  88. const sri = ssri.parse(integrity)
  89. // If `integrity` has multiple entries, pick the first digest
  90. // with available local data.
  91. const algo = sri.pickAlgorithm()
  92. const digests = sri[algo]
  93. if (digests.length <= 1) {
  94. const cpath = contentPath(cache, digests[0])
  95. return fn(cpath, digests[0])
  96. } else {
  97. // Can't use race here because a generic error can happen before
  98. // a ENOENT error, and can happen before a valid result
  99. const results = await Promise.all(digests.map(async (meta) => {
  100. try {
  101. return await withContentSri(cache, meta, fn)
  102. } catch (err) {
  103. if (err.code === 'ENOENT') {
  104. return Object.assign(
  105. new Error('No matching content found for ' + sri.toString()),
  106. { code: 'ENOENT' }
  107. )
  108. }
  109. return err
  110. }
  111. }))
  112. // Return the first non error if it is found
  113. const result = results.find((r) => !(r instanceof Error))
  114. if (result) {
  115. return result
  116. }
  117. // Throw the No matching content found error
  118. const enoentError = results.find((r) => r.code === 'ENOENT')
  119. if (enoentError) {
  120. throw enoentError
  121. }
  122. // Throw generic error
  123. throw results.find((r) => r instanceof Error)
  124. }
  125. }
  126. function sizeError (expected, found) {
  127. /* eslint-disable-next-line max-len */
  128. const err = new Error(`Bad data size: expected inserted data to be ${expected} bytes, but got ${found} instead`)
  129. err.expected = expected
  130. err.found = found
  131. err.code = 'EBADSIZE'
  132. return err
  133. }
  134. function integrityError (sri, path) {
  135. const err = new Error(`Integrity verification failed for ${sri} (${path})`)
  136. err.code = 'EINTEGRITY'
  137. err.sri = sri
  138. err.path = path
  139. return err
  140. }