perf(clients): avoid waiting to read cached relay tokens (#9691)
This commit is contained in:
1 parent
ec8b2119c3
commit
2460649935
2 files changed
+124
-11
No files matched your search
@@ -1,5 +1,8 @@
|
||||
import { EnvironmentId } from "@t3tools/contracts";
|
||||
import { RelayEnvironmentStatusScope } from "@t3tools/contracts/relay";
|
||||
import {
|
||||
RelayEnvironmentConnectScope,
|
||||
RelayEnvironmentStatusScope,
|
||||
} from "@t3tools/contracts/relay";
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
@@ -190,6 +193,102 @@ describe("ManagedRelayClient", () => {
|
||||
}).pipe(Effect.provide(managedRelayTestLayer(fetchFn)));
|
||||
});
|
||||
|
||||
it.effect("uses a cached token while another scope waits for an exchange", () => {
|
||||
const exchangeStarted = Promise.withResolvers<void>();
|
||||
const releaseExchange = Promise.withResolvers<void>();
|
||||
let tokenExchangeCount = 0;
|
||||
const statusTokens: Array<string | null> = [];
|
||||
let persistedTokens: ReadonlyArray<ManagedRelay.ManagedRelayAccessTokenCacheEntry> = [
|
||||
{
|
||||
accountId: "user-1",
|
||||
clientId: "t3-mobile",
|
||||
relayUrl: "https://relay.example.test",
|
||||
thumbprint: "client-thumbprint",
|
||||
scopes: [RelayEnvironmentStatusScope],
|
||||
accessToken: "cached-status-token",
|
||||
expiresAtMillis: Number.MAX_SAFE_INTEGER,
|
||||
},
|
||||
];
|
||||
const accessTokenStore: ManagedRelay.ManagedRelayAccessTokenStore = {
|
||||
load: Effect.sync(() => persistedTokens),
|
||||
save: (entries) =>
|
||||
Effect.sync(() => {
|
||||
persistedTokens = entries;
|
||||
}),
|
||||
clear: Effect.sync(() => {
|
||||
persistedTokens = [];
|
||||
}),
|
||||
};
|
||||
const fetchFn = ((input, init) => {
|
||||
if (String(input).endsWith("/v1/client/dpop-token")) {
|
||||
tokenExchangeCount += 1;
|
||||
exchangeStarted.resolve();
|
||||
return releaseExchange.promise.then(() =>
|
||||
Response.json({
|
||||
access_token: "expanded-scope-token",
|
||||
issued_token_type: "urn:ietf:params:oauth:token-type:access_token",
|
||||
token_type: "DPoP",
|
||||
expires_in: 1_800,
|
||||
scope: `${RelayEnvironmentStatusScope} ${RelayEnvironmentConnectScope}`,
|
||||
}),
|
||||
);
|
||||
}
|
||||
statusTokens.push(new Headers(init?.headers).get("authorization"));
|
||||
return Promise.resolve(
|
||||
Response.json({
|
||||
environmentId: "env-1",
|
||||
endpoint: {
|
||||
httpBaseUrl: "https://desktop.example.test/",
|
||||
wsBaseUrl: "wss://desktop.example.test/ws",
|
||||
providerKind: "cloudflare_tunnel",
|
||||
},
|
||||
status: "online",
|
||||
checkedAt: "2026-09-04T00:00:00.000Z",
|
||||
}),
|
||||
);
|
||||
}) satisfies typeof globalThis.fetch;
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const relayClient = yield* ManagedRelay.ManagedRelayClient;
|
||||
const statusInput = {
|
||||
clerkToken: clerkToken("user-1", "session-1"),
|
||||
scopes: [RelayEnvironmentStatusScope],
|
||||
environmentId: EnvironmentId.make("env-1"),
|
||||
} as const;
|
||||
const expandedScopeInput = {
|
||||
...statusInput,
|
||||
scopes: [RelayEnvironmentStatusScope, RelayEnvironmentConnectScope],
|
||||
} as const;
|
||||
const firstMiss = yield* relayClient
|
||||
.getEnvironmentStatus(expandedScopeInput)
|
||||
.pipe(Effect.forkChild);
|
||||
yield* Effect.promise(() => exchangeStarted.promise);
|
||||
const secondMiss = yield* relayClient
|
||||
.getEnvironmentStatus(expandedScopeInput)
|
||||
.pipe(Effect.forkChild);
|
||||
|
||||
const status = yield* relayClient.getEnvironmentStatus(statusInput);
|
||||
expect(status.status).toBe("online");
|
||||
expect(statusTokens).toEqual(["DPoP cached-status-token"]);
|
||||
|
||||
releaseExchange.resolve();
|
||||
yield* Fiber.join(firstMiss);
|
||||
yield* Fiber.join(secondMiss);
|
||||
expect(tokenExchangeCount).toBe(1);
|
||||
expect(persistedTokens.map((token) => token.accessToken)).toEqual([
|
||||
"cached-status-token",
|
||||
"expanded-scope-token",
|
||||
]);
|
||||
yield* relayClient.resetTokenCache;
|
||||
expect(persistedTokens).toEqual([]);
|
||||
yield* relayClient.getEnvironmentStatus(expandedScopeInput);
|
||||
expect(tokenExchangeCount).toBe(2);
|
||||
}).pipe(
|
||||
Effect.ensuring(Effect.sync(() => releaseExchange.resolve())),
|
||||
Effect.provide(managedRelayTestLayer(fetchFn, undefined, accessTokenStore)),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("reuses a persisted token across runtimes and Clerk session token rotation", () => {
|
||||
let tokenExchangeCount = 0;
|
||||
let persistedTokens: ReadonlyArray<ManagedRelay.ManagedRelayAccessTokenCacheEntry> = [];
|
||||
|
||||
@@ -546,18 +546,32 @@ export const make = Effect.fn("ManagedRelayClient.make")(function* (
|
||||
expiresAtMillis: nowMillis + response.expires_in * 1_000,
|
||||
} satisfies ManagedRelayAccessTokenCacheEntry;
|
||||
}
|
||||
const match = {
|
||||
accountId: accountId.value,
|
||||
clientId: options.clientId,
|
||||
relayUrl,
|
||||
thumbprint: input.thumbprint,
|
||||
scopes: input.scopes,
|
||||
nowMillis,
|
||||
};
|
||||
// Cache hits do not need to wait for an unrelated exchange or store write.
|
||||
const cached = (yield* SynchronizedRef.get(cachedTokens)).find((token) =>
|
||||
tokenMatches(token, match),
|
||||
);
|
||||
if (cached) {
|
||||
yield* Effect.annotateCurrentSpan({
|
||||
"relay.token_cache.result": "hit",
|
||||
});
|
||||
return cached;
|
||||
}
|
||||
return yield* SynchronizedRef.modifyEffect(cachedTokens, (tokens) =>
|
||||
Effect.gen(function* () {
|
||||
const activeTokens = tokens.filter((token) => token.expiresAtMillis > nowMillis + 5_000);
|
||||
const lookupMillis = yield* Clock.currentTimeMillis;
|
||||
const activeTokens = tokens.filter(
|
||||
(token) => token.expiresAtMillis > lookupMillis + 5_000,
|
||||
);
|
||||
const cached = activeTokens.find((token) =>
|
||||
tokenMatches(token, {
|
||||
accountId: accountId.value,
|
||||
clientId: options.clientId,
|
||||
relayUrl,
|
||||
thumbprint: input.thumbprint,
|
||||
scopes: input.scopes,
|
||||
nowMillis,
|
||||
}),
|
||||
tokenMatches(token, { ...match, nowMillis: lookupMillis }),
|
||||
);
|
||||
if (cached) {
|
||||
yield* Effect.annotateCurrentSpan({
|
||||
@@ -576,7 +590,7 @@ export const make = Effect.fn("ManagedRelayClient.make")(function* (
|
||||
thumbprint: input.thumbprint,
|
||||
scopes: input.scopes,
|
||||
accessToken: response.access_token,
|
||||
expiresAtMillis: nowMillis + response.expires_in * 1_000,
|
||||
expiresAtMillis: lookupMillis + response.expires_in * 1_000,
|
||||
};
|
||||
const nextTokens = [...activeTokens, next];
|
||||
if (options.accessTokenStore) {
|
||||
|
||||
Reference in new issue
Block a user