1 var app = angular.module('Workbench', ['Arvados']);
2 app.controller('UploadToCollection', UploadToCollection);
3 app.directive('arvUuid', arvUuid);
6 // Copy the given uuid into the current $scope.
9 link: function(scope, element, attributes) {
10 scope.uuid = attributes.arvUuid;
15 UploadToCollection.$inject = ['$scope', '$filter', '$q', '$timeout',
16 'ArvadosClient', 'arvadosApiToken'];
17 function UploadToCollection($scope, $filter, $q, $timeout,
18 ArvadosClient, arvadosApiToken) {
21 uploader: new QueueUploader(),
22 addFilesToQueue: function(files) {
23 // Angular binding doesn't work its usual magic for file
24 // inputs, so we need to $scope.$apply() this update.
25 $scope.$apply(function(){
27 // Add these new files after the items already waiting
28 // in the queue -- but before the items that are
29 // 'Done' and have therefore been pushed to the
32 (nItemsTodo < $scope.uploadQueue.length &&
33 $scope.uploadQueue[nItemsTodo].state !== 'Done'); ) {
36 for (i=0; i<files.length; i++) {
37 $scope.uploadQueue.splice(nItemsTodo+i, 0,
38 new FileUploader(files[i]));
46 $scope.uploader.stop();
48 removeFileFromQueue: function(index) {
49 var wasRunning = $scope.uploader.running;
50 $scope.uploadQueue[index].stop();
51 $scope.uploadQueue.splice(index, 1);
55 countInStates: function(want_states) {
57 $.each($scope.uploadQueue, function() {
58 if (want_states.indexOf(this.state) >= 0) {
65 ////////////////////////////////
69 function SliceReader(_slice) {
74 ////////////////////////////////
78 // Return a promise, which will be resolved with the
79 // requested slice data.
80 _deferred = $.Deferred();
81 _reader = new FileReader();
82 _reader.onload = resolve;
83 _reader.onerror = _deferred.reject;
84 _reader.onprogress = _deferred.notify;
85 _reader.readAsArrayBuffer(_slice.blob);
86 return _deferred.promise();
89 if (that._reader.result.length !== that._slice.size) {
90 // Sometimes we get an onload event even if the read
91 // did not return the desired number of bytes. We
92 // treat that as a fail.
95 "Short read: wanted " + _slice.size +
96 ", received " + _reader.result.length);
99 return _deferred.resolve(_reader.result);
103 function SliceUploader(_label, _data, _dataSize) {
108 ////////////////////////////////
115 // Send data to the Keep proxy. Retry a few times on
116 // fail. Return a promise that will get resolved with
117 // resolve(locator) when the block is accepted by the
119 _deferred = $.Deferred();
121 return _deferred.promise();
127 textStatus: 'stopped',
128 err: 'interrupted at slice '+_label
137 'Authorization': 'OAuth2 '+arvadosApiToken,
138 'Content-Type': 'application/octet-stream',
139 'X-Keep-Desired-Replicas': '2'
142 // Make an xhr that reports upload progress
143 var xhr = $.ajaxSettings.xhr();
145 xhr.upload.onprogress = onSendProgress;
152 _jqxhr.then(onSendResolve, onSendReject);
154 function onSendProgress(xhrProgressEvent) {
155 _deferred.notify(xhrProgressEvent.loaded, _dataSize);
157 function onSendResolve(data, textStatus, jqxhr) {
158 _deferred.resolve(data, _dataSize);
160 function onSendReject(xhr, textStatus, err) {
161 if (++_failCount < _failMax) {
162 // TODO: nice to tell the user that retry is happening.
163 console.log('slice ' + _label + ': ' +
164 textStatus + ', retry ' + _failCount);
168 {xhr: xhr, textStatus: textStatus, err: err});
171 function proxyUriBase() {
172 return ((keepProxy.service_ssl_flag ? 'https' : 'http') +
173 '://' + keepProxy.service_host + ':' +
174 keepProxy.service_port + '/');
178 function FileUploader(file) {
183 state: 'Queued', // Queued, Uploading, Paused, Uploaded, Done
186 stop: stop // User wants to stop.
188 ////////////////////////////////
190 var _currentUploader;
193 var _maxBlobSize = Math.pow(2,26);
195 var _queueTime = Date.now();
199 var _readPos = 0; // number of bytes confirmed uploaded
202 _deferred.reject({textStatus: 'restarted'});
203 _deferred = $.Deferred();
204 that.state = 'Uploading';
205 _startTime = Date.now();
206 _startByte = _readPos;
209 return _deferred.promise().always(function() { _deferred = null; });
213 that.state = 'Paused';
214 _deferred.reject({textStatus: 'stopped', err: 'interrupted'});
216 if (_currentUploader) {
217 _currentUploader.stop();
218 _currentUploader = null;
222 // Ensure this._deferred gets resolved or rejected --
223 // either right here, or when a new promise arranged right
224 // here is fulfilled.
225 _currentSlice = nextSlice();
226 if (!_currentSlice) {
227 // All slices have been uploaded, but the work won't
228 // be truly Done until the target collection has been
229 // updated by the QueueUploader. This state is called:
230 that.state = 'Uploaded';
231 setProgress(_readPos);
232 _currentUploader = null;
233 _deferred.resolve([that]);
236 _currentUploader = new SliceUploader(
240 _currentUploader.go().then(
245 function onUploaderResolve(locator, dataSize) {
246 var sizeHint = (''+locator).split('+')[1];
247 if (!locator || parseInt(sizeHint) !== dataSize) {
248 console.log("onUploaderResolve, but locator '" + locator +
249 "' with size hint '" + sizeHint +
250 "' does not look right for dataSize=" + dataSize);
251 return onUploaderReject({
253 err: "Bad response from slice upload"
256 that.locators.push(locator);
257 _readPos += dataSize;
258 _currentUploader = null;
261 function onUploaderReject(reason) {
262 that.state = 'Paused';
263 setProgress(_readPos);
264 _currentUploader = null;
266 _deferred.reject(reason);
268 function onUploaderProgress(sliceDone, sliceSize) {
269 setProgress(_readPos + sliceDone);
271 function nextSlice() {
274 that.file.size - _readPos);
275 setProgress(_readPos);
279 var blob = that.file.slice(
280 _readPos, _readPos+size,
281 'application/octet-stream; charset=x-user-defined');
282 return {blob: blob, size: size};
284 function setProgress(bytesDone) {
286 if (that.file.size == 0)
289 that.progress = Math.min(100, 100 * bytesDone / that.file.size);
290 if (bytesDone > _startByte) {
291 kBps = (bytesDone - _startByte) /
292 (Date.now() - _startTime);
294 '' + $filter('number')(bytesDone/1024, '0') + ' KiB ' +
295 'at ~' + $filter('number')(kBps, '0') + ' KiB/s')
296 if (that.state === 'Paused') {
297 that.statistics += ', paused';
298 } else if (that.state === 'Uploading') {
299 that.statistics += ', ETA ' +
302 Date.now() + (that.file.size - bytesDone) / kBps),
306 that.statistics = that.state;
308 if (that.state === 'Uploaded') {
309 // 'Uploaded' gets reported as 'finished', which is a
310 // little misleading because the collection hasn't
311 // been updated yet. But FileUploader's portion of the
312 // work (and the time when it makes sense to show
313 // speed and ETA) is finished.
314 that.statistics += ', finished ' +
315 $filter('date')(Date.now(), 'shortTime');
316 _finishTime = Date.now();
323 function QueueUploader() {
325 state: 'Idle', // Idle, Running, Stopped, Failed
331 ////////////////////////////////
333 var _deferred; // the one we promise to go()'s caller
334 var _deferredAppend; // tracks current appendToCollection
336 if (_deferred) return _deferred.promise();
337 if (_deferredAppend) return _deferredAppend.promise();
338 _deferred = $.Deferred();
339 that.state = 'Running';
340 ArvadosClient.apiPromise(
341 'keep_services', 'list',
342 {filters: [['service_type','=','proxy']]}).
343 then(doQueueWithProxy);
345 return _deferred.promise().always(function() { _deferred = null; });
348 that.state = 'Stopped';
350 _deferred.reject({});
352 for (var i=0; i<$scope.uploadQueue.length; i++)
353 $scope.uploadQueue[i].stop();
356 function doQueueWithProxy(data) {
357 keepProxy = data.items[0];
359 that.state = 'Failed';
361 'There seems to be no Keep proxy service available.';
362 _deferred.reject(null, 'error', that.stateReason);
365 return doQueueWork();
367 function doQueueWork() {
368 // If anything is not Done, do it.
369 if ($scope.uploadQueue.length > 0 &&
370 $scope.uploadQueue[0].state !== 'Done') {
372 that.stateReason = null;
373 return $scope.uploadQueue[0].go().
374 then(appendToCollection, null, onQueueProgress).
375 then(doQueueWork, onQueueReject);
377 // Queue work has been stopped. Just update the
383 // If everything is Done, resolve the promise and clean
384 // up. Note this can happen even after the _deferred
385 // promise has been rejected: specifically, when stop() is
386 // called too late to prevent completion of the last
387 // upload. In that case we want to update state to "Idle",
388 // rather than leave it at "Stopped".
391 function onQueueReject(reason) {
393 // Outcome has already been decided (by stop()).
397 that.state = 'Failed';
399 (reason.textStatus || 'Error') +
400 (reason.xhr && reason.xhr.options
401 ? (' (from ' + reason.xhr.options.url + ')')
405 if (reason.xhr && reason.xhr.responseText)
406 that.stateReason += ' -- ' + reason.xhr.responseText;
407 _deferred.reject(reason);
410 function onQueueResolve() {
412 that.stateReason = 'Done!';
417 function onQueueProgress() {
418 // Ensure updates happen after FileUpload promise callbacks.
419 $timeout(function(){$scope.$apply();});
421 function appendToCollection(uploads) {
422 _deferredAppend = $.Deferred();
423 ArvadosClient.apiPromise(
424 'collections', 'get',
425 { uuid: $scope.uuid }).
426 then(function(collection) {
427 var manifestText = '';
428 $.each(uploads, function(_, upload) {
429 var locators = upload.locators;
430 if (locators.length === 0) {
431 // Every stream must have at least one
432 // data locator, even if it is zero bytes
434 locators = ['d41d8cd98f00b204e9800998ecf8427e+0'];
436 filename = ArvadosClient.uniqueNameForManifest(
437 collection.manifest_text,
438 '.', upload.file.name);
439 collection.manifest_text += '. ' +
441 ' 0:' + upload.file.size.toString() + ':' +
445 return ArvadosClient.apiPromise(
446 'collections', 'update',
450 collection.manifest_text }
454 // Mark the completed upload(s) as Done and push
455 // them to the bottom of the queue.
456 var i, qLen = $scope.uploadQueue.length;
457 for (i=0; i<qLen; i++) {
458 if (uploads.indexOf($scope.uploadQueue[i]) >= 0) {
459 $scope.uploadQueue[i].state = 'Done';
460 $scope.uploadQueue.push.apply(
462 $scope.uploadQueue.splice(i, 1));
468 then(_deferredAppend.resolve,
469 _deferredAppend.reject);
470 return _deferredAppend.promise().
472 _deferredAppend = null;