Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a8c8572fa0 | ||
|
|
8a817fbb26 | ||
|
|
1c9464e389 | ||
|
|
2393953551 | ||
|
|
eb78135632 | ||
|
|
86a88fb3ef | ||
|
|
f1d324b9d2 | ||
|
|
404cba92f6 | ||
|
|
5feb87d274 | ||
|
|
3ea6adf17d | ||
|
|
a56496c7f2 |
No files matched your search
@@ -1,7 +1,6 @@
|
||||
import type { RelayAgentActivityState } from "@t3tools/contracts/relay";
|
||||
import { RelayAgentActivityState as RelayAgentActivityStateSchema } from "@t3tools/contracts/relay";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Data from "effect/Data";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import { cast } from "effect/Function";
|
||||
@@ -13,23 +12,32 @@ import { and, desc, eq, isNull } from "drizzle-orm";
|
||||
import { RelayDb } from "../db.ts";
|
||||
import { relayAgentActivityRows, relayEnvironmentLinks } from "../persistence/schema.ts";
|
||||
|
||||
export class AgentActivityRowUpsertPersistenceError extends Data.TaggedError(
|
||||
export class AgentActivityRowUpsertPersistenceError extends Schema.TaggedErrorClass<AgentActivityRowUpsertPersistenceError>()(
|
||||
"AgentActivityRowUpsertPersistenceError",
|
||||
)<{
|
||||
readonly cause: unknown;
|
||||
}> {}
|
||||
{ cause: Schema.Defect() },
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Failed to persist agent activity state";
|
||||
}
|
||||
}
|
||||
|
||||
export class AgentActivityRowDeletePersistenceError extends Data.TaggedError(
|
||||
export class AgentActivityRowDeletePersistenceError extends Schema.TaggedErrorClass<AgentActivityRowDeletePersistenceError>()(
|
||||
"AgentActivityRowDeletePersistenceError",
|
||||
)<{
|
||||
readonly cause: unknown;
|
||||
}> {}
|
||||
{ cause: Schema.Defect() },
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Failed to delete agent activity state";
|
||||
}
|
||||
}
|
||||
|
||||
export class AgentActivityRowListPersistenceError extends Data.TaggedError(
|
||||
export class AgentActivityRowListPersistenceError extends Schema.TaggedErrorClass<AgentActivityRowListPersistenceError>()(
|
||||
"AgentActivityRowListPersistenceError",
|
||||
)<{
|
||||
readonly cause: unknown;
|
||||
}> {}
|
||||
{ cause: Schema.Defect() },
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Failed to list agent activity state";
|
||||
}
|
||||
}
|
||||
|
||||
export interface AgentActivityRowsShape {
|
||||
readonly upsert: (input: {
|
||||
|
||||
@@ -2,20 +2,13 @@ import * as NodeCrypto from "node:crypto";
|
||||
|
||||
import type { RelayAgentActivityAggregateState } from "@t3tools/contracts/relay";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Data from "effect/Data";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Encoding from "effect/Encoding";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Redacted from "effect/Redacted";
|
||||
import * as Schema from "effect/Schema";
|
||||
import {
|
||||
Headers,
|
||||
HttpClient,
|
||||
HttpClientRequest,
|
||||
type HttpBody,
|
||||
type HttpClientError,
|
||||
} from "effect/unstable/http";
|
||||
import { Headers, HttpClient, HttpClientRequest } from "effect/unstable/http";
|
||||
import type { ApnsCredentials } from "../Config.ts";
|
||||
import type { ApnsNotificationPayload } from "./apnsDeliveryJobs.ts";
|
||||
|
||||
@@ -45,18 +38,39 @@ export interface ApnsDeliveryResult {
|
||||
readonly apnsId: string | null;
|
||||
}
|
||||
|
||||
export class ApnsSigningError extends Data.TaggedError("ApnsSigningError")<{
|
||||
readonly phase: "encoding" | "signing";
|
||||
readonly cause: unknown;
|
||||
}> {}
|
||||
export class ApnsSigningError extends Schema.TaggedErrorClass<ApnsSigningError>()(
|
||||
"ApnsSigningError",
|
||||
{
|
||||
phase: Schema.Literals(["encoding", "signing"]),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed during APNs JWT ${this.phase}`;
|
||||
}
|
||||
}
|
||||
|
||||
export class ApnsHttpRequestError extends Data.TaggedError("ApnsHttpRequestError")<{
|
||||
readonly cause: HttpClientError.HttpClientError | HttpBody.HttpBodyError;
|
||||
}> {}
|
||||
export class ApnsHttpRequestError extends Schema.TaggedErrorClass<ApnsHttpRequestError>()(
|
||||
"ApnsHttpRequestError",
|
||||
{
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "APNs HTTP request failed";
|
||||
}
|
||||
}
|
||||
|
||||
export class ApnsInvalidResponseError extends Data.TaggedError("ApnsInvalidResponseError")<{
|
||||
readonly cause: unknown;
|
||||
}> {}
|
||||
export class ApnsInvalidResponseError extends Schema.TaggedErrorClass<ApnsInvalidResponseError>()(
|
||||
"ApnsInvalidResponseError",
|
||||
{
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "APNs returned an invalid response";
|
||||
}
|
||||
}
|
||||
|
||||
export type ApnsError = ApnsSigningError | ApnsHttpRequestError | ApnsInvalidResponseError;
|
||||
|
||||
|
||||
@@ -9,7 +9,6 @@ import {
|
||||
RelayAgentAwarenessPreferences as RelayAgentAwarenessPreferencesSchema,
|
||||
} from "@t3tools/contracts/relay";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Data from "effect/Data";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
@@ -74,9 +73,16 @@ export type ApnsDeliveryError =
|
||||
| LiveActivities.LiveActivityTargetListPersistenceError
|
||||
| LiveActivities.LiveActivityDeliveryMarkPersistenceError;
|
||||
|
||||
export class ApnsDeliveryJobClaimInFlight extends Data.TaggedError("ApnsDeliveryJobClaimInFlight")<{
|
||||
readonly sourceJobId: string;
|
||||
}> {}
|
||||
export class ApnsDeliveryJobClaimInFlight extends Schema.TaggedErrorClass<ApnsDeliveryJobClaimInFlight>()(
|
||||
"ApnsDeliveryJobClaimInFlight",
|
||||
{
|
||||
sourceJobId: Schema.String,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `APNs delivery job '${this.sourceJobId}' is already in flight`;
|
||||
}
|
||||
}
|
||||
|
||||
const decodeRelayAgentActivityAggregateStateJson = Schema.decodeUnknownOption(
|
||||
Schema.fromJsonString(RelayAgentActivityAggregateStateSchema),
|
||||
|
||||
@@ -2,10 +2,10 @@ import * as Alchemy from "alchemy";
|
||||
import * as Cloudflare from "alchemy/Cloudflare";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Data from "effect/Data";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import type { RelayDeliveryResult } from "@t3tools/contracts/relay";
|
||||
|
||||
@@ -22,9 +22,14 @@ import {
|
||||
} from "./apnsDeliveryJobs.ts";
|
||||
import * as RelayConfiguration from "../Config.ts";
|
||||
|
||||
export class ApnsDeliveryQueueSendError extends Data.TaggedError("ApnsDeliveryQueueSendError")<{
|
||||
readonly cause: unknown;
|
||||
}> {}
|
||||
export class ApnsDeliveryQueueSendError extends Schema.TaggedErrorClass<ApnsDeliveryQueueSendError>()(
|
||||
"ApnsDeliveryQueueSendError",
|
||||
{ cause: Schema.Defect() },
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Failed to enqueue APNs delivery";
|
||||
}
|
||||
}
|
||||
|
||||
export type ApnsDeliveryQueueError = ApnsDeliveryQueueSendError;
|
||||
|
||||
|
||||
@@ -1,20 +1,23 @@
|
||||
import * as Context from "effect/Context";
|
||||
import * as Data from "effect/Data";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import { and, eq, isNull } from "drizzle-orm";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import { RelayDb } from "../db.ts";
|
||||
import { relayDeliveryAttempts } from "../persistence/schema.ts";
|
||||
|
||||
export class DeliveryAttemptRecordPersistenceError extends Data.TaggedError(
|
||||
export class DeliveryAttemptRecordPersistenceError extends Schema.TaggedErrorClass<DeliveryAttemptRecordPersistenceError>()(
|
||||
"DeliveryAttemptRecordPersistenceError",
|
||||
)<{
|
||||
readonly cause: unknown;
|
||||
}> {}
|
||||
{ cause: Schema.Defect() },
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Failed to persist APNs delivery attempt";
|
||||
}
|
||||
}
|
||||
|
||||
export interface DeliveryAttemptInput {
|
||||
readonly userId: string | null;
|
||||
|
||||
@@ -3,31 +3,42 @@ import type {
|
||||
RelayDeviceRegistrationRequest,
|
||||
} from "@t3tools/contracts/relay";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Data from "effect/Data";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Schema from "effect/Schema";
|
||||
import { and, eq } from "drizzle-orm";
|
||||
import { sql } from "drizzle-orm";
|
||||
|
||||
import { RelayDb } from "../db.ts";
|
||||
import { relayLiveActivities, relayMobileDevices } from "../persistence/schema.ts";
|
||||
|
||||
export class DeviceRegistrationPersistenceError extends Data.TaggedError(
|
||||
export class DeviceRegistrationPersistenceError extends Schema.TaggedErrorClass<DeviceRegistrationPersistenceError>()(
|
||||
"DeviceRegistrationPersistenceError",
|
||||
)<{
|
||||
readonly cause: unknown;
|
||||
}> {}
|
||||
{ cause: Schema.Defect() },
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Failed to persist mobile device registration";
|
||||
}
|
||||
}
|
||||
|
||||
export class DeviceUnregistrationPersistenceError extends Data.TaggedError(
|
||||
export class DeviceUnregistrationPersistenceError extends Schema.TaggedErrorClass<DeviceUnregistrationPersistenceError>()(
|
||||
"DeviceUnregistrationPersistenceError",
|
||||
)<{
|
||||
readonly cause: unknown;
|
||||
}> {}
|
||||
{ cause: Schema.Defect() },
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Failed to unregister mobile device";
|
||||
}
|
||||
}
|
||||
|
||||
export class DeviceListPersistenceError extends Data.TaggedError("DeviceListPersistenceError")<{
|
||||
readonly cause: unknown;
|
||||
}> {}
|
||||
export class DeviceListPersistenceError extends Schema.TaggedErrorClass<DeviceListPersistenceError>()(
|
||||
"DeviceListPersistenceError",
|
||||
{ cause: Schema.Defect() },
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Failed to list mobile devices";
|
||||
}
|
||||
}
|
||||
|
||||
export interface DevicesShape {
|
||||
readonly register: (input: {
|
||||
|
||||
@@ -5,7 +5,6 @@ import type {
|
||||
} from "@t3tools/contracts/relay";
|
||||
import { RelayAgentActivityAggregateState as RelayAgentActivityAggregateStateSchema } from "@t3tools/contracts/relay";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Data from "effect/Data";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import { cast } from "effect/Function";
|
||||
@@ -16,23 +15,32 @@ import { and, eq, sql } from "drizzle-orm";
|
||||
import { RelayDb } from "../db.ts";
|
||||
import { relayLiveActivities, relayMobileDevices } from "../persistence/schema.ts";
|
||||
|
||||
export class LiveActivityRegistrationPersistenceError extends Data.TaggedError(
|
||||
export class LiveActivityRegistrationPersistenceError extends Schema.TaggedErrorClass<LiveActivityRegistrationPersistenceError>()(
|
||||
"LiveActivityRegistrationPersistenceError",
|
||||
)<{
|
||||
readonly cause: unknown;
|
||||
}> {}
|
||||
{ cause: Schema.Defect() },
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Failed to persist Live Activity registration";
|
||||
}
|
||||
}
|
||||
|
||||
export class LiveActivityTargetListPersistenceError extends Data.TaggedError(
|
||||
export class LiveActivityTargetListPersistenceError extends Schema.TaggedErrorClass<LiveActivityTargetListPersistenceError>()(
|
||||
"LiveActivityTargetListPersistenceError",
|
||||
)<{
|
||||
readonly cause: unknown;
|
||||
}> {}
|
||||
{ cause: Schema.Defect() },
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Failed to list Live Activity delivery targets";
|
||||
}
|
||||
}
|
||||
|
||||
export class LiveActivityDeliveryMarkPersistenceError extends Data.TaggedError(
|
||||
export class LiveActivityDeliveryMarkPersistenceError extends Schema.TaggedErrorClass<LiveActivityDeliveryMarkPersistenceError>()(
|
||||
"LiveActivityDeliveryMarkPersistenceError",
|
||||
)<{
|
||||
readonly cause: unknown;
|
||||
}> {}
|
||||
{ cause: Schema.Defect() },
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Failed to persist Live Activity delivery state";
|
||||
}
|
||||
}
|
||||
|
||||
export interface DeviceRow {
|
||||
readonly user_id: string;
|
||||
|
||||
@@ -2,7 +2,6 @@ import * as NodeCrypto from "node:crypto";
|
||||
|
||||
import { RelayAgentActivityAggregateState, type RelayDeliveryKind } from "@t3tools/contracts/relay";
|
||||
import { stableStringify } from "@t3tools/shared/relaySigning";
|
||||
import * as Data from "effect/Data";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Redacted from "effect/Redacted";
|
||||
@@ -50,13 +49,23 @@ export const SignedApnsDeliveryJob = Schema.Struct({
|
||||
});
|
||||
export type SignedApnsDeliveryJob = typeof SignedApnsDeliveryJob.Type;
|
||||
|
||||
export class ApnsDeliveryJobInvalid extends Data.TaggedError("ApnsDeliveryJobInvalid")<{
|
||||
readonly message: string;
|
||||
}> {}
|
||||
export class ApnsDeliveryJobInvalid extends Schema.TaggedErrorClass<ApnsDeliveryJobInvalid>()(
|
||||
"ApnsDeliveryJobInvalid",
|
||||
{
|
||||
message: Schema.String,
|
||||
},
|
||||
) {}
|
||||
|
||||
export class ApnsDeliveryJobExpired extends Data.TaggedError("ApnsDeliveryJobExpired")<{
|
||||
readonly expiresAt: string;
|
||||
}> {}
|
||||
export class ApnsDeliveryJobExpired extends Schema.TaggedErrorClass<ApnsDeliveryJobExpired>()(
|
||||
"ApnsDeliveryJobExpired",
|
||||
{
|
||||
expiresAt: Schema.String,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `APNs delivery job expired at ${this.expiresAt}`;
|
||||
}
|
||||
}
|
||||
|
||||
export type ApnsDeliveryJobVerificationError = ApnsDeliveryJobInvalid | ApnsDeliveryJobExpired;
|
||||
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import * as Context from "effect/Context";
|
||||
import * as Data from "effect/Data";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as HttpApiError from "effect/unstable/httpapi/HttpApiError";
|
||||
import { lt } from "drizzle-orm";
|
||||
|
||||
@@ -10,11 +10,16 @@ import { verifyDpopProof } from "@t3tools/shared/dpop";
|
||||
import { RelayDb } from "../db.ts";
|
||||
import { relayDpopProofs } from "../persistence/schema.ts";
|
||||
|
||||
export class DpopProofReplayPersistenceError extends Data.TaggedError(
|
||||
export class DpopProofReplayPersistenceError extends Schema.TaggedErrorClass<DpopProofReplayPersistenceError>()(
|
||||
"DpopProofReplayPersistenceError",
|
||||
)<{
|
||||
readonly cause: unknown;
|
||||
}> {}
|
||||
{
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Failed to persist DPoP proof replay state";
|
||||
}
|
||||
}
|
||||
|
||||
export interface DpopProofReplayShape {
|
||||
readonly verifyAndConsume: (input: {
|
||||
|
||||
@@ -22,6 +22,7 @@ import * as Redacted from "effect/Redacted";
|
||||
import * as Result from "effect/Result";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as TestClock from "effect/testing/TestClock";
|
||||
import * as Tracer from "effect/Tracer";
|
||||
import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/unstable/http";
|
||||
|
||||
import * as EnvironmentLinks from "./EnvironmentLinks.ts";
|
||||
@@ -50,6 +51,9 @@ const decodeHealthRequestBody = Schema.decodeUnknownSync(
|
||||
const decodeMintRequestBody = Schema.decodeUnknownSync(
|
||||
Schema.fromJsonString(RelayCloudMintCredentialRequest),
|
||||
);
|
||||
const isEnvironmentConnectNotAuthorized = Schema.is(
|
||||
EnvironmentConnector.EnvironmentConnectNotAuthorized,
|
||||
);
|
||||
|
||||
function requestBodyText(request: HttpClientRequest.HttpClientRequest): string {
|
||||
return request.body._tag === "Uint8Array" ? new TextDecoder().decode(request.body.body) : "{}";
|
||||
@@ -280,7 +284,13 @@ describe("EnvironmentConnector", () => {
|
||||
|
||||
expect(Result.isFailure(result)).toBe(true);
|
||||
if (Result.isFailure(result)) {
|
||||
expect(result.failure).toBeInstanceOf(EnvironmentConnector.EnvironmentConnectNotAuthorized);
|
||||
expect(isEnvironmentConnectNotAuthorized(result.failure)).toBe(true);
|
||||
if (isEnvironmentConnectNotAuthorized(result.failure)) {
|
||||
expect(result.failure).toMatchObject({
|
||||
operation: "status",
|
||||
reason: "endpoint_provider_not_managed",
|
||||
});
|
||||
}
|
||||
}
|
||||
expect(requestCount).toBe(0);
|
||||
}).pipe(
|
||||
@@ -300,6 +310,14 @@ describe("EnvironmentConnector", () => {
|
||||
|
||||
it.effect("rejects stale managed endpoints before sending a mint request", () => {
|
||||
let requestCount = 0;
|
||||
const spans: Array<Tracer.NativeSpan> = [];
|
||||
const tracer = Tracer.make({
|
||||
span: (options) => {
|
||||
const span = new Tracer.NativeSpan(options);
|
||||
spans.push(span);
|
||||
return span;
|
||||
},
|
||||
});
|
||||
const execute = () =>
|
||||
Effect.sync(() => {
|
||||
requestCount += 1;
|
||||
@@ -318,8 +336,27 @@ describe("EnvironmentConnector", () => {
|
||||
|
||||
expect(Result.isFailure(result)).toBe(true);
|
||||
if (Result.isFailure(result)) {
|
||||
expect(result.failure).toBeInstanceOf(EnvironmentConnector.EnvironmentConnectNotAuthorized);
|
||||
expect(isEnvironmentConnectNotAuthorized(result.failure)).toBe(true);
|
||||
if (isEnvironmentConnectNotAuthorized(result.failure)) {
|
||||
expect(result.failure).toMatchObject({
|
||||
operation: "connect",
|
||||
reason: "managed_endpoint_mismatch",
|
||||
});
|
||||
}
|
||||
}
|
||||
const resolutionSpan = spans.find(
|
||||
(span) => span.name === "relay.environment_connector.resolve_managed_endpoint",
|
||||
);
|
||||
expect(Object.fromEntries(resolutionSpan?.attributes ?? [])).toMatchObject({
|
||||
"relay.authorization.allocation_hostname": "env.example.test",
|
||||
"relay.authorization.allocation_has_ready_at": true,
|
||||
"relay.authorization.allocation_has_tunnel_id": true,
|
||||
"relay.authorization.allocation_has_dns_record_id": true,
|
||||
"relay.authorization.linked_http_base_url": "https://attacker.example.test/",
|
||||
"relay.authorization.linked_ws_base_url": "wss://attacker.example.test/ws",
|
||||
"relay.authorization.resolved_http_base_url": "https://env.example.test/",
|
||||
"relay.authorization.resolved_ws_base_url": "wss://env.example.test/ws",
|
||||
});
|
||||
expect(requestCount).toBe(0);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
@@ -333,6 +370,7 @@ describe("EnvironmentConnector", () => {
|
||||
}),
|
||||
}),
|
||||
),
|
||||
Effect.provideService(Tracer.Tracer, tracer),
|
||||
);
|
||||
});
|
||||
|
||||
@@ -355,7 +393,13 @@ describe("EnvironmentConnector", () => {
|
||||
|
||||
expect(Result.isFailure(result)).toBe(true);
|
||||
if (Result.isFailure(result)) {
|
||||
expect(result.failure).toBeInstanceOf(EnvironmentConnector.EnvironmentConnectNotAuthorized);
|
||||
expect(isEnvironmentConnectNotAuthorized(result.failure)).toBe(true);
|
||||
if (isEnvironmentConnectNotAuthorized(result.failure)) {
|
||||
expect(result.failure).toMatchObject({
|
||||
operation: "status",
|
||||
reason: "managed_endpoint_allocation_not_ready",
|
||||
});
|
||||
}
|
||||
}
|
||||
expect(requestCount).toBe(0);
|
||||
}).pipe(
|
||||
|
||||
@@ -28,7 +28,6 @@ import {
|
||||
import { stableStringify } from "@t3tools/shared/relaySigning";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as Data from "effect/Data";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
@@ -41,29 +40,93 @@ import { FetchHttpClient, HttpClient } from "effect/unstable/http";
|
||||
import * as EnvironmentLinks from "./EnvironmentLinks.ts";
|
||||
import * as ManagedEndpointAllocations from "./ManagedEndpointAllocations.ts";
|
||||
import * as RelayConfiguration from "../Config.ts";
|
||||
import { isManagedEndpointHostname } from "../deploymentConfig.ts";
|
||||
|
||||
export class EnvironmentConnectNotAuthorized extends Data.TaggedError(
|
||||
export const EnvironmentConnectNotAuthorizedReason = Schema.Literals([
|
||||
"client_proof_key_thumbprint_missing",
|
||||
"environment_link_not_found",
|
||||
"endpoint_provider_not_managed",
|
||||
"managed_endpoint_allocation_not_found",
|
||||
"managed_endpoint_base_domain_not_configured",
|
||||
"managed_endpoint_allocation_not_ready",
|
||||
"managed_endpoint_hostname_invalid",
|
||||
"managed_endpoint_mismatch",
|
||||
]);
|
||||
export type EnvironmentConnectNotAuthorizedReason =
|
||||
typeof EnvironmentConnectNotAuthorizedReason.Type;
|
||||
|
||||
function environmentConnectNotAuthorizedReasonMessage(
|
||||
reason: EnvironmentConnectNotAuthorizedReason,
|
||||
): string {
|
||||
switch (reason) {
|
||||
case "client_proof_key_thumbprint_missing":
|
||||
return "the client proof key thumbprint is missing";
|
||||
case "environment_link_not_found":
|
||||
return "no active environment link was found";
|
||||
case "endpoint_provider_not_managed":
|
||||
return "the linked endpoint is not relay-managed";
|
||||
case "managed_endpoint_allocation_not_found":
|
||||
return "no managed endpoint allocation was found";
|
||||
case "managed_endpoint_base_domain_not_configured":
|
||||
return "the managed endpoint base domain is not configured";
|
||||
case "managed_endpoint_allocation_not_ready":
|
||||
return "the managed endpoint allocation is incomplete";
|
||||
case "managed_endpoint_hostname_invalid":
|
||||
return "the managed endpoint hostname is invalid";
|
||||
case "managed_endpoint_mismatch":
|
||||
return "the linked endpoint does not match its managed allocation";
|
||||
}
|
||||
}
|
||||
|
||||
export class EnvironmentConnectNotAuthorized extends Schema.TaggedErrorClass<EnvironmentConnectNotAuthorized>()(
|
||||
"EnvironmentConnectNotAuthorized",
|
||||
)<{
|
||||
readonly environmentId: string;
|
||||
}> {}
|
||||
{
|
||||
environmentId: Schema.String,
|
||||
operation: Schema.Literals(["connect", "status"]),
|
||||
reason: EnvironmentConnectNotAuthorizedReason,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Environment '${this.environmentId}' is not authorized for ${this.operation}: ${environmentConnectNotAuthorizedReasonMessage(this.reason)}`;
|
||||
}
|
||||
}
|
||||
|
||||
export class EnvironmentMintRequestFailed extends Data.TaggedError("EnvironmentMintRequestFailed")<{
|
||||
readonly cause: unknown;
|
||||
}> {}
|
||||
export class EnvironmentMintRequestFailed extends Schema.TaggedErrorClass<EnvironmentMintRequestFailed>()(
|
||||
"EnvironmentMintRequestFailed",
|
||||
{
|
||||
environmentId: Schema.String,
|
||||
operation: Schema.Literals(["connect", "status"]),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Environment '${this.environmentId}' ${this.operation} request failed`;
|
||||
}
|
||||
}
|
||||
|
||||
export class EnvironmentMintRequestTimedOut extends Data.TaggedError(
|
||||
export class EnvironmentMintRequestTimedOut extends Schema.TaggedErrorClass<EnvironmentMintRequestTimedOut>()(
|
||||
"EnvironmentMintRequestTimedOut",
|
||||
)<{
|
||||
readonly environmentId: string;
|
||||
readonly timeoutMs: number;
|
||||
}> {}
|
||||
{
|
||||
environmentId: Schema.String,
|
||||
timeoutMs: Schema.Number,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Environment '${this.environmentId}' mint request timed out after ${this.timeoutMs}ms`;
|
||||
}
|
||||
}
|
||||
|
||||
export class EnvironmentMintResponseInvalid extends Data.TaggedError(
|
||||
export class EnvironmentMintResponseInvalid extends Schema.TaggedErrorClass<EnvironmentMintResponseInvalid>()(
|
||||
"EnvironmentMintResponseInvalid",
|
||||
)<{
|
||||
readonly environmentId: string;
|
||||
}> {}
|
||||
{
|
||||
environmentId: Schema.String,
|
||||
operation: Schema.Literals(["connect", "status"]),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Environment '${this.environmentId}' returned an invalid ${this.operation} response`;
|
||||
}
|
||||
}
|
||||
|
||||
export type EnvironmentConnectorError =
|
||||
| EnvironmentConnectNotAuthorized
|
||||
@@ -233,30 +296,91 @@ const make = Effect.gen(function* () {
|
||||
const resolveManagedEndpoint = Effect.fn("relay.environment_connector.resolve_managed_endpoint")(
|
||||
function* (input: {
|
||||
readonly userId: string;
|
||||
readonly operation: "connect" | "status";
|
||||
readonly link: EnvironmentLinks.RelayLinkedEnvironmentRecord;
|
||||
}) {
|
||||
if (input.link.endpoint.providerKind !== "cloudflare_tunnel") {
|
||||
yield* Effect.annotateCurrentSpan({
|
||||
"relay.authorization.endpoint_provider_kind": input.link.endpoint.providerKind,
|
||||
});
|
||||
return yield* new EnvironmentConnectNotAuthorized({
|
||||
environmentId: input.link.environmentId,
|
||||
operation: input.operation,
|
||||
reason: "endpoint_provider_not_managed",
|
||||
});
|
||||
}
|
||||
const allocation = yield* allocations.get({
|
||||
userId: input.userId,
|
||||
environmentId: input.link.environmentId,
|
||||
});
|
||||
const endpoint = allocation
|
||||
? ManagedEndpointAllocations.resolveReadyManagedEndpoint({
|
||||
allocation,
|
||||
baseDomain: settings.managedEndpointBaseDomain,
|
||||
})
|
||||
: null;
|
||||
if (!allocation) {
|
||||
return yield* new EnvironmentConnectNotAuthorized({
|
||||
environmentId: input.link.environmentId,
|
||||
operation: input.operation,
|
||||
reason: "managed_endpoint_allocation_not_found",
|
||||
});
|
||||
}
|
||||
const allocationAttributes = {
|
||||
"relay.authorization.allocation_hostname": allocation.hostname,
|
||||
"relay.authorization.allocation_has_ready_at": allocation.readyAt !== null,
|
||||
"relay.authorization.allocation_has_tunnel_id": allocation.tunnelId !== null,
|
||||
"relay.authorization.allocation_has_dns_record_id": allocation.dnsRecordId !== null,
|
||||
} as const;
|
||||
if (!settings.managedEndpointBaseDomain) {
|
||||
yield* Effect.annotateCurrentSpan(allocationAttributes);
|
||||
return yield* new EnvironmentConnectNotAuthorized({
|
||||
environmentId: input.link.environmentId,
|
||||
operation: input.operation,
|
||||
reason: "managed_endpoint_base_domain_not_configured",
|
||||
});
|
||||
}
|
||||
if (
|
||||
allocation.readyAt === null ||
|
||||
allocation.tunnelId === null ||
|
||||
allocation.dnsRecordId === null
|
||||
) {
|
||||
yield* Effect.annotateCurrentSpan(allocationAttributes);
|
||||
return yield* new EnvironmentConnectNotAuthorized({
|
||||
environmentId: input.link.environmentId,
|
||||
operation: input.operation,
|
||||
reason: "managed_endpoint_allocation_not_ready",
|
||||
});
|
||||
}
|
||||
if (!isManagedEndpointHostname(allocation.hostname, settings.managedEndpointBaseDomain)) {
|
||||
yield* Effect.annotateCurrentSpan({
|
||||
...allocationAttributes,
|
||||
"relay.authorization.managed_endpoint_base_domain": settings.managedEndpointBaseDomain,
|
||||
});
|
||||
return yield* new EnvironmentConnectNotAuthorized({
|
||||
environmentId: input.link.environmentId,
|
||||
operation: input.operation,
|
||||
reason: "managed_endpoint_hostname_invalid",
|
||||
});
|
||||
}
|
||||
const endpoint = ManagedEndpointAllocations.resolveReadyManagedEndpoint({
|
||||
allocation,
|
||||
baseDomain: settings.managedEndpointBaseDomain,
|
||||
});
|
||||
if (
|
||||
endpoint === null ||
|
||||
endpoint.httpBaseUrl !== input.link.endpoint.httpBaseUrl ||
|
||||
endpoint.wsBaseUrl !== input.link.endpoint.wsBaseUrl
|
||||
) {
|
||||
yield* Effect.annotateCurrentSpan({
|
||||
...allocationAttributes,
|
||||
"relay.authorization.linked_http_base_url": input.link.endpoint.httpBaseUrl,
|
||||
"relay.authorization.linked_ws_base_url": input.link.endpoint.wsBaseUrl,
|
||||
...(endpoint
|
||||
? {
|
||||
"relay.authorization.resolved_http_base_url": endpoint.httpBaseUrl,
|
||||
"relay.authorization.resolved_ws_base_url": endpoint.wsBaseUrl,
|
||||
}
|
||||
: {}),
|
||||
});
|
||||
return yield* new EnvironmentConnectNotAuthorized({
|
||||
environmentId: input.link.environmentId,
|
||||
operation: input.operation,
|
||||
reason: "managed_endpoint_mismatch",
|
||||
});
|
||||
}
|
||||
return endpoint;
|
||||
@@ -271,20 +395,42 @@ const make = Effect.gen(function* () {
|
||||
});
|
||||
const link = yield* links.getForUser(input);
|
||||
if (!link) {
|
||||
return yield* new EnvironmentConnectNotAuthorized({ environmentId: input.environmentId });
|
||||
return yield* new EnvironmentConnectNotAuthorized({
|
||||
environmentId: input.environmentId,
|
||||
operation: "status",
|
||||
reason: "environment_link_not_found",
|
||||
});
|
||||
}
|
||||
const endpoint = yield* resolveManagedEndpoint({ userId: input.userId, link });
|
||||
const endpoint = yield* resolveManagedEndpoint({
|
||||
userId: input.userId,
|
||||
operation: "status",
|
||||
link,
|
||||
});
|
||||
const now = yield* DateTime.now;
|
||||
const expiresAt = DateTime.add(now, { minutes: 2 });
|
||||
const nonce = yield* crypto.randomUUIDv4.pipe(
|
||||
Effect.mapError((cause) => new EnvironmentMintRequestFailed({ cause })),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new EnvironmentMintRequestFailed({
|
||||
environmentId: input.environmentId,
|
||||
operation: "status",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const payload = {
|
||||
iss: relayIssuer,
|
||||
aud: `t3-env:${link.environmentId}`,
|
||||
sub: input.userId,
|
||||
jti: yield* crypto.randomUUIDv4.pipe(
|
||||
Effect.mapError((cause) => new EnvironmentMintRequestFailed({ cause })),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new EnvironmentMintRequestFailed({
|
||||
environmentId: input.environmentId,
|
||||
operation: "status",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
iat: Math.floor(now.epochMilliseconds / 1_000),
|
||||
exp: Math.floor(expiresAt.epochMilliseconds / 1_000),
|
||||
@@ -296,7 +442,16 @@ const make = Effect.gen(function* () {
|
||||
privateKey: Redacted.value(settings.cloudMintPrivateKey),
|
||||
typ: RELAY_HEALTH_REQUEST_TYP,
|
||||
payload,
|
||||
}).pipe(Effect.mapError((cause) => new EnvironmentMintRequestFailed({ cause })));
|
||||
}).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new EnvironmentMintRequestFailed({
|
||||
environmentId: input.environmentId,
|
||||
operation: "status",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const checkedAt = DateTime.formatIso(now);
|
||||
const environmentClient = yield* makeEnvironmentClient(endpoint.httpBaseUrl);
|
||||
const responseOption = yield* environmentClient.cloud.health({ payload: { proof } }).pipe(
|
||||
@@ -336,7 +491,10 @@ const make = Effect.gen(function* () {
|
||||
now: yield* DateTime.now,
|
||||
});
|
||||
if (!verified) {
|
||||
return yield* new EnvironmentMintResponseInvalid({ environmentId: input.environmentId });
|
||||
return yield* new EnvironmentMintResponseInvalid({
|
||||
environmentId: input.environmentId,
|
||||
operation: "status",
|
||||
});
|
||||
}
|
||||
return {
|
||||
environmentId: link.environmentId,
|
||||
@@ -354,24 +512,50 @@ const make = Effect.gen(function* () {
|
||||
...(input.deviceId ? { "relay.mobile.device_id": input.deviceId } : {}),
|
||||
});
|
||||
if (input.clientProofKeyThumbprint.trim().length === 0) {
|
||||
return yield* new EnvironmentConnectNotAuthorized({ environmentId: input.environmentId });
|
||||
return yield* new EnvironmentConnectNotAuthorized({
|
||||
environmentId: input.environmentId,
|
||||
operation: "connect",
|
||||
reason: "client_proof_key_thumbprint_missing",
|
||||
});
|
||||
}
|
||||
const link = yield* links.getForUser(input);
|
||||
if (!link) {
|
||||
return yield* new EnvironmentConnectNotAuthorized({ environmentId: input.environmentId });
|
||||
return yield* new EnvironmentConnectNotAuthorized({
|
||||
environmentId: input.environmentId,
|
||||
operation: "connect",
|
||||
reason: "environment_link_not_found",
|
||||
});
|
||||
}
|
||||
const endpoint = yield* resolveManagedEndpoint({ userId: input.userId, link });
|
||||
const endpoint = yield* resolveManagedEndpoint({
|
||||
userId: input.userId,
|
||||
operation: "connect",
|
||||
link,
|
||||
});
|
||||
const now = yield* DateTime.now;
|
||||
const expiresAt = DateTime.add(now, { minutes: 2 });
|
||||
const nonce = yield* crypto.randomUUIDv4.pipe(
|
||||
Effect.mapError((cause) => new EnvironmentMintRequestFailed({ cause })),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new EnvironmentMintRequestFailed({
|
||||
environmentId: input.environmentId,
|
||||
operation: "connect",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const payload = {
|
||||
iss: relayIssuer,
|
||||
aud: `t3-env:${link.environmentId}`,
|
||||
sub: input.userId,
|
||||
jti: yield* crypto.randomUUIDv4.pipe(
|
||||
Effect.mapError((cause) => new EnvironmentMintRequestFailed({ cause })),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new EnvironmentMintRequestFailed({
|
||||
environmentId: input.environmentId,
|
||||
operation: "connect",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
iat: Math.floor(now.epochMilliseconds / 1_000),
|
||||
exp: Math.floor(expiresAt.epochMilliseconds / 1_000),
|
||||
@@ -386,11 +570,27 @@ const make = Effect.gen(function* () {
|
||||
privateKey: Redacted.value(settings.cloudMintPrivateKey),
|
||||
typ: RELAY_MINT_REQUEST_TYP,
|
||||
payload,
|
||||
}).pipe(Effect.mapError((cause) => new EnvironmentMintRequestFailed({ cause })));
|
||||
}).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new EnvironmentMintRequestFailed({
|
||||
environmentId: input.environmentId,
|
||||
operation: "connect",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const environmentClient = yield* makeEnvironmentClient(endpoint.httpBaseUrl);
|
||||
const decoded = yield* environmentClient.cloud.t3MintCredential({ payload: { proof } }).pipe(
|
||||
withoutRedirects,
|
||||
Effect.mapError((cause) => new EnvironmentMintRequestFailed({ cause })),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new EnvironmentMintRequestFailed({
|
||||
environmentId: input.environmentId,
|
||||
operation: "connect",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Effect.timeoutOption(Duration.millis(ENVIRONMENT_MINT_REQUEST_TIMEOUT_MS)),
|
||||
Effect.flatMap(
|
||||
Option.match({
|
||||
@@ -415,7 +615,10 @@ const make = Effect.gen(function* () {
|
||||
nowEpochSeconds: Math.floor(now.epochMilliseconds / 1_000),
|
||||
});
|
||||
if (!verified) {
|
||||
return yield* new EnvironmentMintResponseInvalid({ environmentId: input.environmentId });
|
||||
return yield* new EnvironmentMintResponseInvalid({
|
||||
environmentId: input.environmentId,
|
||||
operation: "connect",
|
||||
});
|
||||
}
|
||||
return {
|
||||
environmentId: link.environmentId,
|
||||
|
||||
@@ -1,33 +1,42 @@
|
||||
import * as Context from "effect/Context";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as Data from "effect/Data";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Encoding from "effect/Encoding";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Schema from "effect/Schema";
|
||||
import { and, eq, isNull, ne, notExists } from "drizzle-orm";
|
||||
|
||||
import { RelayDb } from "../db.ts";
|
||||
import { relayEnvironmentCredentials, relayEnvironmentLinks } from "../persistence/schema.ts";
|
||||
|
||||
export class EnvironmentCredentialCreatePersistenceError extends Data.TaggedError(
|
||||
export class EnvironmentCredentialCreatePersistenceError extends Schema.TaggedErrorClass<EnvironmentCredentialCreatePersistenceError>()(
|
||||
"EnvironmentCredentialCreatePersistenceError",
|
||||
)<{
|
||||
readonly cause: unknown;
|
||||
}> {}
|
||||
{ cause: Schema.Defect() },
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Failed to persist environment credential";
|
||||
}
|
||||
}
|
||||
|
||||
export class EnvironmentCredentialAuthenticatePersistenceError extends Data.TaggedError(
|
||||
export class EnvironmentCredentialAuthenticatePersistenceError extends Schema.TaggedErrorClass<EnvironmentCredentialAuthenticatePersistenceError>()(
|
||||
"EnvironmentCredentialAuthenticatePersistenceError",
|
||||
)<{
|
||||
readonly cause: unknown;
|
||||
}> {}
|
||||
{ cause: Schema.Defect() },
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Failed to authenticate environment credential";
|
||||
}
|
||||
}
|
||||
|
||||
export class EnvironmentCredentialRevokePersistenceError extends Data.TaggedError(
|
||||
export class EnvironmentCredentialRevokePersistenceError extends Schema.TaggedErrorClass<EnvironmentCredentialRevokePersistenceError>()(
|
||||
"EnvironmentCredentialRevokePersistenceError",
|
||||
)<{
|
||||
readonly cause: unknown;
|
||||
}> {}
|
||||
{ cause: Schema.Defect() },
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Failed to revoke environment credential";
|
||||
}
|
||||
}
|
||||
|
||||
export interface EnvironmentCredentialPrincipal {
|
||||
readonly credentialId: string;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import {
|
||||
RelayEnvironmentLinkProofPayload,
|
||||
type RelayEnvironmentLinkProofInvalidReason,
|
||||
RelayEnvironmentLinkProofInvalidReason,
|
||||
type RelayEnvironmentLinkRequest,
|
||||
} from "@t3tools/contracts/relay";
|
||||
import {
|
||||
@@ -10,7 +10,6 @@ import {
|
||||
verifyRelayJwt,
|
||||
} from "@t3tools/shared/relayJwt";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Data from "effect/Data";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
@@ -23,14 +22,28 @@ import * as EnvironmentLinks from "./EnvironmentLinks.ts";
|
||||
import * as ManagedEndpointProvider from "./ManagedEndpointProvider.ts";
|
||||
import * as RelayConfiguration from "../Config.ts";
|
||||
|
||||
export class EnvironmentLinkProofExpired extends Data.TaggedError("EnvironmentLinkProofExpired")<{
|
||||
readonly expiresAt: string;
|
||||
}> {}
|
||||
export class EnvironmentLinkProofExpired extends Schema.TaggedErrorClass<EnvironmentLinkProofExpired>()(
|
||||
"EnvironmentLinkProofExpired",
|
||||
{
|
||||
expiresAt: Schema.String,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Environment link proof expired at ${this.expiresAt}`;
|
||||
}
|
||||
}
|
||||
|
||||
export class EnvironmentLinkProofInvalid extends Data.TaggedError("EnvironmentLinkProofInvalid")<{
|
||||
readonly environmentId: string;
|
||||
readonly reason: RelayEnvironmentLinkProofInvalidReason;
|
||||
}> {}
|
||||
export class EnvironmentLinkProofInvalid extends Schema.TaggedErrorClass<EnvironmentLinkProofInvalid>()(
|
||||
"EnvironmentLinkProofInvalid",
|
||||
{
|
||||
environmentId: Schema.String,
|
||||
reason: RelayEnvironmentLinkProofInvalidReason,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Environment '${this.environmentId}' link proof is invalid: ${this.reason}`;
|
||||
}
|
||||
}
|
||||
|
||||
export type EnvironmentLinkError =
|
||||
| EnvironmentLinkProofExpired
|
||||
|
||||
@@ -5,10 +5,10 @@ import type {
|
||||
RelayManagedEndpoint,
|
||||
} from "@t3tools/contracts/relay";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Data from "effect/Data";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Schema from "effect/Schema";
|
||||
import { and, eq, isNull, or } from "drizzle-orm";
|
||||
|
||||
import { RelayDb } from "../db.ts";
|
||||
@@ -24,41 +24,59 @@ export interface AgentAwarenessDeliveryUserRecord {
|
||||
readonly liveActivitiesEnabled: boolean;
|
||||
}
|
||||
|
||||
export class EnvironmentLinkUpsertPersistenceError extends Data.TaggedError(
|
||||
export class EnvironmentLinkUpsertPersistenceError extends Schema.TaggedErrorClass<EnvironmentLinkUpsertPersistenceError>()(
|
||||
"EnvironmentLinkUpsertPersistenceError",
|
||||
)<{
|
||||
readonly cause: unknown;
|
||||
}> {}
|
||||
{ cause: Schema.Defect() },
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Failed to persist environment link";
|
||||
}
|
||||
}
|
||||
|
||||
export class EnvironmentLinkUserListPersistenceError extends Data.TaggedError(
|
||||
export class EnvironmentLinkUserListPersistenceError extends Schema.TaggedErrorClass<EnvironmentLinkUserListPersistenceError>()(
|
||||
"EnvironmentLinkUserListPersistenceError",
|
||||
)<{
|
||||
readonly cause: unknown;
|
||||
}> {}
|
||||
{ cause: Schema.Defect() },
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Failed to list users linked to environment";
|
||||
}
|
||||
}
|
||||
|
||||
export class EnvironmentPublicKeyListPersistenceError extends Data.TaggedError(
|
||||
export class EnvironmentPublicKeyListPersistenceError extends Schema.TaggedErrorClass<EnvironmentPublicKeyListPersistenceError>()(
|
||||
"EnvironmentPublicKeyListPersistenceError",
|
||||
)<{
|
||||
readonly cause: unknown;
|
||||
}> {}
|
||||
{ cause: Schema.Defect() },
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Failed to list environment public keys";
|
||||
}
|
||||
}
|
||||
|
||||
export class EnvironmentLinkListPersistenceError extends Data.TaggedError(
|
||||
export class EnvironmentLinkListPersistenceError extends Schema.TaggedErrorClass<EnvironmentLinkListPersistenceError>()(
|
||||
"EnvironmentLinkListPersistenceError",
|
||||
)<{
|
||||
readonly cause: unknown;
|
||||
}> {}
|
||||
{ cause: Schema.Defect() },
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Failed to list environment links";
|
||||
}
|
||||
}
|
||||
|
||||
export class EnvironmentLinkLookupPersistenceError extends Data.TaggedError(
|
||||
export class EnvironmentLinkLookupPersistenceError extends Schema.TaggedErrorClass<EnvironmentLinkLookupPersistenceError>()(
|
||||
"EnvironmentLinkLookupPersistenceError",
|
||||
)<{
|
||||
readonly cause: unknown;
|
||||
}> {}
|
||||
{ cause: Schema.Defect() },
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Failed to look up environment link";
|
||||
}
|
||||
}
|
||||
|
||||
export class EnvironmentLinkRevokePersistenceError extends Data.TaggedError(
|
||||
export class EnvironmentLinkRevokePersistenceError extends Schema.TaggedErrorClass<EnvironmentLinkRevokePersistenceError>()(
|
||||
"EnvironmentLinkRevokePersistenceError",
|
||||
)<{
|
||||
readonly cause: unknown;
|
||||
}> {}
|
||||
{ cause: Schema.Defect() },
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Failed to revoke environment link";
|
||||
}
|
||||
}
|
||||
|
||||
export interface EnvironmentLinksShape {
|
||||
readonly upsert: (input: {
|
||||
|
||||
@@ -11,7 +11,6 @@ import {
|
||||
import { stableStringify } from "@t3tools/shared/relaySigning";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as Data from "effect/Data";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Encoding from "effect/Encoding";
|
||||
@@ -21,23 +20,38 @@ import * as Schema from "effect/Schema";
|
||||
import * as DpopProofs from "../auth/DpopProofs.ts";
|
||||
import * as RelayConfiguration from "../Config.ts";
|
||||
|
||||
export class EnvironmentPublishSignatureExpired extends Data.TaggedError(
|
||||
export class EnvironmentPublishSignatureExpired extends Schema.TaggedErrorClass<EnvironmentPublishSignatureExpired>()(
|
||||
"EnvironmentPublishSignatureExpired",
|
||||
)<{
|
||||
readonly expiresAt: string;
|
||||
}> {}
|
||||
{
|
||||
expiresAt: Schema.String,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Environment publish signature expired at ${this.expiresAt}`;
|
||||
}
|
||||
}
|
||||
|
||||
export class EnvironmentPublishSignatureInvalid extends Data.TaggedError(
|
||||
export class EnvironmentPublishSignatureInvalid extends Schema.TaggedErrorClass<EnvironmentPublishSignatureInvalid>()(
|
||||
"EnvironmentPublishSignatureInvalid",
|
||||
)<{
|
||||
readonly environmentId: string;
|
||||
}> {}
|
||||
{
|
||||
environmentId: Schema.String,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Environment '${this.environmentId}' publish signature is invalid`;
|
||||
}
|
||||
}
|
||||
|
||||
export class EnvironmentPublishPublicKeyMissing extends Data.TaggedError(
|
||||
export class EnvironmentPublishPublicKeyMissing extends Schema.TaggedErrorClass<EnvironmentPublishPublicKeyMissing>()(
|
||||
"EnvironmentPublishPublicKeyMissing",
|
||||
)<{
|
||||
readonly environmentId: string;
|
||||
}> {}
|
||||
{
|
||||
environmentId: Schema.String,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Environment '${this.environmentId}' has no publish public key`;
|
||||
}
|
||||
}
|
||||
|
||||
export type EnvironmentPublishSignatureError =
|
||||
| EnvironmentPublishSignatureExpired
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
import type { RelayManagedEndpoint } from "@t3tools/contracts/relay";
|
||||
import { and, eq } from "drizzle-orm";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Data from "effect/Data";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import { RelayDb } from "../db.ts";
|
||||
import { isManagedEndpointHostname, managedEndpointForHostname } from "../deploymentConfig.ts";
|
||||
@@ -36,11 +36,17 @@ export function resolveReadyManagedEndpoint(input: {
|
||||
return managedEndpointForHostname(input.allocation.hostname);
|
||||
}
|
||||
|
||||
export class ManagedEndpointAllocationPersistenceError extends Data.TaggedError(
|
||||
export class ManagedEndpointAllocationPersistenceError extends Schema.TaggedErrorClass<ManagedEndpointAllocationPersistenceError>()(
|
||||
"ManagedEndpointAllocationPersistenceError",
|
||||
)<{
|
||||
readonly cause: unknown;
|
||||
}> {}
|
||||
{ cause: Schema.Defect() },
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Failed to persist managed endpoint allocation";
|
||||
}
|
||||
}
|
||||
const isManagedEndpointAllocationPersistenceError = Schema.is(
|
||||
ManagedEndpointAllocationPersistenceError,
|
||||
);
|
||||
|
||||
interface ManagedEndpointAllocationKey {
|
||||
readonly userId: string;
|
||||
@@ -98,7 +104,7 @@ const whereAllocation = (input: ManagedEndpointAllocationKey) =>
|
||||
);
|
||||
|
||||
const persistenceError = (cause: unknown) =>
|
||||
cause instanceof ManagedEndpointAllocationPersistenceError
|
||||
isManagedEndpointAllocationPersistenceError(cause)
|
||||
? cause
|
||||
: new ManagedEndpointAllocationPersistenceError({ cause });
|
||||
|
||||
|
||||
@@ -3,12 +3,12 @@ import * as Cloudflare from "alchemy/Cloudflare";
|
||||
import * as Arr from "effect/Array";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as Data from "effect/Data";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Encoding from "effect/Encoding";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Result from "effect/Result";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import type {
|
||||
RelayManagedEndpoint,
|
||||
@@ -25,28 +25,44 @@ import {
|
||||
} from "../deploymentConfig.ts";
|
||||
import { ManagedEndpointAllocations } from "./ManagedEndpointAllocations.ts";
|
||||
|
||||
export class ManagedEndpointProvisioningNotConfigured extends Data.TaggedError(
|
||||
export class ManagedEndpointProvisioningNotConfigured extends Schema.TaggedErrorClass<ManagedEndpointProvisioningNotConfigured>()(
|
||||
"ManagedEndpointProvisioningNotConfigured",
|
||||
)<{}> {}
|
||||
{},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Managed endpoint provisioning is not configured";
|
||||
}
|
||||
}
|
||||
|
||||
export class ManagedEndpointProvisioningFailed extends Data.TaggedError(
|
||||
export class ManagedEndpointProvisioningFailed extends Schema.TaggedErrorClass<ManagedEndpointProvisioningFailed>()(
|
||||
"ManagedEndpointProvisioningFailed",
|
||||
)<{
|
||||
readonly cause: unknown;
|
||||
}> {}
|
||||
{ cause: Schema.Defect() },
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Managed endpoint provisioning failed";
|
||||
}
|
||||
}
|
||||
|
||||
export class ManagedEndpointDeprovisioningFailed extends Data.TaggedError(
|
||||
export class ManagedEndpointDeprovisioningFailed extends Schema.TaggedErrorClass<ManagedEndpointDeprovisioningFailed>()(
|
||||
"ManagedEndpointDeprovisioningFailed",
|
||||
)<{
|
||||
readonly cause: unknown;
|
||||
}> {}
|
||||
{ cause: Schema.Defect() },
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Managed endpoint deprovisioning failed";
|
||||
}
|
||||
}
|
||||
|
||||
export class ManagedEndpointOriginNotAllowed extends Data.TaggedError(
|
||||
export class ManagedEndpointOriginNotAllowed extends Schema.TaggedErrorClass<ManagedEndpointOriginNotAllowed>()(
|
||||
"ManagedEndpointOriginNotAllowed",
|
||||
)<{
|
||||
readonly host: string;
|
||||
readonly port: number;
|
||||
}> {}
|
||||
{
|
||||
host: Schema.String,
|
||||
port: Schema.Number,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Managed endpoint origin '${this.host}:${this.port}' is not allowed`;
|
||||
}
|
||||
}
|
||||
|
||||
export type ManagedEndpointProviderError =
|
||||
| ManagedEndpointProvisioningNotConfigured
|
||||
@@ -80,11 +96,14 @@ interface ManagedEndpointTunnel {
|
||||
readonly name?: string | null;
|
||||
}
|
||||
|
||||
export class ManagedEndpointTunnelClientError extends Data.TaggedError(
|
||||
export class ManagedEndpointTunnelClientError extends Schema.TaggedErrorClass<ManagedEndpointTunnelClientError>()(
|
||||
"ManagedEndpointTunnelClientError",
|
||||
)<{
|
||||
readonly cause: unknown;
|
||||
}> {}
|
||||
{ cause: Schema.Defect() },
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Managed endpoint tunnel provider request failed";
|
||||
}
|
||||
}
|
||||
|
||||
export interface ManagedEndpointTunnelClientShape {
|
||||
readonly list: (request: {
|
||||
@@ -124,11 +143,14 @@ interface ManagedEndpointCnameRecordInput {
|
||||
readonly proxied: true;
|
||||
}
|
||||
|
||||
export class ManagedEndpointDnsClientError extends Data.TaggedError(
|
||||
export class ManagedEndpointDnsClientError extends Schema.TaggedErrorClass<ManagedEndpointDnsClientError>()(
|
||||
"ManagedEndpointDnsClientError",
|
||||
)<{
|
||||
readonly cause: unknown;
|
||||
}> {}
|
||||
{ cause: Schema.Defect() },
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Managed endpoint DNS provider request failed";
|
||||
}
|
||||
}
|
||||
|
||||
export interface ManagedEndpointDnsClientShape {
|
||||
readonly listRecords: (
|
||||
|
||||
+14
-11
@@ -1,6 +1,5 @@
|
||||
import { createClerkClient, verifyToken } from "@clerk/backend";
|
||||
import { sql as drizzleSql } from "drizzle-orm";
|
||||
import * as Data from "effect/Data";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as Context from "effect/Context";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
@@ -813,9 +812,16 @@ export const serverApi = HttpApiBuilder.group(
|
||||
}),
|
||||
);
|
||||
|
||||
class ClerkTokenVerificationFailed extends Data.TaggedError("ClerkTokenVerificationFailed")<{
|
||||
readonly cause: unknown;
|
||||
}> {}
|
||||
class ClerkTokenVerificationFailed extends Schema.TaggedErrorClass<ClerkTokenVerificationFailed>()(
|
||||
"ClerkTokenVerificationFailed",
|
||||
{
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Clerk token verification failed";
|
||||
}
|
||||
}
|
||||
|
||||
const isHttpUnauthorized = Schema.is(HttpApiError.Unauthorized);
|
||||
|
||||
@@ -824,7 +830,7 @@ const currentTraceId = Effect.currentParentSpan.pipe(
|
||||
Effect.orElseSucceed(() => "unavailable"),
|
||||
);
|
||||
|
||||
const COMMON_AUTH_INVALID_REASONS = [
|
||||
const RelayCommonPersistenceError = Schema.Union([
|
||||
Devices.DeviceRegistrationPersistenceError,
|
||||
Devices.DeviceUnregistrationPersistenceError,
|
||||
Devices.DeviceListPersistenceError,
|
||||
@@ -844,18 +850,15 @@ const COMMON_AUTH_INVALID_REASONS = [
|
||||
AgentActivityRows.AgentActivityRowListPersistenceError,
|
||||
LiveActivities.LiveActivityDeliveryMarkPersistenceError,
|
||||
DeliveryAttempts.DeliveryAttemptRecordPersistenceError,
|
||||
] as const;
|
||||
type RelayCommonPersistenceError = InstanceType<(typeof COMMON_AUTH_INVALID_REASONS)[number]>;
|
||||
]);
|
||||
type RelayCommonPersistenceError = typeof RelayCommonPersistenceError.Type;
|
||||
const isRelayCommonPersistenceError = Schema.is(RelayCommonPersistenceError);
|
||||
|
||||
type MapRelayCommonApiError<E> =
|
||||
| Exclude<E, HttpApiError.Unauthorized | RelayCommonPersistenceError>
|
||||
| (Extract<E, HttpApiError.Unauthorized> extends never ? never : RelayAuthInvalidError)
|
||||
| (Extract<E, RelayCommonPersistenceError> extends never ? never : RelayInternalError);
|
||||
|
||||
function isRelayCommonPersistenceError(error: unknown): error is RelayCommonPersistenceError {
|
||||
return COMMON_AUTH_INVALID_REASONS.some((ErrorType) => error instanceof ErrorType);
|
||||
}
|
||||
|
||||
function relayInternalErrorResponse(reason: RelayInternalError["reason"]) {
|
||||
return currentTraceId.pipe(
|
||||
Effect.flatMap((traceId) =>
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer";
|
||||
import { expect, it } from "@effect/vitest";
|
||||
import * as Deferred from "effect/Deferred";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Redacted from "effect/Redacted";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as HttpServer from "effect/unstable/http/HttpServer";
|
||||
import * as HttpServerRequest from "effect/unstable/http/HttpServerRequest";
|
||||
import * as HttpServerResponse from "effect/unstable/http/HttpServerResponse";
|
||||
import type { OtlpTracer } from "effect/unstable/observability";
|
||||
|
||||
import { EnvironmentConnectNotAuthorized } from "./environments/EnvironmentConnector.ts";
|
||||
import { makeRelayTraceLayer } from "./observability.ts";
|
||||
|
||||
interface ExportedRequest {
|
||||
readonly authorization: string | undefined;
|
||||
readonly body: string;
|
||||
readonly dataset: string | undefined;
|
||||
}
|
||||
|
||||
const otlpAttributeValue = (value: {
|
||||
readonly stringValue?: string | null;
|
||||
readonly boolValue?: boolean | null;
|
||||
readonly intValue?: number | null;
|
||||
readonly doubleValue?: number | null;
|
||||
}) => value.stringValue ?? value.boolValue ?? value.intValue ?? value.doubleValue;
|
||||
|
||||
const decodeJson = Schema.decodeUnknownEffect(Schema.UnknownFromJsonString);
|
||||
|
||||
it.effect("exports schema error fields as span attributes", () =>
|
||||
Effect.gen(function* () {
|
||||
const exportedRequest = yield* Deferred.make<ExportedRequest>();
|
||||
yield* HttpServer.serveEffect(
|
||||
Effect.gen(function* () {
|
||||
const request = yield* HttpServerRequest.HttpServerRequest;
|
||||
yield* Deferred.succeed(exportedRequest, {
|
||||
authorization: request.headers.authorization,
|
||||
body: yield* request.text,
|
||||
dataset: request.headers["x-axiom-dataset"],
|
||||
});
|
||||
return HttpServerResponse.empty({ status: 204 });
|
||||
}),
|
||||
);
|
||||
|
||||
yield* Effect.fail(
|
||||
new EnvironmentConnectNotAuthorized({
|
||||
environmentId: "environment-1",
|
||||
operation: "connect",
|
||||
reason: "managed_endpoint_allocation_not_ready",
|
||||
}),
|
||||
).pipe(
|
||||
Effect.withSpan("relay.test.schema_error"),
|
||||
Effect.exit,
|
||||
Effect.provide(
|
||||
makeRelayTraceLayer({
|
||||
tracesEndpoint: "/v1/traces",
|
||||
tracesDatasetName: "relay-test-traces",
|
||||
ingestToken: Redacted.make("test-token"),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const request = yield* Deferred.await(exportedRequest).pipe(Effect.timeout("1 second"));
|
||||
const payload = (yield* decodeJson(request.body)) as OtlpTracer.TraceData;
|
||||
const span = payload.resourceSpans
|
||||
.flatMap((resourceSpan) => resourceSpan.scopeSpans)
|
||||
.flatMap((scopeSpan) => scopeSpan.spans)
|
||||
.find((candidate) => candidate.name === "relay.test.schema_error");
|
||||
const attributes = Object.fromEntries(
|
||||
(span?.attributes ?? []).map((attribute) => [
|
||||
attribute.key,
|
||||
otlpAttributeValue(attribute.value),
|
||||
]),
|
||||
);
|
||||
|
||||
expect(request.authorization).toBe("Bearer test-token");
|
||||
expect(request.dataset).toBe("relay-test-traces");
|
||||
expect(attributes).toMatchObject({
|
||||
"error.type": "EnvironmentConnectNotAuthorized",
|
||||
"error.environmentId": "environment-1",
|
||||
"error.operation": "connect",
|
||||
"error.reason": "managed_endpoint_allocation_not_ready",
|
||||
});
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest), Effect.scoped),
|
||||
);
|
||||
@@ -1,9 +1,14 @@
|
||||
import * as Alchemy from "alchemy";
|
||||
import * as Axiom from "alchemy/Axiom";
|
||||
import * as Output from "alchemy/Output";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Exit from "effect/Exit";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Redacted from "effect/Redacted";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Tracer from "effect/Tracer";
|
||||
import { OtlpSerialization, OtlpTracer } from "effect/unstable/observability";
|
||||
|
||||
import { relayResourceNameForStage } from "./deploymentConfig.ts";
|
||||
@@ -54,23 +59,163 @@ export const withSpanAttributes =
|
||||
Effect.andThen(effect.pipe(Effect.annotateSpans(attributes))),
|
||||
);
|
||||
|
||||
const appendEncodedAttributes = (
|
||||
attributes: Record<string, unknown>,
|
||||
prefix: string,
|
||||
value: unknown,
|
||||
): void => {
|
||||
if (
|
||||
value === null ||
|
||||
typeof value === "string" ||
|
||||
typeof value === "number" ||
|
||||
typeof value === "boolean" ||
|
||||
typeof value === "bigint" ||
|
||||
Array.isArray(value)
|
||||
) {
|
||||
attributes[prefix] = value;
|
||||
return;
|
||||
}
|
||||
if (typeof value !== "object") {
|
||||
return;
|
||||
}
|
||||
for (const [key, child] of Object.entries(value)) {
|
||||
appendEncodedAttributes(attributes, `${prefix}.${key}`, child);
|
||||
}
|
||||
};
|
||||
|
||||
const schemaErrorAttributes = (error: unknown): Record<string, unknown> | undefined => {
|
||||
if (typeof error !== "object" || error === null) {
|
||||
return undefined;
|
||||
}
|
||||
const constructor = error.constructor;
|
||||
if (!Schema.isSchema(constructor)) {
|
||||
return undefined;
|
||||
}
|
||||
const encoded = Schema.encodeUnknownOption(constructor as unknown as Schema.Encoder<unknown>)(
|
||||
error,
|
||||
);
|
||||
if (Option.isNone(encoded) || typeof encoded.value !== "object" || encoded.value === null) {
|
||||
return undefined;
|
||||
}
|
||||
const tag = Reflect.get(encoded.value, "_tag");
|
||||
if (typeof tag !== "string") {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const attributes: Record<string, unknown> = {
|
||||
"error.type": tag,
|
||||
};
|
||||
for (const [key, value] of Object.entries(encoded.value)) {
|
||||
if (key !== "_tag") {
|
||||
appendEncodedAttributes(attributes, `error.${key}`, value);
|
||||
}
|
||||
}
|
||||
return attributes;
|
||||
};
|
||||
|
||||
const annotateSchemaError = (span: Tracer.Span, exit: Exit.Exit<unknown, unknown>): void => {
|
||||
if (Exit.isSuccess(exit)) {
|
||||
return;
|
||||
}
|
||||
for (const reason of exit.cause.reasons) {
|
||||
const error = Cause.isFailReason(reason)
|
||||
? reason.error
|
||||
: Cause.isDieReason(reason)
|
||||
? reason.defect
|
||||
: undefined;
|
||||
const attributes = schemaErrorAttributes(error);
|
||||
if (attributes) {
|
||||
for (const [key, value] of Object.entries(attributes)) {
|
||||
span.attribute(key, value);
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
class RelayTraceSpan implements Tracer.Span {
|
||||
readonly _tag = "Span";
|
||||
private readonly delegate: Tracer.Span;
|
||||
|
||||
constructor(delegate: Tracer.Span) {
|
||||
this.delegate = delegate;
|
||||
}
|
||||
|
||||
get name() {
|
||||
return this.delegate.name;
|
||||
}
|
||||
get spanId() {
|
||||
return this.delegate.spanId;
|
||||
}
|
||||
get traceId() {
|
||||
return this.delegate.traceId;
|
||||
}
|
||||
get parent() {
|
||||
return this.delegate.parent;
|
||||
}
|
||||
get annotations() {
|
||||
return this.delegate.annotations;
|
||||
}
|
||||
get status() {
|
||||
return this.delegate.status;
|
||||
}
|
||||
get attributes() {
|
||||
return this.delegate.attributes;
|
||||
}
|
||||
get links() {
|
||||
return this.delegate.links;
|
||||
}
|
||||
get sampled() {
|
||||
return this.delegate.sampled;
|
||||
}
|
||||
get kind() {
|
||||
return this.delegate.kind;
|
||||
}
|
||||
|
||||
end(endTime: bigint, exit: Exit.Exit<unknown, unknown>): void {
|
||||
annotateSchemaError(this.delegate, exit);
|
||||
this.delegate.end(endTime, exit);
|
||||
}
|
||||
|
||||
attribute(key: string, value: unknown): void {
|
||||
this.delegate.attribute(key, value);
|
||||
}
|
||||
|
||||
event(name: string, startTime: bigint, attributes?: Record<string, unknown>): void {
|
||||
this.delegate.event(name, startTime, attributes);
|
||||
}
|
||||
|
||||
addLinks(links: ReadonlyArray<Tracer.SpanLink>): void {
|
||||
this.delegate.addLinks(links);
|
||||
}
|
||||
}
|
||||
|
||||
const withSchemaErrorAttributes = (delegate: Tracer.Tracer): Tracer.Tracer =>
|
||||
Tracer.make({
|
||||
span: (options) => new RelayTraceSpan(delegate.span(options)),
|
||||
...(delegate.context ? { context: delegate.context } : {}),
|
||||
});
|
||||
|
||||
export const makeRelayTraceLayer = (input: {
|
||||
readonly tracesEndpoint: string;
|
||||
readonly tracesDatasetName: string;
|
||||
readonly ingestToken: Redacted.Redacted<string>;
|
||||
}) =>
|
||||
OtlpTracer.layer({
|
||||
url: input.tracesEndpoint,
|
||||
resource: {
|
||||
serviceName: "t3-code-relay-worker",
|
||||
attributes: {
|
||||
"service.runtime": "cloudflare-worker",
|
||||
"service.component": "relay",
|
||||
Layer.effect(
|
||||
Tracer.Tracer,
|
||||
OtlpTracer.make({
|
||||
url: input.tracesEndpoint,
|
||||
resource: {
|
||||
serviceName: "t3-code-relay-worker",
|
||||
attributes: {
|
||||
"service.runtime": "cloudflare-worker",
|
||||
"service.component": "relay",
|
||||
},
|
||||
},
|
||||
},
|
||||
headers: {
|
||||
Authorization: `Bearer ${Redacted.value(input.ingestToken)}`,
|
||||
"X-Axiom-Dataset": input.tracesDatasetName,
|
||||
},
|
||||
exportInterval: "1 second",
|
||||
}).pipe(Layer.provide(OtlpSerialization.layerJson));
|
||||
headers: {
|
||||
Authorization: `Bearer ${Redacted.value(input.ingestToken)}`,
|
||||
"X-Axiom-Dataset": input.tracesDatasetName,
|
||||
},
|
||||
exportInterval: "1 second",
|
||||
}).pipe(Effect.map(withSchemaErrorAttributes)),
|
||||
).pipe(Layer.provide(OtlpSerialization.layerJson));
|
||||
@@ -329,7 +329,11 @@ export class RelayAuthInvalidError extends Schema.TaggedErrorClass<RelayAuthInva
|
||||
traceId: TrimmedNonEmptyString,
|
||||
},
|
||||
{ httpApiStatus: 401 },
|
||||
) {}
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Relay authentication failed: ${this.reason}`;
|
||||
}
|
||||
}
|
||||
|
||||
export class RelayEnvironmentLinkProofExpiredError extends Schema.TaggedErrorClass<RelayEnvironmentLinkProofExpiredError>()(
|
||||
"RelayEnvironmentLinkProofExpiredError",
|
||||
@@ -338,7 +342,11 @@ export class RelayEnvironmentLinkProofExpiredError extends Schema.TaggedErrorCla
|
||||
traceId: TrimmedNonEmptyString,
|
||||
},
|
||||
{ httpApiStatus: 401 },
|
||||
) {}
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Relay environment link proof expired";
|
||||
}
|
||||
}
|
||||
|
||||
export class RelayEnvironmentLinkProofInvalidError extends Schema.TaggedErrorClass<RelayEnvironmentLinkProofInvalidError>()(
|
||||
"RelayEnvironmentLinkProofInvalidError",
|
||||
@@ -348,7 +356,11 @@ export class RelayEnvironmentLinkProofInvalidError extends Schema.TaggedErrorCla
|
||||
traceId: TrimmedNonEmptyString,
|
||||
},
|
||||
{ httpApiStatus: 400 },
|
||||
) {}
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Relay environment link proof is invalid: ${this.reason}`;
|
||||
}
|
||||
}
|
||||
|
||||
export class RelayEnvironmentConnectNotAuthorizedError extends Schema.TaggedErrorClass<RelayEnvironmentConnectNotAuthorizedError>()(
|
||||
"RelayEnvironmentConnectNotAuthorizedError",
|
||||
@@ -357,7 +369,11 @@ export class RelayEnvironmentConnectNotAuthorizedError extends Schema.TaggedErro
|
||||
traceId: TrimmedNonEmptyString,
|
||||
},
|
||||
{ httpApiStatus: 403 },
|
||||
) {}
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Relay environment connection is not authorized";
|
||||
}
|
||||
}
|
||||
|
||||
export class RelayEnvironmentEndpointUnavailableError extends Schema.TaggedErrorClass<RelayEnvironmentEndpointUnavailableError>()(
|
||||
"RelayEnvironmentEndpointUnavailableError",
|
||||
@@ -367,7 +383,11 @@ export class RelayEnvironmentEndpointUnavailableError extends Schema.TaggedError
|
||||
traceId: TrimmedNonEmptyString,
|
||||
},
|
||||
{ httpApiStatus: 502 },
|
||||
) {}
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Relay environment endpoint is unavailable: ${this.reason}`;
|
||||
}
|
||||
}
|
||||
|
||||
export class RelayEnvironmentEndpointTimedOutError extends Schema.TaggedErrorClass<RelayEnvironmentEndpointTimedOutError>()(
|
||||
"RelayEnvironmentEndpointTimedOutError",
|
||||
@@ -376,7 +396,11 @@ export class RelayEnvironmentEndpointTimedOutError extends Schema.TaggedErrorCla
|
||||
traceId: TrimmedNonEmptyString,
|
||||
},
|
||||
{ httpApiStatus: 504 },
|
||||
) {}
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Relay environment endpoint request timed out";
|
||||
}
|
||||
}
|
||||
|
||||
export class RelayEnvironmentLinkFailedError extends Schema.TaggedErrorClass<RelayEnvironmentLinkFailedError>()(
|
||||
"RelayEnvironmentLinkFailedError",
|
||||
@@ -386,7 +410,11 @@ export class RelayEnvironmentLinkFailedError extends Schema.TaggedErrorClass<Rel
|
||||
traceId: TrimmedNonEmptyString,
|
||||
},
|
||||
{ httpApiStatus: 500 },
|
||||
) {}
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Relay environment link failed: ${this.reason}`;
|
||||
}
|
||||
}
|
||||
|
||||
export class RelayEnvironmentLinkUnavailableError extends Schema.TaggedErrorClass<RelayEnvironmentLinkUnavailableError>()(
|
||||
"RelayEnvironmentLinkUnavailableError",
|
||||
@@ -396,7 +424,11 @@ export class RelayEnvironmentLinkUnavailableError extends Schema.TaggedErrorClas
|
||||
traceId: TrimmedNonEmptyString,
|
||||
},
|
||||
{ httpApiStatus: 503 },
|
||||
) {}
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Relay environment link is unavailable: ${this.reason}`;
|
||||
}
|
||||
}
|
||||
|
||||
export class RelayAgentActivityPublishProofExpiredError extends Schema.TaggedErrorClass<RelayAgentActivityPublishProofExpiredError>()(
|
||||
"RelayAgentActivityPublishProofExpiredError",
|
||||
@@ -405,7 +437,11 @@ export class RelayAgentActivityPublishProofExpiredError extends Schema.TaggedErr
|
||||
traceId: TrimmedNonEmptyString,
|
||||
},
|
||||
{ httpApiStatus: 401 },
|
||||
) {}
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Relay agent activity publish proof expired";
|
||||
}
|
||||
}
|
||||
|
||||
export class RelayAgentActivityPublishProofInvalidError extends Schema.TaggedErrorClass<RelayAgentActivityPublishProofInvalidError>()(
|
||||
"RelayAgentActivityPublishProofInvalidError",
|
||||
@@ -415,7 +451,11 @@ export class RelayAgentActivityPublishProofInvalidError extends Schema.TaggedErr
|
||||
traceId: TrimmedNonEmptyString,
|
||||
},
|
||||
{ httpApiStatus: 401 },
|
||||
) {}
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Relay agent activity publish proof is invalid: ${this.reason}`;
|
||||
}
|
||||
}
|
||||
|
||||
export class RelayInternalError extends Schema.TaggedErrorClass<RelayInternalError>()(
|
||||
"RelayInternalError",
|
||||
@@ -425,7 +465,11 @@ export class RelayInternalError extends Schema.TaggedErrorClass<RelayInternalErr
|
||||
traceId: TrimmedNonEmptyString,
|
||||
},
|
||||
{ httpApiStatus: 500 },
|
||||
) {}
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Relay internal error: ${this.reason}`;
|
||||
}
|
||||
}
|
||||
|
||||
export const RelayProtectedError = Schema.Union([
|
||||
RelayAuthInvalidError,
|
||||
|
||||
@@ -1,13 +1,16 @@
|
||||
import { sha256 } from "@noble/hashes/sha2";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import * as ConfigProvider from "effect/ConfigProvider";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Encoding from "effect/Encoding";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Path from "effect/Path";
|
||||
import * as Sink from "effect/Sink";
|
||||
import * as Stream from "effect/Stream";
|
||||
import * as TestClock from "effect/testing/TestClock";
|
||||
import { HttpClient, HttpClientResponse } from "effect/unstable/http";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
@@ -47,15 +50,13 @@ const makeHttpClientLayer = (bytes: Uint8Array) =>
|
||||
);
|
||||
|
||||
const makeSpawnerLayer = (commands: Array<string>) =>
|
||||
Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make((command) =>
|
||||
Layer.mock(ChildProcessSpawner.ChildProcessSpawner, {
|
||||
spawn: (command) =>
|
||||
Effect.sync(() => {
|
||||
commands.push(ChildProcess.isStandardCommand(command) ? command.command : "piped-command");
|
||||
return makeHandle();
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
describe("RelayClient", () => {
|
||||
it.effect("resolves explicit overrides before managed and PATH executables", () =>
|
||||
@@ -80,7 +81,7 @@ describe("RelayClient", () => {
|
||||
}),
|
||||
});
|
||||
|
||||
expect(yield* manager.resolve).toEqual({
|
||||
assert.deepStrictEqual(yield* manager.resolve, {
|
||||
status: "available",
|
||||
executablePath: overridePath,
|
||||
source: "override",
|
||||
@@ -130,16 +131,17 @@ describe("RelayClient", () => {
|
||||
platform: "linux",
|
||||
arch: "x64",
|
||||
});
|
||||
expect(installed).toEqual({
|
||||
assert.deepStrictEqual(installed, {
|
||||
status: "available",
|
||||
executablePath: managedPath,
|
||||
source: "managed",
|
||||
version: CLOUDFLARED_VERSION,
|
||||
});
|
||||
expect(new TextDecoder().decode(yield* fileSystem.readFile(managedPath))).toBe(
|
||||
assert.equal(
|
||||
new TextDecoder().decode(yield* fileSystem.readFile(managedPath)),
|
||||
"test-cloudflared-binary",
|
||||
);
|
||||
expect(progress).toEqual([
|
||||
assert.deepStrictEqual(progress, [
|
||||
"checking",
|
||||
"waiting_for_lock",
|
||||
"downloading",
|
||||
@@ -148,7 +150,7 @@ describe("RelayClient", () => {
|
||||
"validating",
|
||||
"activating",
|
||||
]);
|
||||
expect(yield* manager.resolve).toEqual(installed);
|
||||
assert.deepStrictEqual(yield* manager.resolve, installed);
|
||||
}).pipe(
|
||||
Effect.scoped,
|
||||
Effect.provide(
|
||||
@@ -180,8 +182,8 @@ describe("RelayClient", () => {
|
||||
});
|
||||
|
||||
const error = yield* manager.install.pipe(Effect.flip);
|
||||
expect(error).toBeInstanceOf(RelayClientInstallError);
|
||||
expect(error.reason).toBe("invalid_checksum");
|
||||
assert.ok(error instanceof RelayClientInstallError);
|
||||
assert.equal(error.reason, "invalid_checksum");
|
||||
}).pipe(
|
||||
Effect.scoped,
|
||||
Effect.provide(
|
||||
@@ -217,12 +219,17 @@ describe("RelayClient", () => {
|
||||
const [first, second] = yield* Effect.all([manager.install, manager.install], {
|
||||
concurrency: "unbounded",
|
||||
});
|
||||
expect(second).toEqual(first);
|
||||
expect(commands).toHaveLength(1);
|
||||
assert.deepStrictEqual(second, first);
|
||||
assert.equal(commands.length, 1);
|
||||
}).pipe(
|
||||
Effect.scoped,
|
||||
Effect.provide(
|
||||
Layer.mergeAll(NodeServices.layer, makeHttpClientLayer(bytes), makeSpawnerLayer(commands)),
|
||||
Layer.mergeAll(
|
||||
TestClock.layer(),
|
||||
NodeServices.layer,
|
||||
makeHttpClientLayer(bytes),
|
||||
makeSpawnerLayer(commands),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
@@ -243,7 +250,7 @@ describe("RelayClient", () => {
|
||||
configProvider: () => ConfigProvider.fromEnv({ env: { PATH: path } }),
|
||||
});
|
||||
|
||||
expect(yield* manager.resolve).toEqual({
|
||||
assert.deepStrictEqual(yield* manager.resolve, {
|
||||
status: "missing",
|
||||
version: CLOUDFLARED_VERSION,
|
||||
});
|
||||
@@ -253,7 +260,7 @@ describe("RelayClient", () => {
|
||||
yield* fileSystem.chmod(executablePath, 0o755);
|
||||
path = binDir;
|
||||
|
||||
expect(yield* manager.resolve).toEqual({
|
||||
assert.deepStrictEqual(yield* manager.resolve, {
|
||||
status: "available",
|
||||
executablePath,
|
||||
source: "path",
|
||||
@@ -270,4 +277,54 @@ describe("RelayClient", () => {
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("removes stale install locks before installing", () => {
|
||||
const commands: Array<string> = [];
|
||||
const bytes = new TextEncoder().encode("test-cloudflared-binary");
|
||||
return Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-cloudflared-test-",
|
||||
});
|
||||
const managedPath = resolveManagedCloudflaredPath({
|
||||
baseDir,
|
||||
platform: "linux",
|
||||
arch: "x64",
|
||||
});
|
||||
const lockPath = `${managedPath}.lock`;
|
||||
yield* fileSystem.makeDirectory(path.dirname(lockPath), { recursive: true });
|
||||
yield* fileSystem.writeFileString(lockPath, "stale");
|
||||
yield* fileSystem.utimes(lockPath, 0, 0);
|
||||
yield* TestClock.adjust(Duration.minutes(6));
|
||||
|
||||
const manager = yield* makeCloudflaredRelayClient({
|
||||
baseDir,
|
||||
platform: "linux",
|
||||
arch: "x64",
|
||||
releaseAsset: {
|
||||
url: "https://example.test/cloudflared",
|
||||
sha256: Encoding.encodeHex(sha256(bytes)),
|
||||
archive: "binary",
|
||||
},
|
||||
configProvider: emptyConfigProvider,
|
||||
});
|
||||
|
||||
const installed = yield* manager.install;
|
||||
|
||||
assert.deepStrictEqual(installed, {
|
||||
status: "available",
|
||||
executablePath: managedPath,
|
||||
source: "managed",
|
||||
version: CLOUDFLARED_VERSION,
|
||||
});
|
||||
assert.equal(yield* fileSystem.exists(lockPath), false);
|
||||
assert.equal(commands.length, 1);
|
||||
}).pipe(
|
||||
Effect.scoped,
|
||||
Effect.provide(
|
||||
Layer.mergeAll(NodeServices.layer, makeHttpClientLayer(bytes), makeSpawnerLayer(commands)),
|
||||
),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,3 @@
|
||||
import * as Clock from "effect/Clock";
|
||||
import type {
|
||||
RelayClientInstallProgressEvent,
|
||||
RelayClientInstallProgressStage,
|
||||
@@ -8,6 +7,8 @@ import * as ConfigProvider from "effect/ConfigProvider";
|
||||
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";
|
||||
import * as Encoding from "effect/Encoding";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
@@ -15,6 +16,7 @@ import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Path from "effect/Path";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import * as Schedule from "effect/Schedule";
|
||||
import * as Semaphore from "effect/Semaphore";
|
||||
import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/unstable/http";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
@@ -99,8 +101,18 @@ const CLOUDFLARED_RELEASE_ASSETS: Readonly<
|
||||
};
|
||||
|
||||
const INSTALL_LOCK_RETRY_COUNT = 100;
|
||||
const INSTALL_LOCK_RETRY_DELAY = "100 millis";
|
||||
const INSTALL_LOCK_STALE_MS = 5 * 60 * 1_000;
|
||||
const INSTALL_LOCK_RETRY_DELAY = Duration.millis(100);
|
||||
const INSTALL_LOCK_STALE_AGE = Duration.minutes(5);
|
||||
|
||||
class RelayClientInstallLockBusy extends Data.TaggedError("RelayClientInstallLockBusy")<{
|
||||
readonly lockPath: string;
|
||||
}> {}
|
||||
|
||||
const retryWhileInstallLockBusy = Schedule.spaced(INSTALL_LOCK_RETRY_DELAY).pipe(
|
||||
Schedule.both(Schedule.recurs(INSTALL_LOCK_RETRY_COUNT - 1)),
|
||||
Schedule.setInputType<RelayClientInstallLockBusy | PlatformError.PlatformError>(),
|
||||
Schedule.while(({ input }) => input._tag === "RelayClientInstallLockBusy"),
|
||||
);
|
||||
|
||||
const trimmedString = (name: string) =>
|
||||
Config.string(name).pipe(
|
||||
@@ -161,8 +173,8 @@ export function resolveManagedCloudflaredPath(input: {
|
||||
function resolveReleaseAsset(
|
||||
platform: NodeJS.Platform,
|
||||
arch: string,
|
||||
): CloudflaredReleaseAsset | null {
|
||||
return CLOUDFLARED_RELEASE_ASSETS[`${platform}-${arch}`] ?? null;
|
||||
): Option.Option<CloudflaredReleaseAsset> {
|
||||
return Option.fromUndefinedOr(CLOUDFLARED_RELEASE_ASSETS[`${platform}-${arch}`]);
|
||||
}
|
||||
|
||||
function isAlreadyExists(error: PlatformError.PlatformError): boolean {
|
||||
@@ -207,7 +219,9 @@ export const makeCloudflaredRelayClient = Effect.fn("cloudflared.make")(function
|
||||
const installSemaphore = yield* Semaphore.make(1);
|
||||
const platform = options.platform ?? process.platform;
|
||||
const arch = options.arch ?? process.arch;
|
||||
const releaseAsset = options.releaseAsset ?? resolveReleaseAsset(platform, arch);
|
||||
const releaseAsset = Option.fromUndefinedOr(options.releaseAsset).pipe(
|
||||
Option.orElse(() => resolveReleaseAsset(platform, arch)),
|
||||
);
|
||||
const loadCloudflaredConfig = Effect.suspend(() =>
|
||||
CloudflaredConfig.pipe(
|
||||
Effect.provideService(
|
||||
@@ -236,15 +250,15 @@ export const makeCloudflaredRelayClient = Effect.fn("cloudflared.make")(function
|
||||
const resolvePathExecutable = Effect.gen(function* () {
|
||||
const config = yield* loadCloudflaredConfig;
|
||||
const pathValue = Option.getOrUndefined(config.path);
|
||||
if (!pathValue) return null;
|
||||
if (!pathValue) return Option.none();
|
||||
const delimiter = platform === "win32" ? ";" : ":";
|
||||
for (const directory of pathValue.split(delimiter)) {
|
||||
const trimmed = directory.trim().replace(/^"|"$/gu, "");
|
||||
if (trimmed.length === 0) continue;
|
||||
const candidate = path.join(trimmed, executableFileName(platform));
|
||||
if (yield* isExecutableFile(candidate)) return candidate;
|
||||
if (yield* isExecutableFile(candidate)) return Option.some(candidate);
|
||||
}
|
||||
return null;
|
||||
return Option.none();
|
||||
});
|
||||
|
||||
const resolve: RelayClientShape["resolve"] = Effect.gen(function* () {
|
||||
@@ -268,15 +282,15 @@ export const makeCloudflaredRelayClient = Effect.fn("cloudflared.make")(function
|
||||
};
|
||||
}
|
||||
const pathExecutable = yield* resolvePathExecutable;
|
||||
if (pathExecutable) {
|
||||
if (Option.isSome(pathExecutable)) {
|
||||
return {
|
||||
status: "available",
|
||||
executablePath: pathExecutable,
|
||||
executablePath: pathExecutable.value,
|
||||
source: "path",
|
||||
version: CLOUDFLARED_VERSION,
|
||||
};
|
||||
}
|
||||
return releaseAsset
|
||||
return Option.isSome(releaseAsset)
|
||||
? { status: "missing", version: CLOUDFLARED_VERSION }
|
||||
: {
|
||||
status: "unsupported",
|
||||
@@ -351,36 +365,56 @@ export const makeCloudflaredRelayClient = Effect.fn("cloudflared.make")(function
|
||||
return bytes;
|
||||
});
|
||||
|
||||
const isInstallLockStale = Effect.fn("cloudflared.isInstallLockStale")(function* (
|
||||
lockPath: string,
|
||||
): Effect.fn.Return<boolean> {
|
||||
const lockInfo = yield* fileSystem.stat(lockPath).pipe(Effect.option);
|
||||
const lockModifiedAt = Option.flatMap(lockInfo, (info) => info.mtime);
|
||||
if (Option.isNone(lockModifiedAt)) return false;
|
||||
|
||||
const now = yield* DateTime.now;
|
||||
const lockAge = DateTime.distance(DateTime.makeUnsafe(lockModifiedAt.value), now);
|
||||
return Duration.isGreaterThan(lockAge, INSTALL_LOCK_STALE_AGE);
|
||||
});
|
||||
|
||||
const attemptAcquireInstallLock = Effect.fn("cloudflared.attemptAcquireInstallLock")(function* (
|
||||
lockPath: string,
|
||||
): Effect.fn.Return<void, RelayClientInstallLockBusy | PlatformError.PlatformError> {
|
||||
const acquired = yield* fileSystem.writeFileString(lockPath, "", { flag: "wx" }).pipe(
|
||||
Effect.as(true),
|
||||
Effect.catch((error) =>
|
||||
isAlreadyExists(error) ? Effect.succeed(false) : Effect.fail(error),
|
||||
),
|
||||
);
|
||||
if (acquired) return;
|
||||
|
||||
if (yield* isInstallLockStale(lockPath)) {
|
||||
yield* fileSystem.remove(lockPath, { force: true });
|
||||
return yield* attemptAcquireInstallLock(lockPath);
|
||||
}
|
||||
|
||||
return yield* new RelayClientInstallLockBusy({ lockPath });
|
||||
});
|
||||
|
||||
const acquireInstallLock = Effect.fn("cloudflared.acquireInstallLock")(function* (
|
||||
lockPath: string,
|
||||
) {
|
||||
for (let attempt = 0; attempt < INSTALL_LOCK_RETRY_COUNT; attempt += 1) {
|
||||
const acquired = yield* fileSystem.writeFileString(lockPath, "", { flag: "wx" }).pipe(
|
||||
Effect.as(true),
|
||||
Effect.catch((error) =>
|
||||
isAlreadyExists(error) ? Effect.succeed(false) : Effect.fail(error),
|
||||
): Effect.fn.Return<void, RelayClientInstallError | PlatformError.PlatformError> {
|
||||
return yield* attemptAcquireInstallLock(lockPath).pipe(
|
||||
Effect.retry(retryWhileInstallLockBusy),
|
||||
Effect.catchTag("RelayClientInstallLockBusy", () =>
|
||||
Effect.fail(
|
||||
new RelayClientInstallError({
|
||||
reason: "install_locked",
|
||||
message: "Another relay client installation is still in progress.",
|
||||
}),
|
||||
),
|
||||
);
|
||||
if (acquired) return;
|
||||
|
||||
const now = yield* Clock.currentTimeMillis;
|
||||
const lockInfo = yield* fileSystem.stat(lockPath).pipe(Effect.option);
|
||||
const mtime = Option.flatMap(lockInfo, (info) => info.mtime);
|
||||
if (Option.isSome(mtime) && now - mtime.value.getTime() > INSTALL_LOCK_STALE_MS) {
|
||||
yield* fileSystem.remove(lockPath, { force: true });
|
||||
continue;
|
||||
}
|
||||
yield* Effect.sleep(INSTALL_LOCK_RETRY_DELAY);
|
||||
}
|
||||
return yield* new RelayClientInstallError({
|
||||
reason: "install_locked",
|
||||
message: "Another relay client installation is still in progress.",
|
||||
});
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
const installUnlocked = Effect.fn("cloudflared.installUnlocked")(function* (
|
||||
report: (stage: RelayClientInstallProgressStage) => Effect.Effect<void>,
|
||||
) {
|
||||
): Effect.fn.Return<AvailableRelayClient, RelayClientInstallError> {
|
||||
yield* report("checking");
|
||||
const existing = yield* resolve;
|
||||
if (existing.status === "available") return existing;
|
||||
@@ -391,7 +425,7 @@ export const makeCloudflaredRelayClient = Effect.fn("cloudflared.make")(function
|
||||
message: `${CLOUDFLARED_PATH_ENV_NAME} does not point to an executable file.`,
|
||||
});
|
||||
}
|
||||
if (!releaseAsset) {
|
||||
if (Option.isNone(releaseAsset)) {
|
||||
return yield* new RelayClientInstallError({
|
||||
reason: "unsupported_platform",
|
||||
message: `T3 Code does not provide a managed relay client binary for ${platform}-${arch}.`,
|
||||
@@ -427,16 +461,16 @@ export const makeCloudflaredRelayClient = Effect.fn("cloudflared.make")(function
|
||||
});
|
||||
const archivePath = path.join(
|
||||
tempDirectory,
|
||||
releaseAsset.archive === "tgz" ? "cloudflared.tgz" : executableFileName(platform),
|
||||
releaseAsset.value.archive === "tgz" ? "cloudflared.tgz" : executableFileName(platform),
|
||||
);
|
||||
const download = yield* downloadAsset(releaseAsset, report);
|
||||
const download = yield* downloadAsset(releaseAsset.value, report);
|
||||
yield* report("installing");
|
||||
yield* fileSystem
|
||||
.writeFile(archivePath, download)
|
||||
.pipe(wrapInstallFailure("write_failed", "Could not write the relay client download."));
|
||||
|
||||
const executablePath = path.join(tempDirectory, executableFileName(platform));
|
||||
if (releaseAsset.archive === "tgz") {
|
||||
if (releaseAsset.value.archive === "tgz") {
|
||||
yield* runCommand("tar", ["-xzf", archivePath, "-C", tempDirectory]).pipe(
|
||||
wrapInstallFailure("write_failed", "Could not extract the relay client."),
|
||||
);
|
||||
|
||||
Reference in new issue
Block a user