{id}.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  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. // Creat the IPFS HTTP Gateway proxy middleware
  37. const proxy = ipfsProxy.createProxy(ipfsHttpGatewayUrl)
  38. const proxyAcceptedContentToIpfsGateway = async (req, res, next) => {
  39. // make sure id exists and was Accepted only then proxy
  40. const dataObject = await runtime.assets.getDataObject(req.params.id)
  41. if (dataObject && dataObject.liaison_judgement.type === 'Accepted') {
  42. req.params.ipfs_content_id = dataObject.ipfs_content_id.toString()
  43. proxy(req, res, next)
  44. } else {
  45. res.status(404).send({ message: 'Content not found' })
  46. }
  47. }
  48. const doc = {
  49. // parameters for all operations in this path
  50. parameters: [
  51. {
  52. name: 'id',
  53. in: 'path',
  54. required: true,
  55. description: 'Joystream Content ID',
  56. schema: {
  57. type: 'string',
  58. },
  59. },
  60. ],
  61. // Put for uploads
  62. async put(req, res) {
  63. if (anonymous) {
  64. errorHandler(res, 'Uploads Not Permitted in Anonymous Mode', 400)
  65. return
  66. }
  67. const id = req.params.id // content id
  68. // Check if content exists
  69. const roleAddress = runtime.identities.key.address
  70. const providerId = runtime.storageProviderId
  71. let dataObject
  72. try {
  73. dataObject = await runtime.assets.getDataObject(id)
  74. } catch (err) {
  75. errorHandler(res, err, 403)
  76. return
  77. }
  78. if (!dataObject) {
  79. res.status(404).send({ message: 'Content Not Found' })
  80. return
  81. }
  82. // Early filtering on content_length..do not wait for fileInfo
  83. // ensure its less than max allowed by node policy.
  84. const filterResult = filter({}, req.headers)
  85. if (filterResult.code !== 200) {
  86. errorHandler(res, new Error(filterResult.message), filterResult.code)
  87. return
  88. }
  89. // Ensure content_length from request equals size in data object.
  90. if (!dataObject.size_in_bytes.eq(filterResult.content_length)) {
  91. errorHandler(res, new Error('Content Length does not match expected size of content'), 403)
  92. return
  93. }
  94. // Ensure we have minimum blance to successfully update state on chain after processing
  95. // upload. Due to the node handling concurrent uploads this check will not always guarantee
  96. // at the point when transactions are sent that the balance will still be sufficient.
  97. const sufficientBalance = await runtime.providerHasMinimumBalance(PROCESS_UPLOAD_TX_COSTS)
  98. if (!sufficientBalance) {
  99. errorHandler(res, 'Server has insufficient balance to process upload.', 503)
  100. return
  101. }
  102. // We'll open a write stream to the backend, but reserve the right to
  103. // abort upload if the filters don't smell right.
  104. let stream
  105. try {
  106. stream = await storage.open(id, 'w')
  107. // Wether we are aborting early because of early file detection not passing filter
  108. let aborted = false
  109. // Early file info detection so we can abort early on.. but we do not reject
  110. // content because we don't yet have ipfs computed
  111. stream.on('fileInfo', async (info) => {
  112. try {
  113. debug('Early file detection info:', info)
  114. const filterResult = filter({}, req.headers, info.mimeType)
  115. if (filterResult.code !== 200) {
  116. aborted = true
  117. debug('Ending stream', filterResult.message)
  118. stream.end()
  119. stream.cleanup()
  120. res.status(filterResult.code).send({ message: filterResult.message })
  121. }
  122. } catch (err) {
  123. errorHandler(res, err)
  124. }
  125. })
  126. stream.on('end', async () => {
  127. if (!aborted) {
  128. try {
  129. // try to get file info and compute ipfs hash before committing the stream to ifps node.
  130. await stream.info()
  131. } catch (err) {
  132. errorHandler(res, err)
  133. }
  134. }
  135. })
  136. // At end of stream we should have file info and computed ipfs hash - this event is emitted
  137. // only by explicitly calling stream.info() in the stream.on('finish') event handler
  138. stream.once('info', async (info, hash) => {
  139. if (hash === dataObject.ipfs_content_id.toString()) {
  140. const filterResult = filter({}, req.headers, info.mimeType)
  141. if (filterResult.code !== 200) {
  142. debug('Rejecting content')
  143. stream.cleanup()
  144. res.status(400).send({ message: 'Rejecting content type' })
  145. } else {
  146. try {
  147. await stream.commit()
  148. } catch (err) {
  149. errorHandler(res, err)
  150. }
  151. }
  152. } else {
  153. stream.cleanup()
  154. res.status(400).send({ message: 'Aborting - Not expected IPFS hash for content' })
  155. }
  156. })
  157. stream.on('committed', async (hash) => {
  158. // they cannot be different unless we did something stupid!
  159. assert(hash === dataObject.ipfs_content_id.toString())
  160. // Send ok response early, no need for client to wait for relationships to be created.
  161. debug('Sending OK response.')
  162. res.status(200).send({ message: 'Asset uploaded.' })
  163. try {
  164. debug('accepting Content')
  165. // Only if judegment is Pending
  166. if (dataObject.liaison_judgement.type === 'Pending') {
  167. await runtime.assets.acceptContent(roleAddress, providerId, id)
  168. }
  169. // Is there any real value in updating this state? Nobody uses it!
  170. const { relationshipId } = await runtime.assets.getStorageRelationshipAndId(providerId, id)
  171. if (!relationshipId) {
  172. debug('creating storage relationship for newly uploaded content')
  173. // Create storage relationship and flip it to ready.
  174. const dosrId = await runtime.assets.createStorageRelationship(roleAddress, providerId, id)
  175. debug('toggling storage relationship for newly uploaded content')
  176. await runtime.assets.toggleStorageRelationshipReady(roleAddress, providerId, dosrId, true)
  177. }
  178. } catch (err) {
  179. debug(`${err.message}`)
  180. }
  181. })
  182. stream.on('error', (err) => {
  183. stream.end()
  184. stream.cleanup()
  185. errorHandler(res, err)
  186. })
  187. req.pipe(stream)
  188. } catch (err) {
  189. errorHandler(res, err)
  190. }
  191. },
  192. async get(req, res, next) {
  193. proxyAcceptedContentToIpfsGateway(req, res, next)
  194. },
  195. async head(req, res, next) {
  196. proxyAcceptedContentToIpfsGateway(req, res, next)
  197. },
  198. }
  199. // doc.get = proxy
  200. // doc.head = proxy
  201. // Note: Adding the middleware this way is causing problems!
  202. // We are loosing some information from the request, specifically req.query.download parameters for some reason.
  203. // Does it have to do with how/when the apiDoc is being processed? binding issue?
  204. // OpenAPI specs
  205. doc.get.apiDoc = {
  206. description: 'Download an asset.',
  207. operationId: 'assetData',
  208. tags: ['asset', 'data'],
  209. parameters: [
  210. {
  211. name: 'download',
  212. in: 'query',
  213. description: 'Download instead of streaming inline.',
  214. required: false,
  215. allowEmptyValue: true,
  216. schema: {
  217. type: 'boolean',
  218. default: false,
  219. },
  220. },
  221. ],
  222. responses: {
  223. 200: {
  224. description: 'Asset download.',
  225. content: {
  226. default: {
  227. schema: {
  228. type: 'string',
  229. format: 'binary',
  230. },
  231. },
  232. },
  233. },
  234. default: {
  235. description: 'Unexpected error',
  236. content: {
  237. 'application/json': {
  238. schema: {
  239. $ref: '#/components/schemas/Error',
  240. },
  241. },
  242. },
  243. },
  244. },
  245. }
  246. doc.put.apiDoc = {
  247. description: 'Asset upload.',
  248. operationId: 'assetUpload',
  249. tags: ['asset', 'data'],
  250. requestBody: {
  251. content: {
  252. '*/*': {
  253. schema: {
  254. type: 'string',
  255. format: 'binary',
  256. },
  257. },
  258. },
  259. },
  260. responses: {
  261. 200: {
  262. description: 'Asset upload.',
  263. content: {
  264. 'application/json': {
  265. schema: {
  266. type: 'object',
  267. required: ['message'],
  268. properties: {
  269. message: {
  270. type: 'string',
  271. },
  272. },
  273. },
  274. },
  275. },
  276. },
  277. default: {
  278. description: 'Unexpected error',
  279. content: {
  280. 'application/json': {
  281. schema: {
  282. $ref: '#/components/schemas/Error',
  283. },
  284. },
  285. },
  286. },
  287. },
  288. }
  289. doc.head.apiDoc = {
  290. description: 'Asset download information.',
  291. operationId: 'assetInfo',
  292. tags: ['asset', 'metadata'],
  293. responses: {
  294. 200: {
  295. description: 'Asset info.',
  296. },
  297. default: {
  298. description: 'Unexpected error',
  299. content: {
  300. 'application/json': {
  301. schema: {
  302. $ref: '#/components/schemas/Error',
  303. },
  304. },
  305. },
  306. },
  307. },
  308. }
  309. return doc
  310. }