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

tomdesair / tus-java-server / 43579910339

14 Nov 2026 09:18AM UTC coverage: 89.558% (-0.3%) from 89.87%
43579910339

Pull #152

github

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

3456 of 4120 branches covered (83.88%)

Branch coverage included in aggregate %.

519 of 563 new or added lines in 39 files covered. (92.18%)

7 existing lines in 3 files now uncovered.

7033 of 7592 relevant lines covered (92.64%)

5.38 hits per line

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

95.65
/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.UploadType;
39
import me.desair.tus.server.upload.UuidUploadIdFactory;
40
import me.desair.tus.server.upload.cache.ThreadLocalCachedStorageAndLockingService;
41
import me.desair.tus.server.upload.disk.DiskStorageService;
42
import me.desair.tus.server.upload.disk.LeaseFileLockingService;
43
import me.desair.tus.server.util.TusServletRequest;
44
import me.desair.tus.server.util.TusServletResponse;
45
import me.desair.tus.server.util.Utils;
46
import org.apache.commons.io.FileUtils;
47
import org.apache.commons.lang3.StringUtils;
48
import org.apache.commons.lang3.Strings;
49
import org.apache.commons.lang3.Validate;
50
import org.slf4j.Logger;
51
import org.slf4j.LoggerFactory;
52

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

318
  /**
319
   * Provide a custom {@link UploadStorageService} implementation that should be used to store
320
   * uploaded bytes and metadata ({@link UploadInfo}).
321
   *
322
   * @param uploadStorageService The custom {@link UploadStorageService} implementation
323
   * @return The current service
324
   */
325
  public TusFileUploadService withUploadStorageService(UploadStorageService uploadStorageService) {
326
    Objects.requireNonNull(uploadStorageService, "The UploadStorageService cannot be null");
8 ✔
327
    // Unwrap any active ThreadLocal cache wrapper so configuration copies between concrete
328
    // delegates and double-wrapping is prevented.
329
    UploadStorageService previousStorage = unwrapStorageService(this.uploadStorageService);
10 ✔
330
    UploadLockingService rawLocking = unwrapLockingService(this.uploadLockingService);
10 ✔
331
    UploadStorageService targetStorage = unwrapStorageService(uploadStorageService);
8 ✔
332

333
    // Copy over previous configuration, preserving backend-specific maxAppendSize defaults
334
    // (such as Azure's 400 GiB limit) unless withMaxAppendSize() was explicitly configured.
335
    targetStorage.setMaxUploadSize(previousStorage.getMaxUploadSize());
10 ✔
336
    if (this.configuredMaxAppendSize != null) {
6 ✔
337
      targetStorage.setMaxAppendSize(this.configuredMaxAppendSize);
4 ✔
338
    }
339
    targetStorage.setMinAppendSize(previousStorage.getMinAppendSize());
8 ✔
340
    targetStorage.setMinSize(previousStorage.getMinSize());
8 ✔
341
    targetStorage.setCloudUploadThreadPoolSize(previousStorage.getCloudUploadThreadPoolSize());
8 ✔
342
    targetStorage.setUploadExpirationPeriod(previousStorage.getUploadExpirationPeriod());
8 ✔
343
    targetStorage.setUploadDeduplicationEnabled(previousStorage.isUploadDeduplicationEnabled());
8 ✔
344
    targetStorage.setJsonSerializationEnabled(previousStorage.isJsonSerializationEnabled());
8 ✔
345
    targetStorage.setDrainTimeout(previousStorage.getDrainTimeout());
8 ✔
346
    // Call setIdFactory on the caller-provided reference so external cache wrappers wired elsewhere
347
    // (such as VirtualConcatenationService) also receive idFactory before unwrapping.
348
    uploadStorageService.setIdFactory(this.idFactory);
8 ✔
349
    targetStorage.setUploadLockingService(rawLocking);
6 ✔
350

351
    if (previousStorage != targetStorage) {
6 !
352
      closeQuietly(previousStorage);
6 ✔
353
    }
354

355
    // Update the upload storage service and re-wrap cache if enabled
356
    this.uploadStorageService = targetStorage;
6 ✔
357
    this.uploadLockingService = rawLocking;
6 ✔
358
    prepareCacheIfEnabled();
4 ✔
359
    return this;
4 ✔
360
  }
361

362
  /**
363
   * Instruct the upload service to use JSON serialization for upload metadata ({@link UploadInfo})
364
   * instead of default Java object serialization.
365
   *
366
   * @return The current service
367
   */
368
  public TusFileUploadService withJsonSerialization() {
369
    return withJsonSerialization(true);
4 ✔
370
  }
371

372
  /**
373
   * Enable or disable JSON serialization for upload metadata ({@link UploadInfo}).
374
   *
375
   * @param enabled True to enable JSON serialization, false otherwise
376
   * @return The current service
377
   */
378
  public TusFileUploadService withJsonSerialization(boolean enabled) {
379
    this.uploadStorageService.setJsonSerializationEnabled(enabled);
4 ✔
380
    return this;
2 ✔
381
  }
382

383
  /**
384
   * Get the current {@link UploadStorageService} configured on this service.
385
   *
386
   * @return The current {@link UploadStorageService}
387
   */
388
  public UploadStorageService getUploadStorageService() {
389
    return this.uploadStorageService;
6 ✔
390
  }
391

392
  /**
393
   * Provide a custom {@link UploadLockingService} implementation that should be used when
394
   * processing uploads. The upload locking service is responsible for locking an upload that is
395
   * being processed so that it cannot be corrupted by simultaneous or delayed requests.
396
   *
397
   * @param uploadLockingService The {@link UploadLockingService} implementation to use
398
   * @return The current service
399
   */
400
  public TusFileUploadService withUploadLockingService(UploadLockingService uploadLockingService) {
401
    Objects.requireNonNull(uploadLockingService, "The UploadLockingService cannot be null");
8 ✔
402
    UploadLockingService previousLocking = unwrapLockingService(this.uploadLockingService);
10 ✔
403
    UploadStorageService rawStorage = unwrapStorageService(this.uploadStorageService);
10 ✔
404
    UploadLockingService targetLocking = unwrapLockingService(uploadLockingService);
8 ✔
405

406
    // Preserve idFactory on both any caller-provided cache wrapper and the underlying delegate.
407
    uploadLockingService.setIdFactory(this.idFactory);
8 ✔
408
    if (rawStorage != null) {
4 !
409
      rawStorage.setUploadLockingService(targetLocking);
6 ✔
410
    }
411
    if (previousLocking != null && previousLocking != targetLocking) {
10 !
412
      closeQuietly(previousLocking);
6 ✔
413
    }
414

415
    // Update the upload locking service and re-wrap cache if enabled
416
    this.uploadStorageService = rawStorage;
6 ✔
417
    this.uploadLockingService = targetLocking;
6 ✔
418
    prepareCacheIfEnabled();
4 ✔
419
    return this;
4 ✔
420
  }
421

422
  /**
423
   * Specify the maximum duration a request will wait to acquire an upload lock held by another
424
   * in-flight request before failing with an {@link
425
   * me.desair.tus.server.exception.UploadAlreadyLockedException} during lock wait and contention
426
   * resolution (e.g. for HEAD or DELETE requests).
427
   *
428
   * <p>Configuring this setting automatically derives:
429
   *
430
   * <ul>
431
   *   <li>The background cloud upload chunk drain timeout for cloud storage backends (S3, Azure),
432
   *       set to {@code lockWaitTimeout - 5 seconds}.
433
   *   <li>The maximum number of lock acquisition retries (polling every {@value
434
   *       #LOCK_RETRY_INTERVAL_MS}ms).
435
   * </ul>
436
   *
437
   * <p>The timeout must be greater than 5 seconds to provide a positive drain window for in-flight
438
   * chunks. Default is 60 seconds (yielding a 55-second drain timeout and 300 retries).
439
   *
440
   * @param lockWaitTimeout The maximum duration to wait for an upload lock (must be &gt; 5 seconds)
441
   * @return The current service
442
   */
443
  public TusFileUploadService withLockWaitTimeout(Duration lockWaitTimeout) {
444
    Validate.notNull(lockWaitTimeout, "The lock wait timeout cannot be null");
6 ✔
445
    Validate.isTrue(
2 ✔
446
        lockWaitTimeout.toMillis() > 5000L, "The lock wait timeout must be greater than 5 seconds");
10 ✔
447
    this.lockWaitTimeout = lockWaitTimeout;
3 ✔
448
    this.maxLockRetries = calculateMaxLockRetries(lockWaitTimeout);
4 ✔
449
    this.uploadStorageService.setDrainTimeout(calculateDrainTimeout(lockWaitTimeout));
5 ✔
450
    return this;
2 ✔
451
  }
452

453
  /**
454
   * Get the maximum duration a request will wait to acquire an upload lock.
455
   *
456
   * @return The current lock wait timeout
457
   */
458
  public Duration getLockWaitTimeout() {
459
    return lockWaitTimeout;
3 ✔
460
  }
461

462
  /**
463
   * Get the maximum number of lock acquisition retries, derived from {@link #getLockWaitTimeout()}.
464
   *
465
   * @return The maximum number of lock acquisition retries
466
   */
467
  public int getMaxLockRetries() {
468
    return maxLockRetries;
3 ✔
469
  }
470

471
  /**
472
   * If you're using the default file system-based storage service, you can use this method to
473
   * specify the path where to store the uploaded bytes and upload information.
474
   *
475
   * @param storagePath The file system path where uploads can be stored (temporarily)
476
   * @return The current service
477
   */
478
  public TusFileUploadService withStoragePath(String storagePath) {
479
    Validate.notBlank(storagePath, "The storage path cannot be blank");
12 ✔
480
    withUploadStorageService(new DiskStorageService(storagePath));
14 ✔
481
    withUploadLockingService(new LeaseFileLockingService(storagePath));
14 ✔
482
    return this;
4 ✔
483
  }
484

485
  /**
486
   * Enable or disable a thread-local based cache of upload data. This can reduce the load on the
487
   * storage backends. By default this cache is disabled.
488
   *
489
   * @param isEnabled True if the cache should be enabled, false otherwise
490
   * @return The current service
491
   */
492
  public TusFileUploadService withThreadLocalCache(boolean isEnabled) {
493
    this.isThreadLocalCacheEnabled = isEnabled;
6 ✔
494
    prepareCacheIfEnabled();
4 ✔
495
    return this;
4 ✔
496
  }
497

498
  /**
499
   * Instruct this service to (not) decode any requests with Transfer-Encoding value "chunked". Use
500
   * this method in case the web container in which this service is running does not decode chunked
501
   * transfers itself. By default, chunked decoding is disabled.
502
   *
503
   * @param isEnabled True if chunked requests should be decoded, false otherwise.
504
   * @return The current service
505
   */
506
  public TusFileUploadService withChunkedTransferDecoding(boolean isEnabled) {
507
    isChunkedTransferDecodingEnabled = isEnabled;
3 ✔
508
    return this;
2 ✔
509
  }
510

511
  /**
512
   * You can set the number of milliseconds after which an upload is considered as expired and
513
   * available for cleanup.
514
   *
515
   * @param expirationPeriod The number of milliseconds after which an upload expires and can be
516
   *     removed
517
   * @return The current service
518
   */
519
  public TusFileUploadService withUploadExpirationPeriod(Long expirationPeriod) {
520
    uploadStorageService.setUploadExpirationPeriod(expirationPeriod);
8 ✔
521
    return this;
4 ✔
522
  }
523

524
  /**
525
   * Enable the unofficial `download` extension that also allows you to download uploaded bytes. By
526
   * default this feature is disabled.
527
   *
528
   * @return The current service
529
   */
530
  public TusFileUploadService withDownloadFeature() {
531
    addTusExtension(new DownloadExtension());
12 ✔
532
    return this;
4 ✔
533
  }
534

535
  /**
536
   * Enable or disable duplicate file processing based on checksum hash.
537
   *
538
   * @param isEnabled True if duplicate file processing should be enabled, false otherwise
539
   * @return The current service
540
   */
541
  public TusFileUploadService withUploadDeduplication(boolean isEnabled) {
542
    this.uploadStorageService.setUploadDeduplicationEnabled(isEnabled);
8 ✔
543
    return this;
4 ✔
544
  }
545

546
  /**
547
   * Add a custom (application-specific) extension that implements the {@link
548
   * me.desair.tus.server.TusExtension} interface. For example you can add your own extension that
549
   * checks authentication and authorization policies within your application for the user doing the
550
   * upload.
551
   *
552
   * @param feature The custom extension implementation
553
   * @return The current service
554
   */
555
  public TusFileUploadService addTusExtension(TusExtension feature) {
556
    Objects.requireNonNull(feature, "A custom feature cannot be null");
8 ✔
557
    enabledFeatures.put(feature.getName(), feature);
14 ✔
558
    updateSupportedHttpMethods();
4 ✔
559
    return this;
4 ✔
560
  }
561

562
  /**
563
   * Disable the TusExtension for which the getName() method matches the provided string. The
564
   * default extensions have names "creation", "checksum", "expiration", "concatenation",
565
   * "termination" and "download". You cannot disable the "core" feature.
566
   *
567
   * @param extensionName The name of the extension to disable
568
   * @return The current service
569
   */
570
  public TusFileUploadService disableTusExtension(String extensionName) {
571
    Objects.requireNonNull(extensionName, "The extension name cannot be null");
8 ✔
572
    Validate.isTrue(
8 ✔
573
        !Strings.CS.equals("core", extensionName), "The core protocol cannot be disabled");
15 ✔
574

575
    enabledFeatures.remove(extensionName);
10 ✔
576
    updateSupportedHttpMethods();
4 ✔
577

578
    if (Strings.CS.equals("creation-with-upload", extensionName)) {
10 ✔
579
      TusExtension creation = enabledFeatures.get("creation");
12 ✔
580
      if (creation instanceof CreationExtension) {
6 !
581
        ((CreationExtension) creation).setCreationWithUploadEnabled(false);
4 ✔
582
      }
583
    }
584

585
    return this;
4 ✔
586
  }
587

588
  /**
589
   * Get all HTTP methods that are supported by this TusUploadService based on the enabled and/or
590
   * disabled tus extensions.
591
   *
592
   * @return The set of enabled HTTP methods
593
   */
594
  public Set<HttpMethod> getSupportedHttpMethods() {
595
    return EnumSet.copyOf(supportedHttpMethods);
4 ✔
596
  }
597

598
  /**
599
   * Get the set of enabled Tus extensions.
600
   *
601
   * @return The set of active extensions
602
   */
603
  public Set<String> getEnabledFeatures() {
604
    return new LinkedHashSet<>(enabledFeatures.keySet());
7 ✔
605
  }
606

607
  /**
608
   * Process a tus upload request. Use this method to process any request made to the main and sub
609
   * tus upload endpoints. This corresponds to the path specified in the withUploadUri() method and
610
   * any sub-path of that URI.
611
   *
612
   * @param servletRequest The {@link HttpServletRequest} of the request
613
   * @param servletResponse The {@link HttpServletResponse} of the request
614
   * @return The processed {@link UploadInfo} or null if no upload was involved or an error occurred
615
   * @throws IOException When saving bytes or information of this requests fails
616
   */
617
  public UploadInfo process(HttpServletRequest servletRequest, HttpServletResponse servletResponse)
618
      throws IOException {
619
    return process(servletRequest, servletResponse, null);
12 ✔
620
  }
621

622
  /**
623
   * Process a tus upload request that belongs to a specific owner. Use this method to process any
624
   * request made to the main and sub tus upload endpoints. This corresponds to the path specified
625
   * in the withUploadUri() method and any sub-path of that URI.
626
   *
627
   * @param servletRequest The {@link HttpServletRequest} of the request
628
   * @param servletResponse The {@link HttpServletResponse} of the request
629
   * @param ownerKey A unique identifier of the owner (group) of this upload
630
   * @return The processed {@link UploadInfo} or null if no upload was involved or an error occurred
631
   * @throws IOException When saving bytes or information of this requests fails
632
   */
633
  public UploadInfo process(
634
      HttpServletRequest servletRequest, HttpServletResponse servletResponse, String ownerKey)
635
      throws IOException {
636
    Objects.requireNonNull(servletRequest, "The HTTP Servlet request cannot be null");
8 ✔
637
    Objects.requireNonNull(servletResponse, "The HTTP Servlet response cannot be null");
8 ✔
638

639
    HttpMethod method = HttpMethod.getMethodIfSupported(servletRequest, supportedHttpMethods);
10 ✔
640

641
    log.debug(
10 ✔
642
        "Processing request with method {} and URL {}", method, servletRequest.getRequestURL());
2 ✔
643

644
    TusServletRequest request =
14 ✔
645
        new TusServletRequest(servletRequest, isChunkedTransferDecodingEnabled);
646
    TusServletResponse response = new TusServletResponse(servletResponse);
10 ✔
647

648
    UploadInfo processedUploadInfo = null;
4 ✔
649
    boolean wasInProgress = true;
4 ✔
650

651
    try (UploadLock lock = acquireUploadLock(method, request.getRequestURI())) {
12 ✔
652
      // Evaluate initial progress state safely under the acquired upload lock
653
      // to avoid uncoordinated disk I/O or race conditions with concurrent requests.
654
      wasInProgress = checkWasInProgress(request, ownerKey);
10 ✔
655
      processedUploadInfo = processLockedRequest(method, request, response, ownerKey);
14 ✔
656

657
    } catch (TusException e) {
2 ✔
658
      log.error("Unable to lock upload for request URI " + request.getRequestURI(), e);
12 ✔
659
      response.setHeader(HttpHeader.CONTENT_LENGTH, null);
8 ✔
660
      response.sendError(e.getStatus(), e.getMessage());
12 ✔
661
    }
2 ✔
662

663
    // Only notify completion listeners for standalone/final uploads, not concatenated PARTIAL
664
    // segments whose data will still be merged into a separate final resource.
665
    if (wasInProgress
10 ✔
666
        && processedUploadInfo != null
667
        && !processedUploadInfo.isUploadInProgress()
8 ✔
668
        && !UploadType.PARTIAL.equals(processedUploadInfo.getUploadType())) {
6 ✔
669
      notifyUploadCompletionListeners(processedUploadInfo);
6 ✔
670
    }
671

672
    return processedUploadInfo;
4 ✔
673
  }
674

675
  protected UploadLock acquireUploadLock(HttpMethod method, String requestUri)
676
      throws TusException, IOException {
677
    UploadLock lock = null;
4 ✔
678
    int retries = 0;
4 ✔
679
    // Lock wait loop: retries every LOCK_RETRY_INTERVAL_MS ms up to the configured lockWaitTimeout
680
    // budget (default 60s / 300 retries). When an in-flight upload is active, requestLockRelease
681
    // signals it to interrupt and cleanly drain in-flight chunks before releasing the lock.
682
    while (retries < maxLockRetries) {
8 !
683
      try {
684
        lock = uploadLockingService.lockUploadByUri(requestUri);
10 ✔
685
        break;
2 ✔
686
      } catch (TusException e) {
2 ✔
687
        if (HttpMethod.HEAD.equals(method) || HttpMethod.DELETE.equals(method)) {
16 ✔
688
          // Throttled contention signal: write stop signal on initial contention (retries == 0)
689
          // and every 12th iteration (~2400ms) rather than every 200ms to avoid write storms on
690
          // S3/Azure.
691
          if (retries == 0 || retries % 12 == 0) {
8 ✔
692
            uploadLockingService.requestLockRelease(requestUri);
8 ✔
693
          }
694
          retries++;
2 ✔
695
          try {
696
            Thread.sleep(LOCK_RETRY_INTERVAL_MS);
4 ✔
697
          } catch (InterruptedException ie) {
1 ✔
698
            Thread.currentThread().interrupt();
2 ✔
699
            throw new IOException("Lock acquisition retry interrupted", ie);
6 ✔
700
          }
2 ✔
701
        } else {
702
          // Concurrent PATCH requests must fail fast (423/409) rather than waiting in a
703
          // contention loop, because a resumed PATCH cannot know the actual committed offset
704
          // without first issuing a HEAD request.
705
          throw e;
4 ✔
706
        }
707
      }
2 ✔
708
    }
709
    if (lock == null) {
4 ✔
710
      lock = uploadLockingService.lockUploadByUri(requestUri);
10 ✔
711
    }
712
    return lock;
4 ✔
713
  }
714

715
  /**
716
   * Method to retrieve the bytes that were uploaded to a specific upload represented by {@link
717
   * UploadInfo}. Validates the owner key under an exclusive upload lock.
718
   *
719
   * @param uploadInfo The upload info representing the upload
720
   * @return An {@link InputStream} that will stream the uploaded bytes, or null if uploadInfo is
721
   *     null, not found, or the owner key does not match
722
   * @throws IOException When retrieving the uploaded bytes fails
723
   * @throws TusException When the upload is still in progress or cannot be found
724
   */
725
  public InputStream getUploadedBytes(UploadInfo uploadInfo) throws IOException, TusException {
726
    if (uploadInfo == null || uploadInfo.getId() == null) {
10 ✔
727
      return null;
2 ✔
728
    }
729
    return getUploadedBytes(uploadInfo.getId(), uploadInfo.getOwnerKey());
14 ✔
730
  }
731

732
  /**
733
   * Method to retrieve the bytes that were uploaded to a specific upload represented by {@link
734
   * UploadInfo} and matching the given owner key.
735
   *
736
   * @param uploadInfo The upload info representing the upload
737
   * @param ownerKey The expected owner key of the upload
738
   * @return An {@link InputStream} that will stream the uploaded bytes, or null if uploadInfo is
739
   *     null, not found, or the owner key does not match
740
   * @throws IOException When retrieving the uploaded bytes fails
741
   * @throws TusException When the upload is still in progress or cannot be found
742
   */
743
  public InputStream getUploadedBytes(UploadInfo uploadInfo, String ownerKey)
744
      throws IOException, TusException {
745
    if (uploadInfo == null || uploadInfo.getId() == null) {
5 ✔
746
      return null;
2 ✔
747
    }
748
    return getUploadedBytes(uploadInfo.getId(), ownerKey);
6 ✔
749
  }
750

751
  /**
752
   * Method to retrieve the bytes that were uploaded to a specific upload represented by {@link
753
   * UploadId}.
754
   *
755
   * @param uploadId The ID of the upload
756
   * @return An {@link InputStream} that will stream the uploaded bytes, or null if uploadId is null
757
   *     or not found
758
   * @throws IOException When retrieving the uploaded bytes fails
759
   * @throws TusException When the upload is still in progress or cannot be found
760
   */
761
  public InputStream getUploadedBytes(UploadId uploadId) throws IOException, TusException {
762
    return getUploadedBytes(uploadId, null);
5 ✔
763
  }
764

765
  /**
766
   * Method to retrieve the bytes that were uploaded to a specific upload represented by {@link
767
   * UploadId} and matching the given owner key.
768
   *
769
   * @param uploadId The ID of the upload
770
   * @param ownerKey The expected owner key of the upload
771
   * @return An {@link InputStream} that will stream the uploaded bytes, or null if uploadId is
772
   *     null, not found, or the owner key does not match
773
   * @throws IOException When retrieving the uploaded bytes fails
774
   * @throws TusException When the upload is still in progress or cannot be found
775
   */
776
  public InputStream getUploadedBytes(UploadId uploadId, String ownerKey)
777
      throws IOException, TusException {
778
    if (uploadId == null) {
4 ✔
779
      return null;
2 ✔
780
    }
781
    UploadLock lock = lockUploadByUri(uploadId.toString());
10 ✔
782
    boolean streamCreated = false;
4 ✔
783
    try {
784
      UploadInfo storedInfo = uploadStorageService.getUploadInfo(uploadId);
10 ✔
785
      if (storedInfo == null || !Objects.equals(storedInfo.getOwnerKey(), ownerKey)) {
14 ✔
786
        return null;
4 ✔
787
      }
788
      InputStream bytesStream = uploadStorageService.getUploadedBytes(uploadId);
10 ✔
789
      InputStream wrapped = wrapStreamWithLock(lock, bytesStream);
10 ✔
790
      streamCreated = wrapped != null;
11 ✔
791
      return wrapped;
8 ✔
792
    } finally {
793
      if (!streamCreated && lock != null) {
8 !
794
        closeLockQuietly(lock, uploadId);
8 ✔
795
      }
796
    }
797
  }
798

799
  /**
800
   * Method to retrieve the bytes that were uploaded to a specific upload URI.
801
   *
802
   * @param uploadUri The URI of the upload
803
   * @return An {@link InputStream} that will stream the uploaded bytes
804
   * @throws IOException When the retreiving the uploaded bytes fails
805
   * @throws TusException When the upload is still in progress or cannot be found
806
   */
807
  public InputStream getUploadedBytes(String uploadUri) throws IOException, TusException {
808
    return getUploadedBytes(uploadUri, null);
×
809
  }
810

811
  /**
812
   * Method to retrieve the bytes that were uploaded to a specific upload URI.
813
   *
814
   * @param uploadUri The URI of the upload
815
   * @param ownerKey The key of the owner of this upload
816
   * @return An {@link InputStream} that will stream the uploaded bytes
817
   * @throws IOException When the retreiving the uploaded bytes fails
818
   * @throws TusException When the upload is still in progress or cannot be found
819
   */
820
  public InputStream getUploadedBytes(String uploadUri, String ownerKey)
821
      throws IOException, TusException {
822
    if (uploadUri == null) {
4 ✔
823
      return null;
2 ✔
824
    }
825
    UploadLock lock = lockUploadByUri(uploadUri);
8 ✔
826
    boolean streamCreated = false;
4 ✔
827
    try {
828
      InputStream bytesStream = uploadStorageService.getUploadedBytes(uploadUri, ownerKey);
12 ✔
829
      InputStream wrapped = wrapStreamWithLock(lock, bytesStream);
10 ✔
830
      streamCreated = wrapped != null;
11 ✔
831
      return wrapped;
8 ✔
832
    } finally {
833
      if (!streamCreated && lock != null) {
8 !
834
        closeLockQuietly(lock, uploadUri);
8 ✔
835
      }
836
    }
837
  }
838

839
  private InputStream wrapStreamWithLock(UploadLock lock, InputStream bytesStream) {
840
    if (bytesStream == null) {
4 ✔
841
      return null;
2 ✔
842
    }
843
    if (lock != null) {
4 ✔
844
      return new LockHoldingInputStream(bytesStream, lock);
12 ✔
845
    }
846
    return bytesStream;
2 ✔
847
  }
848

849
  private void closeLockQuietly(UploadLock lock, Object resourceId) {
850
    try {
851
      lock.close();
4 ✔
852
    } catch (Exception closeEx) {
1 ✔
853
      log.warn(
5 ✔
854
          "Failed to close upload lock after failure retrieving bytes for {}", resourceId, closeEx);
855
    }
2 ✔
856
  }
2 ✔
857

858
  /**
859
   * Get the information on the upload corresponding to the given upload ID.
860
   *
861
   * @param uploadId The ID of the upload
862
   * @return Information on the upload, or null if not found
863
   * @throws IOException When retrieving the upload information fails
864
   * @throws TusException When the upload is still in progress or cannot be found
865
   */
866
  public UploadInfo getUploadInfo(UploadId uploadId) throws IOException, TusException {
867
    return getUploadInfo(uploadId, null);
5 ✔
868
  }
869

870
  /**
871
   * Get the information on the upload corresponding to the given upload ID and matching the given
872
   * owner key.
873
   *
874
   * @param uploadId The ID of the upload
875
   * @param ownerKey The expected owner key of the upload
876
   * @return Information on the upload, or null if not found or the owner key does not match
877
   * @throws IOException When retrieving the upload information fails
878
   * @throws TusException When the upload is still in progress or cannot be found
879
   */
880
  public UploadInfo getUploadInfo(UploadId uploadId, String ownerKey)
881
      throws IOException, TusException {
882
    if (uploadId == null) {
2 ✔
883
      return null;
2 ✔
884
    }
885
    try (UploadLock lock = lockUploadByUri(uploadId.toString())) {
5 ✔
886
      UploadInfo storedInfo = uploadStorageService.getUploadInfo(uploadId);
5 ✔
887
      if (storedInfo == null || !Objects.equals(storedInfo.getOwnerKey(), ownerKey)) {
7 ✔
888
        return null;
4 ✔
889
      }
890
      return storedInfo;
4 ✔
891
    }
4 !
892
  }
893

894
  /**
895
   * Get the information on the upload corresponding to the given upload URI.
896
   *
897
   * @param uploadUri The URI of the upload
898
   * @return Information on the upload
899
   * @throws IOException When retrieving the upload information fails
900
   * @throws TusException When the upload is still in progress or cannot be found
901
   */
902
  public UploadInfo getUploadInfo(String uploadUri) throws IOException, TusException {
903
    return getUploadInfo(uploadUri, null);
5 ✔
904
  }
905

906
  /**
907
   * Get the information on the upload corresponding to the given upload URI.
908
   *
909
   * @param uploadUri The URI of the upload
910
   * @param ownerKey The key of the owner of this upload
911
   * @return Information on the upload
912
   * @throws IOException When retrieving the upload information fails
913
   * @throws TusException When the upload is still in progress or cannot be found
914
   */
915
  public UploadInfo getUploadInfo(String uploadUri, String ownerKey)
916
      throws IOException, TusException {
917
    try (UploadLock lock = lockUploadByUri(uploadUri)) {
8 ✔
918

919
      return uploadStorageService.getUploadInfo(uploadUri, ownerKey);
16 ✔
920
    }
921
  }
922

923
  /**
924
   * Method to delete an upload associated with the given {@link UploadInfo}. Invoke this method if
925
   * you no longer need the upload. Validates the owner key under an exclusive upload lock.
926
   *
927
   * @param uploadInfo The upload info representing the upload to delete
928
   * @throws IOException When deleting the upload fails
929
   * @throws TusException When the upload cannot be found or deleted
930
   */
931
  public void deleteUpload(UploadInfo uploadInfo) throws IOException, TusException {
932
    if (uploadInfo != null && uploadInfo.getId() != null) {
10 ✔
933
      deleteUpload(uploadInfo.getId(), uploadInfo.getOwnerKey());
12 ✔
934
    }
935
  }
2 ✔
936

937
  /**
938
   * Method to delete an upload associated with the given {@link UploadInfo} and matching the given
939
   * owner key. Invoke this method if you no longer need the upload.
940
   *
941
   * @param uploadInfo The upload info representing the upload to delete
942
   * @param ownerKey The expected owner key of the upload
943
   * @throws IOException When deleting the upload fails
944
   * @throws TusException When the upload cannot be found or deleted
945
   */
946
  public void deleteUpload(UploadInfo uploadInfo, String ownerKey)
947
      throws IOException, TusException {
948
    if (uploadInfo != null && uploadInfo.getId() != null) {
5 ✔
949
      deleteUpload(uploadInfo.getId(), ownerKey);
5 ✔
950
    }
951
  }
1 ✔
952

953
  /**
954
   * Method to delete an upload associated with the given {@link UploadId}. Invoke this method if
955
   * you no longer need the upload.
956
   *
957
   * @param uploadId The ID of the upload to delete
958
   * @throws IOException When deleting the upload fails
959
   * @throws TusException When the upload cannot be locked
960
   */
961
  public void deleteUpload(UploadId uploadId) throws IOException, TusException {
962
    deleteUpload(uploadId, null);
4 ✔
963
  }
1 ✔
964

965
  /**
966
   * Method to delete an upload associated with the given {@link UploadId} and matching the given
967
   * owner key. Invoke this method if you no longer need the upload.
968
   *
969
   * @param uploadId The ID of the upload to delete
970
   * @param ownerKey The expected owner key of the upload
971
   * @throws IOException When deleting the upload fails
972
   * @throws TusException When the upload cannot be locked
973
   */
974
  public void deleteUpload(UploadId uploadId, String ownerKey) throws IOException, TusException {
975
    if (uploadId == null) {
4 ✔
976
      return;
1 ✔
977
    }
978
    try (UploadLock lock = lockUploadByUri(uploadId.toString())) {
10 ✔
979
      UploadInfo storedInfo = uploadStorageService.getUploadInfo(uploadId);
10 ✔
980
      if (storedInfo != null && Objects.equals(storedInfo.getOwnerKey(), ownerKey)) {
14 !
981
        uploadStorageService.terminateUpload(storedInfo);
8 ✔
982
      }
983
    }
984
  }
2 ✔
985

986
  /**
987
   * Method to delete an upload associated with the given upload URL. Invoke this method if you no
988
   * longer need the upload.
989
   *
990
   * @param uploadUri The upload URI
991
   */
992
  public void deleteUpload(String uploadUri) throws IOException, TusException {
993
    deleteUpload(uploadUri, null);
4 ✔
994
  }
1 ✔
995

996
  /**
997
   * Method to delete an upload associated with the given upload URL. Invoke this method if you no
998
   * longer need the upload.
999
   *
1000
   * @param uploadUri The upload URI
1001
   * @param ownerKey The key of the owner of this upload
1002
   */
1003
  public void deleteUpload(String uploadUri, String ownerKey) throws IOException, TusException {
1004
    try (UploadLock lock = lockUploadByUri(uploadUri)) {
8 ✔
1005
      UploadInfo uploadInfo = uploadStorageService.getUploadInfo(uploadUri, ownerKey);
12 ✔
1006
      if (uploadInfo != null) {
4 !
1007
        uploadStorageService.terminateUpload(uploadInfo);
8 ✔
1008
      }
1009
    }
1010
  }
2 ✔
1011

1012
  private UploadLock lockUploadByUri(String uploadUri) throws IOException, TusException {
1013
    return uploadLockingService.lockUploadByUri(uploadUri);
10 ✔
1014
  }
1015

1016
  /**
1017
   * This method should be invoked periodically. It will cleanup any expired uploads and stale locks
1018
   *
1019
   * @throws IOException When cleaning fails
1020
   */
1021
  public void cleanup() throws IOException {
1022
    uploadLockingService.cleanupStaleLocks();
6 ✔
1023
    uploadStorageService.cleanupExpiredUploads();
6 ✔
1024
  }
2 ✔
1025

1026
  protected UploadInfo processLockedRequest(
1027
      HttpMethod method, TusServletRequest request, TusServletResponse response, String ownerKey)
1028
      throws IOException {
1029
    ProtocolVersion detectedVersion = detectProtocolVersion(request);
8 ✔
1030

1031
    // Record initial upload offset before request processing starts.
1032
    // If an error occurs (e.g. MaxAppendSizeExceededException), processTusException must only
1033
    // rollback bytes that were actually committed during this request, and never truncate bytes
1034
    // committed by earlier successful requests.
1035
    long initialOffset = 0L;
4 ✔
1036
    try {
1037
      UploadInfo preInfo = resolveUploadInfo(request, null, ownerKey);
12 ✔
1038
      if (preInfo != null) {
4 ✔
1039
        initialOffset = preInfo.getOffset();
8 ✔
1040
      }
1041
    } catch (Exception e) {
1 ✔
1042
      log.debug("Could not resolve initial upload offset: {}", e.getMessage());
5 ✔
1043
    }
2 ✔
1044

1045
    try {
1046
      validateRequest(method, request, ownerKey, detectedVersion);
12 ✔
1047

1048
      executeProcessingByFeatures(method, request, response, ownerKey, detectedVersion);
14 ✔
1049

1050
      return resolveUploadInfo(request, response, ownerKey);
12 ✔
1051

1052
    } catch (TusException e) {
2 ✔
1053
      processTusException(method, request, response, ownerKey, e, detectedVersion, initialOffset);
18 ✔
1054
      return null;
4 ✔
1055
    } catch (RuntimeException e) {
1 ✔
1056
      // Catch unexpected RuntimeException (e.g. NPE in custom extension) and convert it to an
1057
      // internal server error TusException so that it routes through standard error handling
1058
      // (RFC 7807 problem details in RUFH mode, or plain error in Tus mode) rather than an
1059
      // unhandled container 500.
1060
      log.error("Unexpected runtime exception processing request " + request.getRequestURI(), e);
6 ✔
1061
      TusException wrapped =
4 ✔
1062
          new TusException(
1063
              HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
1064
              "Internal server error: " + e.getMessage());
4 ✔
1065
      processTusException(
9 ✔
1066
          method, request, response, ownerKey, wrapped, detectedVersion, initialOffset);
1067
      return null;
2 ✔
1068
    }
1069
  }
1070

1071
  private UploadInfo resolveUploadInfo(
1072
      TusServletRequest request, TusServletResponse response, String ownerKey) throws IOException {
1073
    String uploadUri = response != null ? response.getHeader(HttpHeader.LOCATION) : null;
16 ✔
1074
    if (StringUtils.isBlank(uploadUri) && request != null) {
10 !
1075
      if (Utils.isCreationEndpoint(request, uploadStorageService)) {
10 ✔
1076
        return null;
4 ✔
1077
      }
1078
      uploadUri = request.getRequestURI();
6 ✔
1079
    }
1080
    if (StringUtils.isNotBlank(uploadUri) && uploadStorageService != null) {
12 !
1081
      return uploadStorageService.getUploadInfo(uploadUri, ownerKey);
12 ✔
1082
    }
1083
    return null;
2 ✔
1084
  }
1085

1086
  private boolean checkWasInProgress(TusServletRequest request, String ownerKey) {
1087
    if (request == null || uploadStorageService == null) {
10 !
1088
      return true;
×
1089
    }
1090
    try {
1091
      UploadInfo uploadInfo = resolveUploadInfo(request, null, ownerKey);
12 ✔
1092
      if (uploadInfo != null) {
4 ✔
1093
        return uploadInfo.isUploadInProgress();
6 ✔
1094
      }
1095
    } catch (Exception e) {
1 ✔
1096
      log.debug("Error checking initial upload progress state: {}", e.getMessage());
5 ✔
1097
    }
2 ✔
1098
    return true;
4 ✔
1099
  }
1100

1101
  protected void notifyUploadCompletionListeners(UploadInfo uploadInfo) {
1102
    if (uploadInfo == null || uploadCompletionListeners.isEmpty()) {
12 ✔
1103
      return;
2 ✔
1104
    }
1105
    for (UploadCompletionListener listener : uploadCompletionListeners) {
22 ✔
1106
      try {
1107
        listener.onUploadComplete(uploadInfo, this);
8 ✔
1108
      } catch (Throwable t) {
1 ✔
1109
        log.error(
8 ✔
1110
            "Error executing upload completion listener for upload ID {}: {}",
1111
            uploadInfo.getId(),
5 ✔
1112
            t.getMessage(),
6 ✔
1113
            t);
1114
      }
2 ✔
1115
    }
2 ✔
1116
  }
2 ✔
1117

1118
  public ProtocolVersion detectProtocolVersion(HttpServletRequest request) {
1119
    return Utils.detectProtocolVersion(request, supportedProtocolVersion);
10 ✔
1120
  }
1121

1122
  protected void executeProcessingByFeatures(
1123
      HttpMethod method,
1124
      TusServletRequest servletRequest,
1125
      TusServletResponse servletResponse,
1126
      String ownerKey,
1127
      ProtocolVersion version)
1128
      throws IOException, TusException {
1129

1130
    for (TusExtension feature : enabledFeatures.values()) {
24 ✔
1131
      if (!servletRequest.isProcessedBy(feature)) {
8 !
1132
        servletRequest.addProcessor(feature);
6 ✔
1133
        feature.process(
22 ✔
1134
            method,
1135
            servletRequest,
1136
            servletResponse,
1137
            uploadStorageService,
1138
            uploadLockingService,
1139
            ownerKey,
1140
            version);
1141
      }
1142
    }
2 ✔
1143
  }
2 ✔
1144

1145
  protected void validateRequest(
1146
      HttpMethod method,
1147
      HttpServletRequest servletRequest,
1148
      String ownerKey,
1149
      ProtocolVersion version)
1150
      throws TusException, IOException {
1151

1152
    for (TusExtension feature : enabledFeatures.values()) {
24 ✔
1153
      feature.validate(
20 ✔
1154
          method, servletRequest, uploadStorageService, uploadLockingService, ownerKey, version);
1155
    }
2 ✔
1156
  }
2 ✔
1157

1158
  protected void processTusException(
1159
      HttpMethod method,
1160
      TusServletRequest request,
1161
      TusServletResponse response,
1162
      String ownerKey,
1163
      TusException exception,
1164
      ProtocolVersion version)
1165
      throws IOException {
1166
    processTusException(method, request, response, ownerKey, exception, version, 0L);
9 ✔
1167
  }
1 ✔
1168

1169
  protected void processTusException(
1170
      HttpMethod method,
1171
      TusServletRequest request,
1172
      TusServletResponse response,
1173
      String ownerKey,
1174
      TusException exception,
1175
      ProtocolVersion version,
1176
      long initialOffset)
1177
      throws IOException {
1178

1179
    int status = exception.getStatus();
6 ✔
1180
    String message = exception.getMessage();
6 ✔
1181

1182
    log.warn(
24 ✔
1183
        "Unable to process request {} {}. Sent response status {} with message \"{}\"",
1184
        method,
1185
        request.getRequestURL(),
10 ✔
1186
        status,
12 ✔
1187
        message);
1188

1189
    response.setStatus(status);
6 ✔
1190

1191
    HttpProblemDetails problemDetails = null;
4 ✔
1192
    try {
1193
      for (TusExtension feature : enabledFeatures.values()) {
24 ✔
1194
        if (!request.isProcessedBy(feature) || feature.mustReprocessOnError(method, version)) {
18 ✔
1195
          request.addProcessor(feature);
6 ✔
1196
          HttpProblemDetails pd =
22 ✔
1197
              feature.handleError(
4 ✔
1198
                  method,
1199
                  request,
1200
                  response,
1201
                  uploadStorageService,
1202
                  uploadLockingService,
1203
                  ownerKey,
1204
                  version,
1205
                  exception);
1206
          if (pd != null) {
4 ✔
1207
            problemDetails = pd;
4 ✔
1208
          }
1209
        }
1210
      }
2 ✔
1211

1212
      // Since an error occurred, only rollback bytes that were actually committed during this
1213
      // request. Capping rollback to (uploadInfo.getOffset() - initialOffset) guarantees that if an
1214
      // uncommitted chunk failed (e.g. MaxAppendSizeExceededException where bytes were read into
1215
      // temp storage but never committed to offset), we do not truncate earlier valid data!
1216
      String uploadUri = Utils.getUploadUri(request, response);
8 ✔
1217
      UploadInfo uploadInfo = uploadStorageService.getUploadInfo(uploadUri, ownerKey);
12 ✔
1218
      if (uploadInfo != null) {
4 ✔
1219
        long committedThisRequest = Math.max(0L, uploadInfo.getOffset() - initialOffset);
16 ✔
1220
        long bytesToRollback = Math.min(request.getBytesRead(), committedThisRequest);
10 ✔
1221
        if (bytesToRollback > 0) {
8 ✔
1222
          uploadStorageService.removeLastNumberOfBytes(uploadInfo, bytesToRollback);
10 ✔
1223
        }
1224
      }
1225

1226
    } catch (TusException ex) {
1 ✔
1227
      log.warn("An exception occurred while handling another exception", ex);
4 ✔
1228
    }
2 ✔
1229

1230
    // If one of the features has already committed a response, we don't need to send an error
1231
    // response. Otherwise, we send the error response with the status and message from the
1232
    // exception.
1233
    if (!response.isCommitted()) {
6 ✔
1234
      response.setStatus(status);
6 ✔
1235
      if (problemDetails != null) {
4 ✔
1236
        problemDetails.writeTo(response);
8 ✔
1237
      } else if (status == 460) {
6 ✔
1238
        // Non-standard HTTP status 460 (Checksum Mismatch) is not recognized by standard
1239
        // servlet container error controllers (such as Spring Boot's BasicErrorController),
1240
        // which would cause sendError() to fail with an unhandled IllegalArgumentException
1241
        // and degrade to HTTP 500. We explicitly set the status and omit sendError().
1242
        response.setHeader(HttpHeader.CONTENT_LENGTH, null);
4 ✔
1243
        response.setStatus(status);
4 ✔
1244
      } else {
1245
        response.setHeader(HttpHeader.CONTENT_LENGTH, null);
8 ✔
1246
        response.sendError(status, message);
8 ✔
1247
      }
1248
    }
1249
  }
2 ✔
1250

1251
  private void updateSupportedHttpMethods() {
1252
    supportedHttpMethods.clear();
6 ✔
1253
    for (TusExtension tusFeature : enabledFeatures.values()) {
24 ✔
1254
      supportedHttpMethods.addAll(tusFeature.getMinimalSupportedHttpMethods());
12 ✔
1255
    }
2 ✔
1256
  }
2 ✔
1257

1258
  private void prepareCacheIfEnabled() {
1259
    UploadStorageService rawStorage = unwrapStorageService(this.uploadStorageService);
10 ✔
1260
    UploadLockingService rawLocking = unwrapLockingService(this.uploadLockingService);
10 ✔
1261

1262
    if (isThreadLocalCacheEnabled && rawStorage != null) {
10 !
1263
      ThreadLocalCachedStorageAndLockingService service =
12 ✔
1264
          new ThreadLocalCachedStorageAndLockingService(rawStorage, rawLocking);
1265
      service.setIdFactory(this.idFactory);
8 ✔
1266
      this.uploadStorageService = service;
6 ✔
1267
      this.uploadLockingService = service;
6 ✔
1268
    } else {
2 ✔
1269
      this.uploadStorageService = rawStorage;
6 ✔
1270
      this.uploadLockingService = rawLocking;
6 ✔
1271
    }
1272
  }
2 ✔
1273

1274
  private UploadStorageService unwrapStorageService(UploadStorageService service) {
1275
    if (service instanceof ThreadLocalCachedStorageAndLockingService cached) {
12 ✔
1276
      return cached.getStorageServiceDelegate();
6 ✔
1277
    }
1278
    return service;
4 ✔
1279
  }
1280

1281
  private UploadLockingService unwrapLockingService(UploadLockingService service) {
1282
    if (service instanceof ThreadLocalCachedStorageAndLockingService cached) {
12 ✔
1283
      return cached.getLockingServiceDelegate();
6 ✔
1284
    }
1285
    return service;
4 ✔
1286
  }
1287

1288
  private void closeQuietly(UploadStorageService storageService) {
1289
    if (storageService != null) {
4 !
1290
      try {
1291
        storageService.close();
4 ✔
NEW
1292
      } catch (Exception e) {
×
NEW
1293
        log.warn("Error closing replaced storage service instance: {}", e.getMessage());
×
1294
      }
2 ✔
1295
    }
1296
  }
2 ✔
1297

1298
  private void closeQuietly(UploadLockingService lockingService) {
1299
    if (lockingService != null) {
4 !
1300
      try {
1301
        lockingService.close();
4 ✔
NEW
1302
      } catch (Exception e) {
×
NEW
1303
        log.warn("Error closing replaced locking service instance: {}", e.getMessage());
×
1304
      }
2 ✔
1305
    }
1306
  }
2 ✔
1307

1308
  /**
1309
   * Closes underlying storage and locking services, releasing background threads and resources.
1310
   *
1311
   * @throws IOException If closing fails
1312
   */
1313
  @Override
1314
  public void close() throws IOException {
1315
    if (uploadStorageService instanceof ThreadLocalCachedStorageAndLockingService) {
8 ✔
1316
      // Cache wrapper owns and closes both the locking and storage delegates once.
1317
      uploadStorageService.close();
3 ✔
1318
      return;
1 ✔
1319
    }
1320
    try {
1321
      if (uploadLockingService != null) {
6 !
1322
        uploadLockingService.close();
6 ✔
1323
      }
1324
    } finally {
1325
      if (uploadStorageService != null) {
6 !
1326
        uploadStorageService.close();
6 ✔
1327
      }
1328
    }
1329
  }
2 ✔
1330

1331
  /**
1332
   * FilterInputStream wrapper that retains an active {@link UploadLock} until the consumer closes
1333
   * the stream.
1334
   *
1335
   * <p>This prevents concurrent DELETE or PATCH requests from corrupting, modifying, or truncating
1336
   * upload data while a caller is actively reading the stream.
1337
   */
1338
  private static class LockHoldingInputStream extends FilterInputStream {
1339

1340
    private final UploadLock lock;
1341
    private final AtomicBoolean closed = new AtomicBoolean(false);
12 ✔
1342

1343
    protected LockHoldingInputStream(InputStream in, UploadLock lock) {
1344
      super(Objects.requireNonNull(in, "InputStream must not be null"));
12 ✔
1345
      this.lock = Objects.requireNonNull(lock, "UploadLock must not be null");
12 ✔
1346
    }
2 ✔
1347

1348
    @Override
1349
    public void close() throws IOException {
1350
      if (closed.compareAndSet(false, true)) {
12 ✔
1351
        try {
1352
          super.close();
4 ✔
1353
        } finally {
1354
          lock.close();
6 ✔
1355
        }
1356
      }
1357
    }
2 ✔
1358
  }
1359
}
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