Compare commits

...
35 changed files with 1438 additions and 411 deletions

No files matched your search

@@ -64,6 +64,13 @@ function mockSpawnerLayer(statusJson = "{}") {
);
}
function dieOnSpawnLayer() {
return Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make(() => Effect.die("unexpected tailscale spawn")),
);
}
function makeEnvironmentLayer(baseDir: string, env: Record<string, string | undefined> = {}) {
return makeDesktopEnvironmentLayer({
dirname: "/repo/apps/desktop/src",
@@ -86,6 +93,7 @@ function makeLayer(input: {
readonly baseDir: string;
readonly networkInterfaces?: DesktopNetworkInterfaces;
readonly env?: Record<string, string | undefined>;
readonly spawnerLayer?: Layer.Layer<ChildProcessSpawner.ChildProcessSpawner>;
}) {
const env = { T3CODE_HOME: input.baseDir, ...input.env };
const environmentLayer = makeEnvironmentLayer(input.baseDir, env);
@@ -97,7 +105,7 @@ function makeLayer(input: {
Layer.provideMerge(DesktopAppSettings.layer),
Layer.provideMerge(NodeFileSystem.layer),
Layer.provideMerge(NodeHttpClient.layerUndici),
Layer.provideMerge(mockSpawnerLayer()),
Layer.provideMerge(input.spawnerLayer ?? mockSpawnerLayer()),
Layer.provideMerge(networkLayer),
Layer.provideMerge(DesktopConfig.layerTest(env)),
Layer.provideMerge(environmentLayer),
@@ -116,13 +124,23 @@ const withHarness = <A, E, R>(
| DesktopAppSettings.DesktopAppSettings
>,
env: Record<string, string | undefined> = {},
spawnerLayer?: Layer.Layer<ChildProcessSpawner.ChildProcessSpawner>,
) =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-desktop-server-exposure-test-",
});
return yield* effect.pipe(Effect.provide(makeLayer({ baseDir, networkInterfaces, env })));
return yield* effect.pipe(
Effect.provide(
makeLayer({
baseDir,
networkInterfaces,
env,
...(spawnerLayer ? { spawnerLayer } : {}),
}),
),
);
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped);
describe("DesktopServerExposure", () => {
@@ -239,6 +257,27 @@ describe("DesktopServerExposure", () => {
),
);
it.effect("does not spawn the tailscale CLI while server exposure is local-only", () =>
withHarness(
lanNetworkInterfaces,
Effect.gen(function* () {
const serverExposure = yield* DesktopServerExposure.DesktopServerExposure;
yield* serverExposure.configureFromSettings({ port: 4173 });
// mode stays at default "local-only", tailscaleServeEnabled stays false.
const endpoints = yield* serverExposure.getAdvertisedEndpoints;
// Only the loopback endpoint; no tailscale spawn means the dieOnSpawnLayer
// would have crashed the test if the gate was missing.
assert.deepEqual(
endpoints.map((endpoint) => endpoint.httpBaseUrl),
["http://127.0.0.1:4173/"],
);
}),
{},
dieOnSpawnLayer(),
),
);
it.effect("uses ConfigProvider desktop exposure overrides", () =>
withHarness(
lanNetworkInterfaces,
@@ -12,6 +12,7 @@ import type {
} from "@t3tools/contracts";
import * as Context from "effect/Context";
import * as Data from "effect/Data";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
@@ -22,8 +23,11 @@ import { ChildProcessSpawner } from "effect/unstable/process";
import { DEFAULT_DESKTOP_SETTINGS, type DesktopSettings } from "../settings/DesktopAppSettings.ts";
import * as DesktopConfig from "../app/DesktopConfig.ts";
import { resolveTailscaleAdvertisedEndpoints } from "./tailscaleEndpointProvider.ts";
import { readTailscaleStatus } from "@t3tools/tailscale";
import * as DesktopAppSettingsService from "../settings/DesktopAppSettings.ts";
const TAILSCALE_STATUS_CACHE_TTL = Duration.seconds(60);
export const DESKTOP_LOOPBACK_HOST = "127.0.0.1";
const DESKTOP_LAN_BIND_HOST = "0.0.0.0";
@@ -412,6 +416,18 @@ const make = Effect.gen(function* () {
const desktopSettings = yield* DesktopAppSettingsService.DesktopAppSettings;
const stateRef = yield* Ref.make(initialRuntimeState());
// Cache the `tailscale status` spawn for the TTL. On macOS, the Mac App
// Store Tailscale CLI lives inside Tailscale's sandbox container, so each
// spawn re-triggers the "Other apps" TCC prompt.
const cachedReadMagicDnsName = yield* Effect.cachedWithTTL(
readTailscaleStatus.pipe(
Effect.map((status) => status.magicDnsName),
Effect.orElseSucceed(() => null),
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, childProcessSpawner),
),
TAILSCALE_STATUS_CACHE_TTL,
);
const readNetworkInterfaces = networkInterfaces.read;
const getState = Ref.get(stateRef).pipe(Effect.map(toContractState));
@@ -516,11 +532,20 @@ const make = Effect.gen(function* () {
exposure: toResolvedExposure(state),
customHttpsEndpointUrls: config.desktopHttpsEndpointUrls,
});
// Don't spawn the Tailscale CLI when the user hasn't opted into any
// network exposure. The spawn itself triggers a macOS "Other apps"
// TCC prompt on Mac App Store Tailscale builds.
if (state.mode !== "network-accessible" && !state.tailscaleServeEnabled) {
return coreEndpoints;
}
const tailscaleEndpoints = yield* resolveTailscaleAdvertisedEndpoints({
port: state.port,
serveEnabled: state.tailscaleServeEnabled,
servePort: state.tailscaleServePort,
networkInterfaces: currentNetworkInterfaces,
readMagicDnsName: cachedReadMagicDnsName,
}).pipe(
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, childProcessSpawner),
Effect.provideService(HttpClient.HttpClient, httpClient),
@@ -104,6 +104,25 @@ describe("tailscale endpoint provider", () => {
}).pipe(Effect.provide(unusedTailscaleExternalServicesLayer)),
);
it.effect("uses an injected magic DNS name reader instead of spawning tailscale", () =>
Effect.gen(function* () {
let readerCalls = 0;
const endpoints = yield* resolveTailscaleAdvertisedEndpoints({
port: 3773,
networkInterfaces: {},
readMagicDnsName: Effect.sync(() => {
readerCalls += 1;
return "desktop.tail.ts.net";
}),
});
assert.equal(readerCalls, 1);
assert.deepEqual(
endpoints.map((endpoint) => endpoint.httpBaseUrl),
["https://desktop.tail.ts.net/"],
);
}).pipe(Effect.provide(unusedTailscaleExternalServicesLayer)),
);
it.effect(
"marks the Tailscale HTTPS endpoint available after Serve is enabled and reachable",
() =>
@@ -105,6 +105,11 @@ export const resolveTailscaleAdvertisedEndpoints = Effect.fn("resolveTailscaleAd
readonly servePort?: number;
readonly networkInterfaces: DesktopNetworkInterfaces;
readonly statusJson?: string | null;
readonly readMagicDnsName?: Effect.Effect<
string | null,
never,
ChildProcessSpawner.ChildProcessSpawner
>;
readonly probe?: (baseUrl: string) => Effect.Effect<boolean, never, HttpClient.HttpClient>;
}): Effect.fn.Return<
readonly AdvertisedEndpoint[],
@@ -112,12 +117,15 @@ export const resolveTailscaleAdvertisedEndpoints = Effect.fn("resolveTailscaleAd
ChildProcessSpawner.ChildProcessSpawner | HttpClient.HttpClient
> {
const ipEndpoints = resolveTailscaleIpAdvertisedEndpoints(input);
const readDnsName =
input.readMagicDnsName ??
readTailscaleStatus.pipe(
Effect.map((status) => status.magicDnsName),
Effect.catch(() => Effect.succeed<string | null>(null)),
);
const dnsName =
input.statusJson === undefined
? yield* readTailscaleStatus.pipe(
Effect.map((status) => status.magicDnsName),
Effect.orElseSucceed(() => null),
)
? yield* readDnsName
: input.statusJson
? yield* parseTailscaleMagicDnsName(input.statusJson).pipe(
Effect.orElseSucceed(() => null),
+34 -42
View File
@@ -1,29 +1,35 @@
import { assert, describe, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/unstable/http";
import { afterEach } from "vite-plus/test";
import { fetchCloudAuth, validateClerkFrontendApiUrl } from "./cloudAuth.ts";
const originalClerkPublishableKey = process.env.T3CODE_CLERK_PUBLISHABLE_KEY;
const originalFetch = globalThis.fetch;
const clerkPublishableKey = (hostname: string): string =>
`pk_test_${Buffer.from(`${hostname}$`).toString("base64")}`;
function makeHttpClientLayer(
handler: (
request: HttpClientRequest.HttpClientRequest,
) => Effect.Effect<HttpClientResponse.HttpClientResponse, never>,
) {
return Layer.succeed(
HttpClient.HttpClient,
HttpClient.make((request) => handler(request)),
);
}
type FetchCall = readonly [input: RequestInfo | URL, init: RequestInit];
const recordedFetch = (...responses: ReadonlyArray<Response>) => {
const calls: Array<FetchCall> = [];
let responseIndex = 0;
const fetchFn = ((input, init) => {
calls.push([input, init ?? {}]);
const response = responses[responseIndex++];
if (!response) {
return Promise.reject(new Error("Unexpected fetch call"));
}
return Promise.resolve(response);
}) satisfies typeof fetch;
return { fetchFn, calls };
};
describe("Desktop cloud auth IPC", () => {
afterEach(() => {
globalThis.fetch = originalFetch;
if (originalClerkPublishableKey === undefined) {
delete process.env.T3CODE_CLERK_PUBLISHABLE_KEY;
} else {
@@ -33,16 +39,8 @@ describe("Desktop cloud auth IPC", () => {
it.effect("preserves Clerk's URL-encoded OAuth form content type", () => {
const body = "strategy=oauth_google&redirect_url=t3code%3A%2F%2Fauth%2Fcallback";
let forwardedRequest: HttpClientRequest.HttpClientRequest | null = null;
const layer = makeHttpClientLayer((request) =>
Effect.sync(() => {
forwardedRequest = request;
return HttpClientResponse.fromWeb(
request,
Response.json({ response: { object: "sign_in_attempt" } }),
);
}),
);
const fetch = recordedFetch(Response.json({ response: { object: "sign_in_attempt" } }));
globalThis.fetch = fetch.fetchFn;
return Effect.gen(function* () {
yield* fetchCloudAuth.handler({
@@ -55,32 +53,25 @@ describe("Desktop cloud auth IPC", () => {
body,
});
assert(forwardedRequest !== null);
const forwardedRequest = fetch.calls[0];
assert(forwardedRequest !== undefined);
const [url, init] = forwardedRequest;
assert.equal(String(url), "https://example.clerk.accounts.dev/v1/client/sign_ins");
assert.equal(init.method, "POST");
assert.equal(
forwardedRequest.headers["content-type"],
new Headers(init.headers).get("content-type"),
"application/x-www-form-urlencoded;charset=UTF-8",
);
assert.equal(forwardedRequest.body._tag, "Uint8Array");
if (forwardedRequest.body._tag === "Uint8Array") {
assert.equal(new TextDecoder().decode(forwardedRequest.body.body), body);
}
}).pipe(Effect.provide(layer));
assert.equal(new TextDecoder().decode(init.body as Uint8Array), body);
});
});
it.effect(
"allows the custom Clerk Frontend API host encoded by the configured publishable key",
() => {
process.env.T3CODE_CLERK_PUBLISHABLE_KEY = clerkPublishableKey("clerk.t3.codes");
let forwardedRequest: HttpClientRequest.HttpClientRequest | null = null;
const layer = makeHttpClientLayer((request) =>
Effect.sync(() => {
forwardedRequest = request;
return HttpClientResponse.fromWeb(
request,
Response.json({ response: { object: "client" } }),
);
}),
);
const fetch = recordedFetch(Response.json({ response: { object: "client" } }));
globalThis.fetch = fetch.fetchFn;
return Effect.gen(function* () {
yield* fetchCloudAuth.handler({
@@ -89,9 +80,10 @@ describe("Desktop cloud auth IPC", () => {
headers: {},
});
assert(forwardedRequest !== null);
assert.equal(forwardedRequest.url.toString(), "https://clerk.t3.codes/v1/client");
}).pipe(Effect.provide(layer));
const forwardedRequest = fetch.calls[0];
assert(forwardedRequest !== undefined);
assert.equal(String(forwardedRequest[0]), "https://clerk.t3.codes/v1/client");
});
},
);
+66 -43
View File
@@ -8,9 +8,11 @@ import {
} from "@t3tools/shared/relayAuth";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import { identity } from "effect/Function";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import { Headers, HttpClient, HttpClientRequest } from "effect/unstable/http";
import { FetchHttpClient, HttpClient, HttpClientRequest } from "effect/unstable/http";
import * as DesktopCloudAuth from "../../app/DesktopCloudAuth.ts";
import * as DesktopCloudAuthTokenStore from "../../app/DesktopCloudAuthTokenStore.ts";
@@ -52,6 +54,68 @@ export function validateClerkFrontendApiUrl(rawUrl: string): URL {
return url;
}
function executeCloudAuthFetch(url: URL, input: typeof DesktopCloudAuthFetchInputSchema.Type) {
return Effect.gen(function* () {
const method = (input.method ?? "GET") as "GET" | "POST";
const headers = new Headers(input.headers);
const response = yield* HttpClientRequest.make(method)(url).pipe(
HttpClientRequest.setHeaders(headers),
input.body === undefined
? identity
: HttpClientRequest.bodyText(input.body, headers.get("content-type") ?? undefined),
HttpClient.execute,
Effect.mapError(
(cause) =>
new DesktopCloudAuthFetchError({
reason: "Desktop cloud auth fetch failed to execute.",
cause,
}),
),
);
const body = yield* response.text.pipe(
Effect.mapError(
(cause) =>
new DesktopCloudAuthFetchError({
reason: "Desktop cloud auth fetch response could not be read.",
cause,
}),
),
);
return {
ok: response.status >= 200 && response.status < 300,
status: response.status,
statusText: "",
headers: response.headers,
body,
};
});
}
const electronNetFetchLayer = Layer.unwrap(
Effect.gen(function* () {
const electronFetch = yield* Effect.promise(async () => {
const electron = (await import("electron")) as {
readonly net?: { readonly fetch?: typeof globalThis.fetch };
};
return typeof electron.net?.fetch === "function"
? electron.net.fetch.bind(electron.net)
: null;
}).pipe(Effect.catchCause(() => Effect.succeed(null)));
if (!electronFetch) {
yield* Effect.logWarning(
"electron.net.fetch is not available, falling back to global fetch. This may cause unexpected errors.",
);
}
return FetchHttpClient.layer.pipe(
Layer.provide(Layer.succeed(FetchHttpClient.Fetch, electronFetch ?? globalThis.fetch)),
);
}),
);
export const createCloudAuthRequest = makeIpcMethod({
channel: IpcChannels.CREATE_CLOUD_AUTH_REQUEST_CHANNEL,
payload: Schema.Void,
@@ -108,47 +172,6 @@ export const fetchCloudAuth = makeIpcMethod({
}),
});
const requestWithoutBody = HttpClientRequest.make((input.method ?? "GET") as "GET" | "POST")(
url,
{
headers: input.headers,
},
);
const request =
input.body === undefined
? requestWithoutBody
: HttpClientRequest.bodyText(
requestWithoutBody,
input.body,
Option.getOrUndefined(Headers.get(requestWithoutBody.headers, "content-type")),
);
const response = yield* HttpClient.execute(request).pipe(
Effect.mapError(
(cause) =>
new DesktopCloudAuthFetchError({
reason: "Desktop cloud auth fetch failed.",
cause,
}),
),
);
const body = yield* response.text.pipe(
Effect.mapError(
(cause) =>
new DesktopCloudAuthFetchError({
reason: "Desktop cloud auth fetch response could not be read.",
cause,
}),
),
);
return {
ok: response.status >= 200 && response.status < 300,
status: response.status,
statusText: "",
headers: response.headers,
body,
};
return yield* executeCloudAuthFetch(url, input).pipe(Effect.provide(electronNetFetchLayer));
}),
});
@@ -344,6 +344,26 @@ function runtimeEventToActivities(
];
}
case "tool.denied": {
return [
{
id: event.eventId,
createdAt: event.createdAt,
tone: "error",
kind: "tool.denied",
summary: `Tool denied: ${event.payload.toolName}`,
payload: {
toolName: event.payload.toolName,
...(event.payload.toolUseId ? { toolUseId: event.payload.toolUseId } : {}),
...(event.payload.reason ? { detail: truncateDetail(event.payload.reason) } : {}),
...(event.payload.agentId ? { agentId: event.payload.agentId } : {}),
},
turnId: toTurnId(event.turnId) ?? null,
...maybeSequence,
},
];
}
case "runtime.warning": {
return [
{
@@ -351,7 +371,9 @@ function runtimeEventToActivities(
createdAt: event.createdAt,
tone: "info",
kind: "runtime.warning",
summary: "Runtime warning",
// Use the adapter-supplied message as the row label so the work log
// shows what the warning was about, not a generic "Runtime warning".
summary: truncateDetail(event.payload.message, 120),
payload: {
message: truncateDetail(event.payload.message),
...(event.payload.detail !== undefined ? { detail: event.payload.detail } : {}),
@@ -972,6 +972,52 @@ function sdkNativeMethod(message: SDKMessage): string {
return `claude/${message.type}`;
}
// Discriminator/identity keys carry no human-readable content; everything else
// on an unmodeled SDK message is potentially worth surfacing in the work log.
const SDK_MESSAGE_NOISE_KEYS = new Set([
"type",
"subtype",
"uuid",
"parent_uuid",
"session_id",
"parent_tool_use_id",
"request_id",
]);
// Pull the salient scalar content out of a message the adapter doesn't model
// yet, so the work-log row shows what actually arrived (e.g. a notification's
// text) instead of an opaque "unhandled subtype" placeholder. Nested structures
// are left to the full payload retained in the event's `detail`.
function previewUnknownSdkContent(message: unknown): string | undefined {
if (!message || typeof message !== "object") {
return undefined;
}
const parts: string[] = [];
for (const [key, value] of Object.entries(message as Record<string, unknown>)) {
if (SDK_MESSAGE_NOISE_KEYS.has(key)) {
continue;
}
if (typeof value === "string") {
const trimmed = value.trim();
if (trimmed.length > 0) {
parts.push(`${key}: ${trimmed}`);
}
} else if (typeof value === "number" || typeof value === "boolean") {
parts.push(`${key}: ${String(value)}`);
}
}
if (parts.length === 0) {
return undefined;
}
const joined = parts.join(" · ");
return joined.length > 280 ? `${joined.slice(0, 279)}…` : joined;
}
function describeUnknownSdkMessage(kind: string, message: unknown): string {
const preview = previewUnknownSdkContent(message);
return preview ? `${kind} — ${preview}` : `${kind} (no displayable text content)`;
}
function sdkNativeItemId(message: SDKMessage): string | undefined {
if (message.type === "assistant") {
const maybeId = (message.message as { id?: unknown }).id;
@@ -2267,10 +2313,31 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
},
});
return;
case "thinking_tokens":
return;
case "permission_denied":
yield* offerRuntimeEvent({
...base,
type: "tool.denied",
payload: {
toolName: message.tool_name,
...(message.tool_use_id ? { toolUseId: message.tool_use_id } : {}),
...(message.decision_reason ? { reason: message.decision_reason } : {}),
...(message.agent_id ? { agentId: message.agent_id } : {}),
},
});
return;
case "mirror_error":
yield* emitRuntimeError(
context,
`Claude workspace mirror error: ${message.error}`,
message,
);
return;
default:
yield* emitRuntimeWarning(
context,
`Unhandled Claude system message subtype '${message.subtype}'.`,
describeUnknownSdkMessage(`Claude system message '${message.subtype}'`, message),
message,
);
return;
@@ -2384,7 +2451,7 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
default:
yield* emitRuntimeWarning(
context,
`Unhandled Claude SDK message type '${message.type}'.`,
describeUnknownSdkMessage(`Claude SDK message '${message.type}'`, message),
message,
);
return;
@@ -392,5 +392,20 @@ it.layer(TestLayer)("WorkspaceEntriesLive", (it) => {
expect(error.detail).toBe("Relative filesystem browse paths require a current project.");
}),
);
it.effect("returns an empty listing when the OS denies directory access", () =>
Effect.gen(function* () {
const workspaceEntries = yield* WorkspaceEntries;
const cwd = yield* makeTempDir({ prefix: "t3code-workspace-browse-eacces-" });
const denied = Object.assign(new Error("EACCES: permission denied"), { code: "EACCES" });
vi.spyOn(fsPromises, "readdir").mockRejectedValueOnce(denied);
const result = yield* workspaceEntries.browse({
partialPath: appendSeparator(cwd),
});
expect(result).toEqual({ parentPath: cwd, entries: [] });
}),
);
});
});
@@ -457,7 +457,18 @@ export const makeWorkspaceEntries = Effect.gen(function* () {
detail: `Unable to browse '${parentPath}': ${cause instanceof Error ? cause.message : String(cause)}`,
cause,
}),
});
}).pipe(
// The user can deny macOS TCC prompts for the target dir (Documents,
// Downloads, Music, etc.); surface an empty listing instead of an
// error so the caller doesn't retry-loop the prompt.
Effect.catchIf(
(error) => {
const code = (error.cause as NodeJS.ErrnoException | undefined)?.code;
return code === "EACCES" || code === "EPERM";
},
() => Effect.succeed<Dirent[]>([]),
),
);
const showHidden = endsWithSeparator || prefix.startsWith(".");
const lowerPrefix = prefix.toLowerCase();
+6 -20
View File
@@ -562,11 +562,7 @@ function OpenCommandPaletteDialog() {
!relativePathNeedsActiveProject,
});
const browseEntries = browseResult?.entries ?? EMPTY_BROWSE_ENTRIES;
const {
filteredEntries: filteredBrowseEntries,
highlightedEntry: highlightedBrowseEntry,
exactEntry: exactBrowseEntry,
} = useMemo(
const { filteredEntries: filteredBrowseEntries, exactEntry: exactBrowseEntry } = useMemo(
() => filterBrowseEntries({ browseEntries, browseFilterQuery, highlightedItemValue }),
[browseEntries, browseFilterQuery, highlightedItemValue],
);
@@ -587,27 +583,17 @@ function OpenCommandPaletteDialog() {
[browseEnvironmentId, currentProjectCwdForBrowse, fetchBrowseResult, queryClient],
);
// Prefetch the parent and the most likely next child so browse navigation
// stays warm without scanning every child directory in large trees.
// Prefetch only the parent (for back-navigation). Prefetching the
// highlighted child on every arrow-key press triggers a macOS TCC prompt
// whenever the highlighted entry is a permission-gated home dir (Music,
// Documents, Downloads, Desktop, etc.), so we wait for explicit navigation.
useEffect(() => {
if (!isBrowsing || filteredBrowseEntries.length === 0) return;
if (canNavigateUp(query)) {
prefetchBrowsePath(getBrowseParentPath(query)!);
}
const nextChild = highlightedBrowseEntry ?? exactBrowseEntry;
if (nextChild) {
prefetchBrowsePath(appendBrowsePathSegment(query, nextChild.name));
}
}, [
exactBrowseEntry,
filteredBrowseEntries.length,
highlightedBrowseEntry,
isBrowsing,
prefetchBrowsePath,
query,
]);
}, [filteredBrowseEntries.length, isBrowsing, prefetchBrowsePath, query]);
const openProjectFromSearch = useMemo(
() => async (project: (typeof projects)[number]) => {
@@ -1,7 +1,8 @@
import { scopeThreadRef } from "@t3tools/client-runtime";
import { ThreadId } from "@t3tools/contracts";
import * as Option from "effect/Option";
import { useState } from "react";
import { afterEach, describe, expect, it, vi } from "vite-plus/test";
import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
import { render } from "vitest-browser-react";
const SHARED_THREAD_ID = ThreadId.make("thread-shared");
@@ -26,6 +27,8 @@ const {
activeRunStackedActionDeferredRef,
activeDraftThreadRef,
hasServerThreadRef,
sourceControlDiscoveryRef,
vcsStatusRef,
invalidateSourceControlStateSpy,
refreshVcsStatusSpy,
runStackedActionSpy,
@@ -39,6 +42,26 @@ const {
activeRunStackedActionDeferredRef: { current: createDeferredPromise<never>() },
activeDraftThreadRef: { current: null as unknown },
hasServerThreadRef: { current: true },
sourceControlDiscoveryRef: { current: null as unknown },
vcsStatusRef: {
current: {
isRepo: true,
sourceControlProvider: {
kind: "github",
name: "GitHub",
baseUrl: "https://github.com",
},
hasPrimaryRemote: true,
isDefaultRef: false,
refName: "feature/toast-scope",
hasWorkingTreeChanges: false,
workingTree: { files: [], insertions: 0, deletions: 0 },
hasUpstream: true,
aheadCount: 1,
behindCount: 0,
pr: null,
},
},
invalidateSourceControlStateSpy: vi.fn(() => Promise.resolve()),
refreshVcsStatusSpy: vi.fn(() => Promise.resolve(null)),
runStackedActionSpy: vi.fn(() => activeRunStackedActionDeferredRef.current.promise),
@@ -64,6 +87,10 @@ vi.mock("~/editorPreferences", () => ({
openInPreferredEditor: vi.fn(),
}));
vi.mock("~/lib/sourceControlDiscoveryState", () => ({
useSourceControlDiscovery: vi.fn(() => sourceControlDiscoveryRef.current),
}));
vi.mock("~/lib/sourceControlActions", () => ({
invalidateSourceControlState: invalidateSourceControlStateSpy,
useGitStackedAction: vi.fn(() => ({
@@ -97,23 +124,7 @@ vi.mock("~/lib/vcsStatusState", () => ({
refreshVcsStatus: refreshVcsStatusSpy,
resetVcsStatusStateForTests: () => undefined,
useVcsStatus: vi.fn(() => ({
data: {
isRepo: true,
sourceControlProvider: {
kind: "github",
name: "GitHub",
baseUrl: "https://github.com",
},
hasPrimaryRemote: true,
isDefaultRef: false,
refName: BRANCH_NAME,
hasWorkingTreeChanges: false,
workingTree: { files: [], insertions: 0, deletions: 0 },
hasUpstream: true,
aheadCount: 1,
behindCount: 0,
pr: null,
},
data: vcsStatusRef.current,
error: null,
isPending: false,
})),
@@ -245,6 +256,77 @@ function findButtonByText(text: string): HTMLButtonElement | null {
) ?? null) as HTMLButtonElement | null;
}
function findRadioByText(text: string): HTMLElement | null {
return (Array.from(document.querySelectorAll('[role="radio"]')).find((radio) =>
radio.textContent?.includes(text),
) ?? null) as HTMLElement | null;
}
function setInputValue(input: HTMLInputElement, value: string) {
input.value = value;
input.dispatchEvent(new Event("input", { bubbles: true }));
}
function createDefaultVcsStatus() {
return {
isRepo: true,
sourceControlProvider: {
kind: "github",
name: "GitHub",
baseUrl: "https://github.com",
},
hasPrimaryRemote: true,
isDefaultRef: false,
refName: BRANCH_NAME,
hasWorkingTreeChanges: false,
workingTree: { files: [], insertions: 0, deletions: 0 },
hasUpstream: true,
aheadCount: 1,
behindCount: 0,
pr: null,
};
}
function createDefaultSourceControlDiscovery() {
return {
data: {
versionControlSystems: [],
sourceControlProviders: [
{
kind: "github",
label: "GitHub",
status: "available",
version: Option.some("2.85.0"),
installHint: "Install GitHub CLI.",
detail: Option.none(),
auth: {
status: "authenticated",
account: Option.some("octo"),
host: Option.some("github.com"),
detail: Option.none(),
},
},
{
kind: "gitlab",
label: "GitLab",
status: "available",
version: Option.some("19.0.0"),
installHint: "Install GitLab CLI.",
detail: Option.none(),
auth: {
status: "authenticated",
account: Option.some("tanuki"),
host: Option.some("gitlab.com"),
detail: Option.none(),
},
},
],
},
error: null,
isPending: false,
};
}
function Harness() {
const [activeThreadRef, setActiveThreadRef] = useState(
scopeThreadRef(ENVIRONMENT_A, SHARED_THREAD_ID),
@@ -264,12 +346,19 @@ function Harness() {
}
describe("GitActionsControl thread-scoped progress toast", () => {
beforeEach(() => {
vcsStatusRef.current = createDefaultVcsStatus();
sourceControlDiscoveryRef.current = createDefaultSourceControlDiscovery();
});
afterEach(() => {
vi.useRealTimers();
vi.clearAllMocks();
activeRunStackedActionDeferredRef.current = createDeferredPromise<never>();
activeDraftThreadRef.current = null;
hasServerThreadRef.current = true;
vcsStatusRef.current = createDefaultVcsStatus();
sourceControlDiscoveryRef.current = createDefaultSourceControlDiscovery();
document.body.innerHTML = "";
});
@@ -335,6 +424,58 @@ describe("GitActionsControl thread-scoped progress toast", () => {
}
});
it("derives publish provider and repository defaults while preserving user edits", async () => {
vcsStatusRef.current = {
...createDefaultVcsStatus(),
hasPrimaryRemote: false,
hasUpstream: false,
aheadCount: 0,
};
const host = document.createElement("div");
document.body.append(host);
const screen = await render(
<GitActionsControl
gitCwd={GIT_CWD}
activeThreadRef={scopeThreadRef(ENVIRONMENT_A, SHARED_THREAD_ID)}
/>,
{ container: host },
);
try {
findButtonByText("Publish repository")?.click();
await Promise.resolve();
expect(document.querySelector('[role="dialog"]')?.textContent).toContain(
"Publish repository",
);
findButtonByText("Next")?.click();
await Promise.resolve();
const repositoryInput = document.querySelector<HTMLInputElement>("#publish-repository-path");
expect(repositoryInput?.value).toBe("octo/");
if (!repositoryInput) {
throw new Error("Repository input was not rendered.");
}
setInputValue(repositoryInput, "octo/demo");
expect(repositoryInput.value).toBe("octo/demo");
findButtonByText("Back")?.click();
await Promise.resolve();
findRadioByText("GitLab")?.click();
await Promise.resolve();
findButtonByText("Next")?.click();
await Promise.resolve();
expect(document.querySelector<HTMLInputElement>("#publish-repository-path")?.value).toBe(
"tanuki/",
);
} finally {
await screen.unmount();
host.remove();
}
});
it("debounces focus-driven git status refreshes", async () => {
vi.useFakeTimers();
+17 -30
View File
@@ -348,8 +348,9 @@ interface PublishRepositoryDialogProps {
function PublishRepositoryDialog(props: PublishRepositoryDialogProps) {
const navigate = useNavigate();
const sourceControlDiscovery = useSourceControlDiscovery();
const [publishProvider, setPublishProvider] = useState<PublishProviderKind>("github");
const [publishRepository, setPublishRepository] = useState("");
const [requestedPublishProvider, setRequestedPublishProvider] =
useState<PublishProviderKind>("github");
const [publishRepositoryOverride, setPublishRepositoryOverride] = useState<string | null>(null);
const [publishVisibility, setPublishVisibility] =
useState<SourceControlRepositoryVisibility>("private");
const [publishRemoteName, setPublishRemoteName] = useState("origin");
@@ -360,7 +361,6 @@ function PublishRepositoryDialog(props: PublishRepositoryDialogProps) {
const [publishResult, setPublishResult] = useState<SourceControlPublishRepositoryResult | null>(
null,
);
const [hasUserEditedPublishRepository, setHasUserEditedPublishRepository] = useState(false);
const sourceControlScope = useMemo(
() => ({
environmentId: props.environmentId,
@@ -395,6 +395,13 @@ function PublishRepositoryDialog(props: PublishRepositoryDialogProps) {
]),
) as Record<PublishProviderKind, { readonly ready: boolean; readonly hint: string | null }>;
}, [sourceControlDiscovery.data]);
const firstReadyPublishProvider = PUBLISH_PROVIDER_OPTIONS.find(
(option) => publishProviderReadiness[option.value].ready,
);
const publishProvider =
publishProviderReadiness[requestedPublishProvider].ready || !firstReadyPublishProvider
? requestedPublishProvider
: firstReadyPublishProvider.value;
const hasReadyPublishProvider = useMemo(
() => PUBLISH_PROVIDER_OPTIONS.some((option) => publishProviderReadiness[option.value].ready),
[publishProviderReadiness],
@@ -415,6 +422,7 @@ function PublishRepositoryDialog(props: PublishRepositoryDialogProps) {
const publishRepositoryPrefill = publishAccountByProvider[publishProvider]
? `${publishAccountByProvider[publishProvider]}/`
: "";
const publishRepository = publishRepositoryOverride ?? publishRepositoryPrefill;
const currentPublishProvider = publishProviderOption(publishProvider);
const publishHost = currentPublishProvider.host;
const publishPathPlaceholder = currentPublishProvider.pathPlaceholder;
@@ -426,13 +434,6 @@ function PublishRepositoryDialog(props: PublishRepositoryDialogProps) {
null,
] as const;
useEffect(() => {
if (!props.open || hasUserEditedPublishRepository) {
return;
}
setPublishRepository(publishRepositoryPrefill);
}, [hasUserEditedPublishRepository, props.open, publishRepositoryPrefill]);
const canSubmitPublishRepository = useMemo(() => {
if (!selectedPublishProviderReadiness.ready) return false;
if (publishRepositoryAction.isPending) return false;
@@ -443,21 +444,6 @@ function PublishRepositoryDialog(props: PublishRepositoryDialogProps) {
return owner.length > 0 && name.length > 0;
}, [publishRepository, publishRepositoryAction.isPending, selectedPublishProviderReadiness]);
useEffect(() => {
if (!props.open) {
return;
}
if (publishProviderReadiness[publishProvider].ready) {
return;
}
const firstReadyProvider = PUBLISH_PROVIDER_OPTIONS.find(
(option) => publishProviderReadiness[option.value].ready,
);
if (firstReadyProvider) {
setPublishProvider(firstReadyProvider.value);
}
}, [props.open, publishProvider, publishProviderReadiness]);
const submitPublishRepository = useCallback(() => {
if (!canSubmitPublishRepository) {
return;
@@ -499,8 +485,7 @@ function PublishRepositoryDialog(props: PublishRepositoryDialogProps) {
const resetState = useCallback(() => {
setPublishRemoteName("origin");
setPublishRepository("");
setHasUserEditedPublishRepository(false);
setPublishRepositoryOverride(null);
setPublishWizardStep(0);
setPublishAdvancedOpen(false);
setPublishError(null);
@@ -593,7 +578,10 @@ function PublishRepositoryDialog(props: PublishRepositoryDialogProps) {
</span>
<RadioGroup
value={publishProvider}
onValueChange={(value) => setPublishProvider(value as PublishProviderKind)}
onValueChange={(value) => {
setRequestedPublishProvider(value as PublishProviderKind);
setPublishRepositoryOverride(null);
}}
aria-labelledby="publish-provider-cards-label"
className="grid grid-cols-2 gap-2.5"
>
@@ -679,8 +667,7 @@ function PublishRepositoryDialog(props: PublishRepositoryDialogProps) {
name="publish-repository-path"
value={publishRepository}
onChange={(event) => {
setPublishRepository(event.target.value);
setHasUserEditedPublishRepository(true);
setPublishRepositoryOverride(event.target.value);
}}
onKeyDown={(event) => {
if (event.key === "Enter") {
@@ -1,7 +1,6 @@
import type { RelayAgentActivityState } from "@t3tools/contracts/relay";
import { RelayAgentActivityState as RelayAgentActivityStateSchema } from "@t3tools/contracts/relay";
import * as Context from "effect/Context";
import * as Data from "effect/Data";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import { cast } from "effect/Function";
@@ -13,23 +12,32 @@ import { and, desc, eq, isNull } from "drizzle-orm";
import { RelayDb } from "../db.ts";
import { relayAgentActivityRows, relayEnvironmentLinks } from "../persistence/schema.ts";
export class AgentActivityRowUpsertPersistenceError extends Data.TaggedError(
export class AgentActivityRowUpsertPersistenceError extends Schema.TaggedErrorClass<AgentActivityRowUpsertPersistenceError>()(
"AgentActivityRowUpsertPersistenceError",
)<{
readonly cause: unknown;
}> {}
{ cause: Schema.Defect() },
) {
override get message(): string {
return "Failed to persist agent activity state";
}
}
export class AgentActivityRowDeletePersistenceError extends Data.TaggedError(
export class AgentActivityRowDeletePersistenceError extends Schema.TaggedErrorClass<AgentActivityRowDeletePersistenceError>()(
"AgentActivityRowDeletePersistenceError",
)<{
readonly cause: unknown;
}> {}
{ cause: Schema.Defect() },
) {
override get message(): string {
return "Failed to delete agent activity state";
}
}
export class AgentActivityRowListPersistenceError extends Data.TaggedError(
export class AgentActivityRowListPersistenceError extends Schema.TaggedErrorClass<AgentActivityRowListPersistenceError>()(
"AgentActivityRowListPersistenceError",
)<{
readonly cause: unknown;
}> {}
{ cause: Schema.Defect() },
) {
override get message(): string {
return "Failed to list agent activity state";
}
}
export interface AgentActivityRowsShape {
readonly upsert: (input: {
+32 -18
View File
@@ -2,20 +2,13 @@ import * as NodeCrypto from "node:crypto";
import type { RelayAgentActivityAggregateState } from "@t3tools/contracts/relay";
import * as Context from "effect/Context";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import * as Encoding from "effect/Encoding";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Redacted from "effect/Redacted";
import * as Schema from "effect/Schema";
import {
Headers,
HttpClient,
HttpClientRequest,
type HttpBody,
type HttpClientError,
} from "effect/unstable/http";
import { Headers, HttpClient, HttpClientRequest } from "effect/unstable/http";
import type { ApnsCredentials } from "../Config.ts";
import type { ApnsNotificationPayload } from "./apnsDeliveryJobs.ts";
@@ -45,18 +38,39 @@ export interface ApnsDeliveryResult {
readonly apnsId: string | null;
}
export class ApnsSigningError extends Data.TaggedError("ApnsSigningError")<{
readonly phase: "encoding" | "signing";
readonly cause: unknown;
}> {}
export class ApnsSigningError extends Schema.TaggedErrorClass<ApnsSigningError>()(
"ApnsSigningError",
{
phase: Schema.Literals(["encoding", "signing"]),
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed during APNs JWT ${this.phase}`;
}
}
export class ApnsHttpRequestError extends Data.TaggedError("ApnsHttpRequestError")<{
readonly cause: HttpClientError.HttpClientError | HttpBody.HttpBodyError;
}> {}
export class ApnsHttpRequestError extends Schema.TaggedErrorClass<ApnsHttpRequestError>()(
"ApnsHttpRequestError",
{
cause: Schema.Defect(),
},
) {
override get message(): string {
return "APNs HTTP request failed";
}
}
export class ApnsInvalidResponseError extends Data.TaggedError("ApnsInvalidResponseError")<{
readonly cause: unknown;
}> {}
export class ApnsInvalidResponseError extends Schema.TaggedErrorClass<ApnsInvalidResponseError>()(
"ApnsInvalidResponseError",
{
cause: Schema.Defect(),
},
) {
override get message(): string {
return "APNs returned an invalid response";
}
}
export type ApnsError = ApnsSigningError | ApnsHttpRequestError | ApnsInvalidResponseError;
@@ -9,7 +9,6 @@ import {
RelayAgentAwarenessPreferences as RelayAgentAwarenessPreferencesSchema,
} from "@t3tools/contracts/relay";
import * as Context from "effect/Context";
import * as Data from "effect/Data";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
@@ -74,9 +73,16 @@ export type ApnsDeliveryError =
| LiveActivities.LiveActivityTargetListPersistenceError
| LiveActivities.LiveActivityDeliveryMarkPersistenceError;
export class ApnsDeliveryJobClaimInFlight extends Data.TaggedError("ApnsDeliveryJobClaimInFlight")<{
readonly sourceJobId: string;
}> {}
export class ApnsDeliveryJobClaimInFlight extends Schema.TaggedErrorClass<ApnsDeliveryJobClaimInFlight>()(
"ApnsDeliveryJobClaimInFlight",
{
sourceJobId: Schema.String,
},
) {
override get message(): string {
return `APNs delivery job '${this.sourceJobId}' is already in flight`;
}
}
const decodeRelayAgentActivityAggregateStateJson = Schema.decodeUnknownOption(
Schema.fromJsonString(RelayAgentActivityAggregateStateSchema),
@@ -2,10 +2,10 @@ import * as Alchemy from "alchemy";
import * as Cloudflare from "alchemy/Cloudflare";
import * as Crypto from "effect/Crypto";
import * as Context from "effect/Context";
import * as Data from "effect/Data";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Schema from "effect/Schema";
import type { RelayDeliveryResult } from "@t3tools/contracts/relay";
@@ -22,9 +22,14 @@ import {
} from "./apnsDeliveryJobs.ts";
import * as RelayConfiguration from "../Config.ts";
export class ApnsDeliveryQueueSendError extends Data.TaggedError("ApnsDeliveryQueueSendError")<{
readonly cause: unknown;
}> {}
export class ApnsDeliveryQueueSendError extends Schema.TaggedErrorClass<ApnsDeliveryQueueSendError>()(
"ApnsDeliveryQueueSendError",
{ cause: Schema.Defect() },
) {
override get message(): string {
return "Failed to enqueue APNs delivery";
}
}
export type ApnsDeliveryQueueError = ApnsDeliveryQueueSendError;
@@ -1,20 +1,23 @@
import * as Context from "effect/Context";
import * as Data from "effect/Data";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import { and, eq, isNull } from "drizzle-orm";
import * as Crypto from "effect/Crypto";
import * as Schema from "effect/Schema";
import { RelayDb } from "../db.ts";
import { relayDeliveryAttempts } from "../persistence/schema.ts";
export class DeliveryAttemptRecordPersistenceError extends Data.TaggedError(
export class DeliveryAttemptRecordPersistenceError extends Schema.TaggedErrorClass<DeliveryAttemptRecordPersistenceError>()(
"DeliveryAttemptRecordPersistenceError",
)<{
readonly cause: unknown;
}> {}
{ cause: Schema.Defect() },
) {
override get message(): string {
return "Failed to persist APNs delivery attempt";
}
}
export interface DeliveryAttemptInput {
readonly userId: string | null;
+23 -12
View File
@@ -3,31 +3,42 @@ import type {
RelayDeviceRegistrationRequest,
} from "@t3tools/contracts/relay";
import * as Context from "effect/Context";
import * as Data from "effect/Data";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Schema from "effect/Schema";
import { and, eq } from "drizzle-orm";
import { sql } from "drizzle-orm";
import { RelayDb } from "../db.ts";
import { relayLiveActivities, relayMobileDevices } from "../persistence/schema.ts";
export class DeviceRegistrationPersistenceError extends Data.TaggedError(
export class DeviceRegistrationPersistenceError extends Schema.TaggedErrorClass<DeviceRegistrationPersistenceError>()(
"DeviceRegistrationPersistenceError",
)<{
readonly cause: unknown;
}> {}
{ cause: Schema.Defect() },
) {
override get message(): string {
return "Failed to persist mobile device registration";
}
}
export class DeviceUnregistrationPersistenceError extends Data.TaggedError(
export class DeviceUnregistrationPersistenceError extends Schema.TaggedErrorClass<DeviceUnregistrationPersistenceError>()(
"DeviceUnregistrationPersistenceError",
)<{
readonly cause: unknown;
}> {}
{ cause: Schema.Defect() },
) {
override get message(): string {
return "Failed to unregister mobile device";
}
}
export class DeviceListPersistenceError extends Data.TaggedError("DeviceListPersistenceError")<{
readonly cause: unknown;
}> {}
export class DeviceListPersistenceError extends Schema.TaggedErrorClass<DeviceListPersistenceError>()(
"DeviceListPersistenceError",
{ cause: Schema.Defect() },
) {
override get message(): string {
return "Failed to list mobile devices";
}
}
export interface DevicesShape {
readonly register: (input: {
+21 -13
View File
@@ -5,7 +5,6 @@ import type {
} from "@t3tools/contracts/relay";
import { RelayAgentActivityAggregateState as RelayAgentActivityAggregateStateSchema } from "@t3tools/contracts/relay";
import * as Context from "effect/Context";
import * as Data from "effect/Data";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import { cast } from "effect/Function";
@@ -16,23 +15,32 @@ import { and, eq, sql } from "drizzle-orm";
import { RelayDb } from "../db.ts";
import { relayLiveActivities, relayMobileDevices } from "../persistence/schema.ts";
export class LiveActivityRegistrationPersistenceError extends Data.TaggedError(
export class LiveActivityRegistrationPersistenceError extends Schema.TaggedErrorClass<LiveActivityRegistrationPersistenceError>()(
"LiveActivityRegistrationPersistenceError",
)<{
readonly cause: unknown;
}> {}
{ cause: Schema.Defect() },
) {
override get message(): string {
return "Failed to persist Live Activity registration";
}
}
export class LiveActivityTargetListPersistenceError extends Data.TaggedError(
export class LiveActivityTargetListPersistenceError extends Schema.TaggedErrorClass<LiveActivityTargetListPersistenceError>()(
"LiveActivityTargetListPersistenceError",
)<{
readonly cause: unknown;
}> {}
{ cause: Schema.Defect() },
) {
override get message(): string {
return "Failed to list Live Activity delivery targets";
}
}
export class LiveActivityDeliveryMarkPersistenceError extends Data.TaggedError(
export class LiveActivityDeliveryMarkPersistenceError extends Schema.TaggedErrorClass<LiveActivityDeliveryMarkPersistenceError>()(
"LiveActivityDeliveryMarkPersistenceError",
)<{
readonly cause: unknown;
}> {}
{ cause: Schema.Defect() },
) {
override get message(): string {
return "Failed to persist Live Activity delivery state";
}
}
export interface DeviceRow {
readonly user_id: string;
@@ -2,7 +2,6 @@ import * as NodeCrypto from "node:crypto";
import { RelayAgentActivityAggregateState, type RelayDeliveryKind } from "@t3tools/contracts/relay";
import { stableStringify } from "@t3tools/shared/relaySigning";
import * as Data from "effect/Data";
import * as DateTime from "effect/DateTime";
import * as Option from "effect/Option";
import * as Redacted from "effect/Redacted";
@@ -50,13 +49,23 @@ export const SignedApnsDeliveryJob = Schema.Struct({
});
export type SignedApnsDeliveryJob = typeof SignedApnsDeliveryJob.Type;
export class ApnsDeliveryJobInvalid extends Data.TaggedError("ApnsDeliveryJobInvalid")<{
readonly message: string;
}> {}
export class ApnsDeliveryJobInvalid extends Schema.TaggedErrorClass<ApnsDeliveryJobInvalid>()(
"ApnsDeliveryJobInvalid",
{
message: Schema.String,
},
) {}
export class ApnsDeliveryJobExpired extends Data.TaggedError("ApnsDeliveryJobExpired")<{
readonly expiresAt: string;
}> {}
export class ApnsDeliveryJobExpired extends Schema.TaggedErrorClass<ApnsDeliveryJobExpired>()(
"ApnsDeliveryJobExpired",
{
expiresAt: Schema.String,
},
) {
override get message(): string {
return `APNs delivery job expired at ${this.expiresAt}`;
}
}
export type ApnsDeliveryJobVerificationError = ApnsDeliveryJobInvalid | ApnsDeliveryJobExpired;
+10 -5
View File
@@ -1,8 +1,8 @@
import * as Context from "effect/Context";
import * as Data from "effect/Data";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Schema from "effect/Schema";
import * as HttpApiError from "effect/unstable/httpapi/HttpApiError";
import { lt } from "drizzle-orm";
@@ -10,11 +10,16 @@ import { verifyDpopProof } from "@t3tools/shared/dpop";
import { RelayDb } from "../db.ts";
import { relayDpopProofs } from "../persistence/schema.ts";
export class DpopProofReplayPersistenceError extends Data.TaggedError(
export class DpopProofReplayPersistenceError extends Schema.TaggedErrorClass<DpopProofReplayPersistenceError>()(
"DpopProofReplayPersistenceError",
)<{
readonly cause: unknown;
}> {}
{
cause: Schema.Defect(),
},
) {
override get message(): string {
return "Failed to persist DPoP proof replay state";
}
}
export interface DpopProofReplayShape {
readonly verifyAndConsume: (input: {
@@ -22,6 +22,7 @@ import * as Redacted from "effect/Redacted";
import * as Result from "effect/Result";
import * as Schema from "effect/Schema";
import * as TestClock from "effect/testing/TestClock";
import * as Tracer from "effect/Tracer";
import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/unstable/http";
import * as EnvironmentLinks from "./EnvironmentLinks.ts";
@@ -50,6 +51,9 @@ const decodeHealthRequestBody = Schema.decodeUnknownSync(
const decodeMintRequestBody = Schema.decodeUnknownSync(
Schema.fromJsonString(RelayCloudMintCredentialRequest),
);
const isEnvironmentConnectNotAuthorized = Schema.is(
EnvironmentConnector.EnvironmentConnectNotAuthorized,
);
function requestBodyText(request: HttpClientRequest.HttpClientRequest): string {
return request.body._tag === "Uint8Array" ? new TextDecoder().decode(request.body.body) : "{}";
@@ -280,7 +284,13 @@ describe("EnvironmentConnector", () => {
expect(Result.isFailure(result)).toBe(true);
if (Result.isFailure(result)) {
expect(result.failure).toBeInstanceOf(EnvironmentConnector.EnvironmentConnectNotAuthorized);
expect(isEnvironmentConnectNotAuthorized(result.failure)).toBe(true);
if (isEnvironmentConnectNotAuthorized(result.failure)) {
expect(result.failure).toMatchObject({
operation: "status",
reason: "endpoint_provider_not_managed",
});
}
}
expect(requestCount).toBe(0);
}).pipe(
@@ -300,6 +310,14 @@ describe("EnvironmentConnector", () => {
it.effect("rejects stale managed endpoints before sending a mint request", () => {
let requestCount = 0;
const spans: Array<Tracer.NativeSpan> = [];
const tracer = Tracer.make({
span: (options) => {
const span = new Tracer.NativeSpan(options);
spans.push(span);
return span;
},
});
const execute = () =>
Effect.sync(() => {
requestCount += 1;
@@ -318,8 +336,27 @@ describe("EnvironmentConnector", () => {
expect(Result.isFailure(result)).toBe(true);
if (Result.isFailure(result)) {
expect(result.failure).toBeInstanceOf(EnvironmentConnector.EnvironmentConnectNotAuthorized);
expect(isEnvironmentConnectNotAuthorized(result.failure)).toBe(true);
if (isEnvironmentConnectNotAuthorized(result.failure)) {
expect(result.failure).toMatchObject({
operation: "connect",
reason: "managed_endpoint_mismatch",
});
}
}
const resolutionSpan = spans.find(
(span) => span.name === "relay.environment_connector.resolve_managed_endpoint",
);
expect(Object.fromEntries(resolutionSpan?.attributes ?? [])).toMatchObject({
"relay.authorization.allocation_hostname": "env.example.test",
"relay.authorization.allocation_has_ready_at": true,
"relay.authorization.allocation_has_tunnel_id": true,
"relay.authorization.allocation_has_dns_record_id": true,
"relay.authorization.linked_http_base_url": "https://attacker.example.test/",
"relay.authorization.linked_ws_base_url": "wss://attacker.example.test/ws",
"relay.authorization.resolved_http_base_url": "https://env.example.test/",
"relay.authorization.resolved_ws_base_url": "wss://env.example.test/ws",
});
expect(requestCount).toBe(0);
}).pipe(
Effect.provide(
@@ -333,6 +370,7 @@ describe("EnvironmentConnector", () => {
}),
}),
),
Effect.provideService(Tracer.Tracer, tracer),
);
});
@@ -355,7 +393,13 @@ describe("EnvironmentConnector", () => {
expect(Result.isFailure(result)).toBe(true);
if (Result.isFailure(result)) {
expect(result.failure).toBeInstanceOf(EnvironmentConnector.EnvironmentConnectNotAuthorized);
expect(isEnvironmentConnectNotAuthorized(result.failure)).toBe(true);
if (isEnvironmentConnectNotAuthorized(result.failure)) {
expect(result.failure).toMatchObject({
operation: "status",
reason: "managed_endpoint_allocation_not_ready",
});
}
}
expect(requestCount).toBe(0);
}).pipe(
@@ -28,7 +28,6 @@ import {
import { stableStringify } from "@t3tools/shared/relaySigning";
import * as Context from "effect/Context";
import * as Crypto from "effect/Crypto";
import * as Data from "effect/Data";
import * as DateTime from "effect/DateTime";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
@@ -41,29 +40,93 @@ import { FetchHttpClient, HttpClient } from "effect/unstable/http";
import * as EnvironmentLinks from "./EnvironmentLinks.ts";
import * as ManagedEndpointAllocations from "./ManagedEndpointAllocations.ts";
import * as RelayConfiguration from "../Config.ts";
import { isManagedEndpointHostname } from "../deploymentConfig.ts";
export class EnvironmentConnectNotAuthorized extends Data.TaggedError(
export const EnvironmentConnectNotAuthorizedReason = Schema.Literals([
"client_proof_key_thumbprint_missing",
"environment_link_not_found",
"endpoint_provider_not_managed",
"managed_endpoint_allocation_not_found",
"managed_endpoint_base_domain_not_configured",
"managed_endpoint_allocation_not_ready",
"managed_endpoint_hostname_invalid",
"managed_endpoint_mismatch",
]);
export type EnvironmentConnectNotAuthorizedReason =
typeof EnvironmentConnectNotAuthorizedReason.Type;
function environmentConnectNotAuthorizedReasonMessage(
reason: EnvironmentConnectNotAuthorizedReason,
): string {
switch (reason) {
case "client_proof_key_thumbprint_missing":
return "the client proof key thumbprint is missing";
case "environment_link_not_found":
return "no active environment link was found";
case "endpoint_provider_not_managed":
return "the linked endpoint is not relay-managed";
case "managed_endpoint_allocation_not_found":
return "no managed endpoint allocation was found";
case "managed_endpoint_base_domain_not_configured":
return "the managed endpoint base domain is not configured";
case "managed_endpoint_allocation_not_ready":
return "the managed endpoint allocation is incomplete";
case "managed_endpoint_hostname_invalid":
return "the managed endpoint hostname is invalid";
case "managed_endpoint_mismatch":
return "the linked endpoint does not match its managed allocation";
}
}
export class EnvironmentConnectNotAuthorized extends Schema.TaggedErrorClass<EnvironmentConnectNotAuthorized>()(
"EnvironmentConnectNotAuthorized",
)<{
readonly environmentId: string;
}> {}
{
environmentId: Schema.String,
operation: Schema.Literals(["connect", "status"]),
reason: EnvironmentConnectNotAuthorizedReason,
},
) {
override get message(): string {
return `Environment '${this.environmentId}' is not authorized for ${this.operation}: ${environmentConnectNotAuthorizedReasonMessage(this.reason)}`;
}
}
export class EnvironmentMintRequestFailed extends Data.TaggedError("EnvironmentMintRequestFailed")<{
readonly cause: unknown;
}> {}
export class EnvironmentMintRequestFailed extends Schema.TaggedErrorClass<EnvironmentMintRequestFailed>()(
"EnvironmentMintRequestFailed",
{
environmentId: Schema.String,
operation: Schema.Literals(["connect", "status"]),
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Environment '${this.environmentId}' ${this.operation} request failed`;
}
}
export class EnvironmentMintRequestTimedOut extends Data.TaggedError(
export class EnvironmentMintRequestTimedOut extends Schema.TaggedErrorClass<EnvironmentMintRequestTimedOut>()(
"EnvironmentMintRequestTimedOut",
)<{
readonly environmentId: string;
readonly timeoutMs: number;
}> {}
{
environmentId: Schema.String,
timeoutMs: Schema.Number,
},
) {
override get message(): string {
return `Environment '${this.environmentId}' mint request timed out after ${this.timeoutMs}ms`;
}
}
export class EnvironmentMintResponseInvalid extends Data.TaggedError(
export class EnvironmentMintResponseInvalid extends Schema.TaggedErrorClass<EnvironmentMintResponseInvalid>()(
"EnvironmentMintResponseInvalid",
)<{
readonly environmentId: string;
}> {}
{
environmentId: Schema.String,
operation: Schema.Literals(["connect", "status"]),
},
) {
override get message(): string {
return `Environment '${this.environmentId}' returned an invalid ${this.operation} response`;
}
}
export type EnvironmentConnectorError =
| EnvironmentConnectNotAuthorized
@@ -233,30 +296,91 @@ const make = Effect.gen(function* () {
const resolveManagedEndpoint = Effect.fn("relay.environment_connector.resolve_managed_endpoint")(
function* (input: {
readonly userId: string;
readonly operation: "connect" | "status";
readonly link: EnvironmentLinks.RelayLinkedEnvironmentRecord;
}) {
if (input.link.endpoint.providerKind !== "cloudflare_tunnel") {
yield* Effect.annotateCurrentSpan({
"relay.authorization.endpoint_provider_kind": input.link.endpoint.providerKind,
});
return yield* new EnvironmentConnectNotAuthorized({
environmentId: input.link.environmentId,
operation: input.operation,
reason: "endpoint_provider_not_managed",
});
}
const allocation = yield* allocations.get({
userId: input.userId,
environmentId: input.link.environmentId,
});
const endpoint = allocation
? ManagedEndpointAllocations.resolveReadyManagedEndpoint({
allocation,
baseDomain: settings.managedEndpointBaseDomain,
})
: null;
if (!allocation) {
return yield* new EnvironmentConnectNotAuthorized({
environmentId: input.link.environmentId,
operation: input.operation,
reason: "managed_endpoint_allocation_not_found",
});
}
const allocationAttributes = {
"relay.authorization.allocation_hostname": allocation.hostname,
"relay.authorization.allocation_has_ready_at": allocation.readyAt !== null,
"relay.authorization.allocation_has_tunnel_id": allocation.tunnelId !== null,
"relay.authorization.allocation_has_dns_record_id": allocation.dnsRecordId !== null,
} as const;
if (!settings.managedEndpointBaseDomain) {
yield* Effect.annotateCurrentSpan(allocationAttributes);
return yield* new EnvironmentConnectNotAuthorized({
environmentId: input.link.environmentId,
operation: input.operation,
reason: "managed_endpoint_base_domain_not_configured",
});
}
if (
allocation.readyAt === null ||
allocation.tunnelId === null ||
allocation.dnsRecordId === null
) {
yield* Effect.annotateCurrentSpan(allocationAttributes);
return yield* new EnvironmentConnectNotAuthorized({
environmentId: input.link.environmentId,
operation: input.operation,
reason: "managed_endpoint_allocation_not_ready",
});
}
if (!isManagedEndpointHostname(allocation.hostname, settings.managedEndpointBaseDomain)) {
yield* Effect.annotateCurrentSpan({
...allocationAttributes,
"relay.authorization.managed_endpoint_base_domain": settings.managedEndpointBaseDomain,
});
return yield* new EnvironmentConnectNotAuthorized({
environmentId: input.link.environmentId,
operation: input.operation,
reason: "managed_endpoint_hostname_invalid",
});
}
const endpoint = ManagedEndpointAllocations.resolveReadyManagedEndpoint({
allocation,
baseDomain: settings.managedEndpointBaseDomain,
});
if (
endpoint === null ||
endpoint.httpBaseUrl !== input.link.endpoint.httpBaseUrl ||
endpoint.wsBaseUrl !== input.link.endpoint.wsBaseUrl
) {
yield* Effect.annotateCurrentSpan({
...allocationAttributes,
"relay.authorization.linked_http_base_url": input.link.endpoint.httpBaseUrl,
"relay.authorization.linked_ws_base_url": input.link.endpoint.wsBaseUrl,
...(endpoint
? {
"relay.authorization.resolved_http_base_url": endpoint.httpBaseUrl,
"relay.authorization.resolved_ws_base_url": endpoint.wsBaseUrl,
}
: {}),
});
return yield* new EnvironmentConnectNotAuthorized({
environmentId: input.link.environmentId,
operation: input.operation,
reason: "managed_endpoint_mismatch",
});
}
return endpoint;
@@ -271,20 +395,42 @@ const make = Effect.gen(function* () {
});
const link = yield* links.getForUser(input);
if (!link) {
return yield* new EnvironmentConnectNotAuthorized({ environmentId: input.environmentId });
return yield* new EnvironmentConnectNotAuthorized({
environmentId: input.environmentId,
operation: "status",
reason: "environment_link_not_found",
});
}
const endpoint = yield* resolveManagedEndpoint({ userId: input.userId, link });
const endpoint = yield* resolveManagedEndpoint({
userId: input.userId,
operation: "status",
link,
});
const now = yield* DateTime.now;
const expiresAt = DateTime.add(now, { minutes: 2 });
const nonce = yield* crypto.randomUUIDv4.pipe(
Effect.mapError((cause) => new EnvironmentMintRequestFailed({ cause })),
Effect.mapError(
(cause) =>
new EnvironmentMintRequestFailed({
environmentId: input.environmentId,
operation: "status",
cause,
}),
),
);
const payload = {
iss: relayIssuer,
aud: `t3-env:${link.environmentId}`,
sub: input.userId,
jti: yield* crypto.randomUUIDv4.pipe(
Effect.mapError((cause) => new EnvironmentMintRequestFailed({ cause })),
Effect.mapError(
(cause) =>
new EnvironmentMintRequestFailed({
environmentId: input.environmentId,
operation: "status",
cause,
}),
),
),
iat: Math.floor(now.epochMilliseconds / 1_000),
exp: Math.floor(expiresAt.epochMilliseconds / 1_000),
@@ -296,7 +442,16 @@ const make = Effect.gen(function* () {
privateKey: Redacted.value(settings.cloudMintPrivateKey),
typ: RELAY_HEALTH_REQUEST_TYP,
payload,
}).pipe(Effect.mapError((cause) => new EnvironmentMintRequestFailed({ cause })));
}).pipe(
Effect.mapError(
(cause) =>
new EnvironmentMintRequestFailed({
environmentId: input.environmentId,
operation: "status",
cause,
}),
),
);
const checkedAt = DateTime.formatIso(now);
const environmentClient = yield* makeEnvironmentClient(endpoint.httpBaseUrl);
const responseOption = yield* environmentClient.cloud.health({ payload: { proof } }).pipe(
@@ -336,7 +491,10 @@ const make = Effect.gen(function* () {
now: yield* DateTime.now,
});
if (!verified) {
return yield* new EnvironmentMintResponseInvalid({ environmentId: input.environmentId });
return yield* new EnvironmentMintResponseInvalid({
environmentId: input.environmentId,
operation: "status",
});
}
return {
environmentId: link.environmentId,
@@ -354,24 +512,50 @@ const make = Effect.gen(function* () {
...(input.deviceId ? { "relay.mobile.device_id": input.deviceId } : {}),
});
if (input.clientProofKeyThumbprint.trim().length === 0) {
return yield* new EnvironmentConnectNotAuthorized({ environmentId: input.environmentId });
return yield* new EnvironmentConnectNotAuthorized({
environmentId: input.environmentId,
operation: "connect",
reason: "client_proof_key_thumbprint_missing",
});
}
const link = yield* links.getForUser(input);
if (!link) {
return yield* new EnvironmentConnectNotAuthorized({ environmentId: input.environmentId });
return yield* new EnvironmentConnectNotAuthorized({
environmentId: input.environmentId,
operation: "connect",
reason: "environment_link_not_found",
});
}
const endpoint = yield* resolveManagedEndpoint({ userId: input.userId, link });
const endpoint = yield* resolveManagedEndpoint({
userId: input.userId,
operation: "connect",
link,
});
const now = yield* DateTime.now;
const expiresAt = DateTime.add(now, { minutes: 2 });
const nonce = yield* crypto.randomUUIDv4.pipe(
Effect.mapError((cause) => new EnvironmentMintRequestFailed({ cause })),
Effect.mapError(
(cause) =>
new EnvironmentMintRequestFailed({
environmentId: input.environmentId,
operation: "connect",
cause,
}),
),
);
const payload = {
iss: relayIssuer,
aud: `t3-env:${link.environmentId}`,
sub: input.userId,
jti: yield* crypto.randomUUIDv4.pipe(
Effect.mapError((cause) => new EnvironmentMintRequestFailed({ cause })),
Effect.mapError(
(cause) =>
new EnvironmentMintRequestFailed({
environmentId: input.environmentId,
operation: "connect",
cause,
}),
),
),
iat: Math.floor(now.epochMilliseconds / 1_000),
exp: Math.floor(expiresAt.epochMilliseconds / 1_000),
@@ -386,11 +570,27 @@ const make = Effect.gen(function* () {
privateKey: Redacted.value(settings.cloudMintPrivateKey),
typ: RELAY_MINT_REQUEST_TYP,
payload,
}).pipe(Effect.mapError((cause) => new EnvironmentMintRequestFailed({ cause })));
}).pipe(
Effect.mapError(
(cause) =>
new EnvironmentMintRequestFailed({
environmentId: input.environmentId,
operation: "connect",
cause,
}),
),
);
const environmentClient = yield* makeEnvironmentClient(endpoint.httpBaseUrl);
const decoded = yield* environmentClient.cloud.t3MintCredential({ payload: { proof } }).pipe(
withoutRedirects,
Effect.mapError((cause) => new EnvironmentMintRequestFailed({ cause })),
Effect.mapError(
(cause) =>
new EnvironmentMintRequestFailed({
environmentId: input.environmentId,
operation: "connect",
cause,
}),
),
Effect.timeoutOption(Duration.millis(ENVIRONMENT_MINT_REQUEST_TIMEOUT_MS)),
Effect.flatMap(
Option.match({
@@ -415,7 +615,10 @@ const make = Effect.gen(function* () {
nowEpochSeconds: Math.floor(now.epochMilliseconds / 1_000),
});
if (!verified) {
return yield* new EnvironmentMintResponseInvalid({ environmentId: input.environmentId });
return yield* new EnvironmentMintResponseInvalid({
environmentId: input.environmentId,
operation: "connect",
});
}
return {
environmentId: link.environmentId,
@@ -1,33 +1,42 @@
import * as Context from "effect/Context";
import * as Crypto from "effect/Crypto";
import * as Data from "effect/Data";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Encoding from "effect/Encoding";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import { and, eq, isNull, ne, notExists } from "drizzle-orm";
import { RelayDb } from "../db.ts";
import { relayEnvironmentCredentials, relayEnvironmentLinks } from "../persistence/schema.ts";
export class EnvironmentCredentialCreatePersistenceError extends Data.TaggedError(
export class EnvironmentCredentialCreatePersistenceError extends Schema.TaggedErrorClass<EnvironmentCredentialCreatePersistenceError>()(
"EnvironmentCredentialCreatePersistenceError",
)<{
readonly cause: unknown;
}> {}
{ cause: Schema.Defect() },
) {
override get message(): string {
return "Failed to persist environment credential";
}
}
export class EnvironmentCredentialAuthenticatePersistenceError extends Data.TaggedError(
export class EnvironmentCredentialAuthenticatePersistenceError extends Schema.TaggedErrorClass<EnvironmentCredentialAuthenticatePersistenceError>()(
"EnvironmentCredentialAuthenticatePersistenceError",
)<{
readonly cause: unknown;
}> {}
{ cause: Schema.Defect() },
) {
override get message(): string {
return "Failed to authenticate environment credential";
}
}
export class EnvironmentCredentialRevokePersistenceError extends Data.TaggedError(
export class EnvironmentCredentialRevokePersistenceError extends Schema.TaggedErrorClass<EnvironmentCredentialRevokePersistenceError>()(
"EnvironmentCredentialRevokePersistenceError",
)<{
readonly cause: unknown;
}> {}
{ cause: Schema.Defect() },
) {
override get message(): string {
return "Failed to revoke environment credential";
}
}
export interface EnvironmentCredentialPrincipal {
readonly credentialId: string;
@@ -1,6 +1,6 @@
import {
RelayEnvironmentLinkProofPayload,
type RelayEnvironmentLinkProofInvalidReason,
RelayEnvironmentLinkProofInvalidReason,
type RelayEnvironmentLinkRequest,
} from "@t3tools/contracts/relay";
import {
@@ -10,7 +10,6 @@ import {
verifyRelayJwt,
} from "@t3tools/shared/relayJwt";
import * as Context from "effect/Context";
import * as Data from "effect/Data";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
@@ -23,14 +22,28 @@ import * as EnvironmentLinks from "./EnvironmentLinks.ts";
import * as ManagedEndpointProvider from "./ManagedEndpointProvider.ts";
import * as RelayConfiguration from "../Config.ts";
export class EnvironmentLinkProofExpired extends Data.TaggedError("EnvironmentLinkProofExpired")<{
readonly expiresAt: string;
}> {}
export class EnvironmentLinkProofExpired extends Schema.TaggedErrorClass<EnvironmentLinkProofExpired>()(
"EnvironmentLinkProofExpired",
{
expiresAt: Schema.String,
},
) {
override get message(): string {
return `Environment link proof expired at ${this.expiresAt}`;
}
}
export class EnvironmentLinkProofInvalid extends Data.TaggedError("EnvironmentLinkProofInvalid")<{
readonly environmentId: string;
readonly reason: RelayEnvironmentLinkProofInvalidReason;
}> {}
export class EnvironmentLinkProofInvalid extends Schema.TaggedErrorClass<EnvironmentLinkProofInvalid>()(
"EnvironmentLinkProofInvalid",
{
environmentId: Schema.String,
reason: RelayEnvironmentLinkProofInvalidReason,
},
) {
override get message(): string {
return `Environment '${this.environmentId}' link proof is invalid: ${this.reason}`;
}
}
export type EnvironmentLinkError =
| EnvironmentLinkProofExpired
@@ -5,10 +5,10 @@ import type {
RelayManagedEndpoint,
} from "@t3tools/contracts/relay";
import * as Context from "effect/Context";
import * as Data from "effect/Data";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Schema from "effect/Schema";
import { and, eq, isNull, or } from "drizzle-orm";
import { RelayDb } from "../db.ts";
@@ -24,41 +24,59 @@ export interface AgentAwarenessDeliveryUserRecord {
readonly liveActivitiesEnabled: boolean;
}
export class EnvironmentLinkUpsertPersistenceError extends Data.TaggedError(
export class EnvironmentLinkUpsertPersistenceError extends Schema.TaggedErrorClass<EnvironmentLinkUpsertPersistenceError>()(
"EnvironmentLinkUpsertPersistenceError",
)<{
readonly cause: unknown;
}> {}
{ cause: Schema.Defect() },
) {
override get message(): string {
return "Failed to persist environment link";
}
}
export class EnvironmentLinkUserListPersistenceError extends Data.TaggedError(
export class EnvironmentLinkUserListPersistenceError extends Schema.TaggedErrorClass<EnvironmentLinkUserListPersistenceError>()(
"EnvironmentLinkUserListPersistenceError",
)<{
readonly cause: unknown;
}> {}
{ cause: Schema.Defect() },
) {
override get message(): string {
return "Failed to list users linked to environment";
}
}
export class EnvironmentPublicKeyListPersistenceError extends Data.TaggedError(
export class EnvironmentPublicKeyListPersistenceError extends Schema.TaggedErrorClass<EnvironmentPublicKeyListPersistenceError>()(
"EnvironmentPublicKeyListPersistenceError",
)<{
readonly cause: unknown;
}> {}
{ cause: Schema.Defect() },
) {
override get message(): string {
return "Failed to list environment public keys";
}
}
export class EnvironmentLinkListPersistenceError extends Data.TaggedError(
export class EnvironmentLinkListPersistenceError extends Schema.TaggedErrorClass<EnvironmentLinkListPersistenceError>()(
"EnvironmentLinkListPersistenceError",
)<{
readonly cause: unknown;
}> {}
{ cause: Schema.Defect() },
) {
override get message(): string {
return "Failed to list environment links";
}
}
export class EnvironmentLinkLookupPersistenceError extends Data.TaggedError(
export class EnvironmentLinkLookupPersistenceError extends Schema.TaggedErrorClass<EnvironmentLinkLookupPersistenceError>()(
"EnvironmentLinkLookupPersistenceError",
)<{
readonly cause: unknown;
}> {}
{ cause: Schema.Defect() },
) {
override get message(): string {
return "Failed to look up environment link";
}
}
export class EnvironmentLinkRevokePersistenceError extends Data.TaggedError(
export class EnvironmentLinkRevokePersistenceError extends Schema.TaggedErrorClass<EnvironmentLinkRevokePersistenceError>()(
"EnvironmentLinkRevokePersistenceError",
)<{
readonly cause: unknown;
}> {}
{ cause: Schema.Defect() },
) {
override get message(): string {
return "Failed to revoke environment link";
}
}
export interface EnvironmentLinksShape {
readonly upsert: (input: {
@@ -11,7 +11,6 @@ import {
import { stableStringify } from "@t3tools/shared/relaySigning";
import * as Context from "effect/Context";
import * as Crypto from "effect/Crypto";
import * as Data from "effect/Data";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Encoding from "effect/Encoding";
@@ -21,23 +20,38 @@ import * as Schema from "effect/Schema";
import * as DpopProofs from "../auth/DpopProofs.ts";
import * as RelayConfiguration from "../Config.ts";
export class EnvironmentPublishSignatureExpired extends Data.TaggedError(
export class EnvironmentPublishSignatureExpired extends Schema.TaggedErrorClass<EnvironmentPublishSignatureExpired>()(
"EnvironmentPublishSignatureExpired",
)<{
readonly expiresAt: string;
}> {}
{
expiresAt: Schema.String,
},
) {
override get message(): string {
return `Environment publish signature expired at ${this.expiresAt}`;
}
}
export class EnvironmentPublishSignatureInvalid extends Data.TaggedError(
export class EnvironmentPublishSignatureInvalid extends Schema.TaggedErrorClass<EnvironmentPublishSignatureInvalid>()(
"EnvironmentPublishSignatureInvalid",
)<{
readonly environmentId: string;
}> {}
{
environmentId: Schema.String,
},
) {
override get message(): string {
return `Environment '${this.environmentId}' publish signature is invalid`;
}
}
export class EnvironmentPublishPublicKeyMissing extends Data.TaggedError(
export class EnvironmentPublishPublicKeyMissing extends Schema.TaggedErrorClass<EnvironmentPublishPublicKeyMissing>()(
"EnvironmentPublishPublicKeyMissing",
)<{
readonly environmentId: string;
}> {}
{
environmentId: Schema.String,
},
) {
override get message(): string {
return `Environment '${this.environmentId}' has no publish public key`;
}
}
export type EnvironmentPublishSignatureError =
| EnvironmentPublishSignatureExpired
@@ -1,10 +1,10 @@
import type { RelayManagedEndpoint } from "@t3tools/contracts/relay";
import { and, eq } from "drizzle-orm";
import * as Context from "effect/Context";
import * as Data from "effect/Data";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Schema from "effect/Schema";
import { RelayDb } from "../db.ts";
import { isManagedEndpointHostname, managedEndpointForHostname } from "../deploymentConfig.ts";
@@ -36,11 +36,17 @@ export function resolveReadyManagedEndpoint(input: {
return managedEndpointForHostname(input.allocation.hostname);
}
export class ManagedEndpointAllocationPersistenceError extends Data.TaggedError(
export class ManagedEndpointAllocationPersistenceError extends Schema.TaggedErrorClass<ManagedEndpointAllocationPersistenceError>()(
"ManagedEndpointAllocationPersistenceError",
)<{
readonly cause: unknown;
}> {}
{ cause: Schema.Defect() },
) {
override get message(): string {
return "Failed to persist managed endpoint allocation";
}
}
const isManagedEndpointAllocationPersistenceError = Schema.is(
ManagedEndpointAllocationPersistenceError,
);
interface ManagedEndpointAllocationKey {
readonly userId: string;
@@ -98,7 +104,7 @@ const whereAllocation = (input: ManagedEndpointAllocationKey) =>
);
const persistenceError = (cause: unknown) =>
cause instanceof ManagedEndpointAllocationPersistenceError
isManagedEndpointAllocationPersistenceError(cause)
? cause
: new ManagedEndpointAllocationPersistenceError({ cause });
@@ -3,12 +3,12 @@ import * as Cloudflare from "alchemy/Cloudflare";
import * as Arr from "effect/Array";
import * as Context from "effect/Context";
import * as Crypto from "effect/Crypto";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import * as Encoding from "effect/Encoding";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Result from "effect/Result";
import * as Schema from "effect/Schema";
import type {
RelayManagedEndpoint,
@@ -25,28 +25,44 @@ import {
} from "../deploymentConfig.ts";
import { ManagedEndpointAllocations } from "./ManagedEndpointAllocations.ts";
export class ManagedEndpointProvisioningNotConfigured extends Data.TaggedError(
export class ManagedEndpointProvisioningNotConfigured extends Schema.TaggedErrorClass<ManagedEndpointProvisioningNotConfigured>()(
"ManagedEndpointProvisioningNotConfigured",
)<{}> {}
{},
) {
override get message(): string {
return "Managed endpoint provisioning is not configured";
}
}
export class ManagedEndpointProvisioningFailed extends Data.TaggedError(
export class ManagedEndpointProvisioningFailed extends Schema.TaggedErrorClass<ManagedEndpointProvisioningFailed>()(
"ManagedEndpointProvisioningFailed",
)<{
readonly cause: unknown;
}> {}
{ cause: Schema.Defect() },
) {
override get message(): string {
return "Managed endpoint provisioning failed";
}
}
export class ManagedEndpointDeprovisioningFailed extends Data.TaggedError(
export class ManagedEndpointDeprovisioningFailed extends Schema.TaggedErrorClass<ManagedEndpointDeprovisioningFailed>()(
"ManagedEndpointDeprovisioningFailed",
)<{
readonly cause: unknown;
}> {}
{ cause: Schema.Defect() },
) {
override get message(): string {
return "Managed endpoint deprovisioning failed";
}
}
export class ManagedEndpointOriginNotAllowed extends Data.TaggedError(
export class ManagedEndpointOriginNotAllowed extends Schema.TaggedErrorClass<ManagedEndpointOriginNotAllowed>()(
"ManagedEndpointOriginNotAllowed",
)<{
readonly host: string;
readonly port: number;
}> {}
{
host: Schema.String,
port: Schema.Number,
},
) {
override get message(): string {
return `Managed endpoint origin '${this.host}:${this.port}' is not allowed`;
}
}
export type ManagedEndpointProviderError =
| ManagedEndpointProvisioningNotConfigured
@@ -80,11 +96,14 @@ interface ManagedEndpointTunnel {
readonly name?: string | null;
}
export class ManagedEndpointTunnelClientError extends Data.TaggedError(
export class ManagedEndpointTunnelClientError extends Schema.TaggedErrorClass<ManagedEndpointTunnelClientError>()(
"ManagedEndpointTunnelClientError",
)<{
readonly cause: unknown;
}> {}
{ cause: Schema.Defect() },
) {
override get message(): string {
return "Managed endpoint tunnel provider request failed";
}
}
export interface ManagedEndpointTunnelClientShape {
readonly list: (request: {
@@ -124,11 +143,14 @@ interface ManagedEndpointCnameRecordInput {
readonly proxied: true;
}
export class ManagedEndpointDnsClientError extends Data.TaggedError(
export class ManagedEndpointDnsClientError extends Schema.TaggedErrorClass<ManagedEndpointDnsClientError>()(
"ManagedEndpointDnsClientError",
)<{
readonly cause: unknown;
}> {}
{ cause: Schema.Defect() },
) {
override get message(): string {
return "Managed endpoint DNS provider request failed";
}
}
export interface ManagedEndpointDnsClientShape {
readonly listRecords: (
+14 -11
View File
@@ -1,6 +1,5 @@
import { createClerkClient, verifyToken } from "@clerk/backend";
import { sql as drizzleSql } from "drizzle-orm";
import * as Data from "effect/Data";
import * as Crypto from "effect/Crypto";
import * as Context from "effect/Context";
import * as DateTime from "effect/DateTime";
@@ -813,9 +812,16 @@ export const serverApi = HttpApiBuilder.group(
}),
);
class ClerkTokenVerificationFailed extends Data.TaggedError("ClerkTokenVerificationFailed")<{
readonly cause: unknown;
}> {}
class ClerkTokenVerificationFailed extends Schema.TaggedErrorClass<ClerkTokenVerificationFailed>()(
"ClerkTokenVerificationFailed",
{
cause: Schema.Defect(),
},
) {
override get message(): string {
return "Clerk token verification failed";
}
}
const isHttpUnauthorized = Schema.is(HttpApiError.Unauthorized);
@@ -824,7 +830,7 @@ const currentTraceId = Effect.currentParentSpan.pipe(
Effect.orElseSucceed(() => "unavailable"),
);
const COMMON_AUTH_INVALID_REASONS = [
const RelayCommonPersistenceError = Schema.Union([
Devices.DeviceRegistrationPersistenceError,
Devices.DeviceUnregistrationPersistenceError,
Devices.DeviceListPersistenceError,
@@ -844,18 +850,15 @@ const COMMON_AUTH_INVALID_REASONS = [
AgentActivityRows.AgentActivityRowListPersistenceError,
LiveActivities.LiveActivityDeliveryMarkPersistenceError,
DeliveryAttempts.DeliveryAttemptRecordPersistenceError,
] as const;
type RelayCommonPersistenceError = InstanceType<(typeof COMMON_AUTH_INVALID_REASONS)[number]>;
]);
type RelayCommonPersistenceError = typeof RelayCommonPersistenceError.Type;
const isRelayCommonPersistenceError = Schema.is(RelayCommonPersistenceError);
type MapRelayCommonApiError<E> =
| Exclude<E, HttpApiError.Unauthorized | RelayCommonPersistenceError>
| (Extract<E, HttpApiError.Unauthorized> extends never ? never : RelayAuthInvalidError)
| (Extract<E, RelayCommonPersistenceError> extends never ? never : RelayInternalError);
function isRelayCommonPersistenceError(error: unknown): error is RelayCommonPersistenceError {
return COMMON_AUTH_INVALID_REASONS.some((ErrorType) => error instanceof ErrorType);
}
function relayInternalErrorResponse(reason: RelayInternalError["reason"]) {
return currentTraceId.pipe(
Effect.flatMap((traceId) =>
+85
View File
@@ -0,0 +1,85 @@
import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer";
import { expect, it } from "@effect/vitest";
import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
import * as Redacted from "effect/Redacted";
import * as Schema from "effect/Schema";
import * as HttpServer from "effect/unstable/http/HttpServer";
import * as HttpServerRequest from "effect/unstable/http/HttpServerRequest";
import * as HttpServerResponse from "effect/unstable/http/HttpServerResponse";
import type { OtlpTracer } from "effect/unstable/observability";
import { EnvironmentConnectNotAuthorized } from "./environments/EnvironmentConnector.ts";
import { makeRelayTraceLayer } from "./observability.ts";
interface ExportedRequest {
readonly authorization: string | undefined;
readonly body: string;
readonly dataset: string | undefined;
}
const otlpAttributeValue = (value: {
readonly stringValue?: string | null;
readonly boolValue?: boolean | null;
readonly intValue?: number | null;
readonly doubleValue?: number | null;
}) => value.stringValue ?? value.boolValue ?? value.intValue ?? value.doubleValue;
const decodeJson = Schema.decodeUnknownEffect(Schema.UnknownFromJsonString);
it.effect("exports schema error fields as span attributes", () =>
Effect.gen(function* () {
const exportedRequest = yield* Deferred.make<ExportedRequest>();
yield* HttpServer.serveEffect(
Effect.gen(function* () {
const request = yield* HttpServerRequest.HttpServerRequest;
yield* Deferred.succeed(exportedRequest, {
authorization: request.headers.authorization,
body: yield* request.text,
dataset: request.headers["x-axiom-dataset"],
});
return HttpServerResponse.empty({ status: 204 });
}),
);
yield* Effect.fail(
new EnvironmentConnectNotAuthorized({
environmentId: "environment-1",
operation: "connect",
reason: "managed_endpoint_allocation_not_ready",
}),
).pipe(
Effect.withSpan("relay.test.schema_error"),
Effect.exit,
Effect.provide(
makeRelayTraceLayer({
tracesEndpoint: "/v1/traces",
tracesDatasetName: "relay-test-traces",
ingestToken: Redacted.make("test-token"),
}),
),
);
const request = yield* Deferred.await(exportedRequest).pipe(Effect.timeout("1 second"));
const payload = (yield* decodeJson(request.body)) as OtlpTracer.TraceData;
const span = payload.resourceSpans
.flatMap((resourceSpan) => resourceSpan.scopeSpans)
.flatMap((scopeSpan) => scopeSpan.spans)
.find((candidate) => candidate.name === "relay.test.schema_error");
const attributes = Object.fromEntries(
(span?.attributes ?? []).map((attribute) => [
attribute.key,
otlpAttributeValue(attribute.value),
]),
);
expect(request.authorization).toBe("Bearer test-token");
expect(request.dataset).toBe("relay-test-traces");
expect(attributes).toMatchObject({
"error.type": "EnvironmentConnectNotAuthorized",
"error.environmentId": "environment-1",
"error.operation": "connect",
"error.reason": "managed_endpoint_allocation_not_ready",
});
}).pipe(Effect.provide(NodeHttpServer.layerTest), Effect.scoped),
);
+160 -15
View File
@@ -1,9 +1,14 @@
import * as Alchemy from "alchemy";
import * as Axiom from "alchemy/Axiom";
import * as Output from "alchemy/Output";
import * as Layer from "effect/Layer";
import * as Cause from "effect/Cause";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Redacted from "effect/Redacted";
import * as Schema from "effect/Schema";
import * as Tracer from "effect/Tracer";
import { OtlpSerialization, OtlpTracer } from "effect/unstable/observability";
import { relayResourceNameForStage } from "./deploymentConfig.ts";
@@ -54,23 +59,163 @@ export const withSpanAttributes =
Effect.andThen(effect.pipe(Effect.annotateSpans(attributes))),
);
const appendEncodedAttributes = (
attributes: Record<string, unknown>,
prefix: string,
value: unknown,
): void => {
if (
value === null ||
typeof value === "string" ||
typeof value === "number" ||
typeof value === "boolean" ||
typeof value === "bigint" ||
Array.isArray(value)
) {
attributes[prefix] = value;
return;
}
if (typeof value !== "object") {
return;
}
for (const [key, child] of Object.entries(value)) {
appendEncodedAttributes(attributes, `${prefix}.${key}`, child);
}
};
const schemaErrorAttributes = (error: unknown): Record<string, unknown> | undefined => {
if (typeof error !== "object" || error === null) {
return undefined;
}
const constructor = error.constructor;
if (!Schema.isSchema(constructor)) {
return undefined;
}
const encoded = Schema.encodeUnknownOption(constructor as unknown as Schema.Encoder<unknown>)(
error,
);
if (Option.isNone(encoded) || typeof encoded.value !== "object" || encoded.value === null) {
return undefined;
}
const tag = Reflect.get(encoded.value, "_tag");
if (typeof tag !== "string") {
return undefined;
}
const attributes: Record<string, unknown> = {
"error.type": tag,
};
for (const [key, value] of Object.entries(encoded.value)) {
if (key !== "_tag") {
appendEncodedAttributes(attributes, `error.${key}`, value);
}
}
return attributes;
};
const annotateSchemaError = (span: Tracer.Span, exit: Exit.Exit<unknown, unknown>): void => {
if (Exit.isSuccess(exit)) {
return;
}
for (const reason of exit.cause.reasons) {
const error = Cause.isFailReason(reason)
? reason.error
: Cause.isDieReason(reason)
? reason.defect
: undefined;
const attributes = schemaErrorAttributes(error);
if (attributes) {
for (const [key, value] of Object.entries(attributes)) {
span.attribute(key, value);
}
return;
}
}
};
class RelayTraceSpan implements Tracer.Span {
readonly _tag = "Span";
private readonly delegate: Tracer.Span;
constructor(delegate: Tracer.Span) {
this.delegate = delegate;
}
get name() {
return this.delegate.name;
}
get spanId() {
return this.delegate.spanId;
}
get traceId() {
return this.delegate.traceId;
}
get parent() {
return this.delegate.parent;
}
get annotations() {
return this.delegate.annotations;
}
get status() {
return this.delegate.status;
}
get attributes() {
return this.delegate.attributes;
}
get links() {
return this.delegate.links;
}
get sampled() {
return this.delegate.sampled;
}
get kind() {
return this.delegate.kind;
}
end(endTime: bigint, exit: Exit.Exit<unknown, unknown>): void {
annotateSchemaError(this.delegate, exit);
this.delegate.end(endTime, exit);
}
attribute(key: string, value: unknown): void {
this.delegate.attribute(key, value);
}
event(name: string, startTime: bigint, attributes?: Record<string, unknown>): void {
this.delegate.event(name, startTime, attributes);
}
addLinks(links: ReadonlyArray<Tracer.SpanLink>): void {
this.delegate.addLinks(links);
}
}
const withSchemaErrorAttributes = (delegate: Tracer.Tracer): Tracer.Tracer =>
Tracer.make({
span: (options) => new RelayTraceSpan(delegate.span(options)),
...(delegate.context ? { context: delegate.context } : {}),
});
export const makeRelayTraceLayer = (input: {
readonly tracesEndpoint: string;
readonly tracesDatasetName: string;
readonly ingestToken: Redacted.Redacted<string>;
}) =>
OtlpTracer.layer({
url: input.tracesEndpoint,
resource: {
serviceName: "t3-code-relay-worker",
attributes: {
"service.runtime": "cloudflare-worker",
"service.component": "relay",
Layer.effect(
Tracer.Tracer,
OtlpTracer.make({
url: input.tracesEndpoint,
resource: {
serviceName: "t3-code-relay-worker",
attributes: {
"service.runtime": "cloudflare-worker",
"service.component": "relay",
},
},
},
headers: {
Authorization: `Bearer ${Redacted.value(input.ingestToken)}`,
"X-Axiom-Dataset": input.tracesDatasetName,
},
exportInterval: "1 second",
}).pipe(Layer.provide(OtlpSerialization.layerJson));
headers: {
Authorization: `Bearer ${Redacted.value(input.ingestToken)}`,
"X-Axiom-Dataset": input.tracesDatasetName,
},
exportInterval: "1 second",
}).pipe(Effect.map(withSchemaErrorAttributes)),
).pipe(Layer.provide(OtlpSerialization.layerJson));
+17
View File
@@ -241,6 +241,7 @@ const ModelReroutedType = Schema.Literal("model.rerouted");
const ConfigWarningType = Schema.Literal("config.warning");
const DeprecationNoticeType = Schema.Literal("deprecation.notice");
const FilesPersistedType = Schema.Literal("files.persisted");
const ToolDeniedType = Schema.Literal("tool.denied");
const RuntimeWarningType = Schema.Literal("runtime.warning");
const RuntimeErrorType = Schema.Literal("runtime.error");
@@ -589,6 +590,14 @@ const FilesPersistedPayload = Schema.Struct({
});
export type FilesPersistedPayload = typeof FilesPersistedPayload.Type;
const ToolDeniedPayload = Schema.Struct({
toolName: TrimmedNonEmptyStringSchema,
toolUseId: Schema.optional(TrimmedNonEmptyStringSchema),
reason: Schema.optional(TrimmedNonEmptyStringSchema),
agentId: Schema.optional(TrimmedNonEmptyStringSchema),
});
export type ToolDeniedPayload = typeof ToolDeniedPayload.Type;
const RuntimeWarningPayload = Schema.Struct({
message: TrimmedNonEmptyStringSchema,
detail: Schema.optional(Schema.Unknown),
@@ -934,6 +943,13 @@ const ProviderRuntimeFilesPersistedEvent = Schema.Struct({
});
export type ProviderRuntimeFilesPersistedEvent = typeof ProviderRuntimeFilesPersistedEvent.Type;
const ProviderRuntimeToolDeniedEvent = Schema.Struct({
...ProviderRuntimeEventBase.fields,
type: ToolDeniedType,
payload: ToolDeniedPayload,
});
export type ProviderRuntimeToolDeniedEvent = typeof ProviderRuntimeToolDeniedEvent.Type;
const ProviderRuntimeWarningEvent = Schema.Struct({
...ProviderRuntimeEventBase.fields,
type: RuntimeWarningType,
@@ -994,6 +1010,7 @@ export const ProviderRuntimeEventV2 = Schema.Union([
ProviderRuntimeConfigWarningEvent,
ProviderRuntimeDeprecationNoticeEvent,
ProviderRuntimeFilesPersistedEvent,
ProviderRuntimeToolDeniedEvent,
ProviderRuntimeWarningEvent,
ProviderRuntimeErrorEvent,
]);
+55 -11
View File
@@ -329,7 +329,11 @@ export class RelayAuthInvalidError extends Schema.TaggedErrorClass<RelayAuthInva
traceId: TrimmedNonEmptyString,
},
{ httpApiStatus: 401 },
) {}
) {
override get message(): string {
return `Relay authentication failed: ${this.reason}`;
}
}
export class RelayEnvironmentLinkProofExpiredError extends Schema.TaggedErrorClass<RelayEnvironmentLinkProofExpiredError>()(
"RelayEnvironmentLinkProofExpiredError",
@@ -338,7 +342,11 @@ export class RelayEnvironmentLinkProofExpiredError extends Schema.TaggedErrorCla
traceId: TrimmedNonEmptyString,
},
{ httpApiStatus: 401 },
) {}
) {
override get message(): string {
return "Relay environment link proof expired";
}
}
export class RelayEnvironmentLinkProofInvalidError extends Schema.TaggedErrorClass<RelayEnvironmentLinkProofInvalidError>()(
"RelayEnvironmentLinkProofInvalidError",
@@ -348,7 +356,11 @@ export class RelayEnvironmentLinkProofInvalidError extends Schema.TaggedErrorCla
traceId: TrimmedNonEmptyString,
},
{ httpApiStatus: 400 },
) {}
) {
override get message(): string {
return `Relay environment link proof is invalid: ${this.reason}`;
}
}
export class RelayEnvironmentConnectNotAuthorizedError extends Schema.TaggedErrorClass<RelayEnvironmentConnectNotAuthorizedError>()(
"RelayEnvironmentConnectNotAuthorizedError",
@@ -357,7 +369,11 @@ export class RelayEnvironmentConnectNotAuthorizedError extends Schema.TaggedErro
traceId: TrimmedNonEmptyString,
},
{ httpApiStatus: 403 },
) {}
) {
override get message(): string {
return "Relay environment connection is not authorized";
}
}
export class RelayEnvironmentEndpointUnavailableError extends Schema.TaggedErrorClass<RelayEnvironmentEndpointUnavailableError>()(
"RelayEnvironmentEndpointUnavailableError",
@@ -367,7 +383,11 @@ export class RelayEnvironmentEndpointUnavailableError extends Schema.TaggedError
traceId: TrimmedNonEmptyString,
},
{ httpApiStatus: 502 },
) {}
) {
override get message(): string {
return `Relay environment endpoint is unavailable: ${this.reason}`;
}
}
export class RelayEnvironmentEndpointTimedOutError extends Schema.TaggedErrorClass<RelayEnvironmentEndpointTimedOutError>()(
"RelayEnvironmentEndpointTimedOutError",
@@ -376,7 +396,11 @@ export class RelayEnvironmentEndpointTimedOutError extends Schema.TaggedErrorCla
traceId: TrimmedNonEmptyString,
},
{ httpApiStatus: 504 },
) {}
) {
override get message(): string {
return "Relay environment endpoint request timed out";
}
}
export class RelayEnvironmentLinkFailedError extends Schema.TaggedErrorClass<RelayEnvironmentLinkFailedError>()(
"RelayEnvironmentLinkFailedError",
@@ -386,7 +410,11 @@ export class RelayEnvironmentLinkFailedError extends Schema.TaggedErrorClass<Rel
traceId: TrimmedNonEmptyString,
},
{ httpApiStatus: 500 },
) {}
) {
override get message(): string {
return `Relay environment link failed: ${this.reason}`;
}
}
export class RelayEnvironmentLinkUnavailableError extends Schema.TaggedErrorClass<RelayEnvironmentLinkUnavailableError>()(
"RelayEnvironmentLinkUnavailableError",
@@ -396,7 +424,11 @@ export class RelayEnvironmentLinkUnavailableError extends Schema.TaggedErrorClas
traceId: TrimmedNonEmptyString,
},
{ httpApiStatus: 503 },
) {}
) {
override get message(): string {
return `Relay environment link is unavailable: ${this.reason}`;
}
}
export class RelayAgentActivityPublishProofExpiredError extends Schema.TaggedErrorClass<RelayAgentActivityPublishProofExpiredError>()(
"RelayAgentActivityPublishProofExpiredError",
@@ -405,7 +437,11 @@ export class RelayAgentActivityPublishProofExpiredError extends Schema.TaggedErr
traceId: TrimmedNonEmptyString,
},
{ httpApiStatus: 401 },
) {}
) {
override get message(): string {
return "Relay agent activity publish proof expired";
}
}
export class RelayAgentActivityPublishProofInvalidError extends Schema.TaggedErrorClass<RelayAgentActivityPublishProofInvalidError>()(
"RelayAgentActivityPublishProofInvalidError",
@@ -415,7 +451,11 @@ export class RelayAgentActivityPublishProofInvalidError extends Schema.TaggedErr
traceId: TrimmedNonEmptyString,
},
{ httpApiStatus: 401 },
) {}
) {
override get message(): string {
return `Relay agent activity publish proof is invalid: ${this.reason}`;
}
}
export class RelayInternalError extends Schema.TaggedErrorClass<RelayInternalError>()(
"RelayInternalError",
@@ -425,7 +465,11 @@ export class RelayInternalError extends Schema.TaggedErrorClass<RelayInternalErr
traceId: TrimmedNonEmptyString,
},
{ httpApiStatus: 500 },
) {}
) {
override get message(): string {
return `Relay internal error: ${this.reason}`;
}
}
export const RelayProtectedError = Schema.Union([
RelayAuthInvalidError,