Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Avatar for KuCalc : devops.
Download
50641 views
1
###
2
Jupyter in-memory blob store, which hooks into the raw http server.
3
###
4
5
fs = require('fs')
6
7
misc = require('smc-util/misc')
8
misc_node = require('smc-util-node/misc_node')
9
10
# TODO: are these the only base64 encoded types that jupyter kernels return?
11
BASE64_TYPES = ['image/png', 'image/jpeg', 'application/pdf', 'base64']
12
13
class BlobStore
14
constructor: ->
15
@_blobs = {}
16
17
# data could, e.g., be a uuencoded image
18
# We return the sha1 hash of it, and store it, along with a reference count.
19
# ipynb = optional some original data that is also stored and will be
20
# returned when get_ipynb is called
21
save: (data, type, ipynb) =>
22
if type in BASE64_TYPES
23
data = new Buffer.from(data, 'base64')
24
else
25
data = new Buffer.from(data)
26
sha1 = misc_node.sha1(data)
27
x = @_blobs[sha1] ?= {ref:0, data:data, type:type}
28
x.ref += 1
29
x.ipynb = ipynb
30
return sha1
31
32
readFile: (path, type, cb) =>
33
fs.readFile path, (err, data) =>
34
if err
35
cb(err)
36
else
37
sha1 = misc_node.sha1(data)
38
ext = misc.filename_extension(path)?.toLowerCase()
39
x = @_blobs[sha1] ?= {ref:0, data:data, type:type}
40
x.ref += 1
41
cb(undefined, sha1)
42
43
free: (sha1) =>
44
x = @_blobs[sha1]
45
if x?
46
x.ref -= 1
47
if x.ref <= 0
48
delete @_blobs[sha1]
49
return
50
51
get: (sha1) =>
52
return @_blobs[sha1]?.data
53
54
get_ipynb: (sha1) =>
55
x = @_blobs[sha1]
56
if not x?
57
return
58
if x.ipynb?
59
return x.ipynb
60
if x.type in BASE64_TYPES
61
return x.data.toString('base64')
62
else
63
return x.data.toString()
64
65
keys: =>
66
return misc.keys(@_blobs)
67
68
express_router: (base, express) =>
69
router = express.Router()
70
base += 'blobs/'
71
72
router.get base, (req, res) =>
73
sha1s = misc.to_json(@keys())
74
res.send(sha1s)
75
router.get base + '*', (req, res) =>
76
filename = req.path.slice(base.length)
77
sha1 = req.query.sha1
78
res.type(filename)
79
res.send(@get(sha1))
80
return router
81
82
83
exports.blob_store = new BlobStore()
84
85
86