• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

tomdesair / tus-java-server / 43496996423

13 Nov 2026 07:57PM UTC coverage: 89.614% (-0.3%) from 89.87%
43496996423

Pull #152

github

web-flow
Merge f8dd504cf into bf81f66f9
Pull Request #152: Fix distributed cloud performance, security, and robustness concerns

3328 of 3962 branches covered (84.0%)

Branch coverage included in aggregate %.

188 of 208 new or added lines in 20 files covered. (90.38%)

201 existing lines in 14 files now uncovered.

6862 of 7409 relevant lines covered (92.62%)

5.37 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

96.96
/src/main/java/me/desair/tus/server/TusFileUploadService.java
1
package me.desair.tus.server;
2

3
import jakarta.servlet.http.HttpServletRequest;
4
import jakarta.servlet.http.HttpServletResponse;
5
import java.io.Closeable;
6
import java.io.File;
7
import java.io.FilterInputStream;
8
import java.io.IOException;
9
import java.io.InputStream;
10
import java.time.Duration;
11
import java.util.EnumSet;
12
import java.util.LinkedHashMap;
13
import java.util.LinkedHashSet;
14
import java.util.List;
15
import java.util.Objects;
16
import java.util.Set;
17
import java.util.concurrent.CopyOnWriteArrayList;
18
import java.util.concurrent.atomic.AtomicBoolean;
19
import me.desair.tus.server.checksum.ChecksumExtension;
20
import me.desair.tus.server.concatenation.ConcatenationExtension;
21
import me.desair.tus.server.core.CoreProtocol;
22
import me.desair.tus.server.cors.CorsExtension;
23
import me.desair.tus.server.creation.CreationExtension;
24
import me.desair.tus.server.creationwithupload.CreationWithUploadExtension;
25
import me.desair.tus.server.digest.HttpDigestsExtension;
26
import me.desair.tus.server.download.DownloadExtension;
27
import me.desair.tus.server.exception.TusException;
28
import me.desair.tus.server.expiration.ExpirationExtension;
29
import me.desair.tus.server.rufh.ResumableUploadsForHttpProtocol;
30
import me.desair.tus.server.rufh.util.RufhInterimResponseUtil;
31
import me.desair.tus.server.termination.TerminationExtension;
32
import me.desair.tus.server.upload.UploadId;
33
import me.desair.tus.server.upload.UploadIdFactory;
34
import me.desair.tus.server.upload.UploadInfo;
35
import me.desair.tus.server.upload.UploadLock;
36
import me.desair.tus.server.upload.UploadLockingService;
37
import me.desair.tus.server.upload.UploadStorageService;
38
import me.desair.tus.server.upload.UuidUploadIdFactory;
39
import me.desair.tus.server.upload.cache.ThreadLocalCachedStorageAndLockingService;
40
import me.desair.tus.server.upload.disk.DiskStorageService;
41
import me.desair.tus.server.upload.disk.LeaseFileLockingService;
42
import me.desair.tus.server.util.TusServletRequest;
43
import me.desair.tus.server.util.TusServletResponse;
44
import me.desair.tus.server.util.Utils;
45
import org.apache.commons.io.FileUtils;
46
import org.apache.commons.lang3.StringUtils;
47
import org.apache.commons.lang3.Strings;
48
import org.apache.commons.lang3.Validate;
49
import org.slf4j.Logger;
50
import org.slf4j.LoggerFactory;
51

52
/**
53
 * Helper class that implements the server side tus v1.0.0 upload protocol and the official IETF
54
 * Resumable Uploads for HTTP (RUFH) specification.
55
 */
56
public class TusFileUploadService implements Closeable {
57

58
  public static final String TUS_API_VERSION = "1.0.0";
59

60
  private static final Logger log = LoggerFactory.getLogger(TusFileUploadService.class);
6 ✔
61

62
  public static final Duration DEFAULT_LOCK_WAIT_TIMEOUT = Duration.ofSeconds(60);
6 ✔
63
  public static final long LOCK_RETRY_INTERVAL_MS = 200L;
64
  public static final int DEFAULT_MAX_LOCK_RETRIES =
4 ✔
65
      (int) (DEFAULT_LOCK_WAIT_TIMEOUT.toMillis() / LOCK_RETRY_INTERVAL_MS);
10 ✔
66

67
  private UploadStorageService uploadStorageService;
68
  private UploadLockingService uploadLockingService;
69
  private UploadIdFactory idFactory = new UuidUploadIdFactory();
10 ✔
70
  private final LinkedHashMap<String, TusExtension> enabledFeatures = new LinkedHashMap<>();
10 ✔
71
  private final Set<HttpMethod> supportedHttpMethods = EnumSet.noneOf(HttpMethod.class);
8 ✔
72
  private boolean isThreadLocalCacheEnabled = false;
6 ✔
73
  private boolean isChunkedTransferDecodingEnabled = false;
6 ✔
74
  private ProtocolVersion supportedProtocolVersion = ProtocolVersion.AUTO;
6 ✔
75
  private Duration lockWaitTimeout = DEFAULT_LOCK_WAIT_TIMEOUT;
6 ✔
76
  private int maxLockRetries = DEFAULT_MAX_LOCK_RETRIES;
6 ✔
77
  private final List<UploadCompletionListener> uploadCompletionListeners =
10 ✔
78
      new CopyOnWriteArrayList<>();
79

80
  /** Constructor. */
81
  public TusFileUploadService() {
4 ✔
82
    String storagePath = FileUtils.getTempDirectoryPath() + File.separator + "tus";
8 ✔
83
    this.uploadStorageService = new DiskStorageService(idFactory, storagePath);
16 ✔
84
    this.uploadLockingService = new LeaseFileLockingService(idFactory, storagePath);
16 ✔
85
    this.uploadStorageService.setDrainTimeout(calculateDrainTimeout(DEFAULT_LOCK_WAIT_TIMEOUT));
10 ✔
86
    initFeatures();
4 ✔
87
  }
2 ✔
88

89
  private static Duration calculateDrainTimeout(Duration timeout) {
90
    return timeout.minus(Duration.ofSeconds(5));
10 ✔
91
  }
92

93
  private static int calculateMaxLockRetries(Duration timeout) {
94
    return (int) (timeout.toMillis() / LOCK_RETRY_INTERVAL_MS);
6 ✔
95
  }
96

97
  protected void initFeatures() {
98
    // The order of the features is important: ExpirationExtension must run before ChecksumExtension
99
    // and HttpDigestsExtension so that upload expiration timestamps are already refreshed when
100
    // deduplication triggers on upload completion.
101
    addTusExtension(new CoreProtocol());
12 ✔
102
    CreationExtension creationExtension = new CreationExtension();
8 ✔
103
    addTusExtension(creationExtension);
8 ✔
104
    addTusExtension(new CreationWithUploadExtension(creationExtension));
14 ✔
105
    addTusExtension(new ResumableUploadsForHttpProtocol());
12 ✔
106
    addTusExtension(new ExpirationExtension());
12 ✔
107
    addTusExtension(new ChecksumExtension());
12 ✔
108
    addTusExtension(new HttpDigestsExtension());
12 ✔
109
    addTusExtension(new TerminationExtension());
12 ✔
110
    addTusExtension(new ConcatenationExtension());
12 ✔
111
    addTusExtension(new CorsExtension());
12 ✔
112
  }
2 ✔
113

114
  /**
115
   * Register a callback listener that is invoked when an upload successfully reaches completion.
116
   *
117
   * @param listener The completion listener to register
118
   * @return The current service
119
   */
120
  public TusFileUploadService withUploadCompletionListener(UploadCompletionListener listener) {
121
    return addUploadCompletionListener(listener);
8 ✔
122
  }
123

124
  /**
125
   * Add a callback listener that is invoked when an upload successfully reaches completion.
126
   *
127
   * @param listener The completion listener to add
128
   * @return The current service
129
   */
130
  public TusFileUploadService addUploadCompletionListener(UploadCompletionListener listener) {
131
    if (listener != null) {
4 ✔
132
      this.uploadCompletionListeners.add(listener);
10 ✔
133
    }
134
    return this;
4 ✔
135
  }
136

137
  /**
138
   * Configure the supported protocol version(s) for this service.
139
   *
140
   * @param supportedProtocolVersion ProtocolVersion setting (TUS_1_0_0, RUFH, or AUTO)
141
   * @return The current service
142
   */
143
  public TusFileUploadService withSupportedProtocolVersions(
144
      ProtocolVersion supportedProtocolVersion) {
145
    if (supportedProtocolVersion != null) {
2 ✔
146
      this.supportedProtocolVersion = supportedProtocolVersion;
3 ✔
147
    }
148
    return this;
2 ✔
149
  }
150

151
  /**
152
   * Generates the raw HTTP 104 interim response frame string for an incoming upload creation
153
   * request under the IETF Resumable Uploads protocol (RUFH).
154
   *
155
   * @param servletRequest The incoming {@link HttpServletRequest}
156
   * @param ownerKey The owner key identifier for the upload
157
   * @return The raw HTTP 104 interim response string if applicable, or null if not applicable or if
158
   *     preliminary validation fails
159
   */
160
  public String getRawInterimResponse(HttpServletRequest servletRequest, String ownerKey) {
161
    if (servletRequest == null) {
2 ✔
162
      return null;
2 ✔
163
    }
164
    HttpMethod method =
2 ✔
165
        HttpMethod.getMethodIfSupported(servletRequest, EnumSet.allOf(HttpMethod.class));
3 ✔
166
    if (method == null) {
2 ✔
167
      return null;
2 ✔
168
    }
169

170
    ProtocolVersion version = detectProtocolVersion(servletRequest);
4 ✔
171
    try {
172
      validateRequest(method, servletRequest, ownerKey, version);
6 ✔
173
    } catch (Exception e) {
1 ✔
174
      log.debug("Validation failed before generating interim response: {}", e.getMessage());
5 ✔
175
      // If preliminary validation fails (e.g. invalid metadata, path traversal, or upload length
176
      // exceeding maxUploadSize), return null so that no 104 interim response is emitted and no
177
      // phantom upload is pre-created on storage. The request will proceed down the normal servlet
178
      // container pipeline to process(), where the main validation pipeline will catch the error
179
      // and generate the formal error response (e.g. RFC 7807 problem details or Tus error
180
      // response).
181
      return null;
2 ✔
182
    }
1 ✔
183

184
    if (version == ProtocolVersion.RUFH) {
3 ✔
185
      return RufhInterimResponseUtil.getRawInterimResponse(
6 ✔
186
          servletRequest, uploadStorageService, ownerKey);
187
    }
188

189
    // Protocol versions other than RUFH (such as Tus 1.0.0) do not define HTTP 104 interim
190
    // responses.
191
    // Return null so the request proceeds to normal servlet processing where process() handles it.
192
    return null;
2 ✔
193
  }
194

195
  /**
196
   * Get the configured protocol version setting.
197
   *
198
   * @return Current ProtocolVersion configuration
199
   */
200
  public ProtocolVersion getSupportedProtocolVersion() {
201
    return supportedProtocolVersion;
3 ✔
202
  }
203

204
  /**
205
   * Set the URI or absolute URL under which the main tus upload endpoint is hosted. This can be a
206
   * relative path (for example <code>/files/upload</code>) or an absolute URL (for example <code>
207
   * https://upload.example.com/files/upload</code>). When an absolute URL is provided, the Location
208
   * header in creation responses will contain the full URL. Optionally, this URI may contain regex
209
   * parameters in order to support endpoints that contain URL parameters, for example <code>
210
   * /users/[0-9]+/files/upload</code> or <code>https://upload.example.com/users/[0-9]+/files/upload
211
   * </code>.
212
   *
213
   * @param uploadUri The URI or URL of the main tus upload endpoint
214
   * @return The current service
215
   */
216
  public TusFileUploadService withUploadUri(String uploadUri) {
217
    this.idFactory.setUploadUri(uploadUri);
8 ✔
218
    return this;
4 ✔
219
  }
220

221
  /**
222
   * Specify the maximum number of bytes that can be uploaded per upload. If you don't call this
223
   * method, the maximum number of bytes is Long.MAX_VALUE.
224
   *
225
   * @param maxUploadSize The maximum upload length that is allowed
226
   * @return The current service
227
   */
228
  public TusFileUploadService withMaxUploadSize(Long maxUploadSize) {
229
    Validate.exclusiveBetween(
8 ✔
230
        0, Long.MAX_VALUE, maxUploadSize, "The max upload size must be bigger than 0");
4 ✔
231
    this.uploadStorageService.setMaxUploadSize(maxUploadSize);
8 ✔
232
    return this;
4 ✔
233
  }
234

235
  /**
236
   * Set the maximum size allowed for an individual upload append (PATCH) request in IETF Resumable
237
   * Uploads.
238
   *
239
   * @param maxAppendSize The maximum append size limit in bytes
240
   * @return The current service
241
   */
242
  public TusFileUploadService withMaxAppendSize(Long maxAppendSize) {
243
    if (maxAppendSize != null) {
4 ✔
244
      Validate.exclusiveBetween(
8 ✔
245
          0, Long.MAX_VALUE, maxAppendSize, "The max append size must be bigger than 0");
4 ✔
246
    }
247
    this.uploadStorageService.setMaxAppendSize(maxAppendSize);
8 ✔
248
    return this;
4 ✔
249
  }
250

251
  /**
252
   * Set the minimum size allowed for an individual upload append or creation request in IETF
253
   * Resumable Uploads.
254
   *
255
   * @param minAppendSize The minimum append size limit in bytes, or null for no limit
256
   * @return The current service
257
   */
258
  public TusFileUploadService withMinAppendSize(Long minAppendSize) {
259
    if (minAppendSize != null) {
4 ✔
260
      Validate.exclusiveBetween(
8 ✔
261
          0, Long.MAX_VALUE, minAppendSize, "The min append size must be bigger than 0");
4 ✔
262
    }
263
    this.uploadStorageService.setMinAppendSize(minAppendSize);
8 ✔
264
    return this;
4 ✔
265
  }
266

267
  /**
268
   * Set the minimum total upload representation size limit in bytes for creation requests in IETF
269
   * Resumable Uploads.
270
   *
271
   * @param minSize The minimum total upload size limit in bytes, or null for no limit
272
   * @return The current service
273
   */
274
  public TusFileUploadService withMinSize(Long minSize) {
275
    if (minSize != null) {
2 ✔
276
      Validate.exclusiveBetween(0, Long.MAX_VALUE, minSize, "The min size must be bigger than 0");
6 ✔
277
    }
278
    this.uploadStorageService.setMinSize(minSize);
4 ✔
279
    return this;
2 ✔
280
  }
281

282
  /**
283
   * Set the maximum number of worker threads used for asynchronous background chunk uploading in
284
   * cloud storage backends (S3, Azure). Defaults to 10.
285
   *
286
   * @param cloudUploadThreadPoolSize Number of worker threads (must be > 0)
287
   * @return The current service
288
   */
289
  public TusFileUploadService withCloudUploadThreadPoolSize(int cloudUploadThreadPoolSize) {
290
    Validate.isTrue(
9 ✔
291
        cloudUploadThreadPoolSize > 0, "The cloud upload thread pool size must be greater than 0");
292
    this.uploadStorageService.setCloudUploadThreadPoolSize(cloudUploadThreadPoolSize);
4 ✔
293
    return this;
2 ✔
294
  }
295

296
  /**
297
   * Provide a custom {@link UploadIdFactory} implementation that should be used to generate
298
   * identifiers for the different uploads. Example implementation are {@link
299
   * me.desair.tus.server.upload.UuidUploadIdFactory} and {@link
300
   * me.desair.tus.server.upload.TimeBasedUploadIdFactory}.
301
   *
302
   * @param uploadIdFactory The custom {@link UploadIdFactory} implementation
303
   * @return The current service
304
   */
305
  public TusFileUploadService withUploadIdFactory(UploadIdFactory uploadIdFactory) {
306
    Objects.requireNonNull(uploadIdFactory, "The UploadIdFactory cannot be null");
4 ✔
307
    String previousUploadUri = this.idFactory.getUploadUri();
4 ✔
308
    this.idFactory = uploadIdFactory;
3 ✔
309
    this.idFactory.setUploadUri(previousUploadUri);
4 ✔
310
    this.uploadStorageService.setIdFactory(this.idFactory);
5 ✔
311
    this.uploadLockingService.setIdFactory(this.idFactory);
5 ✔
312
    return this;
2 ✔
313
  }
314

315
  /**
316
   * Provide a custom {@link UploadStorageService} implementation that should be used to store
317
   * uploaded bytes and metadata ({@link UploadInfo}).
318
   *
319
   * @param uploadStorageService The custom {@link UploadStorageService} implementation
320
   * @return The current service
321
   */
322
  public TusFileUploadService withUploadStorageService(UploadStorageService uploadStorageService) {
323
    Objects.requireNonNull(uploadStorageService, "The UploadStorageService cannot be null");
8 ✔
324
    // Copy over any previous configuration
325
    uploadStorageService.setMaxUploadSize(this.uploadStorageService.getMaxUploadSize());
12 ✔
326
    uploadStorageService.setMaxAppendSize(this.uploadStorageService.getMaxAppendSize());
10 ✔
327
    uploadStorageService.setMinAppendSize(this.uploadStorageService.getMinAppendSize());
10 ✔
328
    uploadStorageService.setMinSize(this.uploadStorageService.getMinSize());
10 ✔
329
    uploadStorageService.setCloudUploadThreadPoolSize(
8 ✔
330
        this.uploadStorageService.getCloudUploadThreadPoolSize());
2 ✔
331
    uploadStorageService.setUploadExpirationPeriod(
8 ✔
332
        this.uploadStorageService.getUploadExpirationPeriod());
2 ✔
333
    uploadStorageService.setUploadDeduplicationEnabled(
8 ✔
334
        this.uploadStorageService.isUploadDeduplicationEnabled());
2 ✔
335
    uploadStorageService.setJsonSerializationEnabled(
8 ✔
336
        this.uploadStorageService.isJsonSerializationEnabled());
2 ✔
337
    uploadStorageService.setDrainTimeout(this.uploadStorageService.getDrainTimeout());
10 ✔
338
    uploadStorageService.setIdFactory(this.idFactory);
8 ✔
339
    uploadStorageService.setUploadLockingService(this.uploadLockingService);
8 ✔
340
    // Update the upload storage service
341
    this.uploadStorageService = uploadStorageService;
6 ✔
342
    prepareCacheIfEnabled();
4 ✔
343
    return this;
4 ✔
344
  }
345

346
  /**
347
   * Instruct the upload service to use JSON serialization for upload metadata ({@link UploadInfo})
348
   * instead of default Java object serialization.
349
   *
350
   * @return The current service
351
   */
352
  public TusFileUploadService withJsonSerialization() {
353
    return withJsonSerialization(true);
4 ✔
354
  }
355

356
  /**
357
   * Enable or disable JSON serialization for upload metadata ({@link UploadInfo}).
358
   *
359
   * @param enabled True to enable JSON serialization, false otherwise
360
   * @return The current service
361
   */
362
  public TusFileUploadService withJsonSerialization(boolean enabled) {
363
    this.uploadStorageService.setJsonSerializationEnabled(enabled);
4 ✔
364
    return this;
2 ✔
365
  }
366

367
  /**
368
   * Get the current {@link UploadStorageService} configured on this service.
369
   *
370
   * @return The current {@link UploadStorageService}
371
   */
372
  public UploadStorageService getUploadStorageService() {
373
    return this.uploadStorageService;
6 ✔
374
  }
375

376
  /**
377
   * Provide a custom {@link UploadLockingService} implementation that should be used when
378
   * processing uploads. The upload locking service is responsible for locking an upload that is
379
   * being processed so that it cannot be corrupted by simultaneous or delayed requests.
380
   *
381
   * @param uploadLockingService The {@link UploadLockingService} implementation to use
382
   * @return The current service
383
   */
384
  public TusFileUploadService withUploadLockingService(UploadLockingService uploadLockingService) {
385
    Objects.requireNonNull(uploadLockingService, "The UploadLockingService cannot be null");
8 ✔
386
    uploadLockingService.setIdFactory(this.idFactory);
8 ✔
387
    // Update the upload locking service
388
    this.uploadLockingService = uploadLockingService;
6 ✔
389
    if (this.uploadStorageService != null) {
6 !
390
      this.uploadStorageService.setUploadLockingService(uploadLockingService);
8 ✔
391
    }
392
    prepareCacheIfEnabled();
4 ✔
393
    return this;
4 ✔
394
  }
395

396
  /**
397
   * Specify the maximum duration a request will wait to acquire an upload lock held by another
398
   * in-flight request before failing with an {@link
399
   * me.desair.tus.server.exception.UploadAlreadyLockedException} during lock wait and contention
400
   * resolution (e.g. for HEAD or DELETE requests).
401
   *
402
   * <p>Configuring this setting automatically derives:
403
   *
404
   * <ul>
405
   *   <li>The background cloud upload chunk drain timeout for cloud storage backends (S3, Azure),
406
   *       set to {@code lockWaitTimeout - 5 seconds}.
407
   *   <li>The maximum number of lock acquisition retries (polling every {@value
408
   *       #LOCK_RETRY_INTERVAL_MS}ms).
409
   * </ul>
410
   *
411
   * <p>The timeout must be greater than 5 seconds to provide a positive drain window for in-flight
412
   * chunks. Default is 60 seconds (yielding a 55-second drain timeout and 300 retries).
413
   *
414
   * @param lockWaitTimeout The maximum duration to wait for an upload lock (must be &gt; 5 seconds)
415
   * @return The current service
416
   */
417
  public TusFileUploadService withLockWaitTimeout(Duration lockWaitTimeout) {
418
    Validate.notNull(lockWaitTimeout, "The lock wait timeout cannot be null");
6 ✔
419
    Validate.isTrue(
2 ✔
420
        lockWaitTimeout.toMillis() > 5000L, "The lock wait timeout must be greater than 5 seconds");
10 ✔
421
    this.lockWaitTimeout = lockWaitTimeout;
3 ✔
422
    this.maxLockRetries = calculateMaxLockRetries(lockWaitTimeout);
4 ✔
423
    this.uploadStorageService.setDrainTimeout(calculateDrainTimeout(lockWaitTimeout));
5 ✔
424
    return this;
2 ✔
425
  }
426

427
  /**
428
   * Get the maximum duration a request will wait to acquire an upload lock.
429
   *
430
   * @return The current lock wait timeout
431
   */
432
  public Duration getLockWaitTimeout() {
433
    return lockWaitTimeout;
3 ✔
434
  }
435

436
  /**
437
   * Get the maximum number of lock acquisition retries, derived from {@link #getLockWaitTimeout()}.
438
   *
439
   * @return The maximum number of lock acquisition retries
440
   */
441
  public int getMaxLockRetries() {
442
    return maxLockRetries;
3 ✔
443
  }
444

445
  /**
446
   * If you're using the default file system-based storage service, you can use this method to
447
   * specify the path where to store the uploaded bytes and upload information.
448
   *
449
   * @param storagePath The file system path where uploads can be stored (temporarily)
450
   * @return The current service
451
   */
452
  public TusFileUploadService withStoragePath(String storagePath) {
453
    Validate.notBlank(storagePath, "The storage path cannot be blank");
12 ✔
454
    withUploadStorageService(new DiskStorageService(storagePath));
14 ✔
455
    withUploadLockingService(new LeaseFileLockingService(storagePath));
14 ✔
456
    prepareCacheIfEnabled();
4 ✔
457
    return this;
4 ✔
458
  }
459

460
  /**
461
   * Enable or disable a thread-local based cache of upload data. This can reduce the load on the
462
   * storage backends. By default this cache is disabled.
463
   *
464
   * @param isEnabled True if the cache should be enabled, false otherwise
465
   * @return The current service
466
   */
467
  public TusFileUploadService withThreadLocalCache(boolean isEnabled) {
468
    this.isThreadLocalCacheEnabled = isEnabled;
6 ✔
469
    prepareCacheIfEnabled();
4 ✔
470
    return this;
4 ✔
471
  }
472

473
  /**
474
   * Instruct this service to (not) decode any requests with Transfer-Encoding value "chunked". Use
475
   * this method in case the web container in which this service is running does not decode chunked
476
   * transfers itself. By default, chunked decoding is disabled.
477
   *
478
   * @param isEnabled True if chunked requests should be decoded, false otherwise.
479
   * @return The current service
480
   */
481
  public TusFileUploadService withChunkedTransferDecoding(boolean isEnabled) {
482
    isChunkedTransferDecodingEnabled = isEnabled;
3 ✔
483
    return this;
2 ✔
484
  }
485

486
  /**
487
   * You can set the number of milliseconds after which an upload is considered as expired and
488
   * available for cleanup.
489
   *
490
   * @param expirationPeriod The number of milliseconds after which an upload expires and can be
491
   *     removed
492
   * @return The current service
493
   */
494
  public TusFileUploadService withUploadExpirationPeriod(Long expirationPeriod) {
495
    uploadStorageService.setUploadExpirationPeriod(expirationPeriod);
8 ✔
496
    return this;
4 ✔
497
  }
498

499
  /**
500
   * Enable the unofficial `download` extension that also allows you to download uploaded bytes. By
501
   * default this feature is disabled.
502
   *
503
   * @return The current service
504
   */
505
  public TusFileUploadService withDownloadFeature() {
506
    addTusExtension(new DownloadExtension());
12 ✔
507
    return this;
4 ✔
508
  }
509

510
  /**
511
   * Enable or disable duplicate file processing based on checksum hash.
512
   *
513
   * @param isEnabled True if duplicate file processing should be enabled, false otherwise
514
   * @return The current service
515
   */
516
  public TusFileUploadService withUploadDeduplication(boolean isEnabled) {
517
    this.uploadStorageService.setUploadDeduplicationEnabled(isEnabled);
8 ✔
518
    return this;
4 ✔
519
  }
520

521
  /**
522
   * Add a custom (application-specific) extension that implements the {@link
523
   * me.desair.tus.server.TusExtension} interface. For example you can add your own extension that
524
   * checks authentication and authorization policies within your application for the user doing the
525
   * upload.
526
   *
527
   * @param feature The custom extension implementation
528
   * @return The current service
529
   */
530
  public TusFileUploadService addTusExtension(TusExtension feature) {
531
    Objects.requireNonNull(feature, "A custom feature cannot be null");
8 ✔
532
    enabledFeatures.put(feature.getName(), feature);
14 ✔
533
    updateSupportedHttpMethods();
4 ✔
534
    return this;
4 ✔
535
  }
536

537
  /**
538
   * Disable the TusExtension for which the getName() method matches the provided string. The
539
   * default extensions have names "creation", "checksum", "expiration", "concatenation",
540
   * "termination" and "download". You cannot disable the "core" feature.
541
   *
542
   * @param extensionName The name of the extension to disable
543
   * @return The current service
544
   */
545
  public TusFileUploadService disableTusExtension(String extensionName) {
546
    Objects.requireNonNull(extensionName, "The extension name cannot be null");
8 ✔
547
    Validate.isTrue(
8 ✔
548
        !Strings.CS.equals("core", extensionName), "The core protocol cannot be disabled");
15 ✔
549

550
    enabledFeatures.remove(extensionName);
10 ✔
551
    updateSupportedHttpMethods();
4 ✔
552

553
    if (Strings.CS.equals("creation-with-upload", extensionName)) {
10 ✔
554
      TusExtension creation = enabledFeatures.get("creation");
12 ✔
555
      if (creation instanceof CreationExtension) {
6 !
556
        ((CreationExtension) creation).setCreationWithUploadEnabled(false);
4 ✔
557
      }
558
    }
559

560
    return this;
4 ✔
561
  }
562

563
  /**
564
   * Get all HTTP methods that are supported by this TusUploadService based on the enabled and/or
565
   * disabled tus extensions.
566
   *
567
   * @return The set of enabled HTTP methods
568
   */
569
  public Set<HttpMethod> getSupportedHttpMethods() {
570
    return EnumSet.copyOf(supportedHttpMethods);
4 ✔
571
  }
572

573
  /**
574
   * Get the set of enabled Tus extensions.
575
   *
576
   * @return The set of active extensions
577
   */
578
  public Set<String> getEnabledFeatures() {
579
    return new LinkedHashSet<>(enabledFeatures.keySet());
7 ✔
580
  }
581

582
  /**
583
   * Process a tus upload request. Use this method to process any request made to the main and sub
584
   * tus upload endpoints. This corresponds to the path specified in the withUploadUri() method and
585
   * any sub-path of that URI.
586
   *
587
   * @param servletRequest The {@link HttpServletRequest} of the request
588
   * @param servletResponse The {@link HttpServletResponse} of the request
589
   * @return The processed {@link UploadInfo} or null if no upload was involved or an error occurred
590
   * @throws IOException When saving bytes or information of this requests fails
591
   */
592
  public UploadInfo process(HttpServletRequest servletRequest, HttpServletResponse servletResponse)
593
      throws IOException {
594
    return process(servletRequest, servletResponse, null);
12 ✔
595
  }
596

597
  /**
598
   * Process a tus upload request that belongs to a specific owner. Use this method to process any
599
   * request made to the main and sub tus upload endpoints. This corresponds to the path specified
600
   * in the withUploadUri() method and any sub-path of that URI.
601
   *
602
   * @param servletRequest The {@link HttpServletRequest} of the request
603
   * @param servletResponse The {@link HttpServletResponse} of the request
604
   * @param ownerKey A unique identifier of the owner (group) of this upload
605
   * @return The processed {@link UploadInfo} or null if no upload was involved or an error occurred
606
   * @throws IOException When saving bytes or information of this requests fails
607
   */
608
  public UploadInfo process(
609
      HttpServletRequest servletRequest, HttpServletResponse servletResponse, String ownerKey)
610
      throws IOException {
611
    Objects.requireNonNull(servletRequest, "The HTTP Servlet request cannot be null");
8 ✔
612
    Objects.requireNonNull(servletResponse, "The HTTP Servlet response cannot be null");
8 ✔
613

614
    HttpMethod method = HttpMethod.getMethodIfSupported(servletRequest, supportedHttpMethods);
10 ✔
615

616
    log.debug(
10 ✔
617
        "Processing request with method {} and URL {}", method, servletRequest.getRequestURL());
2 ✔
618

619
    TusServletRequest request =
14 ✔
620
        new TusServletRequest(servletRequest, isChunkedTransferDecodingEnabled);
621
    TusServletResponse response = new TusServletResponse(servletResponse);
10 ✔
622

623
    UploadInfo processedUploadInfo = null;
4 ✔
624
    boolean wasInProgress = true;
4 ✔
625

626
    try (UploadLock lock = acquireUploadLock(method, request.getRequestURI())) {
12 ✔
627
      // Evaluate initial progress state safely under the acquired upload lock
628
      // to avoid uncoordinated disk I/O or race conditions with concurrent requests.
629
      wasInProgress = checkWasInProgress(request, ownerKey);
10 ✔
630
      processedUploadInfo = processLockedRequest(method, request, response, ownerKey);
14 ✔
631

632
    } catch (TusException e) {
2 ✔
633
      log.error("Unable to lock upload for request URI " + request.getRequestURI(), e);
12 ✔
634
      response.setHeader(HttpHeader.CONTENT_LENGTH, null);
8 ✔
635
      response.sendError(e.getStatus(), e.getMessage());
12 ✔
636
    }
2 ✔
637

638
    if (wasInProgress && processedUploadInfo != null && !processedUploadInfo.isUploadInProgress()) {
14 ✔
639
      notifyUploadCompletionListeners(processedUploadInfo);
6 ✔
640
    }
641

642
    return processedUploadInfo;
4 ✔
643
  }
644

645
  protected UploadLock acquireUploadLock(HttpMethod method, String requestUri)
646
      throws TusException, IOException {
647
    UploadLock lock = null;
4 ✔
648
    int retries = 0;
4 ✔
649
    // Lock wait loop: retries every LOCK_RETRY_INTERVAL_MS ms up to the configured lockWaitTimeout
650
    // budget (default 60s / 300 retries). When an in-flight upload is active, requestLockRelease
651
    // signals it to interrupt and cleanly drain in-flight chunks before releasing the lock.
652
    while (retries < maxLockRetries) {
8 !
653
      try {
654
        lock = uploadLockingService.lockUploadByUri(requestUri);
10 ✔
655
        break;
2 ✔
656
      } catch (TusException e) {
2 ✔
657
        if (HttpMethod.HEAD.equals(method) || HttpMethod.DELETE.equals(method)) {
16 ✔
658
          // Throttled contention signal: write stop signal on initial contention (retries == 0)
659
          // and every 12th iteration (~2400ms) rather than every 200ms to avoid write storms on
660
          // S3/Azure.
661
          if (retries == 0 || retries % 12 == 0) {
8 ✔
662
            uploadLockingService.requestLockRelease(requestUri);
8 ✔
663
          }
664
          retries++;
2 ✔
665
          try {
666
            Thread.sleep(LOCK_RETRY_INTERVAL_MS);
4 ✔
667
          } catch (InterruptedException ie) {
1 ✔
668
            Thread.currentThread().interrupt();
2 ✔
669
            throw new IOException("Lock acquisition retry interrupted", ie);
6 ✔
670
          }
2 ✔
671
        } else {
672
          // Concurrent PATCH requests must fail fast (423/409) rather than waiting in a
673
          // contention loop, because a resumed PATCH cannot know the actual committed offset
674
          // without first issuing a HEAD request.
675
          throw e;
4 ✔
676
        }
677
      }
2 ✔
678
    }
679
    if (lock == null) {
4 ✔
680
      lock = uploadLockingService.lockUploadByUri(requestUri);
10 ✔
681
    }
682
    return lock;
4 ✔
683
  }
684

685
  /**
686
   * Method to retrieve the bytes that were uploaded to a specific upload represented by {@link
687
   * UploadInfo}. Validates the owner key under an exclusive upload lock.
688
   *
689
   * @param uploadInfo The upload info representing the upload
690
   * @return An {@link InputStream} that will stream the uploaded bytes, or null if uploadInfo is
691
   *     null, not found, or the owner key does not match
692
   * @throws IOException When retrieving the uploaded bytes fails
693
   * @throws TusException When the upload is still in progress or cannot be found
694
   */
695
  public InputStream getUploadedBytes(UploadInfo uploadInfo) throws IOException, TusException {
696
    if (uploadInfo == null || uploadInfo.getId() == null) {
10 ✔
697
      return null;
2 ✔
698
    }
699
    return getUploadedBytes(uploadInfo.getId(), uploadInfo.getOwnerKey());
14 ✔
700
  }
701

702
  /**
703
   * Method to retrieve the bytes that were uploaded to a specific upload represented by {@link
704
   * UploadInfo} and matching the given owner key.
705
   *
706
   * @param uploadInfo The upload info representing the upload
707
   * @param ownerKey The expected owner key of the upload
708
   * @return An {@link InputStream} that will stream the uploaded bytes, or null if uploadInfo is
709
   *     null, not found, or the owner key does not match
710
   * @throws IOException When retrieving the uploaded bytes fails
711
   * @throws TusException When the upload is still in progress or cannot be found
712
   */
713
  public InputStream getUploadedBytes(UploadInfo uploadInfo, String ownerKey)
714
      throws IOException, TusException {
715
    if (uploadInfo == null || uploadInfo.getId() == null) {
5 ✔
716
      return null;
2 ✔
717
    }
718
    return getUploadedBytes(uploadInfo.getId(), ownerKey);
6 ✔
719
  }
720

721
  /**
722
   * Method to retrieve the bytes that were uploaded to a specific upload represented by {@link
723
   * UploadId}.
724
   *
725
   * @param uploadId The ID of the upload
726
   * @return An {@link InputStream} that will stream the uploaded bytes, or null if uploadId is null
727
   *     or not found
728
   * @throws IOException When retrieving the uploaded bytes fails
729
   * @throws TusException When the upload is still in progress or cannot be found
730
   */
731
  public InputStream getUploadedBytes(UploadId uploadId) throws IOException, TusException {
732
    return getUploadedBytes(uploadId, null);
5 ✔
733
  }
734

735
  /**
736
   * Method to retrieve the bytes that were uploaded to a specific upload represented by {@link
737
   * UploadId} and matching the given owner key.
738
   *
739
   * @param uploadId The ID of the upload
740
   * @param ownerKey The expected owner key of the upload
741
   * @return An {@link InputStream} that will stream the uploaded bytes, or null if uploadId is
742
   *     null, not found, or the owner key does not match
743
   * @throws IOException When retrieving the uploaded bytes fails
744
   * @throws TusException When the upload is still in progress or cannot be found
745
   */
746
  public InputStream getUploadedBytes(UploadId uploadId, String ownerKey)
747
      throws IOException, TusException {
748
    if (uploadId == null) {
4 ✔
749
      return null;
2 ✔
750
    }
751
    UploadLock lock = lockUploadByUri(uploadId.toString());
10 ✔
752
    boolean streamCreated = false;
4 ✔
753
    try {
754
      UploadInfo storedInfo = uploadStorageService.getUploadInfo(uploadId);
10 ✔
755
      if (storedInfo == null || !Objects.equals(storedInfo.getOwnerKey(), ownerKey)) {
14 ✔
756
        return null;
4 ✔
757
      }
758
      InputStream bytesStream = uploadStorageService.getUploadedBytes(uploadId);
10 ✔
759
      InputStream wrapped = wrapStreamWithLock(lock, bytesStream);
10 ✔
760
      streamCreated = wrapped != null;
11 ✔
761
      return wrapped;
8 ✔
762
    } finally {
763
      if (!streamCreated && lock != null) {
8 !
764
        closeLockQuietly(lock, uploadId);
8 ✔
765
      }
766
    }
767
  }
768

769
  /**
770
   * Method to retrieve the bytes that were uploaded to a specific upload URI.
771
   *
772
   * @param uploadUri The URI of the upload
773
   * @return An {@link InputStream} that will stream the uploaded bytes
774
   * @throws IOException When the retreiving the uploaded bytes fails
775
   * @throws TusException When the upload is still in progress or cannot be found
776
   */
777
  public InputStream getUploadedBytes(String uploadUri) throws IOException, TusException {
UNCOV
778
    return getUploadedBytes(uploadUri, null);
×
779
  }
780

781
  /**
782
   * Method to retrieve the bytes that were uploaded to a specific upload URI.
783
   *
784
   * @param uploadUri The URI of the upload
785
   * @param ownerKey The key of the owner of this upload
786
   * @return An {@link InputStream} that will stream the uploaded bytes
787
   * @throws IOException When the retreiving the uploaded bytes fails
788
   * @throws TusException When the upload is still in progress or cannot be found
789
   */
790
  public InputStream getUploadedBytes(String uploadUri, String ownerKey)
791
      throws IOException, TusException {
792
    if (uploadUri == null) {
4 ✔
793
      return null;
2 ✔
794
    }
795
    UploadLock lock = lockUploadByUri(uploadUri);
8 ✔
796
    boolean streamCreated = false;
4 ✔
797
    try {
798
      InputStream bytesStream = uploadStorageService.getUploadedBytes(uploadUri, ownerKey);
12 ✔
799
      InputStream wrapped = wrapStreamWithLock(lock, bytesStream);
10 ✔
800
      streamCreated = wrapped != null;
11 ✔
801
      return wrapped;
8 ✔
802
    } finally {
803
      if (!streamCreated && lock != null) {
8 !
804
        closeLockQuietly(lock, uploadUri);
8 ✔
805
      }
806
    }
807
  }
808

809
  private InputStream wrapStreamWithLock(UploadLock lock, InputStream bytesStream) {
810
    if (bytesStream == null) {
4 ✔
811
      return null;
2 ✔
812
    }
813
    if (lock != null) {
4 ✔
814
      return new LockHoldingInputStream(bytesStream, lock);
12 ✔
815
    }
816
    return bytesStream;
2 ✔
817
  }
818

819
  private void closeLockQuietly(UploadLock lock, Object resourceId) {
820
    try {
821
      lock.close();
4 ✔
822
    } catch (Exception closeEx) {
1 ✔
823
      log.warn(
5 ✔
824
          "Failed to close upload lock after failure retrieving bytes for {}", resourceId, closeEx);
825
    }
2 ✔
826
  }
2 ✔
827

828
  /**
829
   * Get the information on the upload corresponding to the given upload ID.
830
   *
831
   * @param uploadId The ID of the upload
832
   * @return Information on the upload, or null if not found
833
   * @throws IOException When retrieving the upload information fails
834
   * @throws TusException When the upload is still in progress or cannot be found
835
   */
836
  public UploadInfo getUploadInfo(UploadId uploadId) throws IOException, TusException {
837
    return getUploadInfo(uploadId, null);
5 ✔
838
  }
839

840
  /**
841
   * Get the information on the upload corresponding to the given upload ID and matching the given
842
   * owner key.
843
   *
844
   * @param uploadId The ID of the upload
845
   * @param ownerKey The expected owner key of the upload
846
   * @return Information on the upload, or null if not found or the owner key does not match
847
   * @throws IOException When retrieving the upload information fails
848
   * @throws TusException When the upload is still in progress or cannot be found
849
   */
850
  public UploadInfo getUploadInfo(UploadId uploadId, String ownerKey)
851
      throws IOException, TusException {
852
    if (uploadId == null) {
2 ✔
853
      return null;
2 ✔
854
    }
855
    try (UploadLock lock = lockUploadByUri(uploadId.toString())) {
5 ✔
856
      UploadInfo storedInfo = uploadStorageService.getUploadInfo(uploadId);
5 ✔
857
      if (storedInfo == null || !Objects.equals(storedInfo.getOwnerKey(), ownerKey)) {
7 ✔
858
        return null;
4 ✔
859
      }
860
      return storedInfo;
4 ✔
861
    }
4 !
862
  }
863

864
  /**
865
   * Get the information on the upload corresponding to the given upload URI.
866
   *
867
   * @param uploadUri The URI of the upload
868
   * @return Information on the upload
869
   * @throws IOException When retrieving the upload information fails
870
   * @throws TusException When the upload is still in progress or cannot be found
871
   */
872
  public UploadInfo getUploadInfo(String uploadUri) throws IOException, TusException {
873
    return getUploadInfo(uploadUri, null);
5 ✔
874
  }
875

876
  /**
877
   * Get the information on the upload corresponding to the given upload URI.
878
   *
879
   * @param uploadUri The URI of the upload
880
   * @param ownerKey The key of the owner of this upload
881
   * @return Information on the upload
882
   * @throws IOException When retrieving the upload information fails
883
   * @throws TusException When the upload is still in progress or cannot be found
884
   */
885
  public UploadInfo getUploadInfo(String uploadUri, String ownerKey)
886
      throws IOException, TusException {
887
    try (UploadLock lock = lockUploadByUri(uploadUri)) {
8 ✔
888

889
      return uploadStorageService.getUploadInfo(uploadUri, ownerKey);
16 ✔
890
    }
891
  }
892

893
  /**
894
   * Method to delete an upload associated with the given {@link UploadInfo}. Invoke this method if
895
   * you no longer need the upload. Validates the owner key under an exclusive upload lock.
896
   *
897
   * @param uploadInfo The upload info representing the upload to delete
898
   * @throws IOException When deleting the upload fails
899
   * @throws TusException When the upload cannot be found or deleted
900
   */
901
  public void deleteUpload(UploadInfo uploadInfo) throws IOException, TusException {
902
    if (uploadInfo != null && uploadInfo.getId() != null) {
10 ✔
903
      deleteUpload(uploadInfo.getId(), uploadInfo.getOwnerKey());
12 ✔
904
    }
905
  }
2 ✔
906

907
  /**
908
   * Method to delete an upload associated with the given {@link UploadInfo} and matching the given
909
   * owner key. Invoke this method if you no longer need the upload.
910
   *
911
   * @param uploadInfo The upload info representing the upload to delete
912
   * @param ownerKey The expected owner key of the upload
913
   * @throws IOException When deleting the upload fails
914
   * @throws TusException When the upload cannot be found or deleted
915
   */
916
  public void deleteUpload(UploadInfo uploadInfo, String ownerKey)
917
      throws IOException, TusException {
918
    if (uploadInfo != null && uploadInfo.getId() != null) {
5 ✔
919
      deleteUpload(uploadInfo.getId(), ownerKey);
5 ✔
920
    }
921
  }
1 ✔
922

923
  /**
924
   * Method to delete an upload associated with the given {@link UploadId}. Invoke this method if
925
   * you no longer need the upload.
926
   *
927
   * @param uploadId The ID of the upload to delete
928
   * @throws IOException When deleting the upload fails
929
   * @throws TusException When the upload cannot be locked
930
   */
931
  public void deleteUpload(UploadId uploadId) throws IOException, TusException {
932
    deleteUpload(uploadId, null);
4 ✔
933
  }
1 ✔
934

935
  /**
936
   * Method to delete an upload associated with the given {@link UploadId} and matching the given
937
   * owner key. Invoke this method if you no longer need the upload.
938
   *
939
   * @param uploadId The ID of the upload to delete
940
   * @param ownerKey The expected owner key of the upload
941
   * @throws IOException When deleting the upload fails
942
   * @throws TusException When the upload cannot be locked
943
   */
944
  public void deleteUpload(UploadId uploadId, String ownerKey) throws IOException, TusException {
945
    if (uploadId == null) {
4 ✔
946
      return;
1 ✔
947
    }
948
    try (UploadLock lock = lockUploadByUri(uploadId.toString())) {
10 ✔
949
      UploadInfo storedInfo = uploadStorageService.getUploadInfo(uploadId);
10 ✔
950
      if (storedInfo != null && Objects.equals(storedInfo.getOwnerKey(), ownerKey)) {
14 !
951
        uploadStorageService.terminateUpload(storedInfo);
8 ✔
952
      }
953
    }
954
  }
2 ✔
955

956
  /**
957
   * Method to delete an upload associated with the given upload URL. Invoke this method if you no
958
   * longer need the upload.
959
   *
960
   * @param uploadUri The upload URI
961
   */
962
  public void deleteUpload(String uploadUri) throws IOException, TusException {
963
    deleteUpload(uploadUri, null);
4 ✔
964
  }
1 ✔
965

966
  /**
967
   * Method to delete an upload associated with the given upload URL. Invoke this method if you no
968
   * longer need the upload.
969
   *
970
   * @param uploadUri The upload URI
971
   * @param ownerKey The key of the owner of this upload
972
   */
973
  public void deleteUpload(String uploadUri, String ownerKey) throws IOException, TusException {
974
    try (UploadLock lock = lockUploadByUri(uploadUri)) {
8 ✔
975
      UploadInfo uploadInfo = uploadStorageService.getUploadInfo(uploadUri, ownerKey);
12 ✔
976
      if (uploadInfo != null) {
4 !
977
        uploadStorageService.terminateUpload(uploadInfo);
8 ✔
978
      }
979
    }
980
  }
2 ✔
981

982
  private UploadLock lockUploadByUri(String uploadUri) throws IOException, TusException {
983
    return uploadLockingService.lockUploadByUri(uploadUri);
10 ✔
984
  }
985

986
  /**
987
   * This method should be invoked periodically. It will cleanup any expired uploads and stale locks
988
   *
989
   * @throws IOException When cleaning fails
990
   */
991
  public void cleanup() throws IOException {
992
    uploadLockingService.cleanupStaleLocks();
6 ✔
993
    uploadStorageService.cleanupExpiredUploads();
6 ✔
994
  }
2 ✔
995

996
  protected UploadInfo processLockedRequest(
997
      HttpMethod method, TusServletRequest request, TusServletResponse response, String ownerKey)
998
      throws IOException {
999
    ProtocolVersion detectedVersion = detectProtocolVersion(request);
8 ✔
1000

1001
    // Record initial upload offset before request processing starts.
1002
    // If an error occurs (e.g. MaxAppendSizeExceededException), processTusException must only
1003
    // rollback bytes that were actually committed during this request, and never truncate bytes
1004
    // committed by earlier successful requests.
1005
    long initialOffset = 0L;
4 ✔
1006
    try {
1007
      UploadInfo preInfo = resolveUploadInfo(request, null, ownerKey);
12 ✔
1008
      if (preInfo != null) {
4 ✔
1009
        initialOffset = preInfo.getOffset();
8 ✔
1010
      }
1011
    } catch (Exception e) {
1 ✔
1012
      log.debug("Could not resolve initial upload offset: {}", e.getMessage());
5 ✔
1013
    }
2 ✔
1014

1015
    try {
1016
      validateRequest(method, request, ownerKey, detectedVersion);
12 ✔
1017

1018
      executeProcessingByFeatures(method, request, response, ownerKey, detectedVersion);
14 ✔
1019

1020
      return resolveUploadInfo(request, response, ownerKey);
12 ✔
1021

1022
    } catch (TusException e) {
2 ✔
1023
      processTusException(method, request, response, ownerKey, e, detectedVersion, initialOffset);
18 ✔
1024
      return null;
4 ✔
1025
    } catch (RuntimeException e) {
1 ✔
1026
      // Catch unexpected RuntimeException (e.g. NPE in custom extension) and convert it to an
1027
      // internal server error TusException so that it routes through standard error handling
1028
      // (RFC 7807 problem details in RUFH mode, or plain error in Tus mode) rather than an
1029
      // unhandled container 500.
1030
      log.error("Unexpected runtime exception processing request " + request.getRequestURI(), e);
6 ✔
1031
      TusException wrapped =
4 ✔
1032
          new TusException(
1033
              HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
1034
              "Internal server error: " + e.getMessage());
4 ✔
1035
      processTusException(
9 ✔
1036
          method, request, response, ownerKey, wrapped, detectedVersion, initialOffset);
1037
      return null;
2 ✔
1038
    }
1039
  }
1040

1041
  private UploadInfo resolveUploadInfo(
1042
      TusServletRequest request, TusServletResponse response, String ownerKey) throws IOException {
1043
    String uploadUri = response != null ? response.getHeader(HttpHeader.LOCATION) : null;
16 ✔
1044
    if (StringUtils.isBlank(uploadUri) && request != null) {
10 !
1045
      if (Utils.isCreationEndpoint(request, uploadStorageService)) {
10 ✔
1046
        return null;
4 ✔
1047
      }
1048
      uploadUri = request.getRequestURI();
6 ✔
1049
    }
1050
    if (StringUtils.isNotBlank(uploadUri) && uploadStorageService != null) {
12 !
1051
      return uploadStorageService.getUploadInfo(uploadUri, ownerKey);
12 ✔
1052
    }
1053
    return null;
2 ✔
1054
  }
1055

1056
  private boolean checkWasInProgress(TusServletRequest request, String ownerKey) {
1057
    if (request == null || uploadStorageService == null) {
10 !
UNCOV
1058
      return true;
×
1059
    }
1060
    try {
1061
      UploadInfo uploadInfo = resolveUploadInfo(request, null, ownerKey);
12 ✔
1062
      if (uploadInfo != null) {
4 ✔
1063
        return uploadInfo.isUploadInProgress();
6 ✔
1064
      }
1065
    } catch (Exception e) {
1 ✔
1066
      log.debug("Error checking initial upload progress state: {}", e.getMessage());
5 ✔
1067
    }
2 ✔
1068
    return true;
4 ✔
1069
  }
1070

1071
  protected void notifyUploadCompletionListeners(UploadInfo uploadInfo) {
1072
    if (uploadInfo == null || uploadCompletionListeners.isEmpty()) {
12 ✔
1073
      return;
2 ✔
1074
    }
1075
    for (UploadCompletionListener listener : uploadCompletionListeners) {
22 ✔
1076
      try {
1077
        listener.onUploadComplete(uploadInfo, this);
8 ✔
1078
      } catch (Throwable t) {
1 ✔
1079
        log.error(
8 ✔
1080
            "Error executing upload completion listener for upload ID {}: {}",
1081
            uploadInfo.getId(),
5 ✔
1082
            t.getMessage(),
6 ✔
1083
            t);
1084
      }
2 ✔
1085
    }
2 ✔
1086
  }
2 ✔
1087

1088
  public ProtocolVersion detectProtocolVersion(HttpServletRequest request) {
1089
    return Utils.detectProtocolVersion(request, supportedProtocolVersion);
10 ✔
1090
  }
1091

1092
  protected void executeProcessingByFeatures(
1093
      HttpMethod method,
1094
      TusServletRequest servletRequest,
1095
      TusServletResponse servletResponse,
1096
      String ownerKey,
1097
      ProtocolVersion version)
1098
      throws IOException, TusException {
1099

1100
    for (TusExtension feature : enabledFeatures.values()) {
24 ✔
1101
      if (!servletRequest.isProcessedBy(feature)) {
8 !
1102
        servletRequest.addProcessor(feature);
6 ✔
1103
        feature.process(
22 ✔
1104
            method,
1105
            servletRequest,
1106
            servletResponse,
1107
            uploadStorageService,
1108
            uploadLockingService,
1109
            ownerKey,
1110
            version);
1111
      }
1112
    }
2 ✔
1113
  }
2 ✔
1114

1115
  protected void validateRequest(
1116
      HttpMethod method,
1117
      HttpServletRequest servletRequest,
1118
      String ownerKey,
1119
      ProtocolVersion version)
1120
      throws TusException, IOException {
1121

1122
    for (TusExtension feature : enabledFeatures.values()) {
24 ✔
1123
      feature.validate(
20 ✔
1124
          method, servletRequest, uploadStorageService, uploadLockingService, ownerKey, version);
1125
    }
2 ✔
1126
  }
2 ✔
1127

1128
  protected void processTusException(
1129
      HttpMethod method,
1130
      TusServletRequest request,
1131
      TusServletResponse response,
1132
      String ownerKey,
1133
      TusException exception,
1134
      ProtocolVersion version)
1135
      throws IOException {
1136
    processTusException(method, request, response, ownerKey, exception, version, 0L);
9 ✔
1137
  }
1 ✔
1138

1139
  protected void processTusException(
1140
      HttpMethod method,
1141
      TusServletRequest request,
1142
      TusServletResponse response,
1143
      String ownerKey,
1144
      TusException exception,
1145
      ProtocolVersion version,
1146
      long initialOffset)
1147
      throws IOException {
1148

1149
    int status = exception.getStatus();
6 ✔
1150
    String message = exception.getMessage();
6 ✔
1151

1152
    log.warn(
24 ✔
1153
        "Unable to process request {} {}. Sent response status {} with message \"{}\"",
1154
        method,
1155
        request.getRequestURL(),
10 ✔
1156
        status,
12 ✔
1157
        message);
1158

1159
    response.setStatus(status);
6 ✔
1160

1161
    HttpProblemDetails problemDetails = null;
4 ✔
1162
    try {
1163
      for (TusExtension feature : enabledFeatures.values()) {
24 ✔
1164
        if (!request.isProcessedBy(feature) || feature.mustReprocessOnError(method, version)) {
18 ✔
1165
          request.addProcessor(feature);
6 ✔
1166
          HttpProblemDetails pd =
22 ✔
1167
              feature.handleError(
4 ✔
1168
                  method,
1169
                  request,
1170
                  response,
1171
                  uploadStorageService,
1172
                  uploadLockingService,
1173
                  ownerKey,
1174
                  version,
1175
                  exception);
1176
          if (pd != null) {
4 ✔
1177
            problemDetails = pd;
4 ✔
1178
          }
1179
        }
1180
      }
2 ✔
1181

1182
      // Since an error occurred, only rollback bytes that were actually committed during this
1183
      // request. Capping rollback to (uploadInfo.getOffset() - initialOffset) guarantees that if an
1184
      // uncommitted chunk failed (e.g. MaxAppendSizeExceededException where bytes were read into
1185
      // temp storage but never committed to offset), we do not truncate earlier valid data!
1186
      String uploadUri = Utils.getUploadUri(request, response);
8 ✔
1187
      UploadInfo uploadInfo = uploadStorageService.getUploadInfo(uploadUri, ownerKey);
12 ✔
1188
      if (uploadInfo != null) {
4 ✔
1189
        long committedThisRequest = Math.max(0L, uploadInfo.getOffset() - initialOffset);
16 ✔
1190
        long bytesToRollback = Math.min(request.getBytesRead(), committedThisRequest);
10 ✔
1191
        if (bytesToRollback > 0) {
8 ✔
1192
          uploadStorageService.removeLastNumberOfBytes(uploadInfo, bytesToRollback);
10 ✔
1193
        }
1194
      }
1195

1196
    } catch (TusException ex) {
1 ✔
1197
      log.warn("An exception occurred while handling another exception", ex);
4 ✔
1198
    }
2 ✔
1199

1200
    // If one of the features has already committed a response, we don't need to send an error
1201
    // response. Otherwise, we send the error response with the status and message from the
1202
    // exception.
1203
    if (!response.isCommitted()) {
6 ✔
1204
      response.setStatus(status);
6 ✔
1205
      if (problemDetails != null) {
4 ✔
1206
        problemDetails.writeTo(response);
8 ✔
1207
      } else if (status == 460) {
6 ✔
1208
        // Non-standard HTTP status 460 (Checksum Mismatch) is not recognized by standard
1209
        // servlet container error controllers (such as Spring Boot's BasicErrorController),
1210
        // which would cause sendError() to fail with an unhandled IllegalArgumentException
1211
        // and degrade to HTTP 500. We explicitly set the status and omit sendError().
1212
        response.setHeader(HttpHeader.CONTENT_LENGTH, null);
4 ✔
1213
        response.setStatus(status);
4 ✔
1214
      } else {
1215
        response.setHeader(HttpHeader.CONTENT_LENGTH, null);
8 ✔
1216
        response.sendError(status, message);
8 ✔
1217
      }
1218
    }
1219
  }
2 ✔
1220

1221
  private void updateSupportedHttpMethods() {
1222
    supportedHttpMethods.clear();
6 ✔
1223
    for (TusExtension tusFeature : enabledFeatures.values()) {
24 ✔
1224
      supportedHttpMethods.addAll(tusFeature.getMinimalSupportedHttpMethods());
12 ✔
1225
    }
2 ✔
1226
  }
2 ✔
1227

1228
  private void prepareCacheIfEnabled() {
1229
    if (isThreadLocalCacheEnabled && uploadStorageService != null) {
12 !
1230
      ThreadLocalCachedStorageAndLockingService service =
16 ✔
1231
          new ThreadLocalCachedStorageAndLockingService(uploadStorageService, uploadLockingService);
1232
      service.setIdFactory(this.idFactory);
8 ✔
1233
      this.uploadStorageService = service;
6 ✔
1234
      this.uploadLockingService = service;
6 ✔
1235
    }
1236
  }
2 ✔
1237

1238
  /**
1239
   * Closes underlying storage and locking services, releasing background threads and resources.
1240
   *
1241
   * @throws IOException If closing fails
1242
   */
1243
  @Override
1244
  public void close() throws IOException {
1245
    uploadLockingService.close();
6 ✔
1246
    if (uploadStorageService != null) {
6 !
1247
      uploadStorageService.close();
6 ✔
1248
    }
1249
  }
2 ✔
1250

1251
  /**
1252
   * FilterInputStream wrapper that retains an active {@link UploadLock} until the consumer closes
1253
   * the stream.
1254
   *
1255
   * <p>This prevents concurrent DELETE or PATCH requests from corrupting, modifying, or truncating
1256
   * upload data while a caller is actively reading the stream.
1257
   */
1258
  private static class LockHoldingInputStream extends FilterInputStream {
1259

1260
    private final UploadLock lock;
1261
    private final AtomicBoolean closed = new AtomicBoolean(false);
12 ✔
1262

1263
    protected LockHoldingInputStream(InputStream in, UploadLock lock) {
1264
      super(Objects.requireNonNull(in, "InputStream must not be null"));
12 ✔
1265
      this.lock = Objects.requireNonNull(lock, "UploadLock must not be null");
12 ✔
1266
    }
2 ✔
1267

1268
    @Override
1269
    public void close() throws IOException {
1270
      if (closed.compareAndSet(false, true)) {
12 ✔
1271
        try {
1272
          super.close();
4 ✔
1273
        } finally {
1274
          lock.close();
6 ✔
1275
        }
1276
      }
1277
    }
2 ✔
1278
  }
1279
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc