winston = require('./logger').getLogger('blobs')
misc_node = require('@cocalc/backend/misc_node')
misc = require('@cocalc/util/misc')
{defaults, required} = misc
{MAX_BLOB_SIZE} = require('@cocalc/util/db-schema/blobs')
exports.save_blob = (opts) ->
opts = defaults opts,
uuid : undefined
blob : undefined
ttl : undefined
check : true
project_id : undefined
account_id : undefined
database : required
cb : required
dbg = (m) -> winston.debug("save_blob(uuid=#{opts.uuid}): #{m}")
dbg()
err = undefined
if not opts.blob?
err = "save_blob: UG -- error in call to save_blob (uuid=#{opts.uuid}); received a save_blob request with undefined blob"
else if not opts.uuid?
err = "save_blob: BUG -- error in call to save_blob; received a save_blob request without corresponding uuid"
else if not opts.project_id?
err = "save_blob: BUG -- error in call to save_blob; received a save_blob request without corresponding project_id"
else if opts.blob.length > MAX_BLOB_SIZE
err = "save_blob: blobs are limited to #{misc.human_readable_size(MAX_BLOB_SIZE)} and you just tried to save one of size #{opts.blob.length/1000000}MB"
else if opts.check and opts.uuid != misc_node.uuidsha1(opts.blob)
err = "save_blob: uuid=#{opts.uuid} must be derived from the Sha1 hash of blob, but it is not (possible malicious attack)"
if err
dbg(err)
opts.cb(err)
return
opts.database.save_blob
uuid : opts.uuid
blob : opts.blob
ttl : opts.ttl
project_id : opts.project_id
account_id : opts.account_id
cb : (err, ttl) =>
if err
dbg("failed to store blob -- #{err}")
else
dbg("successfully stored blob")
opts.cb(err, ttl)