-
-
Notifications
You must be signed in to change notification settings - Fork 853
New internal idempotency implementation for trigger and batch trigger #2256
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
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
0419fe8
Introduce request idempotency to prevent duplicate triggers
ericallam 84eeeae
Implement request idempotency on trigger
ericallam 8202b92
Use x-trigger-request-idempotency-key header instead
ericallam c0d4a56
Add changeset
ericallam 1ce1260
Oops, lets not hardcode a 408
ericallam 10f2365
A couple of improvements
ericallam File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
--- | ||
"@trigger.dev/sdk": patch | ||
--- | ||
|
||
New internal idempotency implementation for trigger and batch trigger to prevent request retries from duplicating work |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,124 @@ | ||
import { Logger, LogLevel } from "@trigger.dev/core/logger"; | ||
import { createCache, DefaultStatefulContext, Namespace, Cache as UnkeyCache } from "@unkey/cache"; | ||
import { MemoryStore } from "@unkey/cache/stores"; | ||
import { RedisCacheStore } from "./unkey/redisCacheStore.server"; | ||
import { RedisWithClusterOptions } from "~/redis.server"; | ||
import { validate as uuidValidate, version as uuidVersion } from "uuid"; | ||
import { startActiveSpan } from "~/v3/tracer.server"; | ||
|
||
export type RequestIdempotencyServiceOptions<TTypes extends string> = { | ||
types: TTypes[]; | ||
redis: RedisWithClusterOptions; | ||
logger?: Logger; | ||
logLevel?: LogLevel; | ||
ttlInMs?: number; | ||
}; | ||
|
||
const DEFAULT_TTL_IN_MS = 60_000 * 60 * 24; | ||
|
||
type RequestIdempotencyCacheEntry = { | ||
id: string; | ||
}; | ||
|
||
export class RequestIdempotencyService<TTypes extends string> { | ||
private readonly logger: Logger; | ||
private readonly cache: UnkeyCache<{ requests: RequestIdempotencyCacheEntry }>; | ||
|
||
constructor(private readonly options: RequestIdempotencyServiceOptions<TTypes>) { | ||
this.logger = | ||
options.logger ?? new Logger("RequestIdempotencyService", options.logLevel ?? "info"); | ||
|
||
const keyPrefix = options.redis.keyPrefix | ||
? `request-idempotency:${options.redis.keyPrefix}` | ||
: "request-idempotency:"; | ||
|
||
const ctx = new DefaultStatefulContext(); | ||
const memory = new MemoryStore({ persistentMap: new Map() }); | ||
const redisCacheStore = new RedisCacheStore({ | ||
name: "request-idempotency", | ||
connection: { | ||
keyPrefix: keyPrefix, | ||
...options.redis, | ||
}, | ||
}); | ||
|
||
// This cache holds the rate limit configuration for each org, so we don't have to fetch it every request | ||
const cache = createCache({ | ||
requests: new Namespace<RequestIdempotencyCacheEntry>(ctx, { | ||
stores: [memory, redisCacheStore], | ||
fresh: options.ttlInMs ?? DEFAULT_TTL_IN_MS, | ||
stale: options.ttlInMs ?? DEFAULT_TTL_IN_MS, | ||
}), | ||
}); | ||
|
||
this.cache = cache; | ||
} | ||
|
||
async checkRequest(type: TTypes, requestIdempotencyKey: string) { | ||
if (!this.#validateRequestId(requestIdempotencyKey)) { | ||
this.logger.warn("RequestIdempotency: invalid requestIdempotencyKey", { | ||
requestIdempotencyKey, | ||
}); | ||
|
||
return undefined; | ||
} | ||
|
||
return startActiveSpan("RequestIdempotency.checkRequest()", async (span) => { | ||
span.setAttribute("request_id", requestIdempotencyKey); | ||
span.setAttribute("type", type); | ||
|
||
const key = `${type}:${requestIdempotencyKey}`; | ||
const result = await this.cache.requests.get(key); | ||
|
||
this.logger.debug("RequestIdempotency: checking request", { | ||
type, | ||
requestIdempotencyKey, | ||
key, | ||
result, | ||
}); | ||
|
||
return result.val ? result.val : undefined; | ||
}); | ||
} | ||
|
||
async saveRequest( | ||
type: TTypes, | ||
requestIdempotencyKey: string, | ||
value: RequestIdempotencyCacheEntry | ||
) { | ||
if (!this.#validateRequestId(requestIdempotencyKey)) { | ||
this.logger.warn("RequestIdempotency: invalid requestIdempotencyKey", { | ||
requestIdempotencyKey, | ||
}); | ||
return undefined; | ||
} | ||
|
||
const key = `${type}:${requestIdempotencyKey}`; | ||
const result = await this.cache.requests.set(key, value); | ||
|
||
if (result.err) { | ||
this.logger.error("RequestIdempotency: error saving request", { | ||
key, | ||
error: result.err, | ||
}); | ||
} else { | ||
this.logger.debug("RequestIdempotency: saved request", { | ||
type, | ||
requestIdempotencyKey, | ||
key, | ||
value, | ||
}); | ||
} | ||
|
||
return result; | ||
} | ||
|
||
// The requestIdempotencyKey should be a valid UUID | ||
#validateRequestId(requestIdempotencyKey: string): boolean { | ||
return isValidV4UUID(requestIdempotencyKey); | ||
} | ||
} | ||
|
||
function isValidV4UUID(uuid: string): boolean { | ||
return uuidValidate(uuid) && uuidVersion(uuid) === 4; | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.