Skip to content

Commit

Permalink
fix!: Handle TTL as seconds instead of milliseconds
Browse files Browse the repository at this point in the history
  • Loading branch information
blaine-arcjet committed Feb 8, 2024
1 parent de36130 commit 2dad237
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 8 deletions.
16 changes: 10 additions & 6 deletions arcjet/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,10 @@ function isIterable(val: any): val is Iterable<any> {
return typeof val?.[Symbol.iterator] === "function";
}

function nowInSeconds(): number {
return Math.floor(Date.now() / 1000);
}

class Cache<T> {
expires: Map<string, number>;
data: Map<string, T>;
Expand All @@ -75,12 +79,12 @@ class Cache<T> {
}

set(key: string, value: T, ttl: number) {
this.expires.set(key, Date.now() + ttl);
this.expires.set(key, nowInSeconds() + ttl);
this.data.set(key, value);
}

ttl(key: string): number {
const now = Date.now();
const now = nowInSeconds();
const expiresAt = this.expires.get(key) ?? now;
return expiresAt - now;
}
Expand Down Expand Up @@ -906,7 +910,7 @@ export function detectBot(
block.includes(BotType[botResult.bot_type] as ArcjetBotType)
) {
return new ArcjetRuleResult({
ttl: 60000,
ttl: 60,
state: "RUN",
conclusion: "DENY",
reason: new ArcjetBotReason({
Expand All @@ -918,7 +922,7 @@ export function detectBot(
});
} else {
return new ArcjetRuleResult({
ttl: 60000,
ttl: 60,
state: "RUN",
conclusion: "ALLOW",
reason: new ArcjetBotReason({
Expand Down Expand Up @@ -1197,7 +1201,7 @@ export default function arcjet<
// and return this DENY decision.
if (rule.mode !== "DRY_RUN") {
if (results[idx].ttl > 0) {
log.debug("Caching decision for %d milliseconds", decision.ttl, {
log.debug("Caching decision for %d seconds", decision.ttl, {
fingerprint,
conclusion: decision.conclusion,
reason: decision.reason,
Expand Down Expand Up @@ -1231,7 +1235,7 @@ export default function arcjet<
// block locally
if (decision.isDenied() && decision.ttl > 0) {
log.debug(
"decide: Caching block locally for %d milliseconds",
"decide: Caching block locally for %d seconds",
decision.ttl,
);

Expand Down
4 changes: 2 additions & 2 deletions protocol/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -223,8 +223,8 @@ export class ArcjetErrorReason extends ArcjetReason {
export class ArcjetRuleResult {
ruleId: string;
/**
* The duration in milliseconds this result should be considered valid, also
* known as time-to-live.
* The duration in seconds this result should be considered valid, also known
* as time-to-live.
*/
ttl: number;
state: ArcjetRuleState;
Expand Down

0 comments on commit 2dad237

Please sign in to comment.