Skip to content

fix(google-calendar): throw InvalidTokenException on invalid_grant - #1497

Merged
ameya9 merged 15 commits into
dtinit:masterfrom
ameya9:fix_calendar_invalid_token
Jul 7, 2026
Merged

fix(google-calendar): throw InvalidTokenException on invalid_grant#1497
ameya9 merged 15 commits into
dtinit:masterfrom
ameya9:fix_calendar_invalid_token

Conversation

@ameya9

@ameya9 ameya9 commented Jun 22, 2026

Copy link
Copy Markdown
Collaborator

Same as google drive importer so the transfer job recognises the token as invalid instead of treating it as a generic failure

fixes this: #1499

ameya9 and others added 12 commits March 3, 2026 16:13
…t#1484)

Implemented `SynologySignalHandler` to manage job lifecycle signals
(e.g., job started or completion) within the Synology transfer
extension. This ensures that the Synology C2 API is notified of the
final state of a transfer job, allowing for better synchronization.

## Changes
- New Signal Handler: Added `SynologySignalHandler` to process and retry
job lifecycle signals using the
     RetryingCallable framework.
- Service Integration: Added `sendJobSignal` to `SynologyDTPService` to
handle the actual HTTP POST request to the
     Synology C2 API.
- Extension Update: Modified `SynologyTransferExtension` to register the
new SignalHandler during initialization.
   - Configuration & Models:
- Updated `synology.yaml` to include the new `/import/job/signal`
endpoint.
- Updated `C2Api` and its `ApiPath` inner class to support the new
signal path.
   - Testing:
- Added `SynologySignalHandlerTest` to verify successful signal
transmission and the retry mechanism on failure.
- Updated `TestConfigs` to include the signal path for existing tests.
## Goal
The goal of this change is to support large file uploads for
`SynologyDTPService` by implementing streaming. This resolves potential
OutOfMemoryError (OOM) issues that occurred when large media files were
fully buffered into memory during the transfer process.

## Changes
- **Streaming Uploads:** Replaced `ByteStreams.toByteArray()` with a
custom `RequestBody` implementation using **Okio** to stream data
directly from the source (`JobStore` or `URL`) to the network sink.
- **Repeatable Streams for Retries:** Introduced `RequestBodyGenerator`,
a functional interface that allows the `sendPostRequest` method to
re-open the `InputStream` during retries. This ensures that even if a
stream is consumed during a failed attempt, it can be reset for the next
retry.

## Testing
- **New Unit Tests:** Added `SynologyDTPServiceOOMTest` to verify 1GB
streaming.
- **Updated Unit Tests:** Updated `SynologyDTPServiceTest` to
accommodate the new `RequestBodyGenerator` pattern and added cases for
`getMediaInputStreamWrapper`.
## Goal
The goal of this change is to provide a more robust upload mechanism for
large video files in `SynologyDTPService`. By switching from a
single-stream upload to a chunked upload process, we improve reliability
for very large transfers and align with the Synology C2 API's preferred
method for handling significant media payloads.

## Changes
- **Chunked Upload Logic:** Refactored `createVideo` to use a multi-step
upload process:
- `uploadVideoChunks`: Reads the video stream in 50MB increments and
uploads each chunk sequentially to the new `/import/item/chunk`
endpoint.
- `completeVideoUpload`: Sends a final request to
`/import/item/complete` with the total chunk count and metadata (title,
description, timestamp) to finalize the file.
- **API Configuration:**
- Updated `C2Api` and `synology.yaml` to include paths for the new chunk
and completion endpoints.
- **Client Optimization:**
- Updated `configureClient` to force **HTTP/1.1** and increased the
default read timeout to 120 seconds to ensure stable long-running
connections during chunk transmission.
- Simplified `sendPostRequest` by removing the manual timeout override,
relying instead on the pre-configured client.
- **Memory Efficiency:** Reuses a single byte array buffer for chunking
to minimize heap allocations during the transfer of large files.
- **Others:** Move file content to the end of multipart

## Testing
- **OOM Validation:** Updated `SynologyDTPServiceOOMTest` to verify that
a 1GB video is correctly split into multiple chunks and uploaded without
exceeding memory limits.
- **Functional Tests:** Updated `SynologyDTPServiceTest` to accommodate
the new two-step upload flow (Multipart chunks followed by a FormBody
completion) and added a specific case
`shouldSendMultipleChunksForLargeVideo` to verify correct indexing.
Fixing `AppleSignalInterface:: sendPostRequest` to accomodate
Access-Token refresh POST calls.

Co-authored-by: aman-pratik <apratik@apple.com>
Co-authored-by: Sundeep Paruvu <sparuvu@gmail.com>
…#1489)

## Goal
The goal of this change is to improve compatibility of chunked reading
in
 by replacing the Java 9+  method with Guava's
, ensuring the code works correctly in older Java environments.

## Changes
- **Dependency Update:** Added `com.google.guava:guava` to the Synology
extension's `build.gradle`.
- **Code Refactor:** Updated `SynologyDTPService` to use
`ByteStreams.read` when reading video chunks.

Co-authored-by: emma <myshen@synology.com>
)

fixes dtinit#1031, which has some of the investigation confirming this was
really left over and now unused
)

Improve video upload efficiency by implementing an asynchronous
producer-consumer model for chunked uploads. This minimizes idle time
between network requests and increases overall throughput for large
video files.

## Goal
The goal of this change is to optimize video uploads to Synology by
pre-fetching the next data chunk while the current one is being
uploaded, reducing the total duration of sequential transfers.

## Changes
- **Pattern Implementation:** Refactored `uploadVideoChunks` into a
producer-consumer model using a dedicated thread for pre-loading data
from the input stream.
- **Memory Management:** Introduced a `bufferPool` with a fixed size (2
chunks) to ensure predictable memory usage (~100MB) regardless of video
size.
- **Asynchronous Execution:** Utilized `CompletableFuture` and
`LinkedBlockingQueue` for thread-safe coordination between chunk
production and upload.
- **Robustness:** Added explicit error propagation and resource cleanup
(buffers, threads) using `AtomicBoolean` and `finally` blocks.
- **Observability:** Enhanced logging with detailed markers for chunk
fetching, queueing, and upload progress to facilitate monitoring and
debugging.

<img width="1492" height="957" alt="image"
src="https://github.com/user-attachments/assets/e4a1ee82-374e-498c-9d17-b3751e9d427d"
/>
…aims (dtinit#1491)

This PR fixes a critical process-terminating thread crash in the
JobPollingService loop that occurs when a transfer worker attempts to
claim a job that has already been claimed and has credentials stored by
another worker instance.

**Problem**
In a distributed, highly concurrent deployment with multiple worker
instances, a worker can poll a job ID from an eventually consistent
database index that looks free (CREDS_AVAILABLE) but has actually
already been claimed by a faster peer instance.

When our worker performs a strongly consistent read (store.findJob) to
retrieve the job details, it detects the instanceId mismatch (indicating
the job belongs to another worker) and marks the job's state as CANCELED
in memory.

However, in the old implementation:

1. JobPollingService.tryToClaimJob failed to verify whether the
retrieved existingJob was null or canceled, proceeding blindly to build
the updatedJob to claim it.
2. Constructing this job object to transition to state
CREDS_ENCRYPTION_KEY_GENERATED threw a validation exception
(IllegalStateException) because credentials (encryptedAuthData) had
already been set by the peer worker.
3. Because the PortabilityJob builder execution occurred outside the
main try-catch block in tryToClaimJob, this exception was uncaught.
4. This uncaught thread failure propagated up, terminating the periodic
JobPollingService thread and causing the entire container sandbox to
crash.

**Solution**
Implemented two layers of safety in JobPollingService.java to resolve
this:

1. Proactive Prevention (Early Abort): Added null and CANCELED state
checks immediately after retrieving the job from the JobStore. If the
job has been deleted or marked canceled (which happens on instanceId
mismatch), the worker aborts the claim attempt early and returns false
safely.
2. Reactive Safety (Validation Safety Net): Wrapped the PortabilityJob
builder execution in a local try-catch block to safely handle any
unexpected IllegalStateException validation errors during object
construction, returning false (handled failure) instead of propagating
and crashing the thread.

These changes ensure that failing to claim a job (due to losing a race)
is treated as a handled, temporary failure, allowing the worker to
complete the current polling iteration normally and try again in the
next cycle instead of crashing.
Mirror DriveImporter's handling: when calendar/event insertion fails with a
TokenResponseException whose error is "invalid_grant" (HTTP 400 from the
oauth2 token endpoint), wrap and rethrow as InvalidTokenException so the
transfer job recognizes the token as invalid instead of treating it as a
generic failure.
@ameya9 ameya9 changed the title Fix calendar invalid token fix(google-calendar): throw InvalidTokenException on invalid_grant Jun 22, 2026
@ameya9
ameya9 marked this pull request as ready for review June 22, 2026 14:53
@alexeyqu
alexeyqu self-requested a review June 23, 2026 15:25

@alexeyqu alexeyqu left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ok -- please fix the potential NPE before merging

ameya9 and others added 2 commits July 7, 2026 15:03
Co-authored-by: Alex Kulikov <7394728+alexeyqu@users.noreply.github.com>
@ameya9
ameya9 merged commit c07c269 into dtinit:master Jul 7, 2026
7 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

GoogleCalendarImporter does not throw InvalidTokenException on invalid_grant

6 participants