Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f42b2937fe | ||
|
|
30199ae5e5 | ||
|
|
34ca6507db |
No files matched your search
@@ -5,6 +5,7 @@ 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 Schema from "effect/Schema";
|
||||
import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/unstable/http";
|
||||
|
||||
import {
|
||||
@@ -33,6 +34,8 @@ function makeHttpClientLayer(
|
||||
);
|
||||
}
|
||||
|
||||
const isSshHttpBridgeError = Schema.is(SshHttpBridgeError);
|
||||
|
||||
describe("SSH environment IPC", () => {
|
||||
it.effect("fetches and decodes the remote environment descriptor", () => {
|
||||
const requestUrls: string[] = [];
|
||||
@@ -83,7 +86,7 @@ describe("SSH environment IPC", () => {
|
||||
|
||||
assert.instanceOf(error, DesktopSshEnvironmentRequestError);
|
||||
assert.equal(error.operation, "fetch-environment-descriptor");
|
||||
assert.equal(error.cause instanceof SshHttpBridgeError, false);
|
||||
assert.isFalse(isSshHttpBridgeError(error.cause));
|
||||
}).pipe(Effect.provide(layer));
|
||||
});
|
||||
|
||||
@@ -108,7 +111,7 @@ describe("SSH environment IPC", () => {
|
||||
const error = failure.value;
|
||||
|
||||
assert.instanceOf(error, DesktopSshEnvironmentRequestError);
|
||||
assert.instanceOf(error.cause, SshHttpBridgeError);
|
||||
assert.isTrue(isSshHttpBridgeError(error.cause));
|
||||
assert.equal(requestCount, 0);
|
||||
}).pipe(Effect.provide(layer));
|
||||
});
|
||||
|
||||
@@ -50,12 +50,10 @@ const isEnvironmentInternalError = Schema.is(EnvironmentInternalError);
|
||||
const isEnvironmentOperationForbiddenError = Schema.is(EnvironmentOperationForbiddenError);
|
||||
const isEnvironmentRequestInvalidError = Schema.is(EnvironmentRequestInvalidError);
|
||||
const isEnvironmentScopeRequiredError = Schema.is(EnvironmentScopeRequiredError);
|
||||
const isSshHttpBridgeError = Schema.is(SshHttpBridgeError);
|
||||
|
||||
function readSshHttpStatus(cause: DesktopSshEnvironmentRequestCause): number | null {
|
||||
if (
|
||||
cause instanceof RemoteEnvironmentAuthUndeclaredStatusError ||
|
||||
cause instanceof SshHttpBridgeError
|
||||
) {
|
||||
if (cause instanceof RemoteEnvironmentAuthUndeclaredStatusError || isSshHttpBridgeError(cause)) {
|
||||
return cause.status ?? null;
|
||||
}
|
||||
if (isEnvironmentRequestInvalidError(cause)) {
|
||||
|
||||
@@ -25,6 +25,7 @@ import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Path from "effect/Path";
|
||||
import * as Schema from "effect/Schema";
|
||||
import { HttpClient } from "effect/unstable/http";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
@@ -79,11 +80,13 @@ function discoverDesktopSshHostsEffect(input?: { readonly homeDir?: string }) {
|
||||
return discoverSshHosts(input ?? {});
|
||||
}
|
||||
|
||||
const isSshPasswordPromptError = Schema.is(SshPasswordPromptError);
|
||||
|
||||
export function isDesktopSshPasswordPromptCancellation(
|
||||
error: unknown,
|
||||
): error is SshPasswordPromptError {
|
||||
return (
|
||||
error instanceof SshPasswordPromptError &&
|
||||
isSshPasswordPromptError(error) &&
|
||||
DesktopSshPasswordPrompts.isDesktopSshPasswordPromptCancellation(error.cause)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -33,6 +33,7 @@ import {
|
||||
EyeIcon,
|
||||
GlobeIcon,
|
||||
HammerIcon,
|
||||
type LucideIcon,
|
||||
SquarePenIcon,
|
||||
TerminalIcon,
|
||||
Undo2Icon,
|
||||
@@ -103,11 +104,6 @@ interface TimelineRowActivityState {
|
||||
isRevertingCheckpoint: boolean;
|
||||
}
|
||||
|
||||
interface StableRowsSnapshot {
|
||||
source: MessagesTimelineRow[];
|
||||
state: StableMessagesTimelineRowsState;
|
||||
}
|
||||
|
||||
const TimelineRowCtx = createContext<TimelineRowSharedState>(null!);
|
||||
const TimelineRowActivityCtx = createContext<TimelineRowActivityState>(null!);
|
||||
const TIMELINE_LIST_HEADER = <div className="h-3 sm:h-4" />;
|
||||
@@ -1012,34 +1008,19 @@ function UserMessageReviewCommentCard({ comment }: { comment: ReviewCommentConte
|
||||
// so LegendList (and React) can skip re-rendering unchanged items.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function createStableRowsSnapshot(
|
||||
rows: MessagesTimelineRow[],
|
||||
previous?: StableMessagesTimelineRowsState,
|
||||
): StableRowsSnapshot {
|
||||
return {
|
||||
source: rows,
|
||||
state: computeStableMessagesTimelineRows(
|
||||
rows,
|
||||
previous ?? {
|
||||
byId: new Map<string, MessagesTimelineRow>(),
|
||||
result: [],
|
||||
},
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
/** Returns a structurally-shared copy of `rows`: for each row whose content
|
||||
* hasn't changed since last call, the previous object reference is reused. */
|
||||
function useStableRows(rows: MessagesTimelineRow[]): MessagesTimelineRow[] {
|
||||
const [snapshot, setSnapshot] = useState(() => createStableRowsSnapshot(rows));
|
||||
const prevState = useRef<StableMessagesTimelineRowsState>({
|
||||
byId: new Map<string, MessagesTimelineRow>(),
|
||||
result: [],
|
||||
});
|
||||
|
||||
if (snapshot.source !== rows) {
|
||||
const nextSnapshot = createStableRowsSnapshot(rows, snapshot.state);
|
||||
setSnapshot(nextSnapshot);
|
||||
return nextSnapshot.state.result;
|
||||
}
|
||||
|
||||
return snapshot.state.result;
|
||||
return useMemo(() => {
|
||||
const nextState = computeStableMessagesTimelineRows(rows, prevState.current);
|
||||
prevState.current = nextState;
|
||||
return nextState.result;
|
||||
}, [rows]);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -1091,17 +1072,32 @@ function formatMessageMeta(
|
||||
return `${formatTimestamp(createdAt, timestampFormat)} • ${duration}`;
|
||||
}
|
||||
|
||||
function workToneIconClass(tone: TimelineWorkEntry["tone"]): string {
|
||||
function workToneIcon(tone: TimelineWorkEntry["tone"]): {
|
||||
icon: LucideIcon;
|
||||
className: string;
|
||||
} {
|
||||
if (tone === "error") {
|
||||
return "text-foreground/92";
|
||||
return {
|
||||
icon: CircleAlertIcon,
|
||||
className: "text-foreground/92",
|
||||
};
|
||||
}
|
||||
if (tone === "thinking") {
|
||||
return "text-foreground/92";
|
||||
return {
|
||||
icon: BotIcon,
|
||||
className: "text-foreground/92",
|
||||
};
|
||||
}
|
||||
if (tone === "info") {
|
||||
return "text-foreground/92";
|
||||
return {
|
||||
icon: CheckIcon,
|
||||
className: "text-foreground/92",
|
||||
};
|
||||
}
|
||||
return "text-foreground/92";
|
||||
return {
|
||||
icon: ZapIcon,
|
||||
className: "text-foreground/92",
|
||||
};
|
||||
}
|
||||
|
||||
function workToneClass(tone: "thinking" | "tool" | "info" | "error"): string {
|
||||
@@ -1136,36 +1132,29 @@ function workEntryRawCommand(
|
||||
return rawCommand === workEntry.command.trim() ? null : rawCommand;
|
||||
}
|
||||
|
||||
function WorkToneIconGlyph({ tone }: { tone: TimelineWorkEntry["tone"] }) {
|
||||
if (tone === "error") return <CircleAlertIcon className="size-3" />;
|
||||
if (tone === "thinking") return <BotIcon className="size-3" />;
|
||||
if (tone === "info") return <CheckIcon className="size-3" />;
|
||||
return <ZapIcon className="size-3" />;
|
||||
}
|
||||
|
||||
function WorkEntryIconGlyph({ workEntry }: { workEntry: TimelineWorkEntry }) {
|
||||
if (workEntry.requestKind === "command") return <TerminalIcon className="size-3" />;
|
||||
if (workEntry.requestKind === "file-read") return <EyeIcon className="size-3" />;
|
||||
if (workEntry.requestKind === "file-change") return <SquarePenIcon className="size-3" />;
|
||||
function workEntryIcon(workEntry: TimelineWorkEntry): LucideIcon {
|
||||
if (workEntry.requestKind === "command") return TerminalIcon;
|
||||
if (workEntry.requestKind === "file-read") return EyeIcon;
|
||||
if (workEntry.requestKind === "file-change") return SquarePenIcon;
|
||||
|
||||
if (workEntry.itemType === "command_execution" || workEntry.command) {
|
||||
return <TerminalIcon className="size-3" />;
|
||||
return TerminalIcon;
|
||||
}
|
||||
if (workEntry.itemType === "file_change" || (workEntry.changedFiles?.length ?? 0) > 0) {
|
||||
return <SquarePenIcon className="size-3" />;
|
||||
return SquarePenIcon;
|
||||
}
|
||||
if (workEntry.itemType === "web_search") return <GlobeIcon className="size-3" />;
|
||||
if (workEntry.itemType === "image_view") return <EyeIcon className="size-3" />;
|
||||
if (workEntry.itemType === "web_search") return GlobeIcon;
|
||||
if (workEntry.itemType === "image_view") return EyeIcon;
|
||||
|
||||
switch (workEntry.itemType) {
|
||||
case "mcp_tool_call":
|
||||
return <WrenchIcon className="size-3" />;
|
||||
return WrenchIcon;
|
||||
case "dynamic_tool_call":
|
||||
case "collab_agent_tool_call":
|
||||
return <HammerIcon className="size-3" />;
|
||||
return HammerIcon;
|
||||
}
|
||||
|
||||
return <WorkToneIconGlyph tone={workEntry.tone} />;
|
||||
return workToneIcon(workEntry.tone).icon;
|
||||
}
|
||||
|
||||
function capitalizePhrase(value: string): string {
|
||||
@@ -1188,7 +1177,8 @@ const SimpleWorkEntryRow = memo(function SimpleWorkEntryRow(props: {
|
||||
workspaceRoot: string | undefined;
|
||||
}) {
|
||||
const { workEntry, workspaceRoot } = props;
|
||||
const iconClassName = workToneIconClass(workEntry.tone);
|
||||
const iconConfig = workToneIcon(workEntry.tone);
|
||||
const EntryIcon = workEntryIcon(workEntry);
|
||||
const heading = toolWorkEntryHeading(workEntry);
|
||||
const rawPreview = workEntryPreview(workEntry, workspaceRoot);
|
||||
const preview =
|
||||
@@ -1205,8 +1195,10 @@ const SimpleWorkEntryRow = memo(function SimpleWorkEntryRow(props: {
|
||||
return (
|
||||
<div className="rounded-lg px-1 py-1">
|
||||
<div className="flex items-center gap-2 transition-[opacity,translate] duration-200">
|
||||
<span className={cn("flex size-5 shrink-0 items-center justify-center", iconClassName)}>
|
||||
<WorkEntryIconGlyph workEntry={workEntry} />
|
||||
<span
|
||||
className={cn("flex size-5 shrink-0 items-center justify-center", iconConfig.className)}
|
||||
>
|
||||
<EntryIcon className="size-3" />
|
||||
</span>
|
||||
<div className="min-w-0 flex-1 overflow-hidden">
|
||||
{rawCommand ? (
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
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";
|
||||
@@ -12,32 +13,23 @@ import { and, desc, eq, isNull } from "drizzle-orm";
|
||||
import { RelayDb } from "../db.ts";
|
||||
import { relayAgentActivityRows, relayEnvironmentLinks } from "../persistence/schema.ts";
|
||||
|
||||
export class AgentActivityRowUpsertPersistenceError extends Schema.TaggedErrorClass<AgentActivityRowUpsertPersistenceError>()(
|
||||
export class AgentActivityRowUpsertPersistenceError extends Data.TaggedError(
|
||||
"AgentActivityRowUpsertPersistenceError",
|
||||
{ cause: Schema.Defect() },
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Failed to persist agent activity state";
|
||||
}
|
||||
}
|
||||
)<{
|
||||
readonly cause: unknown;
|
||||
}> {}
|
||||
|
||||
export class AgentActivityRowDeletePersistenceError extends Schema.TaggedErrorClass<AgentActivityRowDeletePersistenceError>()(
|
||||
export class AgentActivityRowDeletePersistenceError extends Data.TaggedError(
|
||||
"AgentActivityRowDeletePersistenceError",
|
||||
{ cause: Schema.Defect() },
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Failed to delete agent activity state";
|
||||
}
|
||||
}
|
||||
)<{
|
||||
readonly cause: unknown;
|
||||
}> {}
|
||||
|
||||
export class AgentActivityRowListPersistenceError extends Schema.TaggedErrorClass<AgentActivityRowListPersistenceError>()(
|
||||
export class AgentActivityRowListPersistenceError extends Data.TaggedError(
|
||||
"AgentActivityRowListPersistenceError",
|
||||
{ cause: Schema.Defect() },
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Failed to list agent activity state";
|
||||
}
|
||||
}
|
||||
)<{
|
||||
readonly cause: unknown;
|
||||
}> {}
|
||||
|
||||
export interface AgentActivityRowsShape {
|
||||
readonly upsert: (input: {
|
||||
|
||||
@@ -2,13 +2,20 @@ 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 } from "effect/unstable/http";
|
||||
import {
|
||||
Headers,
|
||||
HttpClient,
|
||||
HttpClientRequest,
|
||||
type HttpBody,
|
||||
type HttpClientError,
|
||||
} from "effect/unstable/http";
|
||||
import type { ApnsCredentials } from "../Config.ts";
|
||||
import type { ApnsNotificationPayload } from "./apnsDeliveryJobs.ts";
|
||||
|
||||
@@ -38,39 +45,18 @@ export interface ApnsDeliveryResult {
|
||||
readonly apnsId: string | null;
|
||||
}
|
||||
|
||||
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 ApnsSigningError extends Data.TaggedError("ApnsSigningError")<{
|
||||
readonly phase: "encoding" | "signing";
|
||||
readonly cause: unknown;
|
||||
}> {}
|
||||
|
||||
export class ApnsHttpRequestError extends Schema.TaggedErrorClass<ApnsHttpRequestError>()(
|
||||
"ApnsHttpRequestError",
|
||||
{
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "APNs HTTP request failed";
|
||||
}
|
||||
}
|
||||
export class ApnsHttpRequestError extends Data.TaggedError("ApnsHttpRequestError")<{
|
||||
readonly cause: HttpClientError.HttpClientError | HttpBody.HttpBodyError;
|
||||
}> {}
|
||||
|
||||
export class ApnsInvalidResponseError extends Schema.TaggedErrorClass<ApnsInvalidResponseError>()(
|
||||
"ApnsInvalidResponseError",
|
||||
{
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "APNs returned an invalid response";
|
||||
}
|
||||
}
|
||||
export class ApnsInvalidResponseError extends Data.TaggedError("ApnsInvalidResponseError")<{
|
||||
readonly cause: unknown;
|
||||
}> {}
|
||||
|
||||
export type ApnsError = ApnsSigningError | ApnsHttpRequestError | ApnsInvalidResponseError;
|
||||
|
||||
|
||||
@@ -9,6 +9,7 @@ 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";
|
||||
@@ -73,16 +74,9 @@ export type ApnsDeliveryError =
|
||||
| LiveActivities.LiveActivityTargetListPersistenceError
|
||||
| LiveActivities.LiveActivityDeliveryMarkPersistenceError;
|
||||
|
||||
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`;
|
||||
}
|
||||
}
|
||||
export class ApnsDeliveryJobClaimInFlight extends Data.TaggedError("ApnsDeliveryJobClaimInFlight")<{
|
||||
readonly sourceJobId: string;
|
||||
}> {}
|
||||
|
||||
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,14 +22,9 @@ import {
|
||||
} from "./apnsDeliveryJobs.ts";
|
||||
import * as RelayConfiguration from "../Config.ts";
|
||||
|
||||
export class ApnsDeliveryQueueSendError extends Schema.TaggedErrorClass<ApnsDeliveryQueueSendError>()(
|
||||
"ApnsDeliveryQueueSendError",
|
||||
{ cause: Schema.Defect() },
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Failed to enqueue APNs delivery";
|
||||
}
|
||||
}
|
||||
export class ApnsDeliveryQueueSendError extends Data.TaggedError("ApnsDeliveryQueueSendError")<{
|
||||
readonly cause: unknown;
|
||||
}> {}
|
||||
|
||||
export type ApnsDeliveryQueueError = ApnsDeliveryQueueSendError;
|
||||
|
||||
|
||||
@@ -1,23 +1,20 @@
|
||||
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 Schema.TaggedErrorClass<DeliveryAttemptRecordPersistenceError>()(
|
||||
export class DeliveryAttemptRecordPersistenceError extends Data.TaggedError(
|
||||
"DeliveryAttemptRecordPersistenceError",
|
||||
{ cause: Schema.Defect() },
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Failed to persist APNs delivery attempt";
|
||||
}
|
||||
}
|
||||
)<{
|
||||
readonly cause: unknown;
|
||||
}> {}
|
||||
|
||||
export interface DeliveryAttemptInput {
|
||||
readonly userId: string | null;
|
||||
|
||||
@@ -3,42 +3,31 @@ 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 Schema.TaggedErrorClass<DeviceRegistrationPersistenceError>()(
|
||||
export class DeviceRegistrationPersistenceError extends Data.TaggedError(
|
||||
"DeviceRegistrationPersistenceError",
|
||||
{ cause: Schema.Defect() },
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Failed to persist mobile device registration";
|
||||
}
|
||||
}
|
||||
)<{
|
||||
readonly cause: unknown;
|
||||
}> {}
|
||||
|
||||
export class DeviceUnregistrationPersistenceError extends Schema.TaggedErrorClass<DeviceUnregistrationPersistenceError>()(
|
||||
export class DeviceUnregistrationPersistenceError extends Data.TaggedError(
|
||||
"DeviceUnregistrationPersistenceError",
|
||||
{ cause: Schema.Defect() },
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Failed to unregister mobile device";
|
||||
}
|
||||
}
|
||||
)<{
|
||||
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 class DeviceListPersistenceError extends Data.TaggedError("DeviceListPersistenceError")<{
|
||||
readonly cause: unknown;
|
||||
}> {}
|
||||
|
||||
export interface DevicesShape {
|
||||
readonly register: (input: {
|
||||
|
||||
@@ -5,6 +5,7 @@ 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";
|
||||
@@ -15,32 +16,23 @@ import { and, eq, sql } from "drizzle-orm";
|
||||
import { RelayDb } from "../db.ts";
|
||||
import { relayLiveActivities, relayMobileDevices } from "../persistence/schema.ts";
|
||||
|
||||
export class LiveActivityRegistrationPersistenceError extends Schema.TaggedErrorClass<LiveActivityRegistrationPersistenceError>()(
|
||||
export class LiveActivityRegistrationPersistenceError extends Data.TaggedError(
|
||||
"LiveActivityRegistrationPersistenceError",
|
||||
{ cause: Schema.Defect() },
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Failed to persist Live Activity registration";
|
||||
}
|
||||
}
|
||||
)<{
|
||||
readonly cause: unknown;
|
||||
}> {}
|
||||
|
||||
export class LiveActivityTargetListPersistenceError extends Schema.TaggedErrorClass<LiveActivityTargetListPersistenceError>()(
|
||||
export class LiveActivityTargetListPersistenceError extends Data.TaggedError(
|
||||
"LiveActivityTargetListPersistenceError",
|
||||
{ cause: Schema.Defect() },
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Failed to list Live Activity delivery targets";
|
||||
}
|
||||
}
|
||||
)<{
|
||||
readonly cause: unknown;
|
||||
}> {}
|
||||
|
||||
export class LiveActivityDeliveryMarkPersistenceError extends Schema.TaggedErrorClass<LiveActivityDeliveryMarkPersistenceError>()(
|
||||
export class LiveActivityDeliveryMarkPersistenceError extends Data.TaggedError(
|
||||
"LiveActivityDeliveryMarkPersistenceError",
|
||||
{ cause: Schema.Defect() },
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Failed to persist Live Activity delivery state";
|
||||
}
|
||||
}
|
||||
)<{
|
||||
readonly cause: unknown;
|
||||
}> {}
|
||||
|
||||
export interface DeviceRow {
|
||||
readonly user_id: string;
|
||||
|
||||
@@ -2,6 +2,7 @@ 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";
|
||||
@@ -49,23 +50,13 @@ export const SignedApnsDeliveryJob = Schema.Struct({
|
||||
});
|
||||
export type SignedApnsDeliveryJob = typeof SignedApnsDeliveryJob.Type;
|
||||
|
||||
export class ApnsDeliveryJobInvalid extends Schema.TaggedErrorClass<ApnsDeliveryJobInvalid>()(
|
||||
"ApnsDeliveryJobInvalid",
|
||||
{
|
||||
message: Schema.String,
|
||||
},
|
||||
) {}
|
||||
export class ApnsDeliveryJobInvalid extends Data.TaggedError("ApnsDeliveryJobInvalid")<{
|
||||
readonly message: 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 class ApnsDeliveryJobExpired extends Data.TaggedError("ApnsDeliveryJobExpired")<{
|
||||
readonly expiresAt: string;
|
||||
}> {}
|
||||
|
||||
export type ApnsDeliveryJobVerificationError = ApnsDeliveryJobInvalid | ApnsDeliveryJobExpired;
|
||||
|
||||
|
||||
@@ -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,16 +10,11 @@ import { verifyDpopProof } from "@t3tools/shared/dpop";
|
||||
import { RelayDb } from "../db.ts";
|
||||
import { relayDpopProofs } from "../persistence/schema.ts";
|
||||
|
||||
export class DpopProofReplayPersistenceError extends Schema.TaggedErrorClass<DpopProofReplayPersistenceError>()(
|
||||
export class DpopProofReplayPersistenceError extends Data.TaggedError(
|
||||
"DpopProofReplayPersistenceError",
|
||||
{
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Failed to persist DPoP proof replay state";
|
||||
}
|
||||
}
|
||||
)<{
|
||||
readonly cause: unknown;
|
||||
}> {}
|
||||
|
||||
export interface DpopProofReplayShape {
|
||||
readonly verifyAndConsume: (input: {
|
||||
|
||||
@@ -22,7 +22,6 @@ 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";
|
||||
@@ -51,9 +50,6 @@ 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) : "{}";
|
||||
@@ -284,13 +280,7 @@ describe("EnvironmentConnector", () => {
|
||||
|
||||
expect(Result.isFailure(result)).toBe(true);
|
||||
if (Result.isFailure(result)) {
|
||||
expect(isEnvironmentConnectNotAuthorized(result.failure)).toBe(true);
|
||||
if (isEnvironmentConnectNotAuthorized(result.failure)) {
|
||||
expect(result.failure).toMatchObject({
|
||||
operation: "status",
|
||||
reason: "endpoint_provider_not_managed",
|
||||
});
|
||||
}
|
||||
expect(result.failure).toBeInstanceOf(EnvironmentConnector.EnvironmentConnectNotAuthorized);
|
||||
}
|
||||
expect(requestCount).toBe(0);
|
||||
}).pipe(
|
||||
@@ -310,14 +300,6 @@ 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;
|
||||
@@ -336,27 +318,8 @@ describe("EnvironmentConnector", () => {
|
||||
|
||||
expect(Result.isFailure(result)).toBe(true);
|
||||
if (Result.isFailure(result)) {
|
||||
expect(isEnvironmentConnectNotAuthorized(result.failure)).toBe(true);
|
||||
if (isEnvironmentConnectNotAuthorized(result.failure)) {
|
||||
expect(result.failure).toMatchObject({
|
||||
operation: "connect",
|
||||
reason: "managed_endpoint_mismatch",
|
||||
});
|
||||
}
|
||||
expect(result.failure).toBeInstanceOf(EnvironmentConnector.EnvironmentConnectNotAuthorized);
|
||||
}
|
||||
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(
|
||||
@@ -370,7 +333,6 @@ describe("EnvironmentConnector", () => {
|
||||
}),
|
||||
}),
|
||||
),
|
||||
Effect.provideService(Tracer.Tracer, tracer),
|
||||
);
|
||||
});
|
||||
|
||||
@@ -393,13 +355,7 @@ describe("EnvironmentConnector", () => {
|
||||
|
||||
expect(Result.isFailure(result)).toBe(true);
|
||||
if (Result.isFailure(result)) {
|
||||
expect(isEnvironmentConnectNotAuthorized(result.failure)).toBe(true);
|
||||
if (isEnvironmentConnectNotAuthorized(result.failure)) {
|
||||
expect(result.failure).toMatchObject({
|
||||
operation: "status",
|
||||
reason: "managed_endpoint_allocation_not_ready",
|
||||
});
|
||||
}
|
||||
expect(result.failure).toBeInstanceOf(EnvironmentConnector.EnvironmentConnectNotAuthorized);
|
||||
}
|
||||
expect(requestCount).toBe(0);
|
||||
}).pipe(
|
||||
|
||||
@@ -28,6 +28,7 @@ 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";
|
||||
@@ -40,93 +41,29 @@ 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 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>()(
|
||||
export class EnvironmentConnectNotAuthorized extends Data.TaggedError(
|
||||
"EnvironmentConnectNotAuthorized",
|
||||
{
|
||||
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)}`;
|
||||
}
|
||||
}
|
||||
)<{
|
||||
readonly environmentId: string;
|
||||
}> {}
|
||||
|
||||
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 EnvironmentMintRequestFailed extends Data.TaggedError("EnvironmentMintRequestFailed")<{
|
||||
readonly cause: unknown;
|
||||
}> {}
|
||||
|
||||
export class EnvironmentMintRequestTimedOut extends Schema.TaggedErrorClass<EnvironmentMintRequestTimedOut>()(
|
||||
export class EnvironmentMintRequestTimedOut extends Data.TaggedError(
|
||||
"EnvironmentMintRequestTimedOut",
|
||||
{
|
||||
environmentId: Schema.String,
|
||||
timeoutMs: Schema.Number,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Environment '${this.environmentId}' mint request timed out after ${this.timeoutMs}ms`;
|
||||
}
|
||||
}
|
||||
)<{
|
||||
readonly environmentId: string;
|
||||
readonly timeoutMs: number;
|
||||
}> {}
|
||||
|
||||
export class EnvironmentMintResponseInvalid extends Schema.TaggedErrorClass<EnvironmentMintResponseInvalid>()(
|
||||
export class EnvironmentMintResponseInvalid extends Data.TaggedError(
|
||||
"EnvironmentMintResponseInvalid",
|
||||
{
|
||||
environmentId: Schema.String,
|
||||
operation: Schema.Literals(["connect", "status"]),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Environment '${this.environmentId}' returned an invalid ${this.operation} response`;
|
||||
}
|
||||
}
|
||||
)<{
|
||||
readonly environmentId: string;
|
||||
}> {}
|
||||
|
||||
export type EnvironmentConnectorError =
|
||||
| EnvironmentConnectNotAuthorized
|
||||
@@ -296,91 +233,30 @@ 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,
|
||||
});
|
||||
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,
|
||||
});
|
||||
const endpoint = allocation
|
||||
? ManagedEndpointAllocations.resolveReadyManagedEndpoint({
|
||||
allocation,
|
||||
baseDomain: settings.managedEndpointBaseDomain,
|
||||
})
|
||||
: null;
|
||||
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;
|
||||
@@ -395,42 +271,20 @@ const make = Effect.gen(function* () {
|
||||
});
|
||||
const link = yield* links.getForUser(input);
|
||||
if (!link) {
|
||||
return yield* new EnvironmentConnectNotAuthorized({
|
||||
environmentId: input.environmentId,
|
||||
operation: "status",
|
||||
reason: "environment_link_not_found",
|
||||
});
|
||||
return yield* new EnvironmentConnectNotAuthorized({ environmentId: input.environmentId });
|
||||
}
|
||||
const endpoint = yield* resolveManagedEndpoint({
|
||||
userId: input.userId,
|
||||
operation: "status",
|
||||
link,
|
||||
});
|
||||
const endpoint = yield* resolveManagedEndpoint({ userId: input.userId, link });
|
||||
const now = yield* DateTime.now;
|
||||
const expiresAt = DateTime.add(now, { minutes: 2 });
|
||||
const nonce = yield* crypto.randomUUIDv4.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new EnvironmentMintRequestFailed({
|
||||
environmentId: input.environmentId,
|
||||
operation: "status",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Effect.mapError((cause) => new EnvironmentMintRequestFailed({ cause })),
|
||||
);
|
||||
const payload = {
|
||||
iss: relayIssuer,
|
||||
aud: `t3-env:${link.environmentId}`,
|
||||
sub: input.userId,
|
||||
jti: yield* crypto.randomUUIDv4.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new EnvironmentMintRequestFailed({
|
||||
environmentId: input.environmentId,
|
||||
operation: "status",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Effect.mapError((cause) => new EnvironmentMintRequestFailed({ cause })),
|
||||
),
|
||||
iat: Math.floor(now.epochMilliseconds / 1_000),
|
||||
exp: Math.floor(expiresAt.epochMilliseconds / 1_000),
|
||||
@@ -442,16 +296,7 @@ const make = Effect.gen(function* () {
|
||||
privateKey: Redacted.value(settings.cloudMintPrivateKey),
|
||||
typ: RELAY_HEALTH_REQUEST_TYP,
|
||||
payload,
|
||||
}).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new EnvironmentMintRequestFailed({
|
||||
environmentId: input.environmentId,
|
||||
operation: "status",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}).pipe(Effect.mapError((cause) => new EnvironmentMintRequestFailed({ cause })));
|
||||
const checkedAt = DateTime.formatIso(now);
|
||||
const environmentClient = yield* makeEnvironmentClient(endpoint.httpBaseUrl);
|
||||
const responseOption = yield* environmentClient.cloud.health({ payload: { proof } }).pipe(
|
||||
@@ -491,10 +336,7 @@ const make = Effect.gen(function* () {
|
||||
now: yield* DateTime.now,
|
||||
});
|
||||
if (!verified) {
|
||||
return yield* new EnvironmentMintResponseInvalid({
|
||||
environmentId: input.environmentId,
|
||||
operation: "status",
|
||||
});
|
||||
return yield* new EnvironmentMintResponseInvalid({ environmentId: input.environmentId });
|
||||
}
|
||||
return {
|
||||
environmentId: link.environmentId,
|
||||
@@ -512,50 +354,24 @@ 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,
|
||||
operation: "connect",
|
||||
reason: "client_proof_key_thumbprint_missing",
|
||||
});
|
||||
return yield* new EnvironmentConnectNotAuthorized({ environmentId: input.environmentId });
|
||||
}
|
||||
const link = yield* links.getForUser(input);
|
||||
if (!link) {
|
||||
return yield* new EnvironmentConnectNotAuthorized({
|
||||
environmentId: input.environmentId,
|
||||
operation: "connect",
|
||||
reason: "environment_link_not_found",
|
||||
});
|
||||
return yield* new EnvironmentConnectNotAuthorized({ environmentId: input.environmentId });
|
||||
}
|
||||
const endpoint = yield* resolveManagedEndpoint({
|
||||
userId: input.userId,
|
||||
operation: "connect",
|
||||
link,
|
||||
});
|
||||
const endpoint = yield* resolveManagedEndpoint({ userId: input.userId, link });
|
||||
const now = yield* DateTime.now;
|
||||
const expiresAt = DateTime.add(now, { minutes: 2 });
|
||||
const nonce = yield* crypto.randomUUIDv4.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new EnvironmentMintRequestFailed({
|
||||
environmentId: input.environmentId,
|
||||
operation: "connect",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Effect.mapError((cause) => new EnvironmentMintRequestFailed({ cause })),
|
||||
);
|
||||
const payload = {
|
||||
iss: relayIssuer,
|
||||
aud: `t3-env:${link.environmentId}`,
|
||||
sub: input.userId,
|
||||
jti: yield* crypto.randomUUIDv4.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new EnvironmentMintRequestFailed({
|
||||
environmentId: input.environmentId,
|
||||
operation: "connect",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Effect.mapError((cause) => new EnvironmentMintRequestFailed({ cause })),
|
||||
),
|
||||
iat: Math.floor(now.epochMilliseconds / 1_000),
|
||||
exp: Math.floor(expiresAt.epochMilliseconds / 1_000),
|
||||
@@ -570,27 +386,11 @@ const make = Effect.gen(function* () {
|
||||
privateKey: Redacted.value(settings.cloudMintPrivateKey),
|
||||
typ: RELAY_MINT_REQUEST_TYP,
|
||||
payload,
|
||||
}).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new EnvironmentMintRequestFailed({
|
||||
environmentId: input.environmentId,
|
||||
operation: "connect",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}).pipe(Effect.mapError((cause) => new EnvironmentMintRequestFailed({ cause })));
|
||||
const environmentClient = yield* makeEnvironmentClient(endpoint.httpBaseUrl);
|
||||
const decoded = yield* environmentClient.cloud.t3MintCredential({ payload: { proof } }).pipe(
|
||||
withoutRedirects,
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new EnvironmentMintRequestFailed({
|
||||
environmentId: input.environmentId,
|
||||
operation: "connect",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Effect.mapError((cause) => new EnvironmentMintRequestFailed({ cause })),
|
||||
Effect.timeoutOption(Duration.millis(ENVIRONMENT_MINT_REQUEST_TIMEOUT_MS)),
|
||||
Effect.flatMap(
|
||||
Option.match({
|
||||
@@ -615,10 +415,7 @@ const make = Effect.gen(function* () {
|
||||
nowEpochSeconds: Math.floor(now.epochMilliseconds / 1_000),
|
||||
});
|
||||
if (!verified) {
|
||||
return yield* new EnvironmentMintResponseInvalid({
|
||||
environmentId: input.environmentId,
|
||||
operation: "connect",
|
||||
});
|
||||
return yield* new EnvironmentMintResponseInvalid({ environmentId: input.environmentId });
|
||||
}
|
||||
return {
|
||||
environmentId: link.environmentId,
|
||||
|
||||
@@ -1,42 +1,33 @@
|
||||
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 Schema.TaggedErrorClass<EnvironmentCredentialCreatePersistenceError>()(
|
||||
export class EnvironmentCredentialCreatePersistenceError extends Data.TaggedError(
|
||||
"EnvironmentCredentialCreatePersistenceError",
|
||||
{ cause: Schema.Defect() },
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Failed to persist environment credential";
|
||||
}
|
||||
}
|
||||
)<{
|
||||
readonly cause: unknown;
|
||||
}> {}
|
||||
|
||||
export class EnvironmentCredentialAuthenticatePersistenceError extends Schema.TaggedErrorClass<EnvironmentCredentialAuthenticatePersistenceError>()(
|
||||
export class EnvironmentCredentialAuthenticatePersistenceError extends Data.TaggedError(
|
||||
"EnvironmentCredentialAuthenticatePersistenceError",
|
||||
{ cause: Schema.Defect() },
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Failed to authenticate environment credential";
|
||||
}
|
||||
}
|
||||
)<{
|
||||
readonly cause: unknown;
|
||||
}> {}
|
||||
|
||||
export class EnvironmentCredentialRevokePersistenceError extends Schema.TaggedErrorClass<EnvironmentCredentialRevokePersistenceError>()(
|
||||
export class EnvironmentCredentialRevokePersistenceError extends Data.TaggedError(
|
||||
"EnvironmentCredentialRevokePersistenceError",
|
||||
{ cause: Schema.Defect() },
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Failed to revoke environment credential";
|
||||
}
|
||||
}
|
||||
)<{
|
||||
readonly cause: unknown;
|
||||
}> {}
|
||||
|
||||
export interface EnvironmentCredentialPrincipal {
|
||||
readonly credentialId: string;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import {
|
||||
RelayEnvironmentLinkProofPayload,
|
||||
RelayEnvironmentLinkProofInvalidReason,
|
||||
type RelayEnvironmentLinkProofInvalidReason,
|
||||
type RelayEnvironmentLinkRequest,
|
||||
} from "@t3tools/contracts/relay";
|
||||
import {
|
||||
@@ -10,6 +10,7 @@ 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";
|
||||
@@ -22,28 +23,14 @@ import * as EnvironmentLinks from "./EnvironmentLinks.ts";
|
||||
import * as ManagedEndpointProvider from "./ManagedEndpointProvider.ts";
|
||||
import * as RelayConfiguration from "../Config.ts";
|
||||
|
||||
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 EnvironmentLinkProofExpired extends Data.TaggedError("EnvironmentLinkProofExpired")<{
|
||||
readonly expiresAt: string;
|
||||
}> {}
|
||||
|
||||
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 class EnvironmentLinkProofInvalid extends Data.TaggedError("EnvironmentLinkProofInvalid")<{
|
||||
readonly environmentId: string;
|
||||
readonly reason: RelayEnvironmentLinkProofInvalidReason;
|
||||
}> {}
|
||||
|
||||
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,59 +24,41 @@ export interface AgentAwarenessDeliveryUserRecord {
|
||||
readonly liveActivitiesEnabled: boolean;
|
||||
}
|
||||
|
||||
export class EnvironmentLinkUpsertPersistenceError extends Schema.TaggedErrorClass<EnvironmentLinkUpsertPersistenceError>()(
|
||||
export class EnvironmentLinkUpsertPersistenceError extends Data.TaggedError(
|
||||
"EnvironmentLinkUpsertPersistenceError",
|
||||
{ cause: Schema.Defect() },
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Failed to persist environment link";
|
||||
}
|
||||
}
|
||||
)<{
|
||||
readonly cause: unknown;
|
||||
}> {}
|
||||
|
||||
export class EnvironmentLinkUserListPersistenceError extends Schema.TaggedErrorClass<EnvironmentLinkUserListPersistenceError>()(
|
||||
export class EnvironmentLinkUserListPersistenceError extends Data.TaggedError(
|
||||
"EnvironmentLinkUserListPersistenceError",
|
||||
{ cause: Schema.Defect() },
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Failed to list users linked to environment";
|
||||
}
|
||||
}
|
||||
)<{
|
||||
readonly cause: unknown;
|
||||
}> {}
|
||||
|
||||
export class EnvironmentPublicKeyListPersistenceError extends Schema.TaggedErrorClass<EnvironmentPublicKeyListPersistenceError>()(
|
||||
export class EnvironmentPublicKeyListPersistenceError extends Data.TaggedError(
|
||||
"EnvironmentPublicKeyListPersistenceError",
|
||||
{ cause: Schema.Defect() },
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Failed to list environment public keys";
|
||||
}
|
||||
}
|
||||
)<{
|
||||
readonly cause: unknown;
|
||||
}> {}
|
||||
|
||||
export class EnvironmentLinkListPersistenceError extends Schema.TaggedErrorClass<EnvironmentLinkListPersistenceError>()(
|
||||
export class EnvironmentLinkListPersistenceError extends Data.TaggedError(
|
||||
"EnvironmentLinkListPersistenceError",
|
||||
{ cause: Schema.Defect() },
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Failed to list environment links";
|
||||
}
|
||||
}
|
||||
)<{
|
||||
readonly cause: unknown;
|
||||
}> {}
|
||||
|
||||
export class EnvironmentLinkLookupPersistenceError extends Schema.TaggedErrorClass<EnvironmentLinkLookupPersistenceError>()(
|
||||
export class EnvironmentLinkLookupPersistenceError extends Data.TaggedError(
|
||||
"EnvironmentLinkLookupPersistenceError",
|
||||
{ cause: Schema.Defect() },
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Failed to look up environment link";
|
||||
}
|
||||
}
|
||||
)<{
|
||||
readonly cause: unknown;
|
||||
}> {}
|
||||
|
||||
export class EnvironmentLinkRevokePersistenceError extends Schema.TaggedErrorClass<EnvironmentLinkRevokePersistenceError>()(
|
||||
export class EnvironmentLinkRevokePersistenceError extends Data.TaggedError(
|
||||
"EnvironmentLinkRevokePersistenceError",
|
||||
{ cause: Schema.Defect() },
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Failed to revoke environment link";
|
||||
}
|
||||
}
|
||||
)<{
|
||||
readonly cause: unknown;
|
||||
}> {}
|
||||
|
||||
export interface EnvironmentLinksShape {
|
||||
readonly upsert: (input: {
|
||||
|
||||
@@ -11,6 +11,7 @@ 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";
|
||||
@@ -20,38 +21,23 @@ import * as Schema from "effect/Schema";
|
||||
import * as DpopProofs from "../auth/DpopProofs.ts";
|
||||
import * as RelayConfiguration from "../Config.ts";
|
||||
|
||||
export class EnvironmentPublishSignatureExpired extends Schema.TaggedErrorClass<EnvironmentPublishSignatureExpired>()(
|
||||
export class EnvironmentPublishSignatureExpired extends Data.TaggedError(
|
||||
"EnvironmentPublishSignatureExpired",
|
||||
{
|
||||
expiresAt: Schema.String,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Environment publish signature expired at ${this.expiresAt}`;
|
||||
}
|
||||
}
|
||||
)<{
|
||||
readonly expiresAt: string;
|
||||
}> {}
|
||||
|
||||
export class EnvironmentPublishSignatureInvalid extends Schema.TaggedErrorClass<EnvironmentPublishSignatureInvalid>()(
|
||||
export class EnvironmentPublishSignatureInvalid extends Data.TaggedError(
|
||||
"EnvironmentPublishSignatureInvalid",
|
||||
{
|
||||
environmentId: Schema.String,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Environment '${this.environmentId}' publish signature is invalid`;
|
||||
}
|
||||
}
|
||||
)<{
|
||||
readonly environmentId: string;
|
||||
}> {}
|
||||
|
||||
export class EnvironmentPublishPublicKeyMissing extends Schema.TaggedErrorClass<EnvironmentPublishPublicKeyMissing>()(
|
||||
export class EnvironmentPublishPublicKeyMissing extends Data.TaggedError(
|
||||
"EnvironmentPublishPublicKeyMissing",
|
||||
{
|
||||
environmentId: Schema.String,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Environment '${this.environmentId}' has no publish public key`;
|
||||
}
|
||||
}
|
||||
)<{
|
||||
readonly environmentId: string;
|
||||
}> {}
|
||||
|
||||
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,17 +36,11 @@ export function resolveReadyManagedEndpoint(input: {
|
||||
return managedEndpointForHostname(input.allocation.hostname);
|
||||
}
|
||||
|
||||
export class ManagedEndpointAllocationPersistenceError extends Schema.TaggedErrorClass<ManagedEndpointAllocationPersistenceError>()(
|
||||
export class ManagedEndpointAllocationPersistenceError extends Data.TaggedError(
|
||||
"ManagedEndpointAllocationPersistenceError",
|
||||
{ cause: Schema.Defect() },
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Failed to persist managed endpoint allocation";
|
||||
}
|
||||
}
|
||||
const isManagedEndpointAllocationPersistenceError = Schema.is(
|
||||
ManagedEndpointAllocationPersistenceError,
|
||||
);
|
||||
)<{
|
||||
readonly cause: unknown;
|
||||
}> {}
|
||||
|
||||
interface ManagedEndpointAllocationKey {
|
||||
readonly userId: string;
|
||||
@@ -104,7 +98,7 @@ const whereAllocation = (input: ManagedEndpointAllocationKey) =>
|
||||
);
|
||||
|
||||
const persistenceError = (cause: unknown) =>
|
||||
isManagedEndpointAllocationPersistenceError(cause)
|
||||
cause instanceof ManagedEndpointAllocationPersistenceError
|
||||
? 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,44 +25,28 @@ import {
|
||||
} from "../deploymentConfig.ts";
|
||||
import { ManagedEndpointAllocations } from "./ManagedEndpointAllocations.ts";
|
||||
|
||||
export class ManagedEndpointProvisioningNotConfigured extends Schema.TaggedErrorClass<ManagedEndpointProvisioningNotConfigured>()(
|
||||
export class ManagedEndpointProvisioningNotConfigured extends Data.TaggedError(
|
||||
"ManagedEndpointProvisioningNotConfigured",
|
||||
{},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Managed endpoint provisioning is not configured";
|
||||
}
|
||||
}
|
||||
)<{}> {}
|
||||
|
||||
export class ManagedEndpointProvisioningFailed extends Schema.TaggedErrorClass<ManagedEndpointProvisioningFailed>()(
|
||||
export class ManagedEndpointProvisioningFailed extends Data.TaggedError(
|
||||
"ManagedEndpointProvisioningFailed",
|
||||
{ cause: Schema.Defect() },
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Managed endpoint provisioning failed";
|
||||
}
|
||||
}
|
||||
)<{
|
||||
readonly cause: unknown;
|
||||
}> {}
|
||||
|
||||
export class ManagedEndpointDeprovisioningFailed extends Schema.TaggedErrorClass<ManagedEndpointDeprovisioningFailed>()(
|
||||
export class ManagedEndpointDeprovisioningFailed extends Data.TaggedError(
|
||||
"ManagedEndpointDeprovisioningFailed",
|
||||
{ cause: Schema.Defect() },
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Managed endpoint deprovisioning failed";
|
||||
}
|
||||
}
|
||||
)<{
|
||||
readonly cause: unknown;
|
||||
}> {}
|
||||
|
||||
export class ManagedEndpointOriginNotAllowed extends Schema.TaggedErrorClass<ManagedEndpointOriginNotAllowed>()(
|
||||
export class ManagedEndpointOriginNotAllowed extends Data.TaggedError(
|
||||
"ManagedEndpointOriginNotAllowed",
|
||||
{
|
||||
host: Schema.String,
|
||||
port: Schema.Number,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Managed endpoint origin '${this.host}:${this.port}' is not allowed`;
|
||||
}
|
||||
}
|
||||
)<{
|
||||
readonly host: string;
|
||||
readonly port: number;
|
||||
}> {}
|
||||
|
||||
export type ManagedEndpointProviderError =
|
||||
| ManagedEndpointProvisioningNotConfigured
|
||||
@@ -96,14 +80,11 @@ interface ManagedEndpointTunnel {
|
||||
readonly name?: string | null;
|
||||
}
|
||||
|
||||
export class ManagedEndpointTunnelClientError extends Schema.TaggedErrorClass<ManagedEndpointTunnelClientError>()(
|
||||
export class ManagedEndpointTunnelClientError extends Data.TaggedError(
|
||||
"ManagedEndpointTunnelClientError",
|
||||
{ cause: Schema.Defect() },
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Managed endpoint tunnel provider request failed";
|
||||
}
|
||||
}
|
||||
)<{
|
||||
readonly cause: unknown;
|
||||
}> {}
|
||||
|
||||
export interface ManagedEndpointTunnelClientShape {
|
||||
readonly list: (request: {
|
||||
@@ -143,14 +124,11 @@ interface ManagedEndpointCnameRecordInput {
|
||||
readonly proxied: true;
|
||||
}
|
||||
|
||||
export class ManagedEndpointDnsClientError extends Schema.TaggedErrorClass<ManagedEndpointDnsClientError>()(
|
||||
export class ManagedEndpointDnsClientError extends Data.TaggedError(
|
||||
"ManagedEndpointDnsClientError",
|
||||
{ cause: Schema.Defect() },
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Managed endpoint DNS provider request failed";
|
||||
}
|
||||
}
|
||||
)<{
|
||||
readonly cause: unknown;
|
||||
}> {}
|
||||
|
||||
export interface ManagedEndpointDnsClientShape {
|
||||
readonly listRecords: (
|
||||
|
||||
+11
-14
@@ -1,5 +1,6 @@
|
||||
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";
|
||||
@@ -812,16 +813,9 @@ export const serverApi = HttpApiBuilder.group(
|
||||
}),
|
||||
);
|
||||
|
||||
class ClerkTokenVerificationFailed extends Schema.TaggedErrorClass<ClerkTokenVerificationFailed>()(
|
||||
"ClerkTokenVerificationFailed",
|
||||
{
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Clerk token verification failed";
|
||||
}
|
||||
}
|
||||
class ClerkTokenVerificationFailed extends Data.TaggedError("ClerkTokenVerificationFailed")<{
|
||||
readonly cause: unknown;
|
||||
}> {}
|
||||
|
||||
const isHttpUnauthorized = Schema.is(HttpApiError.Unauthorized);
|
||||
|
||||
@@ -830,7 +824,7 @@ const currentTraceId = Effect.currentParentSpan.pipe(
|
||||
Effect.orElseSucceed(() => "unavailable"),
|
||||
);
|
||||
|
||||
const RelayCommonPersistenceError = Schema.Union([
|
||||
const COMMON_AUTH_INVALID_REASONS = [
|
||||
Devices.DeviceRegistrationPersistenceError,
|
||||
Devices.DeviceUnregistrationPersistenceError,
|
||||
Devices.DeviceListPersistenceError,
|
||||
@@ -850,15 +844,18 @@ const RelayCommonPersistenceError = Schema.Union([
|
||||
AgentActivityRows.AgentActivityRowListPersistenceError,
|
||||
LiveActivities.LiveActivityDeliveryMarkPersistenceError,
|
||||
DeliveryAttempts.DeliveryAttemptRecordPersistenceError,
|
||||
]);
|
||||
type RelayCommonPersistenceError = typeof RelayCommonPersistenceError.Type;
|
||||
const isRelayCommonPersistenceError = Schema.is(RelayCommonPersistenceError);
|
||||
] as const;
|
||||
type RelayCommonPersistenceError = InstanceType<(typeof COMMON_AUTH_INVALID_REASONS)[number]>;
|
||||
|
||||
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) =>
|
||||
|
||||
@@ -1,85 +0,0 @@
|
||||
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),
|
||||
);
|
||||
@@ -1,14 +1,9 @@
|
||||
import * as Alchemy from "alchemy";
|
||||
import * as Axiom from "alchemy/Axiom";
|
||||
import * as Output from "alchemy/Output";
|
||||
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 Effect from "effect/Effect";
|
||||
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";
|
||||
@@ -59,163 +54,23 @@ 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>;
|
||||
}) =>
|
||||
Layer.effect(
|
||||
Tracer.Tracer,
|
||||
OtlpTracer.make({
|
||||
url: input.tracesEndpoint,
|
||||
resource: {
|
||||
serviceName: "t3-code-relay-worker",
|
||||
attributes: {
|
||||
"service.runtime": "cloudflare-worker",
|
||||
"service.component": "relay",
|
||||
},
|
||||
OtlpTracer.layer({
|
||||
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(Effect.map(withSchemaErrorAttributes)),
|
||||
).pipe(Layer.provide(OtlpSerialization.layerJson));
|
||||
},
|
||||
headers: {
|
||||
Authorization: `Bearer ${Redacted.value(input.ingestToken)}`,
|
||||
"X-Axiom-Dataset": input.tracesDatasetName,
|
||||
},
|
||||
exportInterval: "1 second",
|
||||
}).pipe(Layer.provide(OtlpSerialization.layerJson));
|
||||
@@ -329,11 +329,7 @@ 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",
|
||||
@@ -342,11 +338,7 @@ 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",
|
||||
@@ -356,11 +348,7 @@ 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",
|
||||
@@ -369,11 +357,7 @@ 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",
|
||||
@@ -383,11 +367,7 @@ 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",
|
||||
@@ -396,11 +376,7 @@ 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",
|
||||
@@ -410,11 +386,7 @@ 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",
|
||||
@@ -424,11 +396,7 @@ 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",
|
||||
@@ -437,11 +405,7 @@ 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",
|
||||
@@ -451,11 +415,7 @@ 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",
|
||||
@@ -465,11 +425,7 @@ 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,
|
||||
|
||||
@@ -219,7 +219,7 @@ describe("ssh command", () => {
|
||||
username: "julius",
|
||||
port: 2222,
|
||||
},
|
||||
{ timeoutMs: 1 },
|
||||
{ timeout: Duration.millis(1) },
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -14,7 +14,7 @@ import { buildSshChildEnvironment, type SshAuthOptions } from "./auth.ts";
|
||||
import { SshCommandError, SshInvalidTargetError } from "./errors.ts";
|
||||
|
||||
const PUBLISHABLE_T3_VERSION_PATTERN = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/u;
|
||||
const DEFAULT_SSH_COMMAND_TIMEOUT_MS = 60_000;
|
||||
const DEFAULT_SSH_COMMAND_TIMEOUT = Duration.seconds(60);
|
||||
const MAX_SSH_ERROR_OUTPUT_LENGTH = 4_000;
|
||||
export const SSH_COMMAND = process.platform === "win32" ? "ssh.exe" : "ssh";
|
||||
|
||||
@@ -29,6 +29,8 @@ export interface RunSshCommandOptions extends SshAuthOptions {
|
||||
readonly preHostArgs?: ReadonlyArray<string>;
|
||||
readonly remoteCommandArgs?: ReadonlyArray<string>;
|
||||
readonly stdin?: string;
|
||||
readonly timeout?: Duration.Input;
|
||||
/** @deprecated Prefer `timeout` with an Effect Duration input. */
|
||||
readonly timeoutMs?: number;
|
||||
}
|
||||
|
||||
@@ -157,6 +159,10 @@ function stdinStream(input: string | undefined) {
|
||||
return input === undefined ? Stream.empty : Stream.make(encoder.encode(input));
|
||||
}
|
||||
|
||||
function resolveSshCommandTimeout(input: RunSshCommandOptions): Duration.Duration {
|
||||
return Duration.fromInputUnsafe(input.timeout ?? input.timeoutMs ?? DEFAULT_SSH_COMMAND_TIMEOUT);
|
||||
}
|
||||
|
||||
const runSshCommandInScope = Effect.fn("ssh/command.runSshCommand.inScope")(function* (
|
||||
target: DesktopSshEnvironmentTarget,
|
||||
input: RunSshCommandOptions,
|
||||
@@ -191,11 +197,12 @@ const runSshCommandInScope = Effect.fn("ssh/command.runSshCommand.inScope")(func
|
||||
...(input.remoteCommandArgs ?? []),
|
||||
];
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const timeout = resolveSshCommandTimeout(input);
|
||||
yield* Effect.logDebug("ssh.command.start", {
|
||||
...sshTargetLogFields(target),
|
||||
command: [SSH_COMMAND, ...args],
|
||||
hasStdin: input.stdin !== undefined,
|
||||
timeoutMs: input.timeoutMs ?? DEFAULT_SSH_COMMAND_TIMEOUT_MS,
|
||||
timeoutMs: Duration.toMillis(timeout),
|
||||
});
|
||||
const child = yield* spawner
|
||||
.spawn(
|
||||
@@ -282,10 +289,12 @@ export const runSshCommand = Effect.fn("ssh/command.runSshCommand")(function* (
|
||||
SshCommandError | SshInvalidTargetError,
|
||||
ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path
|
||||
> {
|
||||
const timeout = resolveSshCommandTimeout(input);
|
||||
const timeoutMs = Duration.toMillis(timeout);
|
||||
return yield* Effect.scopedWith((commandScope) =>
|
||||
runSshCommandInScope(target, input, commandScope),
|
||||
).pipe(
|
||||
Effect.timeoutOption(Duration.millis(input.timeoutMs ?? DEFAULT_SSH_COMMAND_TIMEOUT_MS)),
|
||||
Effect.timeoutOption(timeout),
|
||||
Effect.flatMap((result) =>
|
||||
Option.match(result, {
|
||||
onSome: Effect.succeed,
|
||||
@@ -293,7 +302,7 @@ export const runSshCommand = Effect.fn("ssh/command.runSshCommand")(function* (
|
||||
Effect.gen(function* () {
|
||||
yield* Effect.logWarning("ssh.command.timedOut", {
|
||||
...sshTargetLogFields(target),
|
||||
timeoutMs: input.timeoutMs ?? DEFAULT_SSH_COMMAND_TIMEOUT_MS,
|
||||
timeoutMs,
|
||||
remoteCommandArgs: input.remoteCommandArgs ?? [],
|
||||
preHostArgs: input.preHostArgs ?? [],
|
||||
hasStdin: input.stdin !== undefined,
|
||||
@@ -302,7 +311,7 @@ export const runSshCommand = Effect.fn("ssh/command.runSshCommand")(function* (
|
||||
command: ["ssh"],
|
||||
exitCode: null,
|
||||
stderr: "",
|
||||
message: `SSH command timed out after ${input.timeoutMs ?? DEFAULT_SSH_COMMAND_TIMEOUT_MS}ms.`,
|
||||
message: `SSH command timed out after ${timeoutMs}ms.`,
|
||||
});
|
||||
}),
|
||||
}),
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import { SshCommandError, SshError } from "./errors.ts";
|
||||
|
||||
const encodeSshError = Schema.encodeSync(SshError);
|
||||
const isSshError = Schema.is(SshError);
|
||||
|
||||
describe("ssh errors", () => {
|
||||
it("encodes schema-backed SSH errors as tagged serializable data", () => {
|
||||
const error = new SshCommandError({
|
||||
message: "SSH command failed.",
|
||||
command: ["ssh", "devbox"],
|
||||
exitCode: 255,
|
||||
stderr: "permission denied",
|
||||
});
|
||||
|
||||
assert.isTrue(isSshError(error));
|
||||
assert.deepEqual(encodeSshError(error), {
|
||||
_tag: "SshCommandError",
|
||||
message: "SSH command failed.",
|
||||
command: ["ssh", "devbox"],
|
||||
exitCode: 255,
|
||||
stderr: "permission denied",
|
||||
});
|
||||
});
|
||||
});
|
||||
+73
-39
@@ -1,47 +1,81 @@
|
||||
import * as Data from "effect/Data";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
export class SshHostDiscoveryError extends Data.TaggedError("SshHostDiscoveryError")<{
|
||||
readonly message: string;
|
||||
readonly cause: unknown;
|
||||
}> {}
|
||||
const SshCommandArgs = Schema.Array(Schema.String);
|
||||
|
||||
export class SshInvalidTargetError extends Data.TaggedError("SshInvalidTargetError")<{
|
||||
readonly message: string;
|
||||
}> {}
|
||||
export class SshHostDiscoveryError extends Schema.TaggedErrorClass<SshHostDiscoveryError>()(
|
||||
"SshHostDiscoveryError",
|
||||
{
|
||||
message: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {}
|
||||
|
||||
export class SshCommandError extends Data.TaggedError("SshCommandError")<{
|
||||
readonly message: string;
|
||||
readonly command: readonly string[];
|
||||
readonly exitCode: number | null;
|
||||
readonly stderr: string;
|
||||
readonly stdout?: string;
|
||||
readonly cause?: unknown;
|
||||
}> {}
|
||||
export class SshInvalidTargetError extends Schema.TaggedErrorClass<SshInvalidTargetError>()(
|
||||
"SshInvalidTargetError",
|
||||
{
|
||||
message: Schema.String,
|
||||
},
|
||||
) {}
|
||||
|
||||
export class SshLaunchError extends Data.TaggedError("SshLaunchError")<{
|
||||
readonly message: string;
|
||||
readonly stdout: string;
|
||||
readonly cause?: unknown;
|
||||
}> {}
|
||||
export class SshCommandError extends Schema.TaggedErrorClass<SshCommandError>()("SshCommandError", {
|
||||
message: Schema.String,
|
||||
command: SshCommandArgs,
|
||||
exitCode: Schema.NullOr(Schema.Number),
|
||||
stderr: Schema.String,
|
||||
stdout: Schema.optional(Schema.String),
|
||||
cause: Schema.optional(Schema.Defect()),
|
||||
}) {}
|
||||
|
||||
export class SshPairingError extends Data.TaggedError("SshPairingError")<{
|
||||
readonly message: string;
|
||||
readonly stdout: string;
|
||||
readonly cause?: unknown;
|
||||
}> {}
|
||||
export class SshLaunchError extends Schema.TaggedErrorClass<SshLaunchError>()("SshLaunchError", {
|
||||
message: Schema.String,
|
||||
stdout: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect()),
|
||||
}) {}
|
||||
|
||||
export class SshHttpBridgeError extends Data.TaggedError("SshHttpBridgeError")<{
|
||||
readonly message: string;
|
||||
readonly status?: number;
|
||||
readonly cause?: unknown;
|
||||
}> {}
|
||||
export class SshPairingError extends Schema.TaggedErrorClass<SshPairingError>()("SshPairingError", {
|
||||
message: Schema.String,
|
||||
stdout: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect()),
|
||||
}) {}
|
||||
|
||||
export class SshReadinessError extends Data.TaggedError("SshReadinessError")<{
|
||||
readonly message: string;
|
||||
readonly cause?: unknown;
|
||||
}> {}
|
||||
export class SshHttpBridgeError extends Schema.TaggedErrorClass<SshHttpBridgeError>()(
|
||||
"SshHttpBridgeError",
|
||||
{
|
||||
message: Schema.String,
|
||||
status: Schema.optional(Schema.Number),
|
||||
cause: Schema.optional(Schema.Defect()),
|
||||
},
|
||||
) {}
|
||||
|
||||
export class SshPasswordPromptError extends Data.TaggedError("SshPasswordPromptError")<{
|
||||
readonly message: string;
|
||||
readonly cause?: unknown;
|
||||
}> {}
|
||||
export class SshReadinessError extends Schema.TaggedErrorClass<SshReadinessError>()(
|
||||
"SshReadinessError",
|
||||
{
|
||||
message: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect()),
|
||||
},
|
||||
) {}
|
||||
|
||||
export class SshPasswordPromptError extends Schema.TaggedErrorClass<SshPasswordPromptError>()(
|
||||
"SshPasswordPromptError",
|
||||
{
|
||||
message: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect()),
|
||||
},
|
||||
) {}
|
||||
|
||||
export const SshEnvironmentError = Schema.Union([
|
||||
SshCommandError,
|
||||
SshInvalidTargetError,
|
||||
SshLaunchError,
|
||||
SshPairingError,
|
||||
SshReadinessError,
|
||||
SshPasswordPromptError,
|
||||
]);
|
||||
export type SshEnvironmentError = typeof SshEnvironmentError.Type;
|
||||
|
||||
export const SshError = Schema.Union([
|
||||
SshHostDiscoveryError,
|
||||
SshHttpBridgeError,
|
||||
SshEnvironmentError,
|
||||
]);
|
||||
export type SshError = typeof SshError.Type;
|
||||
@@ -242,9 +242,9 @@ describe("ssh tunnel scripts", () => {
|
||||
Effect.result(
|
||||
waitForHttpReady({
|
||||
baseUrl: "http://127.0.0.1:41773/",
|
||||
timeoutMs: 1_000,
|
||||
intervalMs: 100,
|
||||
probeTimeoutMs: 250,
|
||||
timeout: Duration.seconds(1),
|
||||
interval: Duration.millis(100),
|
||||
probeTimeout: Duration.millis(250),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
+50
-22
@@ -51,11 +51,14 @@ import {
|
||||
|
||||
export const DEFAULT_REMOTE_PORT = 3773;
|
||||
const REMOTE_PORT_SCAN_WINDOW = 200;
|
||||
const SSH_READY_TIMEOUT_MS = 20_000;
|
||||
const SSH_READY_PROBE_TIMEOUT_MS = 1_000;
|
||||
const TUNNEL_SHUTDOWN_TIMEOUT_MS = 2_000;
|
||||
const REMOTE_READY_TIMEOUT_MS = 15_000;
|
||||
const REMOTE_REUSE_READY_TIMEOUT_MS = 2_000;
|
||||
const SSH_READY_TIMEOUT = Duration.seconds(20);
|
||||
const SSH_READY_PROBE_TIMEOUT = Duration.seconds(1);
|
||||
const TUNNEL_SHUTDOWN_TIMEOUT = Duration.seconds(2);
|
||||
const REMOTE_READY_TIMEOUT = Duration.seconds(15);
|
||||
const REMOTE_REUSE_READY_TIMEOUT = Duration.seconds(2);
|
||||
const DEFAULT_HTTP_READY_TIMEOUT = Duration.seconds(30);
|
||||
const DEFAULT_HTTP_READY_INTERVAL = Duration.millis(100);
|
||||
const isSshReadinessError = Schema.is(SshReadinessError);
|
||||
|
||||
export interface RemoteT3RunnerOptions {
|
||||
readonly packageSpec?: string;
|
||||
@@ -233,7 +236,7 @@ function applyScriptPlaceholders(
|
||||
}
|
||||
|
||||
export function describeReadinessCause(cause: unknown): unknown {
|
||||
if (cause instanceof SshReadinessError) {
|
||||
if (isSshReadinessError(cause)) {
|
||||
return {
|
||||
_tag: cause._tag,
|
||||
message: cause.message,
|
||||
@@ -682,9 +685,9 @@ export function buildRemoteLaunchScript(input?: RemoteT3RunnerOptions): string {
|
||||
T3_WAIT_READY_SCRIPT: stripTrailingNewlines(REMOTE_WAIT_READY_SCRIPT),
|
||||
T3_DEFAULT_REMOTE_PORT: String(DEFAULT_REMOTE_PORT),
|
||||
T3_REMOTE_PORT_SCAN_WINDOW: String(REMOTE_PORT_SCAN_WINDOW),
|
||||
T3_READY_TIMEOUT_MS: String(REMOTE_READY_TIMEOUT_MS),
|
||||
T3_REUSE_READY_TIMEOUT_MS: String(REMOTE_REUSE_READY_TIMEOUT_MS),
|
||||
T3_READY_PROBE_TIMEOUT_MS: String(SSH_READY_PROBE_TIMEOUT_MS),
|
||||
T3_READY_TIMEOUT_MS: String(Duration.toMillis(REMOTE_READY_TIMEOUT)),
|
||||
T3_REUSE_READY_TIMEOUT_MS: String(Duration.toMillis(REMOTE_REUSE_READY_TIMEOUT)),
|
||||
T3_READY_PROBE_TIMEOUT_MS: String(Duration.toMillis(SSH_READY_PROBE_TIMEOUT)),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -856,7 +859,7 @@ const readRemoteServerLogTail = Effect.fn("ssh/tunnel.readRemoteServerLogTail")(
|
||||
const result = yield* runSshCommand(target, {
|
||||
remoteCommandArgs: ["sh", "-s"],
|
||||
stdin: buildRemoteLogTailScript(target),
|
||||
timeoutMs: 10_000,
|
||||
timeout: Duration.seconds(10),
|
||||
...(input?.authSecret === undefined ? {} : { authSecret: input.authSecret }),
|
||||
...(input?.batchMode === undefined ? {} : { batchMode: input.batchMode }),
|
||||
...(input?.interactiveAuth === undefined ? {} : { interactiveAuth: input.interactiveAuth }),
|
||||
@@ -864,17 +867,42 @@ const readRemoteServerLogTail = Effect.fn("ssh/tunnel.readRemoteServerLogTail")(
|
||||
return result.stdout.trim();
|
||||
});
|
||||
|
||||
function resolveDurationInput(
|
||||
duration: Duration.Input | undefined,
|
||||
durationMs: number | undefined,
|
||||
fallback: Duration.Duration,
|
||||
): Duration.Duration {
|
||||
return Duration.fromInputUnsafe(duration ?? durationMs ?? fallback);
|
||||
}
|
||||
|
||||
export const waitForHttpReady = Effect.fn("ssh/tunnel.waitForHttpReady")(function* (input: {
|
||||
readonly baseUrl: string;
|
||||
readonly timeout?: Duration.Input;
|
||||
readonly interval?: Duration.Input;
|
||||
readonly probeTimeout?: Duration.Input;
|
||||
/** @deprecated Prefer `timeout` with an Effect Duration input. */
|
||||
readonly timeoutMs?: number;
|
||||
/** @deprecated Prefer `interval` with an Effect Duration input. */
|
||||
readonly intervalMs?: number;
|
||||
/** @deprecated Prefer `probeTimeout` with an Effect Duration input. */
|
||||
readonly probeTimeoutMs?: number;
|
||||
readonly path?: string;
|
||||
}): Effect.fn.Return<void, SshReadinessError, HttpClient.HttpClient> {
|
||||
const timeoutMs = input.timeoutMs ?? 30_000;
|
||||
const intervalMs = input.intervalMs ?? 100;
|
||||
const probeTimeoutMs = input.probeTimeoutMs ?? SSH_READY_PROBE_TIMEOUT_MS;
|
||||
const retryPolicy = Schedule.spaced(Duration.millis(intervalMs)).pipe(
|
||||
const timeout = resolveDurationInput(input.timeout, input.timeoutMs, DEFAULT_HTTP_READY_TIMEOUT);
|
||||
const interval = resolveDurationInput(
|
||||
input.interval,
|
||||
input.intervalMs,
|
||||
DEFAULT_HTTP_READY_INTERVAL,
|
||||
);
|
||||
const probeTimeout = resolveDurationInput(
|
||||
input.probeTimeout,
|
||||
input.probeTimeoutMs,
|
||||
SSH_READY_PROBE_TIMEOUT,
|
||||
);
|
||||
const timeoutMs = Duration.toMillis(timeout);
|
||||
const intervalMs = Duration.toMillis(interval);
|
||||
const probeTimeoutMs = Duration.toMillis(probeTimeout);
|
||||
const retryPolicy = Schedule.spaced(interval).pipe(
|
||||
Schedule.take(Math.max(0, Math.ceil(timeoutMs / intervalMs))),
|
||||
);
|
||||
const requestUrl = new URL(input.path ?? "/", input.baseUrl).toString();
|
||||
@@ -896,7 +924,7 @@ export const waitForHttpReady = Effect.fn("ssh/tunnel.waitForHttpReady")(functio
|
||||
Effect.gen(function* () {
|
||||
attempt += 1;
|
||||
const responseOption = yield* effect.pipe(
|
||||
Effect.timeoutOption(Duration.millis(probeTimeoutMs)),
|
||||
Effect.timeoutOption(probeTimeout),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new SshReadinessError({
|
||||
@@ -921,7 +949,7 @@ export const waitForHttpReady = Effect.fn("ssh/tunnel.waitForHttpReady")(functio
|
||||
});
|
||||
}).pipe(
|
||||
Effect.mapError((cause) =>
|
||||
cause instanceof SshReadinessError
|
||||
isSshReadinessError(cause)
|
||||
? cause
|
||||
: new SshReadinessError({
|
||||
message: `Backend readiness probe failed at ${requestUrl}.`,
|
||||
@@ -942,14 +970,14 @@ export const waitForHttpReady = Effect.fn("ssh/tunnel.waitForHttpReady")(functio
|
||||
|
||||
const result = yield* readinessClient.execute(HttpClientRequest.get(requestUrl)).pipe(
|
||||
Effect.mapError((cause) =>
|
||||
cause instanceof SshReadinessError
|
||||
isSshReadinessError(cause)
|
||||
? cause
|
||||
: new SshReadinessError({
|
||||
message: `Backend readiness probe failed at ${requestUrl}.`,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Effect.timeoutOption(Duration.millis(timeoutMs)),
|
||||
Effect.timeoutOption(timeout),
|
||||
);
|
||||
|
||||
return yield* Option.match(result, {
|
||||
@@ -1166,7 +1194,7 @@ const startSshTunnel = Effect.fn("ssh/tunnel.startSshTunnel")(function* (input:
|
||||
yield* Effect.raceFirst(
|
||||
waitForHttpReady({
|
||||
baseUrl: input.httpBaseUrl,
|
||||
timeoutMs: SSH_READY_TIMEOUT_MS,
|
||||
timeout: SSH_READY_TIMEOUT,
|
||||
}),
|
||||
exitFailure,
|
||||
).pipe(
|
||||
@@ -1226,7 +1254,7 @@ const startSshTunnel = Effect.fn("ssh/tunnel.startSshTunnel")(function* (input:
|
||||
: child
|
||||
.kill({
|
||||
killSignal: "SIGTERM",
|
||||
forceKillAfter: TUNNEL_SHUTDOWN_TIMEOUT_MS,
|
||||
forceKillAfter: TUNNEL_SHUTDOWN_TIMEOUT,
|
||||
})
|
||||
.pipe(Effect.ignore),
|
||||
),
|
||||
@@ -1470,7 +1498,7 @@ const makeSshEnvironmentManager = Effect.fn("ssh/tunnel.SshEnvironmentManager.ma
|
||||
[
|
||||
tunnelEntry.process.kill({
|
||||
killSignal: "SIGTERM",
|
||||
forceKillAfter: TUNNEL_SHUTDOWN_TIMEOUT_MS,
|
||||
forceKillAfter: TUNNEL_SHUTDOWN_TIMEOUT,
|
||||
}),
|
||||
stopRemoteServer(
|
||||
tunnelEntry.target,
|
||||
@@ -1524,7 +1552,7 @@ const makeSshEnvironmentManager = Effect.fn("ssh/tunnel.SshEnvironmentManager.ma
|
||||
remotePort: entry.remotePort,
|
||||
});
|
||||
const readinessExit = yield* Effect.exit(
|
||||
waitForHttpReady({ baseUrl: entry.httpBaseUrl, timeoutMs: 2_000 }),
|
||||
waitForHttpReady({ baseUrl: entry.httpBaseUrl, timeout: Duration.seconds(2) }),
|
||||
);
|
||||
if (Exit.isSuccess(readinessExit)) {
|
||||
yield* Effect.logDebug("ssh.environment.tunnel.reused", {
|
||||
|
||||
Reference in new issue
Block a user