{id}.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  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 debug = require('debug')('joystream:colossus:api:asset')
  20. const filter = require('@joystream/storage-node-backend/filter')
  21. const ipfsProxy = require('../../../lib/middleware/ipfs_proxy')
  22. const assert = require('assert')
  23. function errorHandler(response, err, code) {
  24. debug(err)
  25. // Some err types don't have a valid http status code such as one that come from ipfs node for example
  26. const statusCode = typeof err.code === 'number' ? err.code : code
  27. response.status(statusCode || 500).send({ message: err.toString() })
  28. response.end()
  29. }
  30. // The maximum total estimated balance that will be spent submitting transactions
  31. // by the node following processing one upload. Here we assume 3 transactions with
  32. // base transaction fee = 1. In future this estimate will need to be more accurate
  33. // and derived from weight to fee calculation.
  34. const PROCESS_UPLOAD_TX_COSTS = 3
  35. module.exports = function (storage, runtime, ipfsHttpGatewayUrl, anonymous) {
  36. debug('created path handler')
  37. // Creat the IPFS HTTP Gateway proxy middleware
  38. const proxy = ipfsProxy.createProxy(ipfsHttpGatewayUrl)
  39. // Cache of known content mappings and local availability info
  40. const ipfsContentIdMap = new Map()
  41. // Make sure id is valid and was 'Accepted', only then proxy if content is local
  42. const proxyAcceptedContentToIpfsGateway = async (req, res, next) => {
  43. const content_id = req.params.id
  44. if (!ipfsContentIdMap.has(content_id)) {
  45. const hash = runtime.assets.resolveContentIdToIpfsHash(req.params.id)
  46. if (!hash) {
  47. return res.status(404).send({ message: 'Unknown content' })
  48. }
  49. ipfsContentIdMap.set(content_id, {
  50. local: false,
  51. ipfs_content_id: hash,
  52. })
  53. }
  54. const { ipfs_content_id, local } = ipfsContentIdMap.get(content_id)
  55. // Pass on the ipfs hash to the middleware
  56. req.params.ipfs_content_id = ipfs_content_id
  57. // Serve it if we know we have it, or it was recently synced successfully
  58. if (local || storage.syncStatus(ipfs_content_id).synced) {
  59. return proxy(req, res, next)
  60. }
  61. // Not yet processed by sync run, check if we have it locally
  62. try {
  63. const stat = await storage.ipfsStat(ipfs_content_id, 4000)
  64. if (stat.local) {
  65. ipfsContentIdMap.set(content_id, {
  66. local: true,
  67. ipfs_content_id,
  68. })
  69. // We know we have the full content locally, serve it
  70. return proxy(req, res, next)
  71. }
  72. } catch (_err) {
  73. // timeout trying to stat which most likely means we do not have it
  74. // debug('Failed to stat', ipfs_content_id)
  75. }
  76. // Valid content but no certainty that the node has it locally yet.
  77. // We a void serving it to prevent poor performance (ipfs node will have to retrieve it on demand
  78. // which might be slow and wasteful if content is not cached locally)
  79. res.status(404).send({ message: 'Content not available locally' })
  80. }
  81. const doc = {
  82. // parameters for all operations in this path
  83. parameters: [
  84. {
  85. name: 'id',
  86. in: 'path',
  87. required: true,
  88. description: 'Joystream Content ID',
  89. schema: {
  90. type: 'string',
  91. },
  92. },
  93. ],
  94. // Put for uploads
  95. async put(req, res) {
  96. if (anonymous) {
  97. errorHandler(res, 'Uploads Not Permitted in Anonymous Mode', 400)
  98. return
  99. }
  100. const id = req.params.id // content id
  101. // Check if content exists
  102. const roleAddress = runtime.identities.key.address
  103. const providerId = runtime.storageProviderId
  104. let dataObject
  105. try {
  106. dataObject = await runtime.assets.getDataObject(id)
  107. } catch (err) {
  108. errorHandler(res, err, 403)
  109. return
  110. }
  111. if (!dataObject) {
  112. res.status(404).send({ message: 'Content Not Found' })
  113. return
  114. }
  115. // Early filtering on content_length..do not wait for fileInfo
  116. // ensure its less than max allowed by node policy.
  117. const filterResult = filter({}, req.headers)
  118. if (filterResult.code !== 200) {
  119. errorHandler(res, new Error(filterResult.message), filterResult.code)
  120. return
  121. }
  122. // Ensure content_length from request equals size in data object.
  123. if (!dataObject.size_in_bytes.eq(filterResult.content_length)) {
  124. errorHandler(res, new Error('Content Length does not match expected size of content'), 403)
  125. return
  126. }
  127. // Ensure we have minimum blance to successfully update state on chain after processing
  128. // upload. Due to the node handling concurrent uploads this check will not always guarantee
  129. // at the point when transactions are sent that the balance will still be sufficient.
  130. const sufficientBalance = await runtime.providerHasMinimumBalance(PROCESS_UPLOAD_TX_COSTS)
  131. if (!sufficientBalance) {
  132. errorHandler(res, 'Server has insufficient balance to process upload.', 503)
  133. return
  134. }
  135. // We'll open a write stream to the backend, but reserve the right to
  136. // abort upload if the filters don't smell right.
  137. let stream
  138. try {
  139. stream = await storage.open(id, 'w')
  140. // Wether we are aborting early because of early file detection not passing filter
  141. let aborted = false
  142. // Early file info detection so we can abort early on.. but we do not reject
  143. // content because we don't yet have ipfs computed
  144. stream.on('fileInfo', async (info) => {
  145. try {
  146. debug('Early file detection info:', info)
  147. const filterResult = filter({}, req.headers, info.mimeType)
  148. if (filterResult.code !== 200) {
  149. aborted = true
  150. debug('Ending stream', filterResult.message)
  151. stream.end()
  152. stream.cleanup()
  153. res.status(filterResult.code).send({ message: filterResult.message })
  154. }
  155. } catch (err) {
  156. errorHandler(res, err)
  157. }
  158. })
  159. stream.on('end', async () => {
  160. if (!aborted) {
  161. try {
  162. // try to get file info and compute ipfs hash before committing the stream to ifps node.
  163. await stream.info()
  164. } catch (err) {
  165. errorHandler(res, err)
  166. }
  167. }
  168. })
  169. // At end of stream we should have file info and computed ipfs hash - this event is emitted
  170. // only by explicitly calling stream.info() in the stream.on('finish') event handler
  171. stream.once('info', async (info, hash) => {
  172. if (hash === dataObject.ipfs_content_id.toString()) {
  173. const filterResult = filter({}, req.headers, info.mimeType)
  174. if (filterResult.code !== 200) {
  175. debug('Rejecting content')
  176. stream.cleanup()
  177. res.status(400).send({ message: 'Rejecting content type' })
  178. } else {
  179. try {
  180. await stream.commit()
  181. } catch (err) {
  182. errorHandler(res, err)
  183. }
  184. }
  185. } else {
  186. stream.cleanup()
  187. res.status(400).send({ message: 'Aborting - Not expected IPFS hash for content' })
  188. }
  189. })
  190. stream.on('committed', async (hash) => {
  191. // they cannot be different unless we did something stupid!
  192. assert(hash === dataObject.ipfs_content_id.toString())
  193. ipfsContentIdMap.set(id, {
  194. ipfs_content_id: hash,
  195. local: true,
  196. })
  197. // Send ok response early, no need for client to wait for relationships to be created.
  198. debug('Sending OK response.')
  199. res.status(200).send({ message: 'Asset uploaded.' })
  200. try {
  201. debug('accepting Content')
  202. // Only if judegment is Pending
  203. if (dataObject.liaison_judgement.type === 'Pending') {
  204. await runtime.assets.acceptContent(roleAddress, providerId, id)
  205. }
  206. } catch (err) {
  207. debug(`${err.message}`)
  208. }
  209. })
  210. stream.on('error', (err) => {
  211. stream.end()
  212. stream.cleanup()
  213. errorHandler(res, err)
  214. })
  215. req.pipe(stream)
  216. } catch (err) {
  217. errorHandler(res, err)
  218. }
  219. },
  220. async get(req, res, next) {
  221. proxyAcceptedContentToIpfsGateway(req, res, next)
  222. },
  223. async head(req, res, next) {
  224. proxyAcceptedContentToIpfsGateway(req, res, next)
  225. },
  226. }
  227. // doc.get = proxy
  228. // doc.head = proxy
  229. // Note: Adding the middleware this way is causing problems!
  230. // We are loosing some information from the request, specifically req.query.download parameters for some reason.
  231. // Does it have to do with how/when the apiDoc is being processed? binding issue?
  232. // OpenAPI specs
  233. doc.get.apiDoc = {
  234. description: 'Download an asset.',
  235. operationId: 'assetData',
  236. tags: ['asset', 'data'],
  237. parameters: [
  238. {
  239. name: 'download',
  240. in: 'query',
  241. description: 'Download instead of streaming inline.',
  242. required: false,
  243. allowEmptyValue: true,
  244. schema: {
  245. type: 'boolean',
  246. default: false,
  247. },
  248. },
  249. ],
  250. responses: {
  251. 200: {
  252. description: 'Asset download.',
  253. content: {
  254. default: {
  255. schema: {
  256. type: 'string',
  257. format: 'binary',
  258. },
  259. },
  260. },
  261. },
  262. default: {
  263. description: 'Unexpected error',
  264. content: {
  265. 'application/json': {
  266. schema: {
  267. $ref: '#/components/schemas/Error',
  268. },
  269. },
  270. },
  271. },
  272. },
  273. }
  274. doc.put.apiDoc = {
  275. description: 'Asset upload.',
  276. operationId: 'assetUpload',
  277. tags: ['asset', 'data'],
  278. requestBody: {
  279. content: {
  280. '*/*': {
  281. schema: {
  282. type: 'string',
  283. format: 'binary',
  284. },
  285. },
  286. },
  287. },
  288. responses: {
  289. 200: {
  290. description: 'Asset upload.',
  291. content: {
  292. 'application/json': {
  293. schema: {
  294. type: 'object',
  295. required: ['message'],
  296. properties: {
  297. message: {
  298. type: 'string',
  299. },
  300. },
  301. },
  302. },
  303. },
  304. },
  305. default: {
  306. description: 'Unexpected error',
  307. content: {
  308. 'application/json': {
  309. schema: {
  310. $ref: '#/components/schemas/Error',
  311. },
  312. },
  313. },
  314. },
  315. },
  316. }
  317. doc.head.apiDoc = {
  318. description: 'Asset download information.',
  319. operationId: 'assetInfo',
  320. tags: ['asset', 'metadata'],
  321. responses: {
  322. 200: {
  323. description: 'Asset info.',
  324. },
  325. default: {
  326. description: 'Unexpected error',
  327. content: {
  328. 'application/json': {
  329. schema: {
  330. $ref: '#/components/schemas/Error',
  331. },
  332. },
  333. },
  334. },
  335. },
  336. }
  337. return doc
  338. }