Skip to content

fix: realtime streams from tasks now retry if they receive a 408 timeout error from the realtime/trigger.dev server #1952

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Apr 18, 2025

Conversation

ericallam
Copy link
Member

@ericallam ericallam commented Apr 18, 2025

Summary by CodeRabbit

  • Bug Fixes

    • Resolved an issue where realtime streams would unexpectedly stop after 5 minutes, ensuring improved stability and continuity for streaming functionality.
  • New Features

    • Introduced a retry mechanism for realtime streams, allowing automatic recovery from certain network timeouts to maintain uninterrupted streaming.

…out error from the realtime/trigger.dev server
Copy link

changeset-bot bot commented Apr 18, 2025

🦋 Changeset detected

Latest commit: 44308f1

The changes in this PR will be included in the next version bump.

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

Copy link
Contributor

coderabbitai bot commented Apr 18, 2025

Walkthrough

This update refactors the realtime streaming implementation in the @trigger.dev/sdk package to address premature stream termination issues. The previous fetch-based approach is replaced by a manual HTTP/HTTPS request using Node.js native modules, introducing a retry mechanism that resumes the stream from the last successful chunk if a timeout occurs. Additional logic tracks chunk indices, manages retries, and ensures proper stream closure or error handling. The public API is updated to allow configuration of the maximum number of retries. No changes are made to other exported functions or methods.

Changes

File(s) Change Summary
.changeset/hip-cups-wave.md Documents the patch to fix realtime streams cutting off after 5 minutes in the "@trigger.dev/sdk" package.
packages/core/src/v3/runMetadata/metadataStream.ts Replaces fetch-based streaming POST with manual HTTP/HTTPS request, adds retry mechanism for HTTP 408 responses, tracks chunk indices for resuming, introduces configurable maxRetries, and updates stream management logic. Updates MetadataStream<T> class with new private fields and methods, and modifies the public API for retry configuration.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant MetadataStream
    participant Server

    Client->>MetadataStream: start streaming (with options)
    MetadataStream->>Server: HTTP/HTTPS request (stream chunks)
    loop For each chunk
        MetadataStream->>Server: Send chunk (JSON)
        Server-->>MetadataStream: Ack/continue
    end
    alt Timeout (HTTP 408)
        MetadataStream->>Server: Retry request (resume from last chunk)
    end
    Server-->>MetadataStream: Stream complete / error
    MetadataStream-->>Client: Resolve/reject promise
Loading

Possibly related PRs

  • triggerdotdev/trigger.dev#1520: Refactors streaming implementation in metadataStream.ts to use native HTTP/HTTPS requests with retry logic, related to stream management and reliability improvements.

Poem

In the warren of streams, a bug did appear,
Cutting off rabbits mid-hop, causing much fear.
With retries and tracking, the flow’s now robust—
Each chunk hops along, in the server we trust.
No more five-minute naps, the stream runs anew,
Thanks to clever code—hip hip, bunny-hoo! 🐇✨

✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🧹 Nitpick comments (2)
packages/core/src/v3/runMetadata/metadataStream.ts (1)

18-25: controller and several fields are never used – consider pruning to keep the class lean.

controller, serverStream, consumerStream and reader are the only state you actually need for the current implementation.
controller is instantiated but never referenced, while retryCount, maxRetries, currentChunkIndex and reader are all required. Removing dead fields avoids cognitive overhead and keeps the object model simple.

.changeset/hip-cups-wave.md (1)

5-6: Consider elaborating the changelog entry for future maintainers.

A single‑line summary is terse; adding one or two sentences about the switch to http/https native requests and the retry mechanism will make the historical context clearer when scanning the changelog.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 006951a and 44308f1.

📒 Files selected for processing (2)
  • .changeset/hip-cups-wave.md (1 hunks)
  • packages/core/src/v3/runMetadata/metadataStream.ts (2 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (7)
  • GitHub Check: e2e / 🧪 CLI v3 tests (windows-latest - pnpm)
  • GitHub Check: e2e / 🧪 CLI v3 tests (windows-latest - npm)
  • GitHub Check: e2e / 🧪 CLI v3 tests (ubuntu-latest - pnpm)
  • GitHub Check: e2e / 🧪 CLI v3 tests (ubuntu-latest - npm)
  • GitHub Check: typecheck / typecheck
  • GitHub Check: units / 🧪 Unit Tests
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (1)
packages/core/src/v3/runMetadata/metadataStream.ts (1)

146-148: Public wait() is clear and concise – nice touch!

Providing a single promise that represents the lifecycle of the network request gives callers a simple primitive for await‑ing completion.

Comment on lines +117 to +125
if (done) {
req.end();
break;
}

const stringified = JSON.stringify(value) + "\n";
req.write(stringified);
this.currentChunkIndex++;
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Release reader lock once the final chunk is flushed.

After done is returned the lock is still active.
This prevents GC of the stream and can block callers that might wish to re‑read.

-            if (done) {
-              req.end();
-              break;
-            }
+            if (done) {
+              req.end();
+              this.reader.releaseLock();
+              break;
+            }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if (done) {
req.end();
break;
}
const stringified = JSON.stringify(value) + "\n";
req.write(stringified);
this.currentChunkIndex++;
}
if (done) {
req.end();
this.reader.releaseLock();
break;
}
const stringified = JSON.stringify(value) + "\n";
req.write(stringified);
this.currentChunkIndex++;
}

Comment on lines 38 to 49
const readableSource = new ReadableStream<T>({
start: async (controller) => {
for await (const value of this.options.source) {
controller.enqueue(value);
try {
for await (const value of this.options.source) {
controller.enqueue(value);
}
controller.close();
} catch (error) {
controller.error(error);
}

controller.close();
},
});
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Error‑first propagation is good, but release reader lock on failure.

controller.error(error) is great for signalling downstream consumers, however the reader lock on this.serverStream is still held.
If an upstream error is thrown, subsequent retries will fail to acquire the lock, leading to a stalled pipeline.

         } catch (error) {
-          controller.error(error);
+          controller.error(error);
+          // Free the lock so a retry can acquire it.
+          this.reader?.releaseLock?.();
         }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const readableSource = new ReadableStream<T>({
start: async (controller) => {
for await (const value of this.options.source) {
controller.enqueue(value);
try {
for await (const value of this.options.source) {
controller.enqueue(value);
}
controller.close();
} catch (error) {
controller.error(error);
}
controller.close();
},
});
const readableSource = new ReadableStream<T>({
start: async (controller) => {
try {
for await (const value of this.options.source) {
controller.enqueue(value);
}
controller.close();
} catch (error) {
controller.error(error);
// Free the lock so a retry can acquire it.
this.reader?.releaseLock?.();
}
},
});

Comment on lines +54 to 134
private async makeRequest(startFromChunk: number = 0): Promise<void> {
return new Promise((resolve, reject) => {
const url = new URL(this.buildUrl());
const timeout = 15 * 60 * 1000; // 15 minutes

const requestFn = url.protocol === "https:" ? httpsRequest : httpRequest;
const req = requestFn({
method: "POST",
hostname: url.hostname,
port: url.port || (url.protocol === "https:" ? 443 : 80),
path: url.pathname + url.search,
headers: {
...this.options.headers,
"Content-Type": "application/json",
"X-Resume-From-Chunk": startFromChunk.toString(),
},
})
);

return fetch(this.buildUrl(), {
method: "POST",
headers: this.options.headers ?? {},
body: serverStream,
signal: this.controller.signal,
// @ts-expect-error
duplex: "half",
timeout,
});

req.on("error", (error) => {
reject(error);
});

req.on("timeout", () => {
req.destroy(new Error("Request timed out"));
});

req.on("response", (res) => {
if (res.statusCode === 408) {
if (this.retryCount < this.maxRetries) {
this.retryCount++;

resolve(this.makeRequest(this.currentChunkIndex));
return;
}
reject(new Error(`Max retries (${this.maxRetries}) exceeded after timeout`));
return;
}

if (res.statusCode && (res.statusCode < 200 || res.statusCode >= 300)) {
const error = new Error(`HTTP error! status: ${res.statusCode}`);
reject(error);
return;
}

res.on("end", () => {
resolve();
});

res.resume();
});

if (this.options.signal) {
this.options.signal.addEventListener("abort", () => {
req.destroy(new Error("Request aborted"));
});
}

const processStream = async () => {
try {
while (true) {
const { done, value } = await this.reader.read();

if (done) {
req.end();
break;
}

const stringified = JSON.stringify(value) + "\n";
req.write(stringified);
this.currentChunkIndex++;
}
} catch (error) {
req.destroy(error as Error);
}
};

processStream().catch((error) => {
reject(error);
});
});
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Potential socket & memory leak on 408 retry path.

  1. When a 408 is received you resolve(this.makeRequest(...)) but you never:
    • destroy the current socket
    • drain res (to prevent ‘socket hang up’ warnings)
    • release the reader lock

  2. makeRequest is recursively invoked, which builds an ever‑growing call stack if many retries occur.
    A simple loop is safer.

  3. The currentChunkIndex is incremented after the chunk is written, so the value passed in "X-Resume-From-Chunk" on retry points to the next chunk rather than the last confirmed one – the server may miss one chunk.

@@
-        if (res.statusCode === 408) {
-          if (this.retryCount < this.maxRetries) {
-            this.retryCount++;
-
-            resolve(this.makeRequest(this.currentChunkIndex));
-            return;
-          }
-          reject(new Error(`Max retries (${this.maxRetries}) exceeded after timeout`));
-          return;
-        }
+        if (res.statusCode === 408) {
+          res.resume();            // consume data
+          req.destroy();           // close socket
+          this.reader.releaseLock();
+
+          if (this.retryCount < this.maxRetries) {
+            this.retryCount++;
+            // Pass the *last* successful chunk index
+            resolve(this.makeRequest(this.currentChunkIndex - 1));
+            return;
+          }
+          reject(new Error(`Max retries (${this.maxRetries}) exceeded after timeout`));
+          return;
+        }

Optionally, replace the recursive strategy with a while loop to avoid unbounded stack growth.

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.

2 participants