tus-server 2.2.1 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,278 +0,0 @@
1
- # frozen-string-literal: true
2
-
3
- gem "mongo", "~> 2.3"
4
-
5
- require "mongo"
6
-
7
- require "tus/info"
8
- require "tus/response"
9
- require "tus/errors"
10
-
11
- require "digest"
12
-
13
- module Tus
14
- module Storage
15
- class Gridfs
16
- BATCH_SIZE = 5 * 1024 * 1024
17
-
18
- attr_reader :client, :prefix, :bucket, :chunk_size
19
-
20
- # Initializes the GridFS storage and creates necessary indexes.
21
- def initialize(client:, prefix: "fs", chunk_size: 256*1024)
22
- @client = client
23
- @prefix = prefix
24
- @chunk_size = chunk_size
25
- @bucket = client.database.fs(bucket_name: prefix)
26
-
27
- @bucket.send(:ensure_indexes!)
28
- end
29
-
30
- # Creates a file for the specified upload.
31
- def create_file(uid, info = {})
32
- content_type = Tus::Info.new(info).metadata["content_type"]
33
-
34
- create_grid_file(
35
- filename: uid,
36
- content_type: content_type,
37
- )
38
- end
39
-
40
- # Concatenates multiple partial uploads into a single upload, and returns
41
- # the size of the resulting upload. The partial uploads are deleted after
42
- # concatenation.
43
- #
44
- # It concatenates by updating partial upload's GridFS chunks to point to
45
- # the new upload.
46
- #
47
- # Raises Tus::Error if GridFS chunks of partial uploads don't exist or
48
- # aren't completely filled.
49
- def concatenate(uid, part_uids, info = {})
50
- grid_infos = files_collection.find(filename: {"$in" => part_uids}).to_a
51
- grid_infos.sort_by! { |grid_info| part_uids.index(grid_info[:filename]) }
52
-
53
- validate_parts!(grid_infos, part_uids)
54
-
55
- length = grid_infos.map { |doc| doc[:length] }.reduce(0, :+)
56
- content_type = Tus::Info.new(info).metadata["content_type"]
57
-
58
- grid_file = create_grid_file(
59
- filename: uid,
60
- length: length,
61
- content_type: content_type,
62
- )
63
-
64
- # Update the chunks belonging to parts so that they point to the new file.
65
- grid_infos.inject(0) do |offset, grid_info|
66
- result = chunks_collection
67
- .find(files_id: grid_info[:_id])
68
- .update_many(
69
- "$set" => { files_id: grid_file.id },
70
- "$inc" => { n: offset },
71
- )
72
-
73
- offset += result.modified_count
74
- end
75
-
76
- # Delete the parts after concatenation.
77
- files_collection.delete_many(filename: {"$in" => part_uids})
78
-
79
- # Tus server requires us to return the size of the concatenated file.
80
- length
81
- end
82
-
83
- # Appends data to the specified upload in a streaming fashion, and
84
- # returns the number of bytes it managed to save.
85
- #
86
- # It does so by reading the input data in batches of chunks, creating a
87
- # new GridFS chunk for each chunk of data and appending it to the
88
- # existing list.
89
- def patch_file(uid, input, info = {})
90
- grid_info = files_collection.find(filename: uid).first
91
- current_length = grid_info[:length]
92
- chunk_size = grid_info[:chunkSize]
93
- bytes_saved = 0
94
-
95
- # It's possible that the previous data append didn't fill in the last
96
- # GridFS chunk completely, so we fill in that gap now before creating
97
- # new GridFS chunks.
98
- bytes_saved += patch_last_chunk(input, grid_info) if current_length % chunk_size != 0
99
-
100
- # Create an Enumerator which yields chunks of input data which have the
101
- # size of the configured :chunkSize of the GridFS file.
102
- chunks_enumerator = Enumerator.new do |yielder|
103
- while (data = input.read(chunk_size))
104
- yielder << data
105
- end
106
- end
107
-
108
- chunks_in_batch = (BATCH_SIZE.to_f / chunk_size).ceil
109
- chunks_offset = chunks_collection.count(files_id: grid_info[:_id]) - 1
110
-
111
- # Iterate in batches of data chunks and bulk-insert new GridFS chunks.
112
- # This way we try to have a balance between bulking inserts and keeping
113
- # memory usage low.
114
- chunks_enumerator.each_slice(chunks_in_batch) do |chunks|
115
- grid_chunks = chunks.map do |data|
116
- Mongo::Grid::File::Chunk.new(
117
- data: BSON::Binary.new(data),
118
- files_id: grid_info[:_id],
119
- n: chunks_offset += 1,
120
- )
121
- end
122
-
123
- chunks_collection.insert_many(grid_chunks)
124
-
125
- # Update the total length and refresh the upload date on each update,
126
- # which are used in #get_file, #concatenate and #expire_files.
127
- files_collection.find(filename: uid).update_one(
128
- "$inc" => { length: chunks.map(&:bytesize).inject(0, :+) },
129
- "$set" => { uploadDate: Time.now.utc },
130
- )
131
- bytes_saved += chunks.map(&:bytesize).inject(0, :+)
132
-
133
- chunks.each(&:clear) # deallocate strings
134
- end
135
-
136
- bytes_saved
137
- end
138
-
139
- # Returns info of the specified upload. Raises Tus::NotFound if the upload
140
- # wasn't found.
141
- def read_info(uid)
142
- grid_info = files_collection.find(filename: uid).first or raise Tus::NotFound
143
- grid_info[:metadata]
144
- end
145
-
146
- # Updates info of the specified upload.
147
- def update_info(uid, info)
148
- files_collection.update_one({filename: uid}, {"$set" => {metadata: info}})
149
- end
150
-
151
- # Returns a Tus::Response object through which data of the specified
152
- # upload can be retrieved in a streaming fashion. Accepts an optional
153
- # range parameter for selecting a subset of bytes we want to retrieve.
154
- def get_file(uid, info = {}, range: nil)
155
- grid_info = files_collection.find(filename: uid).first
156
-
157
- filter = { files_id: grid_info[:_id] }
158
-
159
- if range
160
- chunk_start = range.begin / grid_info[:chunkSize]
161
- chunk_stop = range.end / grid_info[:chunkSize]
162
-
163
- filter[:n] = {"$gte" => chunk_start, "$lte" => chunk_stop}
164
- end
165
-
166
- # Query only the subset of chunks specified by the range query. We
167
- # cannot use Mongo::FsBucket#open_download_stream here because it
168
- # doesn't support changing the filter.
169
- chunks_view = chunks_collection.find(filter).sort(n: 1)
170
-
171
- # Create an Enumerator which will yield chunks of the requested file
172
- # content, allowing tus server to efficiently stream requested content
173
- # to the client.
174
- chunks = Enumerator.new do |yielder|
175
- chunks_view.each do |document|
176
- data = document[:data].data
177
-
178
- if document[:n] == chunk_start && document[:n] == chunk_stop
179
- byte_start = range.begin % grid_info[:chunkSize]
180
- byte_stop = range.end % grid_info[:chunkSize]
181
- elsif document[:n] == chunk_start
182
- byte_start = range.begin % grid_info[:chunkSize]
183
- byte_stop = grid_info[:chunkSize] - 1
184
- elsif document[:n] == chunk_stop
185
- byte_start = 0
186
- byte_stop = range.end % grid_info[:chunkSize]
187
- end
188
-
189
- # If we're on the first or last chunk, return a subset of the chunk
190
- # specified by the given range, otherwise return the full chunk.
191
- if byte_start && byte_stop
192
- yielder << data[byte_start..byte_stop]
193
- else
194
- yielder << data
195
- end
196
- end
197
- end
198
-
199
- Tus::Response.new(chunks: chunks, close: chunks_view.method(:close_query))
200
- end
201
-
202
- # Deletes the GridFS file and chunks for the specified upload.
203
- def delete_file(uid, info = {})
204
- grid_info = files_collection.find(filename: uid).first
205
- bucket.delete(grid_info[:_id]) if grid_info
206
- end
207
-
208
- # Deletes GridFS file and chunks of uploads older than the specified date.
209
- def expire_files(expiration_date)
210
- grid_infos = files_collection.find(uploadDate: {"$lte" => expiration_date}).to_a
211
- grid_info_ids = grid_infos.map { |info| info[:_id] }
212
-
213
- files_collection.delete_many(_id: {"$in" => grid_info_ids})
214
- chunks_collection.delete_many(files_id: {"$in" => grid_info_ids})
215
- end
216
-
217
- private
218
-
219
- # Creates a GridFS file.
220
- def create_grid_file(**options)
221
- grid_file = Mongo::Grid::File.new("", metadata: {}, chunk_size: chunk_size, **options)
222
-
223
- bucket.insert_one(grid_file)
224
-
225
- grid_file
226
- end
227
-
228
- # If the last GridFS chunk of the file is incomplete (meaning it's smaller
229
- # than the configured :chunkSize of the GridFS file), fills the missing
230
- # data by reading a chunk of the input data.
231
- def patch_last_chunk(input, grid_info)
232
- last_chunk = chunks_collection.find(files_id: grid_info[:_id]).sort(n: -1).limit(1).first
233
- data = last_chunk[:data].data
234
- patch = input.read(grid_info[:chunkSize] - data.bytesize)
235
- data << patch
236
-
237
- chunks_collection.find(files_id: grid_info[:_id], n: last_chunk[:n])
238
- .update_one("$set" => { data: BSON::Binary.new(data) })
239
-
240
- files_collection.find(_id: grid_info[:_id])
241
- .update_one("$inc" => { length: patch.bytesize })
242
-
243
- patch.bytesize
244
- end
245
-
246
- # Validates that GridFS files of partial uploads are suitable for
247
- # concatentation.
248
- def validate_parts!(grid_infos, part_uids)
249
- validate_parts_presence!(grid_infos, part_uids)
250
- validate_parts_full_chunks!(grid_infos)
251
- end
252
-
253
- # Validates that each partial upload has a corresponding GridFS file.
254
- def validate_parts_presence!(grid_infos, part_uids)
255
- if grid_infos.count != part_uids.count
256
- raise Tus::Error, "some parts for concatenation are missing"
257
- end
258
- end
259
-
260
- # Validates that GridFS chunks of each file are filled completely.
261
- def validate_parts_full_chunks!(grid_infos)
262
- grid_infos.each do |grid_info|
263
- if grid_info[:length] % grid_info[:chunkSize] != 0 && grid_info != grid_infos.last
264
- raise Tus::Error, "cannot concatenate parts which aren't evenly distributed across chunks"
265
- end
266
- end
267
- end
268
-
269
- def files_collection
270
- bucket.files_collection
271
- end
272
-
273
- def chunks_collection
274
- bucket.chunks_collection
275
- end
276
- end
277
- end
278
- end