{id}.js 11 KB

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