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

tomdesair / tus-java-server / 38164149750

11 Oct 2026 06:31PM UTC coverage: 94.451% (-0.4%) from 94.834%
38164149750

Pull #138

github

web-flow
Merge a34a8997a into 6a2a41b9e
Pull Request #138: feat: async chunk upload, dynamic part sizing for multi-TB uploads, and RUFH compliance improvements

2944 of 3332 branches covered (88.36%)

Branch coverage included in aggregate %.

1286 of 1336 new or added lines in 34 files covered. (96.26%)

13 existing lines in 3 files now uncovered.

6316 of 6472 relevant lines covered (97.59%)

6.38 hits per line

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

96.47
/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
99
    addTusExtension(new CoreProtocol());
12 ✔
100
    CreationExtension creationExtension = new CreationExtension();
8 ✔
101
    addTusExtension(creationExtension);
8 ✔
102
    addTusExtension(new CreationWithUploadExtension(creationExtension));
14 ✔
103
    addTusExtension(new ResumableUploadsForHttpProtocol());
12 ✔
104
    addTusExtension(new ChecksumExtension());
12 ✔
105
    addTusExtension(new TerminationExtension());
12 ✔
106
    addTusExtension(new ExpirationExtension());
12 ✔
107
    addTusExtension(new ConcatenationExtension());
12 ✔
108
    addTusExtension(new CorsExtension());
12 ✔
109
    addTusExtension(new HttpDigestsExtension());
12 ✔
110
  }
2 ✔
111

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

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

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

149
  /**
150
   * Generates the raw HTTP 104 interim response frame string for an incoming upload creation
151
   * request under the IETF Resumable Uploads protocol (RUFH).
152
   *
153
   * @param servletRequest The incoming {@link HttpServletRequest}
154
   * @param ownerKey The owner key identifier for the upload
155
   * @return The raw HTTP 104 interim response string if applicable, or null if not applicable
156
   */
157
  public String getRawInterimResponse(HttpServletRequest servletRequest, String ownerKey) {
158
    if (detectProtocolVersion(servletRequest) == ProtocolVersion.RUFH) {
5 ✔
159
      return RufhInterimResponseUtil.getRawInterimResponse(
6 ✔
160
          servletRequest, uploadStorageService, ownerKey);
161
    }
162
    return null;
2 ✔
163
  }
164

165
  /**
166
   * Get the configured protocol version setting.
167
   *
168
   * @return Current ProtocolVersion configuration
169
   */
170
  public ProtocolVersion getSupportedProtocolVersion() {
171
    return supportedProtocolVersion;
3 ✔
172
  }
173

174
  /**
175
   * Set the URI or absolute URL under which the main tus upload endpoint is hosted. This can be a
176
   * relative path (for example <code>/files/upload</code>) or an absolute URL (for example <code>
177
   * https://upload.example.com/files/upload</code>). When an absolute URL is provided, the Location
178
   * header in creation responses will contain the full URL. Optionally, this URI may contain regex
179
   * parameters in order to support endpoints that contain URL parameters, for example <code>
180
   * /users/[0-9]+/files/upload</code> or <code>https://upload.example.com/users/[0-9]+/files/upload
181
   * </code>.
182
   *
183
   * @param uploadUri The URI or URL of the main tus upload endpoint
184
   * @return The current service
185
   */
186
  public TusFileUploadService withUploadUri(String uploadUri) {
187
    this.idFactory.setUploadUri(uploadUri);
8 ✔
188
    return this;
4 ✔
189
  }
190

191
  /**
192
   * Specify the maximum number of bytes that can be uploaded per upload. If you don't call this
193
   * method, the maximum number of bytes is Long.MAX_VALUE.
194
   *
195
   * @param maxUploadSize The maximum upload length that is allowed
196
   * @return The current service
197
   */
198
  public TusFileUploadService withMaxUploadSize(Long maxUploadSize) {
199
    Validate.exclusiveBetween(
8 ✔
200
        0, Long.MAX_VALUE, maxUploadSize, "The max upload size must be bigger than 0");
4 ✔
201
    this.uploadStorageService.setMaxUploadSize(maxUploadSize);
8 ✔
202
    return this;
4 ✔
203
  }
204

205
  /**
206
   * Set the maximum size allowed for an individual upload append (PATCH) request in IETF Resumable
207
   * Uploads.
208
   *
209
   * @param maxAppendSize The maximum append size limit in bytes
210
   * @return The current service
211
   */
212
  public TusFileUploadService withMaxAppendSize(Long maxAppendSize) {
213
    if (maxAppendSize != null) {
2 ✔
214
      Validate.exclusiveBetween(
4 ✔
215
          0, Long.MAX_VALUE, maxAppendSize, "The max append size must be bigger than 0");
2 ✔
216
    }
217
    this.uploadStorageService.setMaxAppendSize(maxAppendSize);
4 ✔
218
    return this;
2 ✔
219
  }
220

221
  /**
222
   * Set the minimum size allowed for an individual upload append or creation request in IETF
223
   * Resumable Uploads.
224
   *
225
   * @param minAppendSize The minimum append size limit in bytes, or null for no limit
226
   * @return The current service
227
   */
228
  public TusFileUploadService withMinAppendSize(Long minAppendSize) {
229
    if (minAppendSize != null) {
4 ✔
230
      Validate.exclusiveBetween(
8 ✔
231
          0, Long.MAX_VALUE, minAppendSize, "The min append size must be bigger than 0");
4 ✔
232
    }
233
    this.uploadStorageService.setMinAppendSize(minAppendSize);
8 ✔
234
    return this;
4 ✔
235
  }
236

237
  /**
238
   * Set the minimum total upload representation size limit in bytes for creation requests in IETF
239
   * Resumable Uploads.
240
   *
241
   * @param minSize The minimum total upload size limit in bytes, or null for no limit
242
   * @return The current service
243
   */
244
  public TusFileUploadService withMinSize(Long minSize) {
245
    if (minSize != null) {
2 ✔
246
      Validate.exclusiveBetween(0, Long.MAX_VALUE, minSize, "The min size must be bigger than 0");
6 ✔
247
    }
248
    this.uploadStorageService.setMinSize(minSize);
4 ✔
249
    return this;
2 ✔
250
  }
251

252
  /**
253
   * Set the maximum number of worker threads used for asynchronous background chunk uploading in
254
   * cloud storage backends (S3, Azure). Defaults to 10.
255
   *
256
   * @param cloudUploadThreadPoolSize Number of worker threads (must be > 0)
257
   * @return The current service
258
   */
259
  public TusFileUploadService withCloudUploadThreadPoolSize(int cloudUploadThreadPoolSize) {
260
    Validate.isTrue(
9 ✔
261
        cloudUploadThreadPoolSize > 0, "The cloud upload thread pool size must be greater than 0");
262
    this.uploadStorageService.setCloudUploadThreadPoolSize(cloudUploadThreadPoolSize);
4 ✔
263
    return this;
2 ✔
264
  }
265

266
  /**
267
   * Provide a custom {@link UploadIdFactory} implementation that should be used to generate
268
   * identifiers for the different uploads. Example implementation are {@link
269
   * me.desair.tus.server.upload.UuidUploadIdFactory} and {@link
270
   * me.desair.tus.server.upload.TimeBasedUploadIdFactory}.
271
   *
272
   * @param uploadIdFactory The custom {@link UploadIdFactory} implementation
273
   * @return The current service
274
   */
275
  public TusFileUploadService withUploadIdFactory(UploadIdFactory uploadIdFactory) {
276
    Objects.requireNonNull(uploadIdFactory, "The UploadIdFactory cannot be null");
4 ✔
277
    String previousUploadUri = this.idFactory.getUploadUri();
4 ✔
278
    this.idFactory = uploadIdFactory;
3 ✔
279
    this.idFactory.setUploadUri(previousUploadUri);
4 ✔
280
    this.uploadStorageService.setIdFactory(this.idFactory);
5 ✔
281
    this.uploadLockingService.setIdFactory(this.idFactory);
5 ✔
282
    return this;
2 ✔
283
  }
284

285
  /**
286
   * Provide a custom {@link UploadStorageService} implementation that should be used to store
287
   * uploaded bytes and metadata ({@link UploadInfo}).
288
   *
289
   * @param uploadStorageService The custom {@link UploadStorageService} implementation
290
   * @return The current service
291
   */
292
  public TusFileUploadService withUploadStorageService(UploadStorageService uploadStorageService) {
293
    Objects.requireNonNull(uploadStorageService, "The UploadStorageService cannot be null");
8 ✔
294
    // Copy over any previous configuration
295
    uploadStorageService.setMaxUploadSize(this.uploadStorageService.getMaxUploadSize());
12 ✔
296
    uploadStorageService.setMaxAppendSize(this.uploadStorageService.getMaxAppendSize());
10 ✔
297
    uploadStorageService.setMinAppendSize(this.uploadStorageService.getMinAppendSize());
10 ✔
298
    uploadStorageService.setMinSize(this.uploadStorageService.getMinSize());
10 ✔
299
    uploadStorageService.setCloudUploadThreadPoolSize(
8 ✔
300
        this.uploadStorageService.getCloudUploadThreadPoolSize());
2 ✔
301
    uploadStorageService.setUploadExpirationPeriod(
8 ✔
302
        this.uploadStorageService.getUploadExpirationPeriod());
2 ✔
303
    uploadStorageService.setUploadDeduplicationEnabled(
8 ✔
304
        this.uploadStorageService.isUploadDeduplicationEnabled());
2 ✔
305
    uploadStorageService.setJsonSerializationEnabled(
8 ✔
306
        this.uploadStorageService.isJsonSerializationEnabled());
2 ✔
307
    uploadStorageService.setDrainTimeout(this.uploadStorageService.getDrainTimeout());
10 ✔
308
    uploadStorageService.setIdFactory(this.idFactory);
8 ✔
309
    // Update the upload storage service
310
    this.uploadStorageService = uploadStorageService;
6 ✔
311
    prepareCacheIfEnabled();
4 ✔
312
    return this;
4 ✔
313
  }
314

315
  /**
316
   * Instruct the upload service to use JSON serialization for upload metadata ({@link UploadInfo})
317
   * instead of default Java object serialization.
318
   *
319
   * @return The current service
320
   */
321
  public TusFileUploadService withJsonSerialization() {
322
    return withJsonSerialization(true);
4 ✔
323
  }
324

325
  /**
326
   * Enable or disable JSON serialization for upload metadata ({@link UploadInfo}).
327
   *
328
   * @param enabled True to enable JSON serialization, false otherwise
329
   * @return The current service
330
   */
331
  public TusFileUploadService withJsonSerialization(boolean enabled) {
332
    this.uploadStorageService.setJsonSerializationEnabled(enabled);
4 ✔
333
    return this;
2 ✔
334
  }
335

336
  /**
337
   * Get the current {@link UploadStorageService} configured on this service.
338
   *
339
   * @return The current {@link UploadStorageService}
340
   */
341
  public UploadStorageService getUploadStorageService() {
342
    return this.uploadStorageService;
3 ✔
343
  }
344

345
  /**
346
   * Provide a custom {@link UploadLockingService} implementation that should be used when
347
   * processing uploads. The upload locking service is responsible for locking an upload that is
348
   * being processed so that it cannot be corrupted by simultaneous or delayed requests.
349
   *
350
   * @param uploadLockingService The {@link UploadLockingService} implementation to use
351
   * @return The current service
352
   */
353
  public TusFileUploadService withUploadLockingService(UploadLockingService uploadLockingService) {
354
    Objects.requireNonNull(uploadLockingService, "The UploadLockingService cannot be null");
8 ✔
355
    uploadLockingService.setIdFactory(this.idFactory);
8 ✔
356
    // Update the upload storage service
357
    this.uploadLockingService = uploadLockingService;
6 ✔
358
    prepareCacheIfEnabled();
4 ✔
359
    return this;
4 ✔
360
  }
361

362
  /**
363
   * Specify the maximum duration a request will wait to acquire an upload lock held by another
364
   * in-flight request before failing with an {@link
365
   * me.desair.tus.server.exception.UploadAlreadyLockedException} during lock wait and contention
366
   * resolution (e.g. for HEAD or DELETE requests).
367
   *
368
   * <p>Configuring this setting automatically derives:
369
   *
370
   * <ul>
371
   *   <li>The background cloud upload chunk drain timeout for cloud storage backends (S3, Azure),
372
   *       set to {@code lockWaitTimeout - 5 seconds}.
373
   *   <li>The maximum number of lock acquisition retries (polling every {@value
374
   *       #LOCK_RETRY_INTERVAL_MS}ms).
375
   * </ul>
376
   *
377
   * <p>The timeout must be greater than 5 seconds to provide a positive drain window for in-flight
378
   * chunks. Default is 60 seconds (yielding a 55-second drain timeout and 300 retries).
379
   *
380
   * @param lockWaitTimeout The maximum duration to wait for an upload lock (must be &gt; 5 seconds)
381
   * @return The current service
382
   */
383
  public TusFileUploadService withLockWaitTimeout(Duration lockWaitTimeout) {
384
    Validate.notNull(lockWaitTimeout, "The lock wait timeout cannot be null");
6 ✔
385
    Validate.isTrue(
2 ✔
386
        lockWaitTimeout.toMillis() > 5000L, "The lock wait timeout must be greater than 5 seconds");
10 ✔
387
    this.lockWaitTimeout = lockWaitTimeout;
3 ✔
388
    this.maxLockRetries = calculateMaxLockRetries(lockWaitTimeout);
4 ✔
389
    this.uploadStorageService.setDrainTimeout(calculateDrainTimeout(lockWaitTimeout));
5 ✔
390
    return this;
2 ✔
391
  }
392

393
  /**
394
   * Get the maximum duration a request will wait to acquire an upload lock.
395
   *
396
   * @return The current lock wait timeout
397
   */
398
  public Duration getLockWaitTimeout() {
399
    return lockWaitTimeout;
3 ✔
400
  }
401

402
  /**
403
   * Get the maximum number of lock acquisition retries, derived from {@link #getLockWaitTimeout()}.
404
   *
405
   * @return The maximum number of lock acquisition retries
406
   */
407
  public int getMaxLockRetries() {
408
    return maxLockRetries;
3 ✔
409
  }
410

411
  /**
412
   * If you're using the default file system-based storage service, you can use this method to
413
   * specify the path where to store the uploaded bytes and upload information.
414
   *
415
   * @param storagePath The file system path where uploads can be stored (temporarily)
416
   * @return The current service
417
   */
418
  public TusFileUploadService withStoragePath(String storagePath) {
419
    Validate.notBlank(storagePath, "The storage path cannot be blank");
12 ✔
420
    withUploadStorageService(new DiskStorageService(storagePath));
14 ✔
421
    withUploadLockingService(new LeaseFileLockingService(storagePath));
14 ✔
422
    prepareCacheIfEnabled();
4 ✔
423
    return this;
4 ✔
424
  }
425

426
  /**
427
   * Enable or disable a thread-local based cache of upload data. This can reduce the load on the
428
   * storage backends. By default this cache is disabled.
429
   *
430
   * @param isEnabled True if the cache should be enabled, false otherwise
431
   * @return The current service
432
   */
433
  public TusFileUploadService withThreadLocalCache(boolean isEnabled) {
434
    this.isThreadLocalCacheEnabled = isEnabled;
6 ✔
435
    prepareCacheIfEnabled();
4 ✔
436
    return this;
4 ✔
437
  }
438

439
  /**
440
   * Instruct this service to (not) decode any requests with Transfer-Encoding value "chunked". Use
441
   * this method in case the web container in which this service is running does not decode chunked
442
   * transfers itself. By default, chunked decoding is disabled.
443
   *
444
   * @param isEnabled True if chunked requests should be decoded, false otherwise.
445
   * @return The current service
446
   */
447
  public TusFileUploadService withChunkedTransferDecoding(boolean isEnabled) {
448
    isChunkedTransferDecodingEnabled = isEnabled;
3 ✔
449
    return this;
2 ✔
450
  }
451

452
  /**
453
   * You can set the number of milliseconds after which an upload is considered as expired and
454
   * available for cleanup.
455
   *
456
   * @param expirationPeriod The number of milliseconds after which an upload expires and can be
457
   *     removed
458
   * @return The current service
459
   */
460
  public TusFileUploadService withUploadExpirationPeriod(Long expirationPeriod) {
461
    uploadStorageService.setUploadExpirationPeriod(expirationPeriod);
8 ✔
462
    return this;
4 ✔
463
  }
464

465
  /**
466
   * Enable the unofficial `download` extension that also allows you to download uploaded bytes. By
467
   * default this feature is disabled.
468
   *
469
   * @return The current service
470
   */
471
  public TusFileUploadService withDownloadFeature() {
472
    addTusExtension(new DownloadExtension());
12 ✔
473
    return this;
4 ✔
474
  }
475

476
  /**
477
   * Enable or disable duplicate file processing based on checksum hash.
478
   *
479
   * @param isEnabled True if duplicate file processing should be enabled, false otherwise
480
   * @return The current service
481
   */
482
  public TusFileUploadService withUploadDeduplication(boolean isEnabled) {
483
    this.uploadStorageService.setUploadDeduplicationEnabled(isEnabled);
8 ✔
484
    return this;
4 ✔
485
  }
486

487
  /**
488
   * Add a custom (application-specific) extension that implements the {@link
489
   * me.desair.tus.server.TusExtension} interface. For example you can add your own extension that
490
   * checks authentication and authorization policies within your application for the user doing the
491
   * upload.
492
   *
493
   * @param feature The custom extension implementation
494
   * @return The current service
495
   */
496
  public TusFileUploadService addTusExtension(TusExtension feature) {
497
    Objects.requireNonNull(feature, "A custom feature cannot be null");
8 ✔
498
    enabledFeatures.put(feature.getName(), feature);
14 ✔
499
    updateSupportedHttpMethods();
4 ✔
500
    return this;
4 ✔
501
  }
502

503
  /**
504
   * Disable the TusExtension for which the getName() method matches the provided string. The
505
   * default extensions have names "creation", "checksum", "expiration", "concatenation",
506
   * "termination" and "download". You cannot disable the "core" feature.
507
   *
508
   * @param extensionName The name of the extension to disable
509
   * @return The current service
510
   */
511
  public TusFileUploadService disableTusExtension(String extensionName) {
512
    Objects.requireNonNull(extensionName, "The extension name cannot be null");
8 ✔
513
    Validate.isTrue(
8 ✔
514
        !Strings.CS.equals("core", extensionName), "The core protocol cannot be disabled");
15 ✔
515

516
    enabledFeatures.remove(extensionName);
10 ✔
517
    updateSupportedHttpMethods();
4 ✔
518

519
    if (Strings.CS.equals("creation-with-upload", extensionName)) {
10 ✔
520
      TusExtension creation = enabledFeatures.get("creation");
12 ✔
521
      if (creation instanceof CreationExtension) {
6 !
522
        ((CreationExtension) creation).setCreationWithUploadEnabled(false);
4 ✔
523
      }
524
    }
525

526
    return this;
4 ✔
527
  }
528

529
  /**
530
   * Get all HTTP methods that are supported by this TusUploadService based on the enabled and/or
531
   * disabled tus extensions.
532
   *
533
   * @return The set of enabled HTTP methods
534
   */
535
  public Set<HttpMethod> getSupportedHttpMethods() {
536
    return EnumSet.copyOf(supportedHttpMethods);
4 ✔
537
  }
538

539
  /**
540
   * Get the set of enabled Tus extensions.
541
   *
542
   * @return The set of active extensions
543
   */
544
  public Set<String> getEnabledFeatures() {
545
    return new LinkedHashSet<>(enabledFeatures.keySet());
7 ✔
546
  }
547

548
  /**
549
   * Process a tus upload request. Use this method to process any request made to the main and sub
550
   * tus upload endpoints. This corresponds to the path specified in the withUploadUri() method and
551
   * any sub-path of that URI.
552
   *
553
   * @param servletRequest The {@link HttpServletRequest} of the request
554
   * @param servletResponse The {@link HttpServletResponse} of the request
555
   * @return The processed {@link UploadInfo} or null if no upload was involved or an error occurred
556
   * @throws IOException When saving bytes or information of this requests fails
557
   */
558
  public UploadInfo process(HttpServletRequest servletRequest, HttpServletResponse servletResponse)
559
      throws IOException {
560
    return process(servletRequest, servletResponse, null);
12 ✔
561
  }
562

563
  /**
564
   * Process a tus upload request that belongs to a specific owner. Use this method to process any
565
   * request made to the main and sub tus upload endpoints. This corresponds to the path specified
566
   * in the withUploadUri() method and any sub-path of that URI.
567
   *
568
   * @param servletRequest The {@link HttpServletRequest} of the request
569
   * @param servletResponse The {@link HttpServletResponse} of the request
570
   * @param ownerKey A unique identifier of the owner (group) of this upload
571
   * @return The processed {@link UploadInfo} or null if no upload was involved or an error occurred
572
   * @throws IOException When saving bytes or information of this requests fails
573
   */
574
  public UploadInfo process(
575
      HttpServletRequest servletRequest, HttpServletResponse servletResponse, String ownerKey)
576
      throws IOException {
577
    Objects.requireNonNull(servletRequest, "The HTTP Servlet request cannot be null");
8 ✔
578
    Objects.requireNonNull(servletResponse, "The HTTP Servlet response cannot be null");
8 ✔
579

580
    HttpMethod method = HttpMethod.getMethodIfSupported(servletRequest, supportedHttpMethods);
10 ✔
581

582
    log.debug(
10 ✔
583
        "Processing request with method {} and URL {}", method, servletRequest.getRequestURL());
2 ✔
584

585
    TusServletRequest request =
14 ✔
586
        new TusServletRequest(servletRequest, isChunkedTransferDecodingEnabled);
587
    TusServletResponse response = new TusServletResponse(servletResponse);
10 ✔
588

589
    UploadInfo processedUploadInfo = null;
4 ✔
590
    boolean wasInProgress = true;
4 ✔
591

592
    try (UploadLock lock = acquireUploadLock(method, request.getRequestURI())) {
12 ✔
593
      // Evaluate initial progress state safely under the acquired upload lock
594
      // to avoid uncoordinated disk I/O or race conditions with concurrent requests.
595
      wasInProgress = checkWasInProgress(request, ownerKey);
10 ✔
596
      processedUploadInfo = processLockedRequest(method, request, response, ownerKey);
14 ✔
597

598
    } catch (TusException e) {
2 ✔
599
      log.error("Unable to lock upload for request URI " + request.getRequestURI(), e);
12 ✔
600
      response.setHeader(HttpHeader.CONTENT_LENGTH, null);
8 ✔
601
      response.sendError(e.getStatus(), e.getMessage());
12 ✔
602
    }
2 ✔
603

604
    if (wasInProgress && processedUploadInfo != null && !processedUploadInfo.isUploadInProgress()) {
14 ✔
605
      cleanupLock(processedUploadInfo.getId());
8 ✔
606
      notifyUploadCompletionListeners(processedUploadInfo);
6 ✔
607
    }
608

609
    return processedUploadInfo;
4 ✔
610
  }
611

612
  protected UploadLock acquireUploadLock(HttpMethod method, String requestUri)
613
      throws TusException, IOException {
614
    UploadLock lock = null;
4 ✔
615
    int retries = 0;
4 ✔
616
    // Lock wait loop: retries every LOCK_RETRY_INTERVAL_MS ms up to the configured lockWaitTimeout
617
    // budget (default 60s / 300 retries). When an in-flight upload is active, requestLockRelease
618
    // signals it to interrupt and cleanly drain in-flight chunks before releasing the lock.
619
    while (retries < maxLockRetries) {
8 !
620
      try {
621
        lock = uploadLockingService.lockUploadByUri(requestUri);
10 ✔
622
        break;
2 ✔
623
      } catch (TusException e) {
2 ✔
624
        if (HttpMethod.HEAD.equals(method) || HttpMethod.DELETE.equals(method)) {
16 ✔
625
          uploadLockingService.requestLockRelease(requestUri);
8 ✔
626
          retries++;
2 ✔
627
          try {
628
            Thread.sleep(LOCK_RETRY_INTERVAL_MS);
4 ✔
629
          } catch (InterruptedException ie) {
1 ✔
630
            Thread.currentThread().interrupt();
2 ✔
631
            throw new IOException("Lock acquisition retry interrupted", ie);
6 ✔
632
          }
2 ✔
633
        } else {
634
          throw e;
4 ✔
635
        }
636
      }
2 ✔
637
    }
638
    if (lock == null) {
4 ✔
639
      lock = uploadLockingService.lockUploadByUri(requestUri);
10 ✔
640
    }
641
    return lock;
4 ✔
642
  }
643

644
  /**
645
   * Method to retrieve the bytes that were uploaded to a specific upload represented by {@link
646
   * UploadInfo}. Validates the owner key under an exclusive upload lock.
647
   *
648
   * @param uploadInfo The upload info representing the upload
649
   * @return An {@link InputStream} that will stream the uploaded bytes, or null if uploadInfo is
650
   *     null, not found, or the owner key does not match
651
   * @throws IOException When retrieving the uploaded bytes fails
652
   * @throws TusException When the upload is still in progress or cannot be found
653
   */
654
  public InputStream getUploadedBytes(UploadInfo uploadInfo) throws IOException, TusException {
655
    if (uploadInfo == null || uploadInfo.getId() == null) {
10 ✔
656
      return null;
2 ✔
657
    }
658
    return getUploadedBytes(uploadInfo.getId(), uploadInfo.getOwnerKey());
14 ✔
659
  }
660

661
  /**
662
   * Method to retrieve the bytes that were uploaded to a specific upload represented by {@link
663
   * UploadInfo} and matching the given owner key.
664
   *
665
   * @param uploadInfo The upload info representing the upload
666
   * @param ownerKey The expected owner key of the upload
667
   * @return An {@link InputStream} that will stream the uploaded bytes, or null if uploadInfo is
668
   *     null, not found, or the owner key does not match
669
   * @throws IOException When retrieving the uploaded bytes fails
670
   * @throws TusException When the upload is still in progress or cannot be found
671
   */
672
  public InputStream getUploadedBytes(UploadInfo uploadInfo, String ownerKey)
673
      throws IOException, TusException {
674
    if (uploadInfo == null || uploadInfo.getId() == null) {
5 ✔
675
      return null;
2 ✔
676
    }
677
    return getUploadedBytes(uploadInfo.getId(), ownerKey);
6 ✔
678
  }
679

680
  /**
681
   * Method to retrieve the bytes that were uploaded to a specific upload represented by {@link
682
   * UploadId}.
683
   *
684
   * @param uploadId The ID of the upload
685
   * @return An {@link InputStream} that will stream the uploaded bytes, or null if uploadId is null
686
   *     or not found
687
   * @throws IOException When retrieving the uploaded bytes fails
688
   * @throws TusException When the upload is still in progress or cannot be found
689
   */
690
  public InputStream getUploadedBytes(UploadId uploadId) throws IOException, TusException {
691
    return getUploadedBytes(uploadId, null);
5 ✔
692
  }
693

694
  /**
695
   * Method to retrieve the bytes that were uploaded to a specific upload represented by {@link
696
   * UploadId} and matching the given owner key.
697
   *
698
   * @param uploadId The ID of the upload
699
   * @param ownerKey The expected owner key of the upload
700
   * @return An {@link InputStream} that will stream the uploaded bytes, or null if uploadId is
701
   *     null, not found, or the owner key does not match
702
   * @throws IOException When retrieving the uploaded bytes fails
703
   * @throws TusException When the upload is still in progress or cannot be found
704
   */
705
  public InputStream getUploadedBytes(UploadId uploadId, String ownerKey)
706
      throws IOException, TusException {
707
    if (uploadId == null) {
4 ✔
708
      return null;
2 ✔
709
    }
710
    UploadLock lock = lockUploadByUri(uploadId.toString());
10 ✔
711
    boolean streamCreated = false;
4 ✔
712
    try {
713
      UploadInfo storedInfo = uploadStorageService.getUploadInfo(uploadId);
10 ✔
714
      if (storedInfo == null || !Objects.equals(storedInfo.getOwnerKey(), ownerKey)) {
14 ✔
715
        return null;
4 ✔
716
      }
717
      InputStream bytesStream = uploadStorageService.getUploadedBytes(uploadId);
10 ✔
718
      if (bytesStream == null) {
4 ✔
719
        return null;
4 ✔
720
      }
721
      // If locking is active, wrap in LockHoldingInputStream to retain the lock until
722
      // the stream is fully closed by the caller, preventing concurrent mutations.
723
      if (lock != null) {
4 ✔
724
        LockHoldingInputStream lockHoldingStream = new LockHoldingInputStream(bytesStream, lock);
12 ✔
725
        streamCreated = true;
4 ✔
726
        return lockHoldingStream;
8 ✔
727
      } else {
728
        return bytesStream;
4 ✔
729
      }
730
    } finally {
731
      if (!streamCreated && lock != null) {
6 ✔
732
        try {
733
          lock.close();
2 ✔
734
        } catch (Exception closeEx) {
1 ✔
735
          log.warn(
5 ✔
736
              "Failed to close upload lock after failure retrieving bytes for upload ID {}",
737
              uploadId,
738
              closeEx);
739
        }
1 ✔
740
      }
741
    }
742
  }
743

744
  /**
745
   * Method to retrieve the bytes that were uploaded to a specific upload URI.
746
   *
747
   * @param uploadUri The URI of the upload
748
   * @return An {@link InputStream} that will stream the uploaded bytes
749
   * @throws IOException When the retreiving the uploaded bytes fails
750
   * @throws TusException When the upload is still in progress or cannot be found
751
   */
752
  public InputStream getUploadedBytes(String uploadUri) throws IOException, TusException {
753
    return getUploadedBytes(uploadUri, null);
×
754
  }
755

756
  /**
757
   * Method to retrieve the bytes that were uploaded to a specific upload URI.
758
   *
759
   * @param uploadUri The URI of the upload
760
   * @param ownerKey The key of the owner of this upload
761
   * @return An {@link InputStream} that will stream the uploaded bytes
762
   * @throws IOException When the retreiving the uploaded bytes fails
763
   * @throws TusException When the upload is still in progress or cannot be found
764
   */
765
  public InputStream getUploadedBytes(String uploadUri, String ownerKey)
766
      throws IOException, TusException {
767
    if (uploadUri == null) {
4 ✔
768
      return null;
2 ✔
769
    }
770
    UploadLock lock = lockUploadByUri(uploadUri);
8 ✔
771
    boolean streamCreated = false;
4 ✔
772
    try {
773
      InputStream bytesStream = uploadStorageService.getUploadedBytes(uploadUri, ownerKey);
12 ✔
774
      if (bytesStream == null) {
4 ✔
775
        return null;
4 ✔
776
      }
777
      // If locking is active, wrap in LockHoldingInputStream to retain the lock until
778
      // the stream is fully closed by the caller, preventing concurrent mutations.
779
      if (lock != null) {
4 ✔
780
        LockHoldingInputStream lockHoldingStream = new LockHoldingInputStream(bytesStream, lock);
12 ✔
781
        streamCreated = true;
4 ✔
782
        return lockHoldingStream;
8 ✔
783
      } else {
784
        return bytesStream;
4 ✔
785
      }
786
    } finally {
787
      if (!streamCreated && lock != null) {
8 ✔
788
        try {
789
          lock.close();
4 ✔
790
        } catch (Exception closeEx) {
1 ✔
791
          log.warn(
5 ✔
792
              "Failed to close upload lock after failure retrieving bytes for upload URI {}",
793
              uploadUri,
794
              closeEx);
795
        }
2 ✔
796
      }
797
    }
798
  }
799

800
  /**
801
   * Get the information on the upload corresponding to the given upload ID.
802
   *
803
   * @param uploadId The ID of the upload
804
   * @return Information on the upload, or null if not found
805
   * @throws IOException When retrieving the upload information fails
806
   * @throws TusException When the upload is still in progress or cannot be found
807
   */
808
  public UploadInfo getUploadInfo(UploadId uploadId) throws IOException, TusException {
809
    return getUploadInfo(uploadId, null);
5 ✔
810
  }
811

812
  /**
813
   * Get the information on the upload corresponding to the given upload ID and matching the given
814
   * owner key.
815
   *
816
   * @param uploadId The ID of the upload
817
   * @param ownerKey The expected owner key of the upload
818
   * @return Information on the upload, or null if not found or the owner key does not match
819
   * @throws IOException When retrieving the upload information fails
820
   * @throws TusException When the upload is still in progress or cannot be found
821
   */
822
  public UploadInfo getUploadInfo(UploadId uploadId, String ownerKey)
823
      throws IOException, TusException {
824
    if (uploadId == null) {
2 ✔
825
      return null;
2 ✔
826
    }
827
    try (UploadLock lock = lockUploadByUri(uploadId.toString())) {
5 ✔
828
      UploadInfo storedInfo = uploadStorageService.getUploadInfo(uploadId);
5 ✔
829
      if (storedInfo == null || !Objects.equals(storedInfo.getOwnerKey(), ownerKey)) {
7 ✔
830
        return null;
4 ✔
831
      }
832
      return storedInfo;
4 ✔
833
    }
4 !
834
  }
835

836
  /**
837
   * Get the information on the upload corresponding to the given upload URI.
838
   *
839
   * @param uploadUri The URI of the upload
840
   * @return Information on the upload
841
   * @throws IOException When retrieving the upload information fails
842
   * @throws TusException When the upload is still in progress or cannot be found
843
   */
844
  public UploadInfo getUploadInfo(String uploadUri) throws IOException, TusException {
845
    return getUploadInfo(uploadUri, null);
5 ✔
846
  }
847

848
  /**
849
   * Get the information on the upload corresponding to the given upload URI.
850
   *
851
   * @param uploadUri The URI of the upload
852
   * @param ownerKey The key of the owner of this upload
853
   * @return Information on the upload
854
   * @throws IOException When retrieving the upload information fails
855
   * @throws TusException When the upload is still in progress or cannot be found
856
   */
857
  public UploadInfo getUploadInfo(String uploadUri, String ownerKey)
858
      throws IOException, TusException {
859
    try (UploadLock lock = lockUploadByUri(uploadUri)) {
8 ✔
860

861
      return uploadStorageService.getUploadInfo(uploadUri, ownerKey);
16 ✔
862
    }
863
  }
864

865
  /**
866
   * Method to delete an upload associated with the given {@link UploadInfo}. Invoke this method if
867
   * you no longer need the upload. Validates the owner key under an exclusive upload lock.
868
   *
869
   * @param uploadInfo The upload info representing the upload to delete
870
   * @throws IOException When deleting the upload fails
871
   * @throws TusException When the upload cannot be found or deleted
872
   */
873
  public void deleteUpload(UploadInfo uploadInfo) throws IOException, TusException {
874
    if (uploadInfo != null && uploadInfo.getId() != null) {
10 ✔
875
      deleteUpload(uploadInfo.getId(), uploadInfo.getOwnerKey());
12 ✔
876
    }
877
  }
2 ✔
878

879
  /**
880
   * Method to delete an upload associated with the given {@link UploadInfo} and matching the given
881
   * owner key. Invoke this method if you no longer need the upload.
882
   *
883
   * @param uploadInfo The upload info representing the upload to delete
884
   * @param ownerKey The expected owner key of the upload
885
   * @throws IOException When deleting the upload fails
886
   * @throws TusException When the upload cannot be found or deleted
887
   */
888
  public void deleteUpload(UploadInfo uploadInfo, String ownerKey)
889
      throws IOException, TusException {
890
    if (uploadInfo != null && uploadInfo.getId() != null) {
5 ✔
891
      deleteUpload(uploadInfo.getId(), ownerKey);
5 ✔
892
    }
893
  }
1 ✔
894

895
  /**
896
   * Method to delete an upload associated with the given {@link UploadId}. Invoke this method if
897
   * you no longer need the upload.
898
   *
899
   * @param uploadId The ID of the upload to delete
900
   * @throws IOException When deleting the upload fails
901
   * @throws TusException When the upload cannot be locked
902
   */
903
  public void deleteUpload(UploadId uploadId) throws IOException, TusException {
904
    deleteUpload(uploadId, null);
4 ✔
905
  }
1 ✔
906

907
  /**
908
   * Method to delete an upload associated with the given {@link UploadId} and matching the given
909
   * owner key. Invoke this method if you no longer need the upload.
910
   *
911
   * @param uploadId The ID of 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 locked
915
   */
916
  public void deleteUpload(UploadId uploadId, String ownerKey) throws IOException, TusException {
917
    if (uploadId == null) {
4 ✔
918
      return;
1 ✔
919
    }
920
    try (UploadLock lock = lockUploadByUri(uploadId.toString())) {
10 ✔
921
      UploadInfo storedInfo = uploadStorageService.getUploadInfo(uploadId);
10 ✔
922
      if (storedInfo != null && Objects.equals(storedInfo.getOwnerKey(), ownerKey)) {
14 !
923
        uploadStorageService.terminateUpload(storedInfo);
8 ✔
924
      }
925
    }
926
  }
2 ✔
927

928
  /**
929
   * Method to delete an upload associated with the given upload URL. Invoke this method if you no
930
   * longer need the upload.
931
   *
932
   * @param uploadUri The upload URI
933
   */
934
  public void deleteUpload(String uploadUri) throws IOException, TusException {
935
    deleteUpload(uploadUri, null);
4 ✔
936
  }
1 ✔
937

938
  /**
939
   * Method to delete an upload associated with the given upload URL. Invoke this method if you no
940
   * longer need the upload.
941
   *
942
   * @param uploadUri The upload URI
943
   * @param ownerKey The key of the owner of this upload
944
   */
945
  public void deleteUpload(String uploadUri, String ownerKey) throws IOException, TusException {
946
    try (UploadLock lock = lockUploadByUri(uploadUri)) {
8 ✔
947
      UploadInfo uploadInfo = uploadStorageService.getUploadInfo(uploadUri, ownerKey);
12 ✔
948
      if (uploadInfo != null) {
4 !
949
        uploadStorageService.terminateUpload(uploadInfo);
8 ✔
950
        cleanupLock(uploadInfo.getId());
8 ✔
951
      }
952
    }
953
  }
2 ✔
954

955
  private UploadLock lockUploadByUri(String uploadUri) throws IOException, TusException {
956
    return uploadLockingService.lockUploadByUri(uploadUri);
10 ✔
957
  }
958

959
  /**
960
   * This method should be invoked periodically. It will cleanup any expired uploads and stale locks
961
   *
962
   * @throws IOException When cleaning fails
963
   */
964
  public void cleanup() throws IOException {
965
    uploadLockingService.cleanupStaleLocks();
6 ✔
966
    uploadStorageService.cleanupExpiredUploads(uploadLockingService);
10 ✔
967
  }
2 ✔
968

969
  protected UploadInfo processLockedRequest(
970
      HttpMethod method, TusServletRequest request, TusServletResponse response, String ownerKey)
971
      throws IOException {
972
    ProtocolVersion detectedVersion = detectProtocolVersion(request);
8 ✔
973

974
    try {
975
      validateRequest(method, request, ownerKey, detectedVersion);
12 ✔
976

977
      executeProcessingByFeatures(method, request, response, ownerKey, detectedVersion);
14 ✔
978

979
      return resolveUploadInfo(request, response, ownerKey);
12 ✔
980

981
    } catch (TusException e) {
2 ✔
982
      processTusException(method, request, response, ownerKey, e, detectedVersion);
16 ✔
983
      return null;
4 ✔
984
    } catch (RuntimeException e) {
1 ✔
985
      // Catch unexpected RuntimeException (e.g. NPE in custom extension) and convert it to an
986
      // internal server error TusException so that it routes through standard error handling
987
      // (RFC 7807 problem details in RUFH mode, or plain error in Tus mode) rather than an
988
      // unhandled container 500.
989
      log.error("Unexpected runtime exception processing request " + request.getRequestURI(), e);
6 ✔
990
      TusException wrapped =
4 ✔
991
          new TusException(
992
              HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
993
              "Internal server error: " + e.getMessage());
4 ✔
994
      processTusException(method, request, response, ownerKey, wrapped, detectedVersion);
8 ✔
995
      return null;
2 ✔
996
    }
997
  }
998

999
  private UploadInfo resolveUploadInfo(
1000
      TusServletRequest request, TusServletResponse response, String ownerKey) throws IOException {
1001
    String uploadUri = response != null ? response.getHeader(HttpHeader.LOCATION) : null;
16 ✔
1002
    if (StringUtils.isBlank(uploadUri) && request != null) {
10 !
1003
      if (Utils.isCreationEndpoint(request, uploadStorageService)) {
10 ✔
1004
        return null;
4 ✔
1005
      }
1006
      uploadUri = request.getRequestURI();
6 ✔
1007
    }
1008
    if (StringUtils.isNotBlank(uploadUri) && uploadStorageService != null) {
12 !
1009
      return uploadStorageService.getUploadInfo(uploadUri, ownerKey);
12 ✔
1010
    }
1011
    return null;
2 ✔
1012
  }
1013

1014
  private boolean checkWasInProgress(TusServletRequest request, String ownerKey) {
1015
    if (request == null || uploadStorageService == null) {
10 !
1016
      return true;
×
1017
    }
1018
    try {
1019
      UploadInfo uploadInfo = resolveUploadInfo(request, null, ownerKey);
12 ✔
1020
      if (uploadInfo != null) {
4 ✔
1021
        return uploadInfo.isUploadInProgress();
6 ✔
1022
      }
1023
    } catch (Exception e) {
1 ✔
1024
      log.debug("Error checking initial upload progress state: {}", e.getMessage());
5 ✔
1025
    }
2 ✔
1026
    return true;
4 ✔
1027
  }
1028

1029
  protected void notifyUploadCompletionListeners(UploadInfo uploadInfo) {
1030
    if (uploadInfo == null || uploadCompletionListeners.isEmpty()) {
12 ✔
1031
      return;
2 ✔
1032
    }
1033
    for (UploadCompletionListener listener : uploadCompletionListeners) {
22 ✔
1034
      try {
1035
        listener.onUploadComplete(uploadInfo, this);
8 ✔
1036
      } catch (Throwable t) {
1 ✔
1037
        log.error(
8 ✔
1038
            "Error executing upload completion listener for upload ID {}: {}",
1039
            uploadInfo.getId(),
5 ✔
1040
            t.getMessage(),
6 ✔
1041
            t);
1042
      }
2 ✔
1043
    }
2 ✔
1044
  }
2 ✔
1045

1046
  private void cleanupLock(UploadId id) {
1047
    if (id != null && uploadLockingService != null) {
10 !
1048
      try {
1049
        uploadLockingService.cleanupLock(id);
8 ✔
NEW
1050
      } catch (Exception e) {
×
NEW
1051
        log.debug("Error cleaning up lock for upload ID {}: {}", id, e.getMessage());
×
1052
      }
2 ✔
1053
    }
1054
  }
2 ✔
1055

1056
  public ProtocolVersion detectProtocolVersion(HttpServletRequest request) {
1057
    return Utils.detectProtocolVersion(request, supportedProtocolVersion);
10 ✔
1058
  }
1059

1060
  protected void executeProcessingByFeatures(
1061
      HttpMethod method,
1062
      TusServletRequest servletRequest,
1063
      TusServletResponse servletResponse,
1064
      String ownerKey,
1065
      ProtocolVersion version)
1066
      throws IOException, TusException {
1067

1068
    for (TusExtension feature : enabledFeatures.values()) {
24 ✔
1069
      if (!servletRequest.isProcessedBy(feature)) {
8 !
1070
        servletRequest.addProcessor(feature);
6 ✔
1071
        feature.process(
22 ✔
1072
            method,
1073
            servletRequest,
1074
            servletResponse,
1075
            uploadStorageService,
1076
            uploadLockingService,
1077
            ownerKey,
1078
            version);
1079
      }
1080
    }
2 ✔
1081
  }
2 ✔
1082

1083
  protected void validateRequest(
1084
      HttpMethod method,
1085
      HttpServletRequest servletRequest,
1086
      String ownerKey,
1087
      ProtocolVersion version)
1088
      throws TusException, IOException {
1089

1090
    for (TusExtension feature : enabledFeatures.values()) {
24 ✔
1091
      feature.validate(
20 ✔
1092
          method, servletRequest, uploadStorageService, uploadLockingService, ownerKey, version);
1093
    }
2 ✔
1094
  }
2 ✔
1095

1096
  protected void processTusException(
1097
      HttpMethod method,
1098
      TusServletRequest request,
1099
      TusServletResponse response,
1100
      String ownerKey,
1101
      TusException exception,
1102
      ProtocolVersion version)
1103
      throws IOException {
1104

1105
    int status = exception.getStatus();
6 ✔
1106
    String message = exception.getMessage();
6 ✔
1107

1108
    log.warn(
24 ✔
1109
        "Unable to process request {} {}. Sent response status {} with message \"{}\"",
1110
        method,
1111
        request.getRequestURL(),
10 ✔
1112
        status,
12 ✔
1113
        message);
1114

1115
    response.setStatus(status);
6 ✔
1116

1117
    HttpProblemDetails problemDetails = null;
4 ✔
1118
    try {
1119
      for (TusExtension feature : enabledFeatures.values()) {
24 ✔
1120
        if (!request.isProcessedBy(feature) || feature.mustReprocessOnError(method, version)) {
18 ✔
1121
          request.addProcessor(feature);
6 ✔
1122
          HttpProblemDetails pd =
22 ✔
1123
              feature.handleError(
4 ✔
1124
                  method,
1125
                  request,
1126
                  response,
1127
                  uploadStorageService,
1128
                  uploadLockingService,
1129
                  ownerKey,
1130
                  version,
1131
                  exception);
1132
          if (pd != null) {
4 ✔
1133
            problemDetails = pd;
4 ✔
1134
          }
1135
        }
1136
      }
2 ✔
1137

1138
      // Since an error occurred, the bytes we have written are probably not valid.
1139
      // So remove them.
1140
      String uploadUri = Utils.getUploadUri(request, response);
8 ✔
1141
      UploadInfo uploadInfo = uploadStorageService.getUploadInfo(uploadUri, ownerKey);
12 ✔
1142
      if (uploadInfo != null) {
4 ✔
1143
        uploadStorageService.removeLastNumberOfBytes(uploadInfo, request.getBytesRead());
12 ✔
1144
      }
1145

1146
    } catch (TusException ex) {
1 ✔
1147
      log.warn("An exception occurred while handling another exception", ex);
4 ✔
1148
    }
2 ✔
1149

1150
    // If one of the features has already committed a response, we don't need to send an error
1151
    // response. Otherwise, we send the error response with the status and message from the
1152
    // exception.
1153
    if (!response.isCommitted()) {
6 ✔
1154
      response.setStatus(status);
6 ✔
1155
      if (problemDetails != null) {
4 ✔
1156
        problemDetails.writeTo(response);
8 ✔
1157
      } else if (status == 460) {
6 ✔
1158
        // Non-standard HTTP status 460 (Checksum Mismatch) is not recognized by standard
1159
        // servlet container error controllers (such as Spring Boot's BasicErrorController),
1160
        // which would cause sendError() to fail with an unhandled IllegalArgumentException
1161
        // and degrade to HTTP 500. We explicitly set the status and omit sendError().
1162
        response.setHeader(HttpHeader.CONTENT_LENGTH, null);
4 ✔
1163
        response.setStatus(status);
4 ✔
1164
      } else {
1165
        response.setHeader(HttpHeader.CONTENT_LENGTH, null);
8 ✔
1166
        response.sendError(status, message);
8 ✔
1167
      }
1168
    }
1169
  }
2 ✔
1170

1171
  private void updateSupportedHttpMethods() {
1172
    supportedHttpMethods.clear();
6 ✔
1173
    for (TusExtension tusFeature : enabledFeatures.values()) {
24 ✔
1174
      supportedHttpMethods.addAll(tusFeature.getMinimalSupportedHttpMethods());
12 ✔
1175
    }
2 ✔
1176
  }
2 ✔
1177

1178
  private void prepareCacheIfEnabled() {
1179
    if (isThreadLocalCacheEnabled && uploadStorageService != null && uploadLockingService != null) {
18 !
1180
      ThreadLocalCachedStorageAndLockingService service =
16 ✔
1181
          new ThreadLocalCachedStorageAndLockingService(uploadStorageService, uploadLockingService);
1182
      service.setIdFactory(this.idFactory);
8 ✔
1183
      this.uploadStorageService = service;
6 ✔
1184
      this.uploadLockingService = service;
6 ✔
1185
    }
1186
  }
2 ✔
1187

1188
  /**
1189
   * Closes underlying storage and locking services, releasing background threads and resources.
1190
   *
1191
   * @throws IOException If closing fails
1192
   */
1193
  @Override
1194
  public void close() throws IOException {
1195
    if (uploadLockingService != null) {
3 !
1196
      uploadLockingService.close();
3 ✔
1197
    }
1198
    if (uploadStorageService != null) {
3 !
1199
      uploadStorageService.close();
3 ✔
1200
    }
1201
  }
1 ✔
1202

1203
  /**
1204
   * FilterInputStream wrapper that retains an active {@link UploadLock} until the consumer closes
1205
   * the stream.
1206
   *
1207
   * <p>This prevents concurrent DELETE or PATCH requests from corrupting, modifying, or truncating
1208
   * upload data while a caller is actively reading the stream.
1209
   */
1210
  private static class LockHoldingInputStream extends FilterInputStream {
1211

1212
    private final UploadLock lock;
1213
    private final AtomicBoolean closed = new AtomicBoolean(false);
12 ✔
1214

1215
    protected LockHoldingInputStream(InputStream in, UploadLock lock) {
1216
      super(Objects.requireNonNull(in, "InputStream must not be null"));
12 ✔
1217
      this.lock = Objects.requireNonNull(lock, "UploadLock must not be null");
12 ✔
1218
    }
2 ✔
1219

1220
    @Override
1221
    public void close() throws IOException {
1222
      if (closed.compareAndSet(false, true)) {
12 ✔
1223
        try {
1224
          super.close();
4 ✔
1225
        } finally {
1226
          lock.close();
6 ✔
1227
        }
1228
      }
1229
    }
2 ✔
1230
  }
1231
}
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