storage.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  1. /*
  2. * This file is part of the storage node for the Joystream project.
  3. * Copyright (C) 2019 Joystream Contributors
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. */
  18. 'use strict'
  19. const { Transform } = require('stream')
  20. const fs = require('fs')
  21. const debug = require('debug')('joystream:storage:storage')
  22. const Promise = require('bluebird')
  23. Promise.config({
  24. cancellation: true,
  25. })
  26. const fileType = require('file-type')
  27. const ipfsClient = require('ipfs-http-client')
  28. const temp = require('temp').track()
  29. const _ = require('lodash')
  30. // Default request timeout; imposed on top of the IPFS client, because the
  31. // client doesn't seem to care.
  32. const DEFAULT_TIMEOUT = 30 * 1000
  33. // Default/dummy resolution implementation.
  34. const DEFAULT_RESOLVE_CONTENT_ID = async (original) => {
  35. debug('Warning: Default resolution returns original CID', original)
  36. return original
  37. }
  38. // Default file info if nothing could be detected.
  39. const DEFAULT_FILE_INFO = {
  40. mimeType: 'application/octet-stream',
  41. ext: 'bin',
  42. }
  43. /*
  44. * fileType is a weird name, because we're really looking at MIME types.
  45. * Also, the type field includes extension info, so we're going to call
  46. * it fileInfo { mimeType, ext } instead.
  47. * Nitpicking, but it also means we can add our default type if things
  48. * go wrong.
  49. */
  50. function fixFileInfo(info) {
  51. if (!info) {
  52. info = DEFAULT_FILE_INFO
  53. } else {
  54. info.mimeType = info.mime
  55. delete info.mime
  56. }
  57. return info
  58. }
  59. function fixFileInfoOnStream(stream) {
  60. const info = fixFileInfo(stream.fileType)
  61. delete stream.fileType
  62. stream.fileInfo = info
  63. return stream
  64. }
  65. /*
  66. * Internal Transform stream for helping write to a temporary location, adding
  67. * MIME type detection, and a commit() function.
  68. */
  69. class StorageWriteStream extends Transform {
  70. constructor(storage, options) {
  71. options = _.clone(options || {})
  72. super(options)
  73. this.storage = storage
  74. // Create temp target.
  75. this.temp = temp.createWriteStream()
  76. this.buf = Buffer.alloc(0)
  77. }
  78. _transform(chunk, encoding, callback) {
  79. // Deal with buffers only
  80. if (typeof chunk === 'string') {
  81. chunk = Buffer.from(chunk)
  82. }
  83. // Logging this all the time is too verbose
  84. // debug('Writing temporary chunk', chunk.length, chunk);
  85. this.temp.write(chunk)
  86. // Try to detect file type during streaming.
  87. if (!this.fileInfo && this.buf.byteLength < fileType.minimumBytes) {
  88. this.buf = Buffer.concat([this.buf, chunk])
  89. if (this.buf >= fileType.minimumBytes) {
  90. const info = fileType(this.buf)
  91. // No info? We will try again at the end of the stream.
  92. if (info) {
  93. this.fileInfo = fixFileInfo(info)
  94. this.emit('fileInfo', this.fileInfo)
  95. }
  96. }
  97. }
  98. callback(null)
  99. }
  100. _flush(callback) {
  101. debug('Flushing temporary stream:', this.temp.path)
  102. this.temp.end()
  103. // TODO: compute ipfs hash and include it in emitted event fileInfo
  104. // Since we're finished, we can try to detect the file type again.
  105. // If we don't find type we should still emit with some indication of detection error.
  106. if (!this.fileInfo) {
  107. const read = fs.createReadStream(this.temp.path)
  108. fileType
  109. .stream(read)
  110. .then((stream) => {
  111. this.fileInfo = fixFileInfoOnStream(stream).fileInfo
  112. this.emit('fileInfo', this.fileInfo)
  113. })
  114. .catch((err) => {
  115. debug('Error trying to detect file type at end-of-stream:', err)
  116. this.emit('fileInfo', null)
  117. })
  118. }
  119. callback(null)
  120. }
  121. /*
  122. * Commit this stream to the IPFS backend.
  123. */
  124. commit() {
  125. if (!this.temp) {
  126. throw new Error('Cannot commit a temporary stream that does not exist. Did you call cleanup()?')
  127. }
  128. debug('Committing temporary stream: ', this.temp.path)
  129. this.storage.ipfs
  130. .addFromFs(this.temp.path)
  131. .then(async (result) => {
  132. const hash = result[0].hash
  133. debug('Stream committed as', hash)
  134. this.emit('committed', hash)
  135. await this.storage.ipfs.pin.add(hash)
  136. })
  137. .catch((err) => {
  138. debug('Error committing stream', err)
  139. this.emit('error', err)
  140. })
  141. }
  142. /*
  143. * Clean up temporary data.
  144. */
  145. cleanup() {
  146. debug('Cleaning up temporary file: ', this.temp.path)
  147. fs.unlink(this.temp.path, () => {
  148. /* Ignore errors. */
  149. })
  150. delete this.temp
  151. }
  152. }
  153. /*
  154. * Manages the storage backend interaction. This provides a Promise-based API.
  155. *
  156. * Usage:
  157. *
  158. * const store = await Storage.create({ ... });
  159. * store.open(...);
  160. */
  161. class Storage {
  162. /*
  163. * Create a Storage instance. Options include:
  164. *
  165. * - an `ipfs` property, which is itself a hash containing
  166. * - `connect_options` to be passed to the IPFS client library for
  167. * connecting to an IPFS node.
  168. * - a `resolve_content_id` function, which translates Joystream
  169. * content IDs to IPFS content IDs or vice versa. The default is to
  170. * not perform any translation, which is not practical for a production
  171. * system, but serves its function during development and testing. The
  172. * function must be asynchronous.
  173. * - a `timeout` parameter, defaulting to DEFAULT_TIMEOUT. After this time,
  174. * requests to the IPFS backend time out.
  175. *
  176. * Functions in this class accept an optional timeout parameter. If the
  177. * timeout is given, it is used - otherwise, the `option.timeout` value
  178. * above is used.
  179. */
  180. static create(options) {
  181. const storage = new Storage()
  182. storage._init(options)
  183. return storage
  184. }
  185. _init(options) {
  186. this.options = _.clone(options || {})
  187. this.options.ipfs = this.options.ipfs || {}
  188. this._timeout = this.options.timeout || DEFAULT_TIMEOUT
  189. this._resolve_content_id = this.options.resolve_content_id || DEFAULT_RESOLVE_CONTENT_ID
  190. this.ipfs = ipfsClient(this.options.ipfsHost || 'localhost', '5001', { protocol: 'http' })
  191. this.pinned = {}
  192. this.pinning = {}
  193. this.ipfs.id((err, identity) => {
  194. if (err) {
  195. debug(`Warning IPFS daemon not running: ${err.message}`)
  196. } else {
  197. debug(`IPFS node is up with identity: ${identity.id}`)
  198. // TODO: wait for IPFS daemon to be online for this to be effective..?
  199. // set the IPFS HTTP Gateway config we desire.. operator might need
  200. // to restart their daemon if the config was changed.
  201. this.ipfs.config.set('Gateway.PublicGateways', { 'localhost': null })
  202. }
  203. })
  204. }
  205. /*
  206. * Uses bluebird's timeout mechanism to return a Promise that times out after
  207. * the given timeout interval, and tries to execute the given operation within
  208. * that time.
  209. */
  210. async withSpecifiedTimeout(timeout, operation) {
  211. // TODO: rewrite this method to async-await style
  212. // eslint-disable-next-line no-async-promise-executor
  213. return new Promise(async (resolve, reject) => {
  214. try {
  215. resolve(await new Promise(operation))
  216. } catch (err) {
  217. reject(err)
  218. }
  219. }).timeout(timeout || this._timeout)
  220. }
  221. /*
  222. * Resolve content ID with timeout.
  223. */
  224. async resolveContentIdWithTimeout(timeout, contentId) {
  225. return await this.withSpecifiedTimeout(timeout, async (resolve, reject) => {
  226. try {
  227. resolve(await this._resolve_content_id(contentId))
  228. } catch (err) {
  229. reject(err)
  230. }
  231. })
  232. }
  233. /*
  234. * Stat a content ID.
  235. */
  236. async stat(contentId, timeout) {
  237. const resolved = await this.resolveContentIdWithTimeout(timeout, contentId)
  238. return await this.withSpecifiedTimeout(timeout, (resolve, reject) => {
  239. this.ipfs.files.stat(`/ipfs/${resolved}`, { withLocal: true }, (err, res) => {
  240. if (err) {
  241. reject(err)
  242. return
  243. }
  244. resolve(res)
  245. })
  246. })
  247. }
  248. /*
  249. * Return the size of a content ID.
  250. */
  251. async size(contentId, timeout) {
  252. const stat = await this.stat(contentId, timeout)
  253. return stat.size
  254. }
  255. /*
  256. * Opens the specified content in read or write mode, and returns a Promise
  257. * with the stream.
  258. *
  259. * Read streams will contain a fileInfo property, with:
  260. * - a `mimeType` field providing the file's MIME type, or a default.
  261. * - an `ext` property, providing a file extension suggestion, or a default.
  262. *
  263. * Write streams have a slightly different flow, in order to allow for MIME
  264. * type detection and potential filtering. First off, they are written to a
  265. * temporary location, and only committed to the backend once their
  266. * `commit()` function is called.
  267. *
  268. * When the commit has finished, a `committed` event is emitted, which
  269. * contains the IPFS backend's content ID.
  270. *
  271. * Write streams also emit a `fileInfo` event during writing. It is passed
  272. * the `fileInfo` field as described above. Event listeners may now opt to
  273. * abort the write or continue and eventually `commit()` the file. There is
  274. * an explicit `cleanup()` function that removes temporary files as well,
  275. * in case comitting is not desired.
  276. */
  277. async open(contentId, mode, timeout) {
  278. if (mode !== 'r' && mode !== 'w') {
  279. throw Error('The only supported modes are "r", "w" and "a".')
  280. }
  281. // Write stream
  282. if (mode === 'w') {
  283. return await this.createWriteStream(contentId, timeout)
  284. }
  285. // Read stream - with file type detection
  286. return await this.createReadStream(contentId, timeout)
  287. }
  288. async createWriteStream() {
  289. // IPFS wants us to just dump a stream into its storage, then returns a
  290. // content ID (of its own).
  291. // We need to instead return a stream immediately, that we eventually
  292. // decorate with the content ID when that's available.
  293. return new Promise((resolve) => {
  294. const stream = new StorageWriteStream(this)
  295. resolve(stream)
  296. })
  297. }
  298. async createReadStream(contentId, timeout) {
  299. const resolved = await this.resolveContentIdWithTimeout(timeout, contentId)
  300. let found = false
  301. return await this.withSpecifiedTimeout(timeout, (resolve, reject) => {
  302. const ls = this.ipfs.getReadableStream(resolved)
  303. ls.on('data', async (result) => {
  304. if (result.path === resolved) {
  305. found = true
  306. const ftStream = await fileType.stream(result.content)
  307. resolve(fixFileInfoOnStream(ftStream))
  308. }
  309. })
  310. ls.on('error', (err) => {
  311. ls.end()
  312. debug(err)
  313. reject(err)
  314. })
  315. ls.on('end', () => {
  316. if (!found) {
  317. const err = new Error('No matching content found for', contentId)
  318. debug(err)
  319. reject(err)
  320. }
  321. })
  322. ls.resume()
  323. })
  324. }
  325. /*
  326. * Synchronize the given content ID
  327. */
  328. async synchronize(contentId, callback) {
  329. const resolved = await this.resolveContentIdWithTimeout(this._timeout, contentId)
  330. // TODO: validate resolved id is proper ipfs_cid, not null or empty string
  331. if (!this.pinning[resolved] && !this.pinned[resolved]) {
  332. debug(`Pinning hash: ${resolved} content-id: ${contentId}`)
  333. this.pinning[resolved] = true
  334. // Callback passed to add() will be called on error or when the entire file
  335. // is retrieved. So on success we consider the content synced.
  336. this.ipfs.pin.add(resolved, { quiet: true, pin: true }, (err) => {
  337. delete this.pinning[resolved]
  338. if (err) {
  339. debug(`Error Pinning: ${resolved}`)
  340. callback && callback(err)
  341. } else {
  342. debug(`Pinned ${resolved}`)
  343. this.pinned[resolved] = true
  344. callback && callback(null, this.syncStatus(resolved))
  345. }
  346. })
  347. } else {
  348. callback && callback(null, this.syncStatus(resolved))
  349. }
  350. }
  351. syncStatus(ipfsHash) {
  352. return {
  353. syncing: this.pinning[ipfsHash] === true,
  354. synced: this.pinned[ipfsHash] === true,
  355. }
  356. }
  357. }
  358. module.exports = {
  359. Storage,
  360. }