GcsPersistor.js 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  1. const fs = require('fs')
  2. const { pipeline } = require('stream/promises')
  3. const { PassThrough } = require('stream')
  4. const { Storage, IdempotencyStrategy } = require('@google-cloud/storage')
  5. const { WriteError, ReadError, NotFoundError } = require('./Errors')
  6. const asyncPool = require('tiny-async-pool')
  7. const AbstractPersistor = require('./AbstractPersistor')
  8. const PersistorHelper = require('./PersistorHelper')
  9. const Logger = require('@overleaf/logger')
  10. module.exports = class GcsPersistor extends AbstractPersistor {
  11. constructor(settings) {
  12. super()
  13. this.settings = settings
  14. // endpoint settings will be null by default except for tests
  15. // that's OK - GCS uses the locally-configured service account by default
  16. const storageOptions = {}
  17. if (this.settings.endpoint) {
  18. storageOptions.projectId = this.settings.endpoint.projectId
  19. storageOptions.apiEndpoint = this.settings.endpoint.apiEndpoint
  20. }
  21. storageOptions.retryOptions = { ...this.settings.retryOptions }
  22. if (storageOptions.retryOptions) {
  23. if (storageOptions.retryOptions.idempotencyStrategy) {
  24. const value =
  25. IdempotencyStrategy[this.settings.retryOptions.idempotencyStrategy]
  26. if (value === undefined) {
  27. throw new Error(
  28. 'Unrecognised value for retryOptions.idempotencyStrategy'
  29. )
  30. }
  31. Logger.info(
  32. `Setting retryOptions.idempotencyStrategy to ${storageOptions.retryOptions.idempotencyStrategy} (${value})`
  33. )
  34. storageOptions.retryOptions.idempotencyStrategy = value
  35. }
  36. }
  37. this.storage = new Storage(storageOptions)
  38. }
  39. async sendFile(bucketName, key, fsPath) {
  40. return await this.sendStream(bucketName, key, fs.createReadStream(fsPath))
  41. }
  42. async sendStream(bucketName, key, readStream, opts = {}) {
  43. try {
  44. const observeOptions = {
  45. metric: 'gcs.egress', // egress from us to GCS
  46. bucket: bucketName,
  47. }
  48. let sourceMd5 = opts.sourceMd5
  49. if (!sourceMd5) {
  50. // if there is no supplied md5 hash, we calculate the hash as the data passes through
  51. observeOptions.hash = 'md5'
  52. }
  53. const observer = new PersistorHelper.ObserverStream(observeOptions)
  54. const writeOptions = {
  55. // disabling of resumable uploads is recommended by Google:
  56. resumable: false,
  57. }
  58. if (sourceMd5) {
  59. writeOptions.validation = 'md5'
  60. writeOptions.metadata = writeOptions.metadata || {}
  61. writeOptions.metadata.md5Hash = PersistorHelper.hexToBase64(sourceMd5)
  62. }
  63. if (opts.contentType) {
  64. writeOptions.metadata = writeOptions.metadata || {}
  65. writeOptions.metadata.contentType = opts.contentType
  66. }
  67. if (opts.contentEncoding) {
  68. writeOptions.metadata = writeOptions.metadata || {}
  69. writeOptions.metadata.contentEncoding = opts.contentEncoding
  70. }
  71. const uploadStream = this.storage
  72. .bucket(bucketName)
  73. .file(key)
  74. .createWriteStream(writeOptions)
  75. await pipeline(readStream, observer, uploadStream)
  76. // if we didn't have an md5 hash, we should compare our computed one with Google's
  77. // as we couldn't tell GCS about it beforehand
  78. if (!sourceMd5) {
  79. sourceMd5 = observer.getHash()
  80. // throws on mismatch
  81. await PersistorHelper.verifyMd5(this, bucketName, key, sourceMd5)
  82. }
  83. } catch (err) {
  84. throw PersistorHelper.wrapError(
  85. err,
  86. 'upload to GCS failed',
  87. { bucketName, key },
  88. WriteError
  89. )
  90. }
  91. }
  92. async getObjectStream(bucketName, key, opts = {}) {
  93. const observer = new PersistorHelper.ObserverStream({
  94. metric: 'gcs.ingress', // ingress to us from GCS
  95. bucket: bucketName,
  96. })
  97. const stream = this.storage
  98. .bucket(bucketName)
  99. .file(key)
  100. .createReadStream({ decompress: false, ...opts })
  101. try {
  102. await new Promise((resolve, reject) => {
  103. stream.on('response', res => {
  104. switch (res.statusCode) {
  105. case 200: // full response
  106. case 206: // partial response
  107. return resolve()
  108. case 404:
  109. return reject(new NotFoundError())
  110. default:
  111. return reject(new Error('non success status: ' + res.statusCode))
  112. }
  113. })
  114. stream.on('error', reject)
  115. stream.read(0) // kick off request
  116. })
  117. } catch (err) {
  118. throw PersistorHelper.wrapError(
  119. err,
  120. 'error reading file from GCS',
  121. { bucketName, key, opts },
  122. ReadError
  123. )
  124. }
  125. // Return a PassThrough stream with a minimal interface. It will buffer until the caller starts reading. It will emit errors from the source stream (Stream.pipeline passes errors along).
  126. const pass = new PassThrough()
  127. pipeline(stream, observer, pass).catch(() => {})
  128. return pass
  129. }
  130. async getRedirectUrl(bucketName, key) {
  131. if (this.settings.unsignedUrls) {
  132. // Construct a direct URL to the object download endpoint
  133. // (see https://cloud.google.com/storage/docs/request-endpoints#json-api)
  134. const apiEndpoint =
  135. this.settings.endpoint.apiEndpoint || 'https://storage.googleapis.com'
  136. return `${apiEndpoint}/download/storage/v1/b/${bucketName}/o/${key}?alt=media`
  137. }
  138. try {
  139. const [url] = await this.storage
  140. .bucket(bucketName)
  141. .file(key)
  142. .getSignedUrl({
  143. action: 'read',
  144. expires: Date.now() + this.settings.signedUrlExpiryInMs,
  145. })
  146. return url
  147. } catch (err) {
  148. throw PersistorHelper.wrapError(
  149. err,
  150. 'error generating signed url for GCS file',
  151. { bucketName, key },
  152. ReadError
  153. )
  154. }
  155. }
  156. async getObjectSize(bucketName, key) {
  157. try {
  158. const [metadata] = await this.storage
  159. .bucket(bucketName)
  160. .file(key)
  161. .getMetadata()
  162. return metadata.size
  163. } catch (err) {
  164. throw PersistorHelper.wrapError(
  165. err,
  166. 'error getting size of GCS object',
  167. { bucketName, key },
  168. ReadError
  169. )
  170. }
  171. }
  172. async getObjectMd5Hash(bucketName, key) {
  173. try {
  174. const [metadata] = await this.storage
  175. .bucket(bucketName)
  176. .file(key)
  177. .getMetadata()
  178. return PersistorHelper.base64ToHex(metadata.md5Hash)
  179. } catch (err) {
  180. throw PersistorHelper.wrapError(
  181. err,
  182. 'error getting hash of GCS object',
  183. { bucketName, key },
  184. ReadError
  185. )
  186. }
  187. }
  188. async deleteObject(bucketName, key) {
  189. try {
  190. const file = this.storage.bucket(bucketName).file(key)
  191. if (this.settings.deletedBucketSuffix) {
  192. await file.copy(
  193. this.storage
  194. .bucket(`${bucketName}${this.settings.deletedBucketSuffix}`)
  195. .file(`${key}-${new Date().toISOString()}`)
  196. )
  197. }
  198. if (this.settings.unlockBeforeDelete) {
  199. await file.setMetadata({ eventBasedHold: false })
  200. }
  201. await file.delete()
  202. } catch (err) {
  203. // ignore 404s: it's fine if the file doesn't exist.
  204. if (err.code === 404) {
  205. return
  206. }
  207. throw PersistorHelper.wrapError(
  208. err,
  209. 'error deleting GCS object',
  210. { bucketName, key },
  211. WriteError
  212. )
  213. }
  214. }
  215. async deleteDirectory(bucketName, key) {
  216. const prefix = ensurePrefixIsDirectory(key)
  217. let query = { prefix, autoPaginate: false }
  218. do {
  219. try {
  220. const [files, nextQuery] = await this.storage
  221. .bucket(bucketName)
  222. .getFiles(query)
  223. // iterate over paginated results using the nextQuery returned by getFiles
  224. query = nextQuery
  225. if (Array.isArray(files) && files.length > 0) {
  226. await asyncPool(
  227. this.settings.deleteConcurrency,
  228. files,
  229. async file => {
  230. await this.deleteObject(bucketName, file.name)
  231. }
  232. )
  233. }
  234. } catch (err) {
  235. const error = PersistorHelper.wrapError(
  236. err,
  237. 'failed to delete directory in GCS',
  238. { bucketName, key },
  239. WriteError
  240. )
  241. if (error instanceof NotFoundError) {
  242. return
  243. }
  244. throw error
  245. }
  246. } while (query)
  247. }
  248. async directorySize(bucketName, key) {
  249. let files
  250. const prefix = ensurePrefixIsDirectory(key)
  251. try {
  252. const [response] = await this.storage
  253. .bucket(bucketName)
  254. .getFiles({ prefix })
  255. files = response
  256. } catch (err) {
  257. throw PersistorHelper.wrapError(
  258. err,
  259. 'failed to list objects in GCS',
  260. { bucketName, key },
  261. ReadError
  262. )
  263. }
  264. return files.reduce((acc, file) => Number(file.metadata.size) + acc, 0)
  265. }
  266. async checkIfObjectExists(bucketName, key) {
  267. try {
  268. const [response] = await this.storage
  269. .bucket(bucketName)
  270. .file(key)
  271. .exists()
  272. return response
  273. } catch (err) {
  274. throw PersistorHelper.wrapError(
  275. err,
  276. 'error checking if file exists in GCS',
  277. { bucketName, key },
  278. ReadError
  279. )
  280. }
  281. }
  282. async copyObject(bucketName, sourceKey, destKey) {
  283. try {
  284. const src = this.storage.bucket(bucketName).file(sourceKey)
  285. const dest = this.storage.bucket(bucketName).file(destKey)
  286. await src.copy(dest)
  287. } catch (err) {
  288. // fake-gcs-server has a bug that returns an invalid response when the file does not exist
  289. if (err.message === 'Cannot parse response as JSON: not found\n') {
  290. err.code = 404
  291. }
  292. throw PersistorHelper.wrapError(
  293. err,
  294. 'failed to copy file in GCS',
  295. { bucketName, sourceKey, destKey },
  296. WriteError
  297. )
  298. }
  299. }
  300. }
  301. function ensurePrefixIsDirectory(key) {
  302. return key === '' || key.endsWith('/') ? key : `${key}/`
  303. }