Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6ebcddac0f | ||
|
|
d45cbde1cd | ||
|
|
6f2607445f | ||
|
|
327cc7d919 | ||
|
|
28107e89c2 | ||
|
|
82a9bcc7f4 | ||
|
|
61f8d46fa2 | ||
|
|
0debebafbb |
No files matched your search
@@ -48,7 +48,9 @@ Review changed TypeScript and directly affected call sites for the conventions b
|
||||
- Define service failures with `Schema.TaggedErrorClass` and structured attributes. Derive `message` from those attributes rather than storing an unstructured message as the only data.
|
||||
- `Schema.Defect()` is not a substitute for modeling a generic error: its tag, fields, or both must identify the failure structurally, and its `message` must not merely stringify an opaque cause. A semantically precise error tag may preserve a real `cause` without inventing a redundant singleton field when no additional variable context exists; still retain any real path, resource, request, or entity context available at the wrapping site.
|
||||
- Capture stable, serializable domain context such as the operation or stage, resource/path or entity identifier, and normalized category/status. Map failures where that context is known instead of wrapping an entire multi-step pipeline in one generic error. Do not add a `detail` field that merely copies `cause.message` and then use it to construct the wrapper message.
|
||||
- Keep direct error attributes and log annotations safe and bounded. Do not copy raw wire payloads, command arguments or output, signed URLs, credentials, query strings, fragments, selectors, or arbitrary defect text into `detail`, `reason`, `message`, or a parallel log payload. Preserve the exact underlying value only as `cause`; expose normalized categories plus lengths/counts and safe URL protocol/hostname diagnostics where useful. Logging a sanitized error must not reintroduce a removed legacy `detail` or serialized `cause` field beside it.
|
||||
- When translating or wrapping a real failure, preserve the immediate underlying error itself as `cause` alongside the structural fields so the complete error chain and stack remain available. If every construction wraps a failure, `cause` should be required; make it optional only when the same error can legitimately originate without an underlying failure.
|
||||
- At a translation boundary, pass through an already structured domain error when it is part of the declared target error channel. Wrap only unknown or genuinely lower-level failures. A static factory or mapper may perform this classification when it is reused and keeps the policy next to the target error type.
|
||||
- Derive the wrapper's `message` exclusively from its stable structural attributes, never from `cause`, `cause.message`, or a stringified defect. Do not replace the immediate error with only `error.cause`, erase a structured upstream error into a string, or manufacture an `Error` merely to populate `cause`. Pure validation/domain errors created without an underlying failure do not need a cause.
|
||||
- Do not encode the same distinction twice with both a specific error tag and a single-value `operation`, `reason`, `kind`, or `phase` literal. Choose one coherent model: use distinct error classes and omit the redundant discriminator when callers or messages treat the failures as genuinely different, or use one service-level error with a multi-value operation discriminator and a generic message derived from that operation when the failures share the same semantics.
|
||||
- Treat an error message exposed through an HTTP/RPC response, persisted state, UI, or another caller-visible boundary as behavior. Preserve those messages during a structural refactor. Existing distinct caller-visible messages are evidence that the failures should normally remain distinct error tags without redundant singleton discriminators, rather than being collapsed into a generic operation error.
|
||||
@@ -56,6 +58,9 @@ Review changed TypeScript and directly affected call sites for the conventions b
|
||||
- Use `Schema.Union` of error classes when a shared schema, predicate, or helper type is useful.
|
||||
- Export direct schema predicates such as `export const isFoo = Schema.is(Foo)`. Flag a private `Schema.is` constant wrapped by a redundant function with the same signature.
|
||||
- Do not introduce a large `switch` or lookup table in an error's `message` getter to model failures that deserve separate error classes.
|
||||
- Catch statically known tagged failures with `Effect.catchTags({ ... })`, including when handling only one tag. Do not use `catchIf` with a schema predicate merely to recover one or more known `_tag` variants, and do not use `catchTag`. `Effect.catch` is appropriate when the entire error channel is intentionally handled; `catchIf` remains appropriate for genuinely structural predicates such as inspecting an underlying platform error code.
|
||||
- Do not add a helper whose only behavior is `(...args) => new SomeError({ ...args })`, including curried aliases used once with `mapError`. Construct the error at the failure boundary so its attributes and cause remain visible. Keep a mapper only when it performs real normalization, passes through existing domain errors, or adds reusable context/control flow.
|
||||
- When a reusable error-to-error translation clearly belongs to the target error type, prefer a descriptive static factory on that error class over a detached production-side switch. Do not force a static method for one-off inline mappings.
|
||||
|
||||
## File layout and migrations
|
||||
|
||||
@@ -73,4 +78,6 @@ Review changed TypeScript and directly affected call sites for the conventions b
|
||||
|
||||
## Reporting
|
||||
|
||||
Report only concrete violations introduced or retained in the pull request's changed scope. Prefer precise inline comments on the smallest relevant line range and state the expected fix. A clear convention violation may fail the check. Do not fail for optional style preferences or unrelated legacy code. If there are no findings, report exactly `All clear`.
|
||||
Report only concrete violations introduced or retained in the pull request's changed scope. Prefer precise inline comments on the smallest relevant line range and state the expected fix. A clear convention violation may fail the check. Do not fail for optional style preferences or unrelated legacy code.
|
||||
|
||||
This check defaults to failure. When there are no findings, stop immediately and make the entire final response exactly `All clear` on one line. Do not add a title, explanation, punctuation, Markdown, JSON, or trailing analysis, and do not continue reasoning after deciding the review is clean.
|
||||
@@ -104,13 +104,16 @@ const capabilitiesLayer = Layer.succeedContext(
|
||||
}),
|
||||
),
|
||||
);
|
||||
if (token === null) {
|
||||
return yield* new ConnectionBlockedError({
|
||||
reason: "authentication",
|
||||
detail: "The T3 Cloud session is unavailable.",
|
||||
});
|
||||
}
|
||||
return token;
|
||||
return yield* Option.match(token, {
|
||||
onNone: () =>
|
||||
Effect.fail(
|
||||
new ConnectionBlockedError({
|
||||
reason: "authentication",
|
||||
detail: "The T3 Cloud session is unavailable.",
|
||||
}),
|
||||
),
|
||||
onSome: Effect.succeed,
|
||||
});
|
||||
}),
|
||||
}),
|
||||
).pipe(
|
||||
|
||||
@@ -1,12 +1,17 @@
|
||||
import { ClerkProvider, useAuth } from "@clerk/expo";
|
||||
import { tokenCache } from "@clerk/expo/token-cache";
|
||||
import { ManagedRelay, setManagedRelaySession } from "@t3tools/client-runtime/relay";
|
||||
import {
|
||||
ManagedRelay,
|
||||
ManagedRelaySessionTokenReadError,
|
||||
setManagedRelaySession,
|
||||
} from "@t3tools/client-runtime/relay";
|
||||
import {
|
||||
reportAtomCommandResult,
|
||||
settleAsyncResult,
|
||||
settlePromise,
|
||||
} from "@t3tools/client-runtime/state/runtime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Option from "effect/Option";
|
||||
import { type ReactNode, useEffect, useRef } from "react";
|
||||
|
||||
import { environmentCatalog } from "../../connection/catalog";
|
||||
@@ -39,7 +44,11 @@ export function activateCloudRelayAccount(
|
||||
setAgentAwarenessRelayTokenProvider(tokenProvider, accountId);
|
||||
setManagedRelaySession(appAtomRegistry, {
|
||||
accountId,
|
||||
readClerkToken: tokenProvider,
|
||||
readClerkToken: () =>
|
||||
Effect.tryPromise({
|
||||
try: tokenProvider,
|
||||
catch: (cause) => new ManagedRelaySessionTokenReadError({ cause }),
|
||||
}).pipe(Effect.map(Option.fromNullOr)),
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -44,8 +44,8 @@ const failingSessionLookupRepositoryLayer = Layer.succeed(AuthSessions.AuthSessi
|
||||
create: () => Effect.void,
|
||||
getById: () => Effect.fail(repositoryFailure),
|
||||
listActive: () => Effect.succeed([]),
|
||||
revoke: () => Effect.succeed(false),
|
||||
revokeAllExcept: () => Effect.succeed([]),
|
||||
revoke: () => Effect.fail(repositoryFailure),
|
||||
revokeAllExcept: () => Effect.fail(repositoryFailure),
|
||||
setLastConnectedAt: () => Effect.void,
|
||||
});
|
||||
|
||||
@@ -104,11 +104,29 @@ it.layer(NodeServices.layer)("SessionStore.layer", (it) => {
|
||||
|
||||
const sessionError = yield* Effect.flip(sessions.verify(issued.token));
|
||||
const websocketError = yield* Effect.flip(sessions.verifyWebSocketToken(websocket.token));
|
||||
const revokeError = yield* Effect.flip(sessions.revoke(issued.sessionId));
|
||||
const revokeOthersError = yield* Effect.flip(sessions.revokeAllExcept(issued.sessionId));
|
||||
|
||||
expect(sessionError._tag).toBe("SessionCredentialVerificationError");
|
||||
expect(websocketError._tag).toBe("WebSocketTokenVerificationError");
|
||||
expect(sessionError.cause).toBe(repositoryFailure);
|
||||
expect(websocketError.cause).toBe(repositoryFailure);
|
||||
if (sessionError._tag === "SessionCredentialVerificationError") {
|
||||
expect(sessionError.sessionId).toBe(issued.sessionId);
|
||||
}
|
||||
if (websocketError._tag === "WebSocketTokenVerificationError") {
|
||||
expect(websocketError.sessionId).toBe(issued.sessionId);
|
||||
}
|
||||
expect(revokeError).toMatchObject({
|
||||
_tag: "SessionRevocationError",
|
||||
sessionId: issued.sessionId,
|
||||
cause: repositoryFailure,
|
||||
});
|
||||
expect(revokeOthersError).toMatchObject({
|
||||
_tag: "OtherSessionsRevocationError",
|
||||
currentSessionId: issued.sessionId,
|
||||
cause: repositoryFailure,
|
||||
});
|
||||
}).pipe(Effect.provide(failingSessionLookupCredentialLayer)),
|
||||
);
|
||||
it.effect("verifies session tokens against the Effect clock", () =>
|
||||
@@ -145,7 +163,52 @@ it.layer(NodeServices.layer)("SessionStore.layer", (it) => {
|
||||
yield* TestClock.adjust(Duration.seconds(2));
|
||||
|
||||
const error = yield* Effect.flip(sessions.verifyWebSocketToken(websocket.token));
|
||||
expect(error.message).toContain("expired");
|
||||
expect(error._tag).toBe("WebSocketSessionExpiredError");
|
||||
if (error._tag === "WebSocketSessionExpiredError") {
|
||||
expect(error.sessionId).toBe(issued.sessionId);
|
||||
expect(error.expiresAt.epochMilliseconds).toBe(issued.expiresAt.epochMilliseconds);
|
||||
expect(error.observedAt.epochMilliseconds).toBeGreaterThan(
|
||||
error.expiresAt.epochMilliseconds,
|
||||
);
|
||||
}
|
||||
}).pipe(Effect.provide(Layer.merge(makeSessionStoreLayer(), TestClock.layer()))),
|
||||
);
|
||||
|
||||
it.effect("includes expiry context when session and websocket tokens expire", () =>
|
||||
Effect.gen(function* () {
|
||||
const sessions = yield* SessionStore.SessionStore;
|
||||
const issued = yield* sessions.issue({
|
||||
method: "bearer-access-token",
|
||||
subject: "short-lived-token",
|
||||
ttl: Duration.seconds(1),
|
||||
});
|
||||
const websocket = yield* sessions.issueWebSocketToken(issued.sessionId, {
|
||||
ttl: Duration.seconds(1),
|
||||
});
|
||||
|
||||
yield* TestClock.adjust(Duration.seconds(2));
|
||||
|
||||
const sessionError = yield* Effect.flip(sessions.verify(issued.token));
|
||||
const websocketError = yield* Effect.flip(sessions.verifyWebSocketToken(websocket.token));
|
||||
|
||||
expect(sessionError._tag).toBe("SessionTokenExpiredError");
|
||||
if (sessionError._tag === "SessionTokenExpiredError") {
|
||||
expect(sessionError.sessionId).toBe(issued.sessionId);
|
||||
expect(sessionError.expiresAt.epochMilliseconds).toBe(issued.expiresAt.epochMilliseconds);
|
||||
expect(sessionError.observedAt.epochMilliseconds).toBeGreaterThan(
|
||||
sessionError.expiresAt.epochMilliseconds,
|
||||
);
|
||||
}
|
||||
expect(websocketError._tag).toBe("WebSocketTokenExpiredError");
|
||||
if (websocketError._tag === "WebSocketTokenExpiredError") {
|
||||
expect(websocketError.sessionId).toBe(issued.sessionId);
|
||||
expect(websocketError.expiresAt.epochMilliseconds).toBe(
|
||||
websocket.expiresAt.epochMilliseconds,
|
||||
);
|
||||
expect(websocketError.observedAt.epochMilliseconds).toBeGreaterThan(
|
||||
websocketError.expiresAt.epochMilliseconds,
|
||||
);
|
||||
}
|
||||
}).pipe(Effect.provide(Layer.merge(makeSessionStoreLayer(), TestClock.layer()))),
|
||||
);
|
||||
|
||||
@@ -173,12 +236,16 @@ it.layer(NodeServices.layer)("SessionStore.layer", (it) => {
|
||||
ipAddress: "192.168.1.88",
|
||||
},
|
||||
});
|
||||
const clientWebSocket = yield* sessions.issueWebSocketToken(client.sessionId);
|
||||
|
||||
yield* sessions.markConnected(client.sessionId);
|
||||
const beforeRevoke = yield* sessions.listActive();
|
||||
const revokedCount = yield* sessions.revokeAllExcept(administrative.sessionId);
|
||||
const afterRevoke = yield* sessions.listActive();
|
||||
const revokedClient = yield* Effect.flip(sessions.verify(client.token));
|
||||
const revokedClientWebSocket = yield* Effect.flip(
|
||||
sessions.verifyWebSocketToken(clientWebSocket.token),
|
||||
);
|
||||
|
||||
expect(beforeRevoke).toHaveLength(2);
|
||||
expect(beforeRevoke.find((entry) => entry.sessionId === client.sessionId)?.connected).toBe(
|
||||
@@ -194,7 +261,16 @@ it.layer(NodeServices.layer)("SessionStore.layer", (it) => {
|
||||
expect(revokedCount).toBe(1);
|
||||
expect(afterRevoke).toHaveLength(1);
|
||||
expect(afterRevoke[0]?.sessionId).toBe(administrative.sessionId);
|
||||
expect(revokedClient.message).toContain("revoked");
|
||||
expect(revokedClient._tag).toBe("SessionTokenRevokedError");
|
||||
if (revokedClient._tag === "SessionTokenRevokedError") {
|
||||
expect(revokedClient.sessionId).toBe(client.sessionId);
|
||||
expect(revokedClient.revokedAt.epochMilliseconds).toBeGreaterThanOrEqual(0);
|
||||
}
|
||||
expect(revokedClientWebSocket._tag).toBe("WebSocketSessionRevokedError");
|
||||
if (revokedClientWebSocket._tag === "WebSocketSessionRevokedError") {
|
||||
expect(revokedClientWebSocket.sessionId).toBe(client.sessionId);
|
||||
expect(revokedClientWebSocket.revokedAt.epochMilliseconds).toBeGreaterThanOrEqual(0);
|
||||
}
|
||||
}).pipe(Effect.provide(makeSessionStoreLayer())),
|
||||
);
|
||||
|
||||
|
||||
@@ -7,7 +7,6 @@ import {
|
||||
type AuthEnvironmentScope,
|
||||
type ServerAuthSessionMethod,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Clock from "effect/Clock";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
@@ -93,7 +92,11 @@ export class InvalidSessionTokenPayloadError extends Schema.TaggedErrorClass<Inv
|
||||
|
||||
export class SessionTokenExpiredError extends Schema.TaggedErrorClass<SessionTokenExpiredError>()(
|
||||
"SessionTokenExpiredError",
|
||||
{},
|
||||
{
|
||||
sessionId: AuthSessionId,
|
||||
expiresAt: Schema.DateTimeUtc,
|
||||
observedAt: Schema.DateTimeUtc,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Session token expired.";
|
||||
@@ -102,7 +105,9 @@ export class SessionTokenExpiredError extends Schema.TaggedErrorClass<SessionTok
|
||||
|
||||
export class UnknownSessionTokenError extends Schema.TaggedErrorClass<UnknownSessionTokenError>()(
|
||||
"UnknownSessionTokenError",
|
||||
{},
|
||||
{
|
||||
sessionId: AuthSessionId,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Unknown session token.";
|
||||
@@ -111,7 +116,10 @@ export class UnknownSessionTokenError extends Schema.TaggedErrorClass<UnknownSes
|
||||
|
||||
export class SessionTokenRevokedError extends Schema.TaggedErrorClass<SessionTokenRevokedError>()(
|
||||
"SessionTokenRevokedError",
|
||||
{},
|
||||
{
|
||||
sessionId: AuthSessionId,
|
||||
revokedAt: Schema.DateTimeUtc,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Session token revoked.";
|
||||
@@ -120,7 +128,10 @@ export class SessionTokenRevokedError extends Schema.TaggedErrorClass<SessionTok
|
||||
|
||||
export class InvalidSessionExpirationClaimError extends Schema.TaggedErrorClass<InvalidSessionExpirationClaimError>()(
|
||||
"InvalidSessionExpirationClaimError",
|
||||
{},
|
||||
{
|
||||
sessionId: AuthSessionId,
|
||||
expirationClaim: Schema.Number,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Invalid `exp` claim";
|
||||
@@ -158,7 +169,11 @@ export class InvalidWebSocketTokenPayloadError extends Schema.TaggedErrorClass<I
|
||||
|
||||
export class WebSocketTokenExpiredError extends Schema.TaggedErrorClass<WebSocketTokenExpiredError>()(
|
||||
"WebSocketTokenExpiredError",
|
||||
{},
|
||||
{
|
||||
sessionId: AuthSessionId,
|
||||
expiresAt: Schema.DateTimeUtc,
|
||||
observedAt: Schema.DateTimeUtc,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Websocket token expired.";
|
||||
@@ -167,7 +182,9 @@ export class WebSocketTokenExpiredError extends Schema.TaggedErrorClass<WebSocke
|
||||
|
||||
export class UnknownWebSocketSessionError extends Schema.TaggedErrorClass<UnknownWebSocketSessionError>()(
|
||||
"UnknownWebSocketSessionError",
|
||||
{},
|
||||
{
|
||||
sessionId: AuthSessionId,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Unknown websocket session.";
|
||||
@@ -176,7 +193,11 @@ export class UnknownWebSocketSessionError extends Schema.TaggedErrorClass<Unknow
|
||||
|
||||
export class WebSocketSessionExpiredError extends Schema.TaggedErrorClass<WebSocketSessionExpiredError>()(
|
||||
"WebSocketSessionExpiredError",
|
||||
{},
|
||||
{
|
||||
sessionId: AuthSessionId,
|
||||
expiresAt: Schema.DateTimeUtc,
|
||||
observedAt: Schema.DateTimeUtc,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Websocket session expired.";
|
||||
@@ -185,7 +206,10 @@ export class WebSocketSessionExpiredError extends Schema.TaggedErrorClass<WebSoc
|
||||
|
||||
export class WebSocketSessionRevokedError extends Schema.TaggedErrorClass<WebSocketSessionRevokedError>()(
|
||||
"WebSocketSessionRevokedError",
|
||||
{},
|
||||
{
|
||||
sessionId: AuthSessionId,
|
||||
revokedAt: Schema.DateTimeUtc,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Websocket session revoked.";
|
||||
@@ -218,6 +242,7 @@ const sessionCredentialInternalErrorContext = {
|
||||
export class SessionClaimsEncodingError extends Schema.TaggedErrorClass<SessionClaimsEncodingError>()(
|
||||
"SessionClaimsEncodingError",
|
||||
{
|
||||
sessionId: AuthSessionId,
|
||||
operation: Schema.Literals(["encode_session_claims", "encode_websocket_claims"]),
|
||||
...sessionCredentialInternalErrorContext,
|
||||
},
|
||||
@@ -230,6 +255,7 @@ export class SessionClaimsEncodingError extends Schema.TaggedErrorClass<SessionC
|
||||
export class SessionCredentialIssueError extends Schema.TaggedErrorClass<SessionCredentialIssueError>()(
|
||||
"SessionCredentialIssueError",
|
||||
{
|
||||
sessionId: Schema.optional(AuthSessionId),
|
||||
...sessionCredentialInternalErrorContext,
|
||||
},
|
||||
) {
|
||||
@@ -241,6 +267,7 @@ export class SessionCredentialIssueError extends Schema.TaggedErrorClass<Session
|
||||
export class SessionCredentialVerificationError extends Schema.TaggedErrorClass<SessionCredentialVerificationError>()(
|
||||
"SessionCredentialVerificationError",
|
||||
{
|
||||
sessionId: AuthSessionId,
|
||||
...sessionCredentialInternalErrorContext,
|
||||
},
|
||||
) {
|
||||
@@ -252,6 +279,7 @@ export class SessionCredentialVerificationError extends Schema.TaggedErrorClass<
|
||||
export class WebSocketTokenIssueError extends Schema.TaggedErrorClass<WebSocketTokenIssueError>()(
|
||||
"WebSocketTokenIssueError",
|
||||
{
|
||||
sessionId: AuthSessionId,
|
||||
...sessionCredentialInternalErrorContext,
|
||||
},
|
||||
) {
|
||||
@@ -263,6 +291,7 @@ export class WebSocketTokenIssueError extends Schema.TaggedErrorClass<WebSocketT
|
||||
export class WebSocketTokenVerificationError extends Schema.TaggedErrorClass<WebSocketTokenVerificationError>()(
|
||||
"WebSocketTokenVerificationError",
|
||||
{
|
||||
sessionId: AuthSessionId,
|
||||
...sessionCredentialInternalErrorContext,
|
||||
},
|
||||
) {
|
||||
@@ -285,6 +314,7 @@ export class ActiveSessionsListError extends Schema.TaggedErrorClass<ActiveSessi
|
||||
export class SessionRevocationError extends Schema.TaggedErrorClass<SessionRevocationError>()(
|
||||
"SessionRevocationError",
|
||||
{
|
||||
sessionId: AuthSessionId,
|
||||
...sessionCredentialInternalErrorContext,
|
||||
},
|
||||
) {
|
||||
@@ -296,6 +326,7 @@ export class SessionRevocationError extends Schema.TaggedErrorClass<SessionRevoc
|
||||
export class OtherSessionsRevocationError extends Schema.TaggedErrorClass<OtherSessionsRevocationError>()(
|
||||
"OtherSessionsRevocationError",
|
||||
{
|
||||
currentSessionId: AuthSessionId,
|
||||
...sessionCredentialInternalErrorContext,
|
||||
},
|
||||
) {
|
||||
@@ -539,7 +570,11 @@ export const make = Effect.gen(function* () {
|
||||
const encodeClaims = Schema.encodeEffect(Schema.fromJsonString(SessionClaims));
|
||||
const issue: SessionStore["Service"]["issue"] = Effect.fn("SessionStore.issue")(
|
||||
function* (input) {
|
||||
const sessionId = AuthSessionId.make(yield* crypto.randomUUIDv4);
|
||||
const sessionId = AuthSessionId.make(
|
||||
yield* crypto.randomUUIDv4.pipe(
|
||||
Effect.mapError((cause) => new SessionCredentialIssueError({ cause })),
|
||||
),
|
||||
);
|
||||
const issuedAt = yield* DateTime.now;
|
||||
const expiresAt = DateTime.add(issuedAt, {
|
||||
milliseconds: Duration.toMillis(input?.ttl ?? DEFAULT_SESSION_TTL),
|
||||
@@ -559,27 +594,37 @@ export const make = Effect.gen(function* () {
|
||||
const encodedPayload = yield* encodeClaims(claims).pipe(
|
||||
Effect.map(base64UrlEncode),
|
||||
Effect.mapError(
|
||||
(cause) => new SessionClaimsEncodingError({ operation: "encode_session_claims", cause }),
|
||||
(cause) =>
|
||||
new SessionCredentialIssueError({
|
||||
sessionId,
|
||||
cause: new SessionClaimsEncodingError({
|
||||
sessionId,
|
||||
operation: "encode_session_claims",
|
||||
cause,
|
||||
}),
|
||||
}),
|
||||
),
|
||||
);
|
||||
const signature = signPayload(encodedPayload, signingSecret);
|
||||
const client = input?.client ?? createDefaultClientMetadata();
|
||||
yield* authSessions.create({
|
||||
sessionId,
|
||||
subject: claims.sub,
|
||||
scopes: claims.scopes,
|
||||
method: claims.method,
|
||||
client: {
|
||||
label: client.label ?? null,
|
||||
ipAddress: client.ipAddress ?? null,
|
||||
userAgent: client.userAgent ?? null,
|
||||
deviceType: client.deviceType,
|
||||
os: client.os ?? null,
|
||||
browser: client.browser ?? null,
|
||||
},
|
||||
issuedAt,
|
||||
expiresAt,
|
||||
});
|
||||
yield* authSessions
|
||||
.create({
|
||||
sessionId,
|
||||
subject: claims.sub,
|
||||
scopes: claims.scopes,
|
||||
method: claims.method,
|
||||
client: {
|
||||
label: client.label ?? null,
|
||||
ipAddress: client.ipAddress ?? null,
|
||||
userAgent: client.userAgent ?? null,
|
||||
deviceType: client.deviceType,
|
||||
os: client.os ?? null,
|
||||
browser: client.browser ?? null,
|
||||
},
|
||||
issuedAt,
|
||||
expiresAt,
|
||||
})
|
||||
.pipe(Effect.mapError((cause) => new SessionCredentialIssueError({ sessionId, cause })));
|
||||
yield* emitUpsert(
|
||||
toAuthClientSession({
|
||||
sessionId,
|
||||
@@ -604,7 +649,6 @@ export const make = Effect.gen(function* () {
|
||||
...(claims.jkt ? { proofKeyThumbprint: claims.jkt } : {}),
|
||||
} satisfies IssuedSession;
|
||||
},
|
||||
Effect.mapError((cause) => new SessionCredentialIssueError({ cause })),
|
||||
);
|
||||
|
||||
const verify: SessionStore["Service"]["verify"] = Effect.fn("SessionStore.verify")(
|
||||
@@ -623,22 +667,37 @@ export const make = Effect.gen(function* () {
|
||||
Effect.mapError((cause) => new InvalidSessionTokenPayloadError({ cause })),
|
||||
);
|
||||
|
||||
const now = yield* Clock.currentTimeMillis;
|
||||
if (claims.exp <= now) {
|
||||
return yield* new SessionTokenExpiredError({});
|
||||
}
|
||||
|
||||
const row = yield* authSessions.getById({ sessionId: claims.sid });
|
||||
if (Option.isNone(row)) {
|
||||
return yield* new UnknownSessionTokenError({});
|
||||
}
|
||||
if (row.value.revokedAt !== null) {
|
||||
return yield* new SessionTokenRevokedError({});
|
||||
}
|
||||
|
||||
const observedAt = yield* DateTime.now;
|
||||
const expiresAt = DateTime.make(claims.exp);
|
||||
if (Option.isNone(expiresAt)) {
|
||||
return yield* new InvalidSessionExpirationClaimError({});
|
||||
return yield* new InvalidSessionExpirationClaimError({
|
||||
sessionId: claims.sid,
|
||||
expirationClaim: claims.exp,
|
||||
});
|
||||
}
|
||||
if (claims.exp <= observedAt.epochMilliseconds) {
|
||||
return yield* new SessionTokenExpiredError({
|
||||
sessionId: claims.sid,
|
||||
expiresAt: expiresAt.value,
|
||||
observedAt,
|
||||
});
|
||||
}
|
||||
|
||||
const row = yield* authSessions
|
||||
.getById({ sessionId: claims.sid })
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) => new SessionCredentialVerificationError({ sessionId: claims.sid, cause }),
|
||||
),
|
||||
);
|
||||
if (Option.isNone(row)) {
|
||||
return yield* new UnknownSessionTokenError({ sessionId: claims.sid });
|
||||
}
|
||||
if (row.value.revokedAt !== null) {
|
||||
return yield* new SessionTokenRevokedError({
|
||||
sessionId: claims.sid,
|
||||
revokedAt: row.value.revokedAt,
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
@@ -652,95 +711,111 @@ export const make = Effect.gen(function* () {
|
||||
...(claims.jkt ? { proofKeyThumbprint: claims.jkt } : {}),
|
||||
} satisfies VerifiedSession;
|
||||
},
|
||||
Effect.mapError((cause) =>
|
||||
isSessionCredentialInvalidError(cause)
|
||||
? cause
|
||||
: new SessionCredentialVerificationError({ cause }),
|
||||
),
|
||||
);
|
||||
|
||||
const encodeWsClaims = Schema.encodeEffect(Schema.fromJsonString(WebSocketClaims));
|
||||
const issueWebSocketToken: SessionStore["Service"]["issueWebSocketToken"] = Effect.fn(
|
||||
"SessionStore.issueWebSocketToken",
|
||||
)(
|
||||
function* (sessionId, input) {
|
||||
const issuedAt = yield* DateTime.now;
|
||||
const expiresAt = DateTime.add(issuedAt, {
|
||||
milliseconds: Duration.toMillis(input?.ttl ?? DEFAULT_WEBSOCKET_TOKEN_TTL),
|
||||
});
|
||||
const claims: WebSocketClaims = {
|
||||
v: 1,
|
||||
kind: "websocket",
|
||||
sid: sessionId,
|
||||
iat: issuedAt.epochMilliseconds,
|
||||
exp: expiresAt.epochMilliseconds,
|
||||
};
|
||||
const encodedPayload = yield* encodeWsClaims(claims).pipe(
|
||||
Effect.map(base64UrlEncode),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new SessionClaimsEncodingError({ operation: "encode_websocket_claims", cause }),
|
||||
),
|
||||
);
|
||||
const signature = signPayload(encodedPayload, signingSecret);
|
||||
return {
|
||||
token: `${encodedPayload}.${signature}`,
|
||||
expiresAt,
|
||||
};
|
||||
},
|
||||
Effect.mapError((cause) => new WebSocketTokenIssueError({ cause })),
|
||||
);
|
||||
)(function* (sessionId, input) {
|
||||
const issuedAt = yield* DateTime.now;
|
||||
const expiresAt = DateTime.add(issuedAt, {
|
||||
milliseconds: Duration.toMillis(input?.ttl ?? DEFAULT_WEBSOCKET_TOKEN_TTL),
|
||||
});
|
||||
const claims: WebSocketClaims = {
|
||||
v: 1,
|
||||
kind: "websocket",
|
||||
sid: sessionId,
|
||||
iat: issuedAt.epochMilliseconds,
|
||||
exp: expiresAt.epochMilliseconds,
|
||||
};
|
||||
const encodedPayload = yield* encodeWsClaims(claims).pipe(
|
||||
Effect.map(base64UrlEncode),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new WebSocketTokenIssueError({
|
||||
sessionId,
|
||||
cause: new SessionClaimsEncodingError({
|
||||
sessionId,
|
||||
operation: "encode_websocket_claims",
|
||||
cause,
|
||||
}),
|
||||
}),
|
||||
),
|
||||
);
|
||||
const signature = signPayload(encodedPayload, signingSecret);
|
||||
return {
|
||||
token: `${encodedPayload}.${signature}`,
|
||||
expiresAt,
|
||||
};
|
||||
});
|
||||
|
||||
const verifyWebSocketToken: SessionStore["Service"]["verifyWebSocketToken"] = Effect.fn(
|
||||
"SessionStore.verifyWebSocketToken",
|
||||
)(
|
||||
function* (token) {
|
||||
const [encodedPayload, signature] = token.split(".");
|
||||
if (!encodedPayload || !signature) {
|
||||
return yield* new MalformedWebSocketTokenError({});
|
||||
}
|
||||
)(function* (token) {
|
||||
const [encodedPayload, signature] = token.split(".");
|
||||
if (!encodedPayload || !signature) {
|
||||
return yield* new MalformedWebSocketTokenError({});
|
||||
}
|
||||
|
||||
const expectedSignature = signPayload(encodedPayload, signingSecret);
|
||||
if (!timingSafeEqualBase64Url(signature, expectedSignature)) {
|
||||
return yield* new InvalidWebSocketTokenSignatureError({});
|
||||
}
|
||||
const expectedSignature = signPayload(encodedPayload, signingSecret);
|
||||
if (!timingSafeEqualBase64Url(signature, expectedSignature)) {
|
||||
return yield* new InvalidWebSocketTokenSignatureError({});
|
||||
}
|
||||
|
||||
const claims = yield* decodeWebSocketClaims(base64UrlDecodeUtf8(encodedPayload)).pipe(
|
||||
Effect.mapError((cause) => new InvalidWebSocketTokenPayloadError({ cause })),
|
||||
const claims = yield* decodeWebSocketClaims(base64UrlDecodeUtf8(encodedPayload)).pipe(
|
||||
Effect.mapError((cause) => new InvalidWebSocketTokenPayloadError({ cause })),
|
||||
);
|
||||
|
||||
const observedAt = yield* DateTime.now;
|
||||
const expiresAt = DateTime.make(claims.exp);
|
||||
if (Option.isNone(expiresAt)) {
|
||||
return yield* new InvalidSessionExpirationClaimError({
|
||||
sessionId: claims.sid,
|
||||
expirationClaim: claims.exp,
|
||||
});
|
||||
}
|
||||
if (claims.exp <= observedAt.epochMilliseconds) {
|
||||
return yield* new WebSocketTokenExpiredError({
|
||||
sessionId: claims.sid,
|
||||
expiresAt: expiresAt.value,
|
||||
observedAt,
|
||||
});
|
||||
}
|
||||
|
||||
const row = yield* authSessions
|
||||
.getById({ sessionId: claims.sid })
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) => new WebSocketTokenVerificationError({ sessionId: claims.sid, cause }),
|
||||
),
|
||||
);
|
||||
|
||||
const now = yield* Clock.currentTimeMillis;
|
||||
if (claims.exp <= now) {
|
||||
return yield* new WebSocketTokenExpiredError({});
|
||||
}
|
||||
|
||||
const row = yield* authSessions.getById({ sessionId: claims.sid });
|
||||
if (Option.isNone(row)) {
|
||||
return yield* new UnknownWebSocketSessionError({});
|
||||
}
|
||||
if (row.value.expiresAt.epochMilliseconds <= now) {
|
||||
return yield* new WebSocketSessionExpiredError({});
|
||||
}
|
||||
if (row.value.revokedAt !== null) {
|
||||
return yield* new WebSocketSessionRevokedError({});
|
||||
}
|
||||
|
||||
return {
|
||||
sessionId: row.value.sessionId,
|
||||
token,
|
||||
method: row.value.method,
|
||||
client: toClientMetadata(row.value.client),
|
||||
if (Option.isNone(row)) {
|
||||
return yield* new UnknownWebSocketSessionError({ sessionId: claims.sid });
|
||||
}
|
||||
if (row.value.expiresAt.epochMilliseconds <= observedAt.epochMilliseconds) {
|
||||
return yield* new WebSocketSessionExpiredError({
|
||||
sessionId: claims.sid,
|
||||
expiresAt: row.value.expiresAt,
|
||||
subject: row.value.subject,
|
||||
scopes: row.value.scopes,
|
||||
} satisfies VerifiedSession;
|
||||
},
|
||||
Effect.mapError((cause) =>
|
||||
isSessionCredentialInvalidError(cause)
|
||||
? cause
|
||||
: new WebSocketTokenVerificationError({ cause }),
|
||||
),
|
||||
);
|
||||
observedAt,
|
||||
});
|
||||
}
|
||||
if (row.value.revokedAt !== null) {
|
||||
return yield* new WebSocketSessionRevokedError({
|
||||
sessionId: claims.sid,
|
||||
revokedAt: row.value.revokedAt,
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
sessionId: row.value.sessionId,
|
||||
token,
|
||||
method: row.value.method,
|
||||
client: toClientMetadata(row.value.client),
|
||||
expiresAt: row.value.expiresAt,
|
||||
subject: row.value.subject,
|
||||
scopes: row.value.scopes,
|
||||
} satisfies VerifiedSession;
|
||||
});
|
||||
|
||||
const listActive: SessionStore["Service"]["listActive"] = Effect.fn("SessionStore.listActive")(
|
||||
function* () {
|
||||
@@ -768,10 +843,12 @@ export const make = Effect.gen(function* () {
|
||||
const revoke: SessionStore["Service"]["revoke"] = Effect.fn("SessionStore.revoke")(
|
||||
function* (sessionId) {
|
||||
const revokedAt = yield* DateTime.now;
|
||||
const revoked = yield* authSessions.revoke({
|
||||
sessionId,
|
||||
revokedAt,
|
||||
});
|
||||
const revoked = yield* authSessions
|
||||
.revoke({
|
||||
sessionId,
|
||||
revokedAt,
|
||||
})
|
||||
.pipe(Effect.mapError((cause) => new SessionRevocationError({ sessionId, cause })));
|
||||
if (revoked) {
|
||||
yield* Ref.update(connectedSessionsRef, (current) => {
|
||||
const next = new Map(current);
|
||||
@@ -782,39 +859,41 @@ export const make = Effect.gen(function* () {
|
||||
}
|
||||
return revoked;
|
||||
},
|
||||
Effect.mapError((cause) => new SessionRevocationError({ cause })),
|
||||
);
|
||||
|
||||
const revokeAllExcept: SessionStore["Service"]["revokeAllExcept"] = Effect.fn(
|
||||
"SessionStore.revokeAllExcept",
|
||||
)(
|
||||
function* (sessionId) {
|
||||
const revokedAt = yield* DateTime.now;
|
||||
const revokedSessionIds = yield* authSessions.revokeAllExcept({
|
||||
)(function* (sessionId) {
|
||||
const revokedAt = yield* DateTime.now;
|
||||
const revokedSessionIds = yield* authSessions
|
||||
.revokeAllExcept({
|
||||
currentSessionId: sessionId,
|
||||
revokedAt,
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) => new OtherSessionsRevocationError({ currentSessionId: sessionId, cause }),
|
||||
),
|
||||
);
|
||||
if (revokedSessionIds.length > 0) {
|
||||
yield* Ref.update(connectedSessionsRef, (current) => {
|
||||
const next = new Map(current);
|
||||
for (const revokedSessionId of revokedSessionIds) {
|
||||
next.delete(revokedSessionId);
|
||||
}
|
||||
return next;
|
||||
});
|
||||
if (revokedSessionIds.length > 0) {
|
||||
yield* Ref.update(connectedSessionsRef, (current) => {
|
||||
const next = new Map(current);
|
||||
for (const revokedSessionId of revokedSessionIds) {
|
||||
next.delete(revokedSessionId);
|
||||
}
|
||||
return next;
|
||||
});
|
||||
yield* Effect.forEach(
|
||||
revokedSessionIds,
|
||||
(revokedSessionId) => emitRemoved(revokedSessionId),
|
||||
{
|
||||
concurrency: "unbounded",
|
||||
discard: true,
|
||||
},
|
||||
);
|
||||
}
|
||||
return revokedSessionIds.length;
|
||||
},
|
||||
Effect.mapError((cause) => new OtherSessionsRevocationError({ cause })),
|
||||
);
|
||||
yield* Effect.forEach(
|
||||
revokedSessionIds,
|
||||
(revokedSessionId) => emitRemoved(revokedSessionId),
|
||||
{
|
||||
concurrency: "unbounded",
|
||||
discard: true,
|
||||
},
|
||||
);
|
||||
}
|
||||
return revokedSessionIds.length;
|
||||
});
|
||||
|
||||
return SessionStore.of({
|
||||
cookieName,
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import { managedRelaySessionAtom, setManagedRelaySession } from "@t3tools/client-runtime/relay";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Option from "effect/Option";
|
||||
import { afterEach, describe, expect, it, vi } from "vite-plus/test";
|
||||
|
||||
import { appAtomRegistry } from "../rpc/atomRegistry";
|
||||
@@ -45,7 +47,7 @@ describe("managed relay authentication", () => {
|
||||
it("replaces an existing account session atomically", () => {
|
||||
setManagedRelaySession(appAtomRegistry, {
|
||||
accountId: "account-1",
|
||||
readClerkToken: async () => "account-1-token",
|
||||
readClerkToken: () => Effect.succeed(Option.some("account-1-token")),
|
||||
});
|
||||
|
||||
activateManagedRelayAuthentication("account-2", async () => "account-2-token");
|
||||
|
||||
@@ -1,11 +1,16 @@
|
||||
import { useAuth } from "@clerk/react";
|
||||
import { ManagedRelay, setManagedRelaySession } from "@t3tools/client-runtime/relay";
|
||||
import {
|
||||
ManagedRelay,
|
||||
ManagedRelaySessionTokenReadError,
|
||||
setManagedRelaySession,
|
||||
} from "@t3tools/client-runtime/relay";
|
||||
import {
|
||||
reportAtomCommandResult,
|
||||
settleAsyncResult,
|
||||
settlePromise,
|
||||
} from "@t3tools/client-runtime/state/runtime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Option from "effect/Option";
|
||||
import { useEffect, useRef, type ReactNode } from "react";
|
||||
|
||||
import { environmentCatalog } from "../connection/catalog";
|
||||
@@ -32,7 +37,11 @@ export function activateManagedRelayAuthentication(
|
||||
relayTokenProvider = readClerkToken;
|
||||
setManagedRelaySession(appAtomRegistry, {
|
||||
accountId,
|
||||
readClerkToken,
|
||||
readClerkToken: () =>
|
||||
Effect.tryPromise({
|
||||
try: readClerkToken,
|
||||
catch: (cause) => new ManagedRelaySessionTokenReadError({ cause }),
|
||||
}).pipe(Effect.map(Option.fromNullOr)),
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -38,7 +38,7 @@ import { resolveThreadRouteRef } from "../threadRoutes";
|
||||
import { useClientSettings } from "../hooks/useSettings";
|
||||
import { formatShortTimestamp } from "../timestampFormat";
|
||||
import { DiffPanelLoadingState, DiffPanelShell, type DiffPanelMode } from "./DiffPanelShell";
|
||||
import { AnnotatableCodeView, type AnnotatableCodeViewHandle } from "./diffs/AnnotatableFileDiff";
|
||||
import { AnnotatableCodeView, type AnnotatableCodeViewHandle } from "./diffs/AnnotatableCodeView";
|
||||
import { ToggleGroup, Toggle } from "./ui/toggle-group";
|
||||
import { Switch } from "./ui/switch";
|
||||
import {
|
||||
|
||||
+1
-179
@@ -6,13 +6,7 @@ import type {
|
||||
FileDiffMetadata,
|
||||
SelectedLineRange,
|
||||
} from "@pierre/diffs";
|
||||
import {
|
||||
CodeView,
|
||||
type CodeViewHandle,
|
||||
type CodeViewProps,
|
||||
FileDiff,
|
||||
type FileDiffProps,
|
||||
} from "@pierre/diffs/react";
|
||||
import { CodeView, type CodeViewHandle, type CodeViewProps } from "@pierre/diffs/react";
|
||||
import type { ScopedThreadRef } from "@t3tools/contracts";
|
||||
import { useCallback, useMemo, useState, type ReactNode, type Ref } from "react";
|
||||
|
||||
@@ -76,178 +70,6 @@ function appendAnnotationEntry(
|
||||
);
|
||||
}
|
||||
|
||||
interface AnnotatableFileDiffProps {
|
||||
fileDiff: FileDiffMetadata;
|
||||
filePath: string;
|
||||
sectionId: string;
|
||||
sectionTitle: string;
|
||||
composerDraftTarget: ScopedThreadRef | DraftId;
|
||||
options: FileDiffProps<DiffCommentAnnotationGroup>["options"];
|
||||
renderHeaderPrefix: (fileDiff: FileDiffMetadata) => ReactNode;
|
||||
}
|
||||
|
||||
export function AnnotatableFileDiff({
|
||||
fileDiff,
|
||||
filePath,
|
||||
sectionId,
|
||||
sectionTitle,
|
||||
composerDraftTarget,
|
||||
options,
|
||||
renderHeaderPrefix,
|
||||
}: AnnotatableFileDiffProps) {
|
||||
const addReviewComment = useComposerDraftStore((store) => store.addReviewComment);
|
||||
const removeReviewComment = useComposerDraftStore((store) => store.removeReviewComment);
|
||||
const reviewComments = useComposerDraftStore(
|
||||
(store) => store.getComposerDraft(composerDraftTarget)?.reviewComments ?? EMPTY_REVIEW_COMMENTS,
|
||||
);
|
||||
const [selectedRange, setSelectedRange] = useState<SelectedLineRange | null>(null);
|
||||
const [draftAnnotation, setDraftAnnotation] = useState<DiffCommentLineAnnotation | null>(null);
|
||||
const persistedAnnotations = useMemo(
|
||||
() =>
|
||||
reviewComments
|
||||
.filter(
|
||||
(comment) =>
|
||||
comment.sectionId === sectionId &&
|
||||
comment.filePath === filePath &&
|
||||
(comment.fenceLanguage ?? "diff") === "diff",
|
||||
)
|
||||
.reduce<DiffCommentLineAnnotation[]>((annotations, comment) => {
|
||||
const range = restoreDiffReviewCommentRange(fileDiff, comment);
|
||||
if (!range) return annotations;
|
||||
return appendAnnotationEntry(annotations, range, {
|
||||
id: comment.id,
|
||||
kind: "comment",
|
||||
range,
|
||||
rangeLabel: comment.rangeLabel,
|
||||
text: comment.text,
|
||||
});
|
||||
}, []),
|
||||
[fileDiff, filePath, reviewComments, sectionId],
|
||||
);
|
||||
const lineAnnotations = useMemo(
|
||||
() => (draftAnnotation ? [...persistedAnnotations, draftAnnotation] : persistedAnnotations),
|
||||
[draftAnnotation, persistedAnnotations],
|
||||
);
|
||||
|
||||
const removeAnnotationEntry = useCallback(
|
||||
(entryId: string) => {
|
||||
setSelectedRange(null);
|
||||
if (
|
||||
draftAnnotation?.metadata.entries.some(
|
||||
(entry) => entry.id === entryId && entry.kind === "draft",
|
||||
)
|
||||
) {
|
||||
setDraftAnnotation(null);
|
||||
return;
|
||||
}
|
||||
removeReviewComment(composerDraftTarget, entryId);
|
||||
},
|
||||
[composerDraftTarget, draftAnnotation, removeReviewComment],
|
||||
);
|
||||
|
||||
const submitAnnotationEntry = useCallback(
|
||||
(entryId: string, text: string) => {
|
||||
const entry = draftAnnotation?.metadata.entries.find((candidate) => candidate.id === entryId);
|
||||
if (!entry) return;
|
||||
|
||||
const comment = buildDiffReviewComment({
|
||||
id: entry.id,
|
||||
sectionId,
|
||||
sectionTitle,
|
||||
filePath,
|
||||
fileDiff,
|
||||
range: entry.range,
|
||||
text,
|
||||
});
|
||||
if (comment) {
|
||||
addReviewComment(composerDraftTarget, comment);
|
||||
}
|
||||
setSelectedRange(null);
|
||||
setDraftAnnotation(null);
|
||||
},
|
||||
[
|
||||
addReviewComment,
|
||||
composerDraftTarget,
|
||||
fileDiff,
|
||||
filePath,
|
||||
draftAnnotation,
|
||||
sectionId,
|
||||
sectionTitle,
|
||||
],
|
||||
);
|
||||
|
||||
const beginComment = useCallback(
|
||||
(range: SelectedLineRange) => {
|
||||
const id = nextFileCommentId();
|
||||
const comment = buildDiffReviewComment({
|
||||
id,
|
||||
sectionId,
|
||||
sectionTitle,
|
||||
filePath,
|
||||
fileDiff,
|
||||
range,
|
||||
text: "",
|
||||
});
|
||||
if (!comment) return;
|
||||
|
||||
const draftEntry: DiffCommentAnnotationEntry = {
|
||||
id,
|
||||
kind: "draft",
|
||||
range,
|
||||
rangeLabel: comment.rangeLabel,
|
||||
text: "",
|
||||
};
|
||||
setDraftAnnotation({
|
||||
side: annotationSide(range),
|
||||
lineNumber: range.end,
|
||||
metadata: { entries: [draftEntry] },
|
||||
});
|
||||
},
|
||||
[fileDiff, filePath, sectionId, sectionTitle],
|
||||
);
|
||||
|
||||
const hasOpenCommentForm = draftAnnotation !== null;
|
||||
const handleLineSelectionEnd = useCallback(
|
||||
(range: SelectedLineRange | null) => {
|
||||
setSelectedRange(range);
|
||||
if (range) beginComment(range);
|
||||
},
|
||||
[beginComment],
|
||||
);
|
||||
|
||||
return (
|
||||
<FileDiff<DiffCommentAnnotationGroup>
|
||||
fileDiff={fileDiff}
|
||||
renderHeaderPrefix={renderHeaderPrefix}
|
||||
options={{
|
||||
...options,
|
||||
enableGutterUtility: !hasOpenCommentForm,
|
||||
enableLineSelection: !hasOpenCommentForm,
|
||||
onGutterUtilityClick: setSelectedRange,
|
||||
onLineSelectionChange: setSelectedRange,
|
||||
onLineSelectionEnd: handleLineSelectionEnd,
|
||||
}}
|
||||
selectedLines={selectedRange}
|
||||
lineAnnotations={lineAnnotations}
|
||||
renderAnnotation={(annotation) => (
|
||||
<div className="py-1">
|
||||
{annotation.metadata.entries.map((entry) => (
|
||||
<LocalCommentAnnotation
|
||||
key={entry.id}
|
||||
kind={entry.kind}
|
||||
rangeLabel={entry.rangeLabel}
|
||||
text={entry.text}
|
||||
onCancel={() => removeAnnotationEntry(entry.id)}
|
||||
onComment={(text) => submitAnnotationEntry(entry.id, text)}
|
||||
onDelete={() => removeAnnotationEntry(entry.id)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
interface AnnotatableCodeViewProps {
|
||||
files: ReadonlyArray<{
|
||||
fileDiff: FileDiffMetadata;
|
||||
@@ -176,13 +176,16 @@ const capabilitiesLayer = Layer.effectContext(
|
||||
}),
|
||||
),
|
||||
);
|
||||
if (token === null) {
|
||||
return yield* new ConnectionBlockedError({
|
||||
reason: "authentication",
|
||||
detail: "The T3 Cloud session is unavailable.",
|
||||
});
|
||||
}
|
||||
return token;
|
||||
return yield* Option.match(token, {
|
||||
onNone: () =>
|
||||
Effect.fail(
|
||||
new ConnectionBlockedError({
|
||||
reason: "authentication",
|
||||
detail: "The T3 Cloud session is unavailable.",
|
||||
}),
|
||||
),
|
||||
onSome: Effect.succeed,
|
||||
});
|
||||
}),
|
||||
});
|
||||
const identity = RelayDeviceIdentity.of({
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
import { EnvironmentId, ThreadId } from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { ThreadArchiveBlockedError } from "./useThreadActions";
|
||||
|
||||
describe("ThreadArchiveBlockedError", () => {
|
||||
it("keeps the blocked thread context with the fixed message", () => {
|
||||
const error = new ThreadArchiveBlockedError({
|
||||
environmentId: EnvironmentId.make("environment-1"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
});
|
||||
|
||||
expect(error).toMatchObject({
|
||||
environmentId: "environment-1",
|
||||
threadId: "thread-1",
|
||||
});
|
||||
expect(error.message).toBe("Cannot archive a running thread.");
|
||||
});
|
||||
});
|
||||
@@ -4,9 +4,9 @@ import {
|
||||
scopeThreadRef,
|
||||
} from "@t3tools/client-runtime/environment";
|
||||
import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
|
||||
import { type ScopedThreadRef, ThreadId } from "@t3tools/contracts";
|
||||
import { EnvironmentId, type ScopedThreadRef, ThreadId } from "@t3tools/contracts";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Data from "effect/Data";
|
||||
import * as Schema from "effect/Schema";
|
||||
import { AsyncResult } from "effect/unstable/reactivity";
|
||||
import { useRouter } from "@tanstack/react-router";
|
||||
import { useCallback, useMemo, useRef } from "react";
|
||||
@@ -27,9 +27,17 @@ import { stackedThreadToast, toastManager } from "../components/ui/toast";
|
||||
import { useClientSettings } from "./useSettings";
|
||||
import { useAtomCommand } from "../state/use-atom-command";
|
||||
|
||||
export class ThreadArchiveBlockedError extends Data.TaggedError("ThreadArchiveBlockedError")<{
|
||||
readonly message: string;
|
||||
}> {}
|
||||
export class ThreadArchiveBlockedError extends Schema.TaggedErrorClass<ThreadArchiveBlockedError>()(
|
||||
"ThreadArchiveBlockedError",
|
||||
{
|
||||
environmentId: EnvironmentId,
|
||||
threadId: ThreadId,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Cannot archive a running thread.";
|
||||
}
|
||||
}
|
||||
|
||||
export function useThreadActions() {
|
||||
const closeTerminal = useAtomCommand(terminalEnvironment.close);
|
||||
@@ -89,7 +97,8 @@ export function useThreadActions() {
|
||||
return AsyncResult.failure(
|
||||
Cause.fail(
|
||||
new ThreadArchiveBlockedError({
|
||||
message: "Cannot archive a running thread.",
|
||||
environmentId: threadRef.environmentId,
|
||||
threadId: threadRef.threadId,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -4,11 +4,15 @@ import type {
|
||||
RelayClientEnvironmentRecord,
|
||||
RelayEnvironmentStatusResponse,
|
||||
} from "@t3tools/contracts/relay";
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import { assert, describe, expect, it } from "@effect/vitest";
|
||||
import * as Deferred from "effect/Deferred";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Fiber from "effect/Fiber";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Stream from "effect/Stream";
|
||||
import * as TestClock from "effect/testing/TestClock";
|
||||
import { Atom, AtomRegistry } from "effect/unstable/reactivity";
|
||||
import { afterEach, vi } from "vite-plus/test";
|
||||
|
||||
@@ -96,7 +100,7 @@ function createManager(
|
||||
function setSession() {
|
||||
setManagedRelaySession(registry, {
|
||||
accountId: "account-1",
|
||||
readClerkToken: () => Promise.resolve("clerk-token"),
|
||||
readClerkToken: () => Effect.succeed(Option.some("clerk-token")),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -115,20 +119,17 @@ describe("createManagedRelayQueryManager", () => {
|
||||
|
||||
setSession();
|
||||
|
||||
expect(yield* Fiber.join(tokenFiber)).toBe("clerk-token");
|
||||
expect(registry.getNodes().get(managedRelaySessionAtom)?.listeners.size).toBe(0);
|
||||
assert.equal(yield* Fiber.join(tokenFiber), "clerk-token");
|
||||
assert.equal(registry.getNodes().get(managedRelaySessionAtom)?.listeners.size, 0);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("deduplicates concurrent Clerk token reads and reuses the token until JWT expiry", () =>
|
||||
Effect.gen(function* () {
|
||||
const token = clerkToken(4_102_444_800);
|
||||
let resolveToken!: (value: string) => void;
|
||||
const readClerkToken = vi.fn(
|
||||
() =>
|
||||
new Promise<string>((resolve) => {
|
||||
resolveToken = resolve;
|
||||
}),
|
||||
const tokenDeferred = yield* Deferred.make<string>();
|
||||
const readClerkToken = vi.fn(() =>
|
||||
Deferred.await(tokenDeferred).pipe(Effect.map(Option.some)),
|
||||
);
|
||||
const session = createManagedRelaySession({
|
||||
accountId: "account-1",
|
||||
@@ -139,48 +140,69 @@ describe("createManagedRelayQueryManager", () => {
|
||||
concurrency: "unbounded",
|
||||
}).pipe(Effect.forkChild);
|
||||
yield* Effect.yieldNow;
|
||||
expect(readClerkToken).toHaveBeenCalledTimes(1);
|
||||
assert.equal(readClerkToken.mock.calls.length, 1);
|
||||
|
||||
resolveToken(token);
|
||||
expect(yield* Fiber.join(readsFiber)).toEqual([token, token]);
|
||||
expect(yield* session.readClerkToken()).toBe(token);
|
||||
expect(readClerkToken).toHaveBeenCalledTimes(1);
|
||||
yield* Deferred.succeed(tokenDeferred, token);
|
||||
assert.deepEqual(yield* Fiber.join(readsFiber), [Option.some(token), Option.some(token)]);
|
||||
assert.equal(Option.getOrThrow(yield* session.readClerkToken()), token);
|
||||
assert.equal(readClerkToken.mock.calls.length, 1);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("refreshes the cached Clerk token after JWT expiry using TestClock", () =>
|
||||
Effect.gen(function* () {
|
||||
const firstToken = clerkToken(10);
|
||||
const secondToken = clerkToken(30);
|
||||
const tokens = [firstToken, secondToken];
|
||||
const readClerkToken = vi.fn(() =>
|
||||
Effect.sync(() => Option.some(tokens.shift() ?? "unexpected-token")),
|
||||
);
|
||||
const session = createManagedRelaySession({
|
||||
accountId: "account-1",
|
||||
readClerkToken,
|
||||
});
|
||||
|
||||
assert.equal(Option.getOrThrow(yield* session.readClerkToken()), firstToken);
|
||||
assert.equal(Option.getOrThrow(yield* session.readClerkToken()), firstToken);
|
||||
assert.equal(readClerkToken.mock.calls.length, 1);
|
||||
|
||||
yield* TestClock.adjust(Duration.seconds(6));
|
||||
|
||||
assert.equal(Option.getOrThrow(yield* session.readClerkToken()), secondToken);
|
||||
assert.equal(readClerkToken.mock.calls.length, 2);
|
||||
}).pipe(Effect.provide(TestClock.layer())),
|
||||
);
|
||||
|
||||
it.effect("updates the token provider without replacing a same-account session", () =>
|
||||
Effect.gen(function* () {
|
||||
const firstRead = vi.fn(() => Promise.resolve<string | null>(null));
|
||||
const firstRead = vi.fn(() => Effect.succeed(Option.none<string>()));
|
||||
setManagedRelaySession(registry, {
|
||||
accountId: "account-1",
|
||||
readClerkToken: firstRead,
|
||||
});
|
||||
const firstSession = registry.get(managedRelaySessionAtom);
|
||||
expect(firstSession).not.toBeNull();
|
||||
expect(yield* firstSession!.readClerkToken()).toBeNull();
|
||||
assert.isTrue(Option.isNone(yield* firstSession!.readClerkToken()));
|
||||
|
||||
const secondRead = vi.fn(() => Promise.resolve<string | null>("refreshed-token"));
|
||||
const secondRead = vi.fn(() => Effect.succeed(Option.some("refreshed-token")));
|
||||
setManagedRelaySession(registry, {
|
||||
accountId: "account-1",
|
||||
readClerkToken: secondRead,
|
||||
});
|
||||
|
||||
expect(registry.get(managedRelaySessionAtom)).toBe(firstSession);
|
||||
expect(yield* firstSession!.readClerkToken()).toBe("refreshed-token");
|
||||
expect(firstRead).toHaveBeenCalledTimes(1);
|
||||
expect(secondRead).toHaveBeenCalledTimes(1);
|
||||
assert.equal(Option.getOrThrow(yield* firstSession!.readClerkToken()), "refreshed-token");
|
||||
assert.equal(firstRead.mock.calls.length, 1);
|
||||
assert.equal(secondRead.mock.calls.length, 1);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("does not pin a refreshed session to an older pending token read", () =>
|
||||
Effect.gen(function* () {
|
||||
let resolveFirst!: (token: string) => void;
|
||||
const firstTokenDeferred = yield* Deferred.make<string>();
|
||||
setManagedRelaySession(registry, {
|
||||
accountId: "account-1",
|
||||
readClerkToken: () =>
|
||||
new Promise<string>((resolve) => {
|
||||
resolveFirst = resolve;
|
||||
}),
|
||||
readClerkToken: () => Deferred.await(firstTokenDeferred).pipe(Effect.map(Option.some)),
|
||||
});
|
||||
const session = registry.get(managedRelaySessionAtom);
|
||||
const firstRead = yield* session!.readClerkToken().pipe(Effect.forkChild);
|
||||
@@ -188,19 +210,19 @@ describe("createManagedRelayQueryManager", () => {
|
||||
|
||||
setManagedRelaySession(registry, {
|
||||
accountId: "account-1",
|
||||
readClerkToken: () => Promise.resolve("refreshed-token"),
|
||||
readClerkToken: () => Effect.succeed(Option.some("refreshed-token")),
|
||||
});
|
||||
|
||||
expect(yield* session!.readClerkToken()).toBe("refreshed-token");
|
||||
resolveFirst("older-token");
|
||||
expect(yield* Fiber.join(firstRead)).toBe("older-token");
|
||||
assert.equal(Option.getOrThrow(yield* session!.readClerkToken()), "refreshed-token");
|
||||
yield* Deferred.succeed(firstTokenDeferred, "older-token");
|
||||
assert.equal(Option.getOrThrow(yield* Fiber.join(firstRead)), "older-token");
|
||||
}),
|
||||
);
|
||||
|
||||
it("emits credential changes only when the managed relay account changes", async () => {
|
||||
setManagedRelaySession(registry, {
|
||||
accountId: "account-1",
|
||||
readClerkToken: () => Promise.resolve("first-token"),
|
||||
readClerkToken: () => Effect.succeed(Option.some("first-token")),
|
||||
});
|
||||
const changes = Effect.runPromise(
|
||||
managedRelayAccountChanges(registry).pipe(Stream.take(2), Stream.runCollect),
|
||||
@@ -211,11 +233,11 @@ describe("createManagedRelayQueryManager", () => {
|
||||
|
||||
setManagedRelaySession(registry, {
|
||||
accountId: "account-1",
|
||||
readClerkToken: () => Promise.resolve("refreshed-token"),
|
||||
readClerkToken: () => Effect.succeed(Option.some("refreshed-token")),
|
||||
});
|
||||
setManagedRelaySession(registry, {
|
||||
accountId: "account-2",
|
||||
readClerkToken: () => Promise.resolve("second-token"),
|
||||
readClerkToken: () => Effect.succeed(Option.some("second-token")),
|
||||
});
|
||||
setManagedRelaySession(registry, null);
|
||||
|
||||
@@ -234,7 +256,7 @@ describe("createManagedRelayQueryManager", () => {
|
||||
},
|
||||
} satisfies RelayClientEnvironmentRecord;
|
||||
const token = clerkToken(4_102_444_800);
|
||||
const readClerkToken = vi.fn(() => Promise.resolve(token));
|
||||
const readClerkToken = vi.fn(() => Effect.succeed(Option.some(token)));
|
||||
const manager = createManager({
|
||||
listEnvironments: () => Effect.succeed([environment, secondEnvironment]),
|
||||
getEnvironmentStatus: ({ environmentId }) => {
|
||||
|
||||
@@ -9,27 +9,30 @@ import {
|
||||
import { decodeRelayJwt } from "@t3tools/shared/relayJwt";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Clock from "effect/Clock";
|
||||
import * as Data from "effect/Data";
|
||||
import * as Deferred from "effect/Deferred";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Exit from "effect/Exit";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Stream from "effect/Stream";
|
||||
import { AsyncResult, Atom, AtomRegistry } from "effect/unstable/reactivity";
|
||||
|
||||
import { findErrorTraceId } from "../errors/errorTrace.ts";
|
||||
import * as ManagedRelay from "./managedRelay.ts";
|
||||
|
||||
const DEFAULT_STALE_TIME_MS = 15_000;
|
||||
const DEFAULT_IDLE_TTL_MS = 5 * 60_000;
|
||||
const CLERK_TOKEN_EXPIRY_SKEW_MS = 5_000;
|
||||
const DEFAULT_STALE_TIME = Duration.seconds(15);
|
||||
const DEFAULT_IDLE_TTL = Duration.minutes(5);
|
||||
const CLERK_TOKEN_EXPIRY_SKEW = Duration.seconds(5);
|
||||
|
||||
export interface ManagedRelaySession {
|
||||
readonly accountId: string;
|
||||
readonly readClerkToken: () => Effect.Effect<string | null, ManagedRelaySessionError>;
|
||||
readonly readClerkToken: () => Effect.Effect<Option.Option<string>, ManagedRelaySessionError>;
|
||||
}
|
||||
|
||||
export interface ManagedRelaySessionInput {
|
||||
readonly accountId: string;
|
||||
readonly readClerkToken: () => Promise<string | null>;
|
||||
readonly readClerkToken: () => Effect.Effect<Option.Option<string>, ManagedRelaySessionError>;
|
||||
}
|
||||
|
||||
interface ManagedRelaySessionControl {
|
||||
@@ -55,14 +58,36 @@ export interface ManagedRelayQueryEvent {
|
||||
readonly traceId?: string | null;
|
||||
}
|
||||
|
||||
export class ManagedRelaySessionError extends Data.TaggedError("ManagedRelaySessionError")<{
|
||||
readonly message: string;
|
||||
readonly cause?: unknown;
|
||||
}> {}
|
||||
export class ManagedRelaySessionTokenReadError extends Schema.TaggedErrorClass<ManagedRelaySessionTokenReadError>()(
|
||||
"ManagedRelaySessionTokenReadError",
|
||||
{ cause: Schema.Defect() },
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Could not obtain the T3 Cloud session token.";
|
||||
}
|
||||
}
|
||||
|
||||
export class ManagedRelaySnapshotError extends Data.TaggedError("ManagedRelaySnapshotError")<{
|
||||
readonly message: string;
|
||||
}> {}
|
||||
export class ManagedRelaySessionTokenUnavailableError extends Schema.TaggedErrorClass<ManagedRelaySessionTokenUnavailableError>()(
|
||||
"ManagedRelaySessionTokenUnavailableError",
|
||||
{ reason: Schema.Literals(["missing-session", "missing-token"]) },
|
||||
) {
|
||||
override get message(): string {
|
||||
return this.reason === "missing-session"
|
||||
? "Sign in to T3 Cloud before loading relay data."
|
||||
: "The T3 Cloud session token is unavailable.";
|
||||
}
|
||||
}
|
||||
|
||||
export const ManagedRelaySessionError = Schema.Union([
|
||||
ManagedRelaySessionTokenReadError,
|
||||
ManagedRelaySessionTokenUnavailableError,
|
||||
]);
|
||||
export type ManagedRelaySessionError = typeof ManagedRelaySessionError.Type;
|
||||
|
||||
export class ManagedRelaySnapshotError extends Schema.TaggedErrorClass<ManagedRelaySnapshotError>()(
|
||||
"ManagedRelaySnapshotError",
|
||||
{ message: Schema.String },
|
||||
) {}
|
||||
|
||||
export const managedRelaySessionAtom = Atom.make<ManagedRelaySession | null>(null).pipe(
|
||||
Atom.keepAlive,
|
||||
@@ -71,69 +96,102 @@ export const managedRelaySessionAtom = Atom.make<ManagedRelaySession | null>(nul
|
||||
|
||||
const managedRelaySessionControls = new WeakMap<ManagedRelaySession, ManagedRelaySessionControl>();
|
||||
|
||||
interface CachedClerkToken {
|
||||
readonly token: string;
|
||||
readonly expiresAtMillis: number;
|
||||
}
|
||||
|
||||
interface PendingClerkTokenRead {
|
||||
readonly deferred: Deferred.Deferred<Option.Option<string>, ManagedRelaySessionError>;
|
||||
}
|
||||
|
||||
interface ManagedRelaySessionCacheState {
|
||||
readonly readClerkToken: ManagedRelaySessionInput["readClerkToken"];
|
||||
readonly generation: number;
|
||||
readonly cachedToken: Option.Option<CachedClerkToken>;
|
||||
readonly pendingToken: Option.Option<PendingClerkTokenRead>;
|
||||
}
|
||||
|
||||
function isFreshCachedToken(cachedToken: CachedClerkToken, nowMillis: number): boolean {
|
||||
return cachedToken.expiresAtMillis > nowMillis + Duration.toMillis(CLERK_TOKEN_EXPIRY_SKEW);
|
||||
}
|
||||
|
||||
function decodeCachedToken(token: string): Option.Option<CachedClerkToken> {
|
||||
try {
|
||||
const expiresAtSeconds = decodeRelayJwt(token).exp;
|
||||
return typeof expiresAtSeconds === "number"
|
||||
? Option.some({ token, expiresAtMillis: expiresAtSeconds * 1_000 })
|
||||
: Option.none();
|
||||
} catch {
|
||||
return Option.none();
|
||||
}
|
||||
}
|
||||
|
||||
export function createManagedRelaySession(input: ManagedRelaySessionInput): ManagedRelaySession {
|
||||
let cachedToken: { readonly token: string; readonly expiresAtMillis: number } | null = null;
|
||||
let pendingToken: Promise<string | null> | null = null;
|
||||
let readClerkToken = input.readClerkToken;
|
||||
let tokenProviderGeneration = 0;
|
||||
|
||||
const readCachedClerkToken = async (nowMillis: number): Promise<string | null> => {
|
||||
if (cachedToken && cachedToken.expiresAtMillis > nowMillis + CLERK_TOKEN_EXPIRY_SKEW_MS) {
|
||||
return cachedToken.token;
|
||||
}
|
||||
if (pendingToken) {
|
||||
return await pendingToken;
|
||||
}
|
||||
|
||||
const operationGeneration = tokenProviderGeneration;
|
||||
const operation = readClerkToken().then((token) => {
|
||||
if (operationGeneration !== tokenProviderGeneration) {
|
||||
return token;
|
||||
}
|
||||
if (!token) {
|
||||
cachedToken = null;
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
const expiresAtSeconds = decodeRelayJwt(token).exp;
|
||||
cachedToken =
|
||||
typeof expiresAtSeconds === "number"
|
||||
? { token, expiresAtMillis: expiresAtSeconds * 1_000 }
|
||||
: null;
|
||||
} catch {
|
||||
cachedToken = null;
|
||||
}
|
||||
return token;
|
||||
});
|
||||
pendingToken = operation;
|
||||
try {
|
||||
return await operation;
|
||||
} finally {
|
||||
if (pendingToken === operation) {
|
||||
pendingToken = null;
|
||||
}
|
||||
}
|
||||
let state: ManagedRelaySessionCacheState = {
|
||||
readClerkToken: input.readClerkToken,
|
||||
generation: 0,
|
||||
cachedToken: Option.none(),
|
||||
pendingToken: Option.none(),
|
||||
};
|
||||
|
||||
const session: ManagedRelaySession = {
|
||||
accountId: input.accountId,
|
||||
readClerkToken: Effect.fn("clientRuntime.managedRelaySession.readClerkToken")(function* () {
|
||||
const nowMillis = yield* Clock.currentTimeMillis;
|
||||
return yield* Effect.tryPromise({
|
||||
try: () => readCachedClerkToken(nowMillis),
|
||||
catch: (cause) =>
|
||||
new ManagedRelaySessionError({
|
||||
message: "Could not obtain the T3 Cloud session token.",
|
||||
cause,
|
||||
}),
|
||||
});
|
||||
const current = state;
|
||||
if (
|
||||
Option.isSome(current.cachedToken) &&
|
||||
isFreshCachedToken(current.cachedToken.value, nowMillis)
|
||||
) {
|
||||
return Option.some(current.cachedToken.value.token);
|
||||
}
|
||||
if (Option.isSome(current.pendingToken)) {
|
||||
return yield* Deferred.await(current.pendingToken.value.deferred);
|
||||
}
|
||||
|
||||
const deferred = yield* Deferred.make<Option.Option<string>, ManagedRelaySessionError>();
|
||||
state = {
|
||||
...state,
|
||||
pendingToken: Option.some({ deferred }),
|
||||
};
|
||||
|
||||
const readExit = yield* Effect.exit(current.readClerkToken());
|
||||
if (Exit.isSuccess(readExit)) {
|
||||
if (state.generation === current.generation) {
|
||||
state = {
|
||||
...state,
|
||||
cachedToken: Option.isSome(readExit.value)
|
||||
? decodeCachedToken(readExit.value.value)
|
||||
: Option.none(),
|
||||
};
|
||||
}
|
||||
yield* Deferred.succeed(deferred, readExit.value).pipe(Effect.orDie);
|
||||
} else {
|
||||
yield* Deferred.failCause(deferred, readExit.cause).pipe(Effect.orDie);
|
||||
}
|
||||
|
||||
if (Option.isSome(state.pendingToken) && state.pendingToken.value.deferred === deferred) {
|
||||
state = {
|
||||
...state,
|
||||
pendingToken: Option.none(),
|
||||
};
|
||||
}
|
||||
|
||||
if (Exit.isSuccess(readExit)) {
|
||||
return readExit.value;
|
||||
}
|
||||
return yield* Effect.failCause(readExit.cause);
|
||||
}),
|
||||
};
|
||||
managedRelaySessionControls.set(session, {
|
||||
updateReadClerkToken: (nextReadClerkToken) => {
|
||||
readClerkToken = nextReadClerkToken;
|
||||
tokenProviderGeneration += 1;
|
||||
pendingToken = null;
|
||||
state = {
|
||||
readClerkToken: nextReadClerkToken,
|
||||
generation: state.generation + 1,
|
||||
cachedToken: Option.none(),
|
||||
pendingToken: Option.none(),
|
||||
};
|
||||
},
|
||||
});
|
||||
return session;
|
||||
@@ -176,14 +234,12 @@ function readSessionClerkToken(
|
||||
session: ManagedRelaySession,
|
||||
): Effect.Effect<string, ManagedRelaySessionError> {
|
||||
return session.readClerkToken().pipe(
|
||||
Effect.flatMap((token) =>
|
||||
token
|
||||
? Effect.succeed(token)
|
||||
: Effect.fail(
|
||||
new ManagedRelaySessionError({
|
||||
message: "The T3 Cloud session token is unavailable.",
|
||||
}),
|
||||
),
|
||||
Effect.flatMap(
|
||||
Option.match({
|
||||
onNone: () =>
|
||||
Effect.fail(new ManagedRelaySessionTokenUnavailableError({ reason: "missing-token" })),
|
||||
onSome: Effect.succeed,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -224,11 +280,7 @@ function requireClerkToken(
|
||||
): Effect.Effect<string, ManagedRelaySessionError> {
|
||||
const session = get(managedRelaySessionAtom);
|
||||
if (!session || session.accountId !== accountId) {
|
||||
return Effect.fail(
|
||||
new ManagedRelaySessionError({
|
||||
message: "Sign in to T3 Cloud before loading relay data.",
|
||||
}),
|
||||
);
|
||||
return Effect.fail(new ManagedRelaySessionTokenUnavailableError({ reason: "missing-session" }));
|
||||
}
|
||||
return readSessionClerkToken(session);
|
||||
}
|
||||
@@ -315,8 +367,8 @@ export function createManagedRelayQueryManager(
|
||||
readonly onQueryEvent?: (event: ManagedRelayQueryEvent) => void;
|
||||
},
|
||||
) {
|
||||
const staleTime = options?.staleTimeMs ?? DEFAULT_STALE_TIME_MS;
|
||||
const idleTtl = options?.idleTtlMs ?? DEFAULT_IDLE_TTL_MS;
|
||||
const staleTime = options?.staleTimeMs ?? Duration.toMillis(DEFAULT_STALE_TIME);
|
||||
const idleTtl = options?.idleTtlMs ?? Duration.toMillis(DEFAULT_IDLE_TTL);
|
||||
const observe = <A, E, R>(
|
||||
input: Omit<ManagedRelayQueryEvent, "phase" | "message" | "traceId">,
|
||||
effect: Effect.Effect<A, E, R>,
|
||||
|
||||
Reference in new issue
Block a user