@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 230 lines 7.09 KB
Raw
1 import * as Context from "effect/Context";
2 import * as Effect from "effect/Effect";
3 import * as HttpApi from "effect/http-api/HttpApi";
4 import * as HttpApiEndpoint from "effect/http-api/HttpApiEndpoint";
5 import * as HttpApiError from "effect/http-api/HttpApiError";
6 import * as HttpApiGroup from "effect/http-api/HttpApiGroup";
7 import * as HttpApiMiddleware from "effect/http-api/HttpApiMiddleware";
8 import * as HttpApiSchema from "effect/http-api/HttpApiSchema";
9 import * as HttpApiSecurity from "effect/http-api/HttpApiSecurity";
10 import * as Layer from "effect/Layer";
11 import * as Redacted from "effect/Redacted";
12 import * as Schema from "effect/Schema";
13 import { UserFacingError } from "../UserFacingError.ts";
14
15 /**
16 * Resource-state payload shape on the wire.
17 *
18 * Pinned to JSON encoding via {@link HttpApiSchema.asJson} so that both
19 * sides of the API agree on `Content-Type: application/json`. With a
20 * bare `Schema.Any` the server's payload-decoder map is keyed off the
21 * default content type only — any client request that arrives with a
22 * differently-shaped body (or a transport that drops the
23 * `Content-Type` header entirely) falls into the `payloadBy.get(
24 * contentType)` miss branch in `HttpApiBuilder.decodePayload` and
25 * surfaces as a confusing `415 Unsupported Media Type`. Annotating
26 * the schema makes the encoding explicit on both endpoints and the
27 * client encoder, so the wire format is unambiguous.
28 */
29 export const ResourceStateSchema = Schema.Any.pipe(HttpApiSchema.asJson());
30
31 export class BearerTokenValidator extends Context.Service<
32 BearerTokenValidator,
33 {
34 readonly validate: (token: string) => Effect.Effect<void, HttpApiError.Unauthorized>;
35 }
36 >()("alchemy/State/BearerTokenValidator") {}
37
38 export class StateAuth extends HttpApiMiddleware.Service<
39 StateAuth,
40 { requires: BearerTokenValidator }
41 >()("alchemy/State/StateAuth", {
42 security: {
43 bearer: HttpApiSecurity.bearer,
44 },
45 error: HttpApiError.UnauthorizedNoContent,
46 }) {}
47
48 export const StateAuthLive: Layer.Layer<StateAuth, never, BearerTokenValidator> = Layer.effect(
49 StateAuth,
50 Effect.gen(function* () {
51 const validator = yield* BearerTokenValidator;
52 return {
53 bearer: (httpEffect, { credential }) =>
54 validator.validate(Redacted.value(credential)).pipe(Effect.flatMap(() => httpEffect)),
55 };
56 }),
57 );
58
59 /** `stack` path segment for nested REST resources. */
60 const StackParams = Schema.Struct({
61 stack: Schema.String,
62 });
63
64 /** Optional stage selector for stack deletion. */
65 const OptionalStageQuery = Schema.Struct({
66 stage: Schema.optional(Schema.String),
67 });
68
69 /** `(stack, stage)` path segments shared by stage-scoped endpoints. */
70 const StackStage = Schema.Struct({
71 stack: Schema.String,
72 stage: Schema.String,
73 });
74
75 /** `(stack, stage, fqn)` path segments for a single resource. */
76 const ResourceKey = Schema.Struct({
77 stack: Schema.String,
78 stage: Schema.String,
79 fqn: Schema.String,
80 });
81
82 /**
83 * The store failed to serve a request: which operation, and the kind of
84 * failure (its tag). Never the failure's message, which can carry state; the
85 * Worker logs the full cause. Without it, any failure behind the auth
86 * middleware was encoded as its `Unauthorized` and surfaced as a bare 500.
87 */
88 export class StateStoreFailure extends Schema.TaggedError<StateStoreFailure>()(
89 "StateStoreFailure",
90 { operation: Schema.String, reason: Schema.String },
91 { httpApiStatus: 500 },
92 ) {
93 readonly [UserFacingError] = true;
94 override get message() {
95 return `State store failed to ${this.operation} (${this.reason}); its logs have the cause`;
96 }
97 }
98
99 export const ListStacks = HttpApiEndpoint.get("listStacks", "/state/stacks", {
100 success: Schema.Array(Schema.String),
101 error: StateStoreFailure,
102 });
103
104 export const ListStages = HttpApiEndpoint.get("listStages", "/state/stacks/:stack/stages", {
105 params: StackParams,
106 success: Schema.Array(Schema.String),
107 error: StateStoreFailure,
108 });
109
110 export const ListResources = HttpApiEndpoint.get(
111 "listResources",
112 "/state/stacks/:stack/stages/:stage/resources",
113 {
114 params: StackStage,
115 success: Schema.Array(Schema.String),
116 error: StateStoreFailure,
117 },
118 );
119
120 export const GetState = HttpApiEndpoint.get(
121 "getState",
122 "/state/stacks/:stack/stages/:stage/resources/:fqn",
123 {
124 params: ResourceKey,
125 success: Schema.UndefinedOr(ResourceStateSchema),
126 error: StateStoreFailure,
127 },
128 );
129
130 export const SetState = HttpApiEndpoint.put(
131 "setState",
132 "/state/stacks/:stack/stages/:stage/resources/:fqn",
133 {
134 params: ResourceKey,
135 payload: ResourceStateSchema,
136 success: ResourceStateSchema,
137 error: StateStoreFailure,
138 },
139 );
140
141 export const DeleteState = HttpApiEndpoint.delete(
142 "deleteState",
143 "/state/stacks/:stack/stages/:stage/resources/:fqn",
144 {
145 params: ResourceKey,
146 success: HttpApiSchema.NoContent,
147 error: StateStoreFailure,
148 },
149 );
150
151 export const DeleteStack = HttpApiEndpoint.delete("deleteStack", "/state/stacks/:stack", {
152 params: StackParams,
153 query: OptionalStageQuery,
154 success: HttpApiSchema.NoContent,
155 error: StateStoreFailure,
156 });
157
158 export const GetReplacedResources = HttpApiEndpoint.get(
159 "getReplacedResources",
160 "/state/stacks/:stack/stages/:stage/replaced-resources",
161 {
162 params: StackStage,
163 success: Schema.Array(ResourceStateSchema),
164 error: StateStoreFailure,
165 },
166 );
167
168 export const GetStackOutput = HttpApiEndpoint.get(
169 "getStackOutput",
170 "/state/stacks/:stack/stages/:stage/output",
171 {
172 params: StackStage,
173 success: Schema.UndefinedOr(ResourceStateSchema),
174 error: StateStoreFailure,
175 },
176 );
177
178 export const SetStackOutput = HttpApiEndpoint.put(
179 "setStackOutput",
180 "/state/stacks/:stack/stages/:stage/output",
181 {
182 params: StackStage,
183 payload: ResourceStateSchema,
184 success: ResourceStateSchema,
185 error: StateStoreFailure,
186 },
187 );
188
189 /**
190 * Version of the State Store wire / behavioural contract.
191 *
192 * Bump this whenever the wire format or runtime behaviour of an HTTP
193 * state-store changes in a way that an older deployed copy can no
194 * longer satisfy. Clients query `/version` on the deployed worker and
195 * compare against this constant; a mismatch (or 404) triggers a
196 * forced redeploy via the bootstrap flow.
197 */
198 export const STATE_STORE_VERSION = 5 as const;
199
200 /** Response shape for the unauthenticated `/version` probe. */
201 export const VersionResponse = Schema.Struct({
202 version: Schema.Number,
203 });
204
205 /**
206 * Unauthenticated probe so clients can detect a stale (or absent)
207 * deployed worker without holding a valid bearer token. The returned
208 * version is bumped whenever the wire / behavioural contract changes
209 * in a way that requires a redeploy.
210 */
211 export const GetVersion = HttpApiEndpoint.get("getVersion", "/version", {
212 success: VersionResponse,
213 });
214
215 export class StateGroup extends HttpApiGroup.make("state")
216 .add(ListStacks)
217 .add(ListStages)
218 .add(ListResources)
219 .add(GetState)
220 .add(SetState)
221 .add(DeleteState)
222 .add(GetReplacedResources)
223 .add(DeleteStack)
224 .add(GetStackOutput)
225 .add(SetStackOutput)
226 .middleware(StateAuth) {}
227
228 export class VersionGroup extends HttpApiGroup.make("version").add(GetVersion) {}
229
230 export class StateApi extends HttpApi.make("alchemy-state").add(StateGroup).add(VersionGroup) {}