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, 03:37 UTC
| 1 | import { msg } from "gt-i18n"; |
| 2 | import { |
| 3 | MarkedText, |
| 4 | markedTextEnglish, |
| 5 | messageFromError, |
| 6 | translatableMessage, |
| 7 | withI18nMessage, |
| 8 | } from "../errors/translatable.ts"; |
| 9 | import { |
| 10 | EnvironmentAuthorizationError, |
| 11 | clientRpcRequiredScopes, |
| 12 | authScopeRequiredResponse, |
| 13 | type AuthEnvironmentScope, |
| 14 | type EnvironmentId, |
| 15 | type ClientGuardedRpcTag, |
| 16 | ORCHESTRATION_V2_WS_METHODS, |
| 17 | WS_METHODS, |
| 18 | } from "@t3tools/contracts"; |
| 19 | import * as Cause from "effect/Cause"; |
| 20 | import * as Context from "effect/Context"; |
| 21 | import * as Duration from "effect/Duration"; |
| 22 | import * as Effect from "effect/Effect"; |
| 23 | import * as Option from "effect/Option"; |
| 24 | import * as Schema from "effect/Schema"; |
| 25 | import * as Stream from "effect/Stream"; |
| 26 | import * as SubscriptionRef from "effect/SubscriptionRef"; |
| 27 | import { RpcClientError } from "effect/rpc"; |
| 28 | |
| 29 | import * as EnvironmentSupervisor from "../connection/supervisor.ts"; |
| 30 | import type { WsRpcProtocolClient } from "../rpc/protocol.ts"; |
| 31 | import type { RpcSession } from "../rpc/session.ts"; |
| 32 | |
| 33 | export class EnvironmentRpcUnavailableError extends Schema.TaggedError<EnvironmentRpcUnavailableError>()( |
| 34 | "EnvironmentRpcUnavailableError", |
| 35 | { |
| 36 | environmentId: Schema.String, |
| 37 | message: Schema.String, |
| 38 | i18nMessage: Schema.optionalKey(MarkedText), |
| 39 | }, |
| 40 | ) {} |
| 41 | |
| 42 | export interface EnvironmentRpcRequestObservation { |
| 43 | readonly environmentId: string; |
| 44 | readonly environmentLabel: string; |
| 45 | readonly method: string; |
| 46 | } |
| 47 | |
| 48 | export class EnvironmentRpcRequestObserver extends Context.Reference<{ |
| 49 | readonly observe: ( |
| 50 | request: EnvironmentRpcRequestObservation, |
| 51 | ) => Effect.Effect<Effect.Effect<void>>; |
| 52 | }>("@t3tools/client-runtime/rpc/EnvironmentRpcRequestObserver", { |
| 53 | defaultValue: () => ({ |
| 54 | observe: () => Effect.succeed(Effect.void), |
| 55 | }), |
| 56 | }) {} |
| 57 | |
| 58 | export type EnvironmentRpcTag = keyof WsRpcProtocolClient & string; |
| 59 | type RpcMethod<TTag extends EnvironmentRpcTag> = WsRpcProtocolClient[TTag]; |
| 60 | |
| 61 | export type EnvironmentSubscriptionRpcTag = |
| 62 | | typeof WS_METHODS.providerAuthSubscribe |
| 63 | | typeof WS_METHODS.providerInstallSubscribe |
| 64 | | typeof ORCHESTRATION_V2_WS_METHODS.subscribeShell |
| 65 | | typeof ORCHESTRATION_V2_WS_METHODS.subscribeThread |
| 66 | | typeof WS_METHODS.peerLinksSubscribeThread |
| 67 | | typeof ORCHESTRATION_V2_WS_METHODS.subscribeCommandOutput |
| 68 | | typeof ORCHESTRATION_V2_WS_METHODS.subscribePromptSuggestion |
| 69 | | typeof ORCHESTRATION_V2_WS_METHODS.searchThreadStream |
| 70 | | typeof WS_METHODS.subscribeAuthAccess |
| 71 | | typeof WS_METHODS.subscribeServerConfig |
| 72 | | typeof WS_METHODS.subscribeServerLifecycle |
| 73 | | typeof WS_METHODS.scheduledTasksSubscribe |
| 74 | | typeof WS_METHODS.serverGetStorageCleanupReport |
| 75 | | typeof WS_METHODS.serverGetDatabaseStorage |
| 76 | | typeof WS_METHODS.subscribeTerminalMetadata |
| 77 | | typeof WS_METHODS.subscribePreviewEvents |
| 78 | | typeof WS_METHODS.subscribeDiscoveredLocalServers |
| 79 | | typeof WS_METHODS.subscribeDeviceState |
| 80 | | typeof WS_METHODS.subscribeResourceTelemetry |
| 81 | | typeof WS_METHODS.pullRequestsSubscribeRefreshes |
| 82 | | typeof WS_METHODS.pullRequestsSubscribeLinkedThreadRefreshes |
| 83 | | typeof WS_METHODS.subscribeVcsStatus |
| 84 | | typeof WS_METHODS.subscribeVcsBranch |
| 85 | | typeof WS_METHODS.subscribeWorktreeSetup |
| 86 | | typeof WS_METHODS.subscribeProjectClones |
| 87 | | typeof WS_METHODS.terminalAttach |
| 88 | | typeof WS_METHODS.terminalObserve; |
| 89 | |
| 90 | export type EnvironmentStreamCommandRpcTag = |
| 91 | | typeof WS_METHODS.chatGptHandoffSubscribe |
| 92 | | typeof WS_METHODS.cloudInstallRelayClient |
| 93 | | typeof WS_METHODS.serverUpdateServerWithProgress |
| 94 | | typeof WS_METHODS.gitRunStackedAction; |
| 95 | |
| 96 | export type EnvironmentStreamRpcTag = |
| 97 | | EnvironmentSubscriptionRpcTag |
| 98 | | EnvironmentStreamCommandRpcTag; |
| 99 | |
| 100 | export type EnvironmentUnaryRpcTag = Exclude<EnvironmentRpcTag, EnvironmentStreamRpcTag>; |
| 101 | |
| 102 | export interface EnvironmentRpcSubscriptionObservation { |
| 103 | readonly environmentId: string; |
| 104 | readonly method: EnvironmentSubscriptionRpcTag; |
| 105 | readonly input: unknown; |
| 106 | } |
| 107 | |
| 108 | export class EnvironmentRpcSubscriptionObserver extends Context.Reference<{ |
| 109 | readonly observe: ( |
| 110 | subscription: EnvironmentRpcSubscriptionObservation, |
| 111 | ) => Effect.Effect<Effect.Effect<void>>; |
| 112 | }>("@t3tools/client-runtime/rpc/EnvironmentRpcSubscriptionObserver", { |
| 113 | defaultValue: () => ({ |
| 114 | observe: () => Effect.succeed(Effect.void), |
| 115 | }), |
| 116 | }) {} |
| 117 | |
| 118 | export const isRpcClientError = Schema.is(RpcClientError.RpcClientError); |
| 119 | const isEnvironmentAuthorizationError = Schema.is(EnvironmentAuthorizationError); |
| 120 | |
| 121 | export function scopeRequiredError(scope: AuthEnvironmentScope): EnvironmentAuthorizationError { |
| 122 | const text = msg("This connection requires {scope}.", { scope }); |
| 123 | return withI18nMessage( |
| 124 | new EnvironmentAuthorizationError({ |
| 125 | ...authScopeRequiredResponse(scope), |
| 126 | message: markedTextEnglish([text]), |
| 127 | }), |
| 128 | text, |
| 129 | ); |
| 130 | } |
| 131 | |
| 132 | /** A subscription never retries an authorization failure on its own. */ |
| 133 | export const isAuthorizationFailure = (cause: Cause.Cause<unknown>) => |
| 134 | cause.reasons.some( |
| 135 | (reason) => reason._tag === "Fail" && isEnvironmentAuthorizationError(reason.error), |
| 136 | ); |
| 137 | |
| 138 | const MAX_EXPECTED_FAILURE_RETRY_DELAY_MS = 30_000; |
| 139 | const STREAM_FAILURE_RETRY_DELAY = Duration.seconds(1); |
| 140 | |
| 141 | export const subscriptionRetryDelay = (base: Duration.Input, retries: number) => |
| 142 | Duration.millis( |
| 143 | Math.min(Duration.toMillis(base) * 2 ** retries, MAX_EXPECTED_FAILURE_RETRY_DELAY_MS), |
| 144 | ); |
| 145 | |
| 146 | export type EnvironmentRpcInput<TTag extends EnvironmentRpcTag> = Parameters<RpcMethod<TTag>>[0]; |
| 147 | |
| 148 | export type EnvironmentRpcSuccess<TTag extends EnvironmentUnaryRpcTag> = |
| 149 | RpcMethod<TTag> extends (input: any, options?: any) => Effect.Effect<infer A, any, any> |
| 150 | ? A |
| 151 | : never; |
| 152 | |
| 153 | export type EnvironmentRpcFailure<TTag extends EnvironmentUnaryRpcTag> = |
| 154 | RpcMethod<TTag> extends (input: any, options?: any) => Effect.Effect<any, infer E, any> |
| 155 | ? E |
| 156 | : never; |
| 157 | |
| 158 | export type EnvironmentRpcStreamValue<TTag extends EnvironmentStreamRpcTag> = |
| 159 | RpcMethod<TTag> extends (input: any, options?: any) => Stream.Stream<infer A, any, any> |
| 160 | ? A |
| 161 | : never; |
| 162 | |
| 163 | export type EnvironmentRpcStreamFailure<TTag extends EnvironmentStreamRpcTag> = |
| 164 | RpcMethod<TTag> extends (input: any, options?: any) => Stream.Stream<any, infer E, any> |
| 165 | ? E |
| 166 | : never; |
| 167 | |
| 168 | export const currentSession = Effect.fn("EnvironmentRpc.currentSession")(function* () { |
| 169 | const supervisor = yield* EnvironmentSupervisor.EnvironmentSupervisor; |
| 170 | return yield* SubscriptionRef.get(supervisor.session).pipe( |
| 171 | Effect.flatMap( |
| 172 | Option.match({ |
| 173 | onNone: () => |
| 174 | Effect.fail( |
| 175 | new EnvironmentRpcUnavailableError({ |
| 176 | environmentId: supervisor.target.environmentId, |
| 177 | ...translatableMessage( |
| 178 | msg("{host} is not connected.", { host: supervisor.target.label }), |
| 179 | ), |
| 180 | }), |
| 181 | ), |
| 182 | onSome: Effect.succeed, |
| 183 | }), |
| 184 | ), |
| 185 | ); |
| 186 | }); |
| 187 | |
| 188 | export const getInitialServerConfig = Effect.fn("EnvironmentRpc.getInitialServerConfig")( |
| 189 | function* () { |
| 190 | const session = yield* currentSession(); |
| 191 | return yield* session.initialConfig; |
| 192 | }, |
| 193 | ); |
| 194 | |
| 195 | /** Installed by the shared command boundary. A missing boundary denies protected writes. */ |
| 196 | export class RpcPermissionGuard extends Context.Reference<{ |
| 197 | readonly authorize: ( |
| 198 | environmentId: EnvironmentId, |
| 199 | method: string, |
| 200 | input: unknown, |
| 201 | ) => Effect.Effect<void, EnvironmentAuthorizationError>; |
| 202 | }>("@t3tools/client-runtime/rpc/RpcPermissionGuard", { |
| 203 | defaultValue: () => ({ |
| 204 | authorize: (_environmentId, method, input) => { |
| 205 | const scope = clientRpcRequiredScopes(method, input)[0]; |
| 206 | return scope === undefined ? Effect.void : Effect.fail(scopeRequiredError(scope)); |
| 207 | }, |
| 208 | }), |
| 209 | }) {} |
| 210 | |
| 211 | const authorizeRequest = Effect.fn("EnvironmentRpc.authorize")(function* ( |
| 212 | method: string, |
| 213 | input: unknown, |
| 214 | ) { |
| 215 | if (clientRpcRequiredScopes(method, input).length === 0) return; |
| 216 | const supervisor = yield* EnvironmentSupervisor.EnvironmentSupervisor; |
| 217 | const guard = yield* RpcPermissionGuard; |
| 218 | yield* guard.authorize(supervisor.target.environmentId, method, input); |
| 219 | }); |
| 220 | |
| 221 | export const requestInSession = Effect.fn("EnvironmentRpc.request")(function* < |
| 222 | TTag extends EnvironmentUnaryRpcTag, |
| 223 | >(session: RpcSession, tag: TTag, input: EnvironmentRpcInput<TTag>) { |
| 224 | const supervisor = yield* EnvironmentSupervisor.EnvironmentSupervisor; |
| 225 | yield* Effect.annotateCurrentSpan({ |
| 226 | "environment.id": supervisor.target.environmentId, |
| 227 | "rpc.method": tag, |
| 228 | }); |
| 229 | yield* authorizeRequest(tag, input); |
| 230 | const observer = yield* EnvironmentRpcRequestObserver; |
| 231 | const method = session.client[tag] as ( |
| 232 | input: EnvironmentRpcInput<TTag>, |
| 233 | ) => Effect.Effect<EnvironmentRpcSuccess<TTag>, EnvironmentRpcFailure<TTag>>; |
| 234 | const completeObservation = yield* observer.observe({ |
| 235 | environmentId: supervisor.target.environmentId, |
| 236 | environmentLabel: supervisor.target.label, |
| 237 | method: tag, |
| 238 | }); |
| 239 | return yield* method(input).pipe(Effect.ensuring(completeObservation)); |
| 240 | }); |
| 241 | |
| 242 | // The session-bound request owns the existing EnvironmentRpc.request span. |
| 243 | export const requestGuarded = Effect.fnUntraced(function* <TTag extends EnvironmentUnaryRpcTag>( |
| 244 | tag: TTag, |
| 245 | input: EnvironmentRpcInput<TTag>, |
| 246 | ) { |
| 247 | return yield* requestInSession(yield* currentSession(), tag, input); |
| 248 | }); |
| 249 | |
| 250 | export function runStreamGuarded<TTag extends EnvironmentStreamCommandRpcTag>( |
| 251 | tag: TTag, |
| 252 | input: EnvironmentRpcInput<TTag>, |
| 253 | ): Stream.Stream< |
| 254 | EnvironmentRpcStreamValue<TTag>, |
| 255 | | EnvironmentRpcStreamFailure<TTag> |
| 256 | | EnvironmentRpcUnavailableError |
| 257 | | EnvironmentAuthorizationError, |
| 258 | EnvironmentSupervisor.EnvironmentSupervisor |
| 259 | > { |
| 260 | return Stream.unwrap( |
| 261 | currentSession().pipe(Effect.map((session) => runStreamInSession(session, tag, input))), |
| 262 | ); |
| 263 | } |
| 264 | |
| 265 | export function runStreamInSession<TTag extends EnvironmentStreamCommandRpcTag>( |
| 266 | session: RpcSession, |
| 267 | tag: TTag, |
| 268 | input: EnvironmentRpcInput<TTag>, |
| 269 | ): Stream.Stream< |
| 270 | EnvironmentRpcStreamValue<TTag>, |
| 271 | EnvironmentRpcStreamFailure<TTag> | EnvironmentAuthorizationError, |
| 272 | EnvironmentSupervisor.EnvironmentSupervisor |
| 273 | > { |
| 274 | const method = session.client[tag] as ( |
| 275 | input: EnvironmentRpcInput<TTag>, |
| 276 | ) => Stream.Stream<EnvironmentRpcStreamValue<TTag>, EnvironmentRpcStreamFailure<TTag>>; |
| 277 | return Stream.unwrap(authorizeRequest(tag, input).pipe(Effect.map(() => method(input)))).pipe( |
| 278 | Stream.withSpan("EnvironmentRpc.runStream", { |
| 279 | attributes: { "rpc.method": tag }, |
| 280 | }), |
| 281 | ); |
| 282 | } |
| 283 | |
| 284 | interface SubscriptionOptions<TTag extends EnvironmentSubscriptionRpcTag> { |
| 285 | /** Reports defects; the subscription then waits for the next session or resubscribe. */ |
| 286 | readonly onDefect?: ( |
| 287 | cause: Cause.Cause<EnvironmentRpcStreamFailure<TTag>>, |
| 288 | ) => Effect.Effect<void, never, never>; |
| 289 | readonly onExpectedFailure?: ( |
| 290 | cause: Cause.Cause<EnvironmentRpcStreamFailure<TTag>>, |
| 291 | ) => Effect.Effect<void, never, never>; |
| 292 | readonly retryExpectedFailureAfter?: Duration.Input; |
| 293 | readonly resubscribe?: Stream.Stream<unknown, never, never>; |
| 294 | } |
| 295 | |
| 296 | function subscribeDynamicMapped<TTag extends EnvironmentSubscriptionRpcTag, A>( |
| 297 | tag: TTag, |
| 298 | makeInput: (session: RpcSession) => Effect.Effect<EnvironmentRpcInput<TTag>>, |
| 299 | mapStream: ( |
| 300 | session: RpcSession, |
| 301 | stream: Stream.Stream<EnvironmentRpcStreamValue<TTag>, EnvironmentRpcStreamFailure<TTag>>, |
| 302 | ) => Stream.Stream<A, EnvironmentRpcStreamFailure<TTag>>, |
| 303 | options?: SubscriptionOptions<TTag>, |
| 304 | ): Stream.Stream< |
| 305 | A, |
| 306 | EnvironmentRpcStreamFailure<TTag>, |
| 307 | EnvironmentSupervisor.EnvironmentSupervisor |
| 308 | > { |
| 309 | return Stream.unwrap( |
| 310 | Effect.gen(function* () { |
| 311 | const supervisor = yield* EnvironmentSupervisor.EnvironmentSupervisor; |
| 312 | const observer = yield* EnvironmentRpcSubscriptionObserver; |
| 313 | const sessionChanges = SubscriptionRef.changes(supervisor.session); |
| 314 | const sessions = |
| 315 | options?.resubscribe === undefined |
| 316 | ? sessionChanges |
| 317 | : Stream.merge( |
| 318 | sessionChanges, |
| 319 | options.resubscribe.pipe( |
| 320 | Stream.mapEffect(() => SubscriptionRef.get(supervisor.session)), |
| 321 | ), |
| 322 | ); |
| 323 | return sessions.pipe( |
| 324 | Stream.switchMap( |
| 325 | Option.match({ |
| 326 | onNone: () => Stream.empty, |
| 327 | onSome: (session) => { |
| 328 | const method = ( |
| 329 | tag === WS_METHODS.subscribeServerConfig |
| 330 | ? session.subscribeServerConfig |
| 331 | : session.client[tag] |
| 332 | ) as ( |
| 333 | input: EnvironmentRpcInput<TTag>, |
| 334 | ) => Stream.Stream< |
| 335 | EnvironmentRpcStreamValue<TTag>, |
| 336 | EnvironmentRpcStreamFailure<TTag> |
| 337 | >; |
| 338 | let expectedFailureRetries = 0; |
| 339 | // Not reset by a first value: a stream can emit before every chunk failure. |
| 340 | let streamFailureRetries = 0; |
| 341 | const subscribeToSession = (): Stream.Stream<A, EnvironmentRpcStreamFailure<TTag>> => |
| 342 | Stream.suspend(() => |
| 343 | Stream.unwrap( |
| 344 | Effect.gen(function* () { |
| 345 | const input = yield* makeInput(session); |
| 346 | const completeObservation = yield* observer.observe({ |
| 347 | environmentId: supervisor.target.environmentId, |
| 348 | method: tag, |
| 349 | input, |
| 350 | }); |
| 351 | const stream = mapStream( |
| 352 | session, |
| 353 | Stream.suspend(() => method(input)), |
| 354 | ).pipe( |
| 355 | Stream.onFirst(() => |
| 356 | Effect.sync(() => { |
| 357 | expectedFailureRetries = 0; |
| 358 | }), |
| 359 | ), |
| 360 | ); |
| 361 | return stream.pipe(Stream.ensuring(completeObservation)); |
| 362 | }), |
| 363 | ).pipe( |
| 364 | Stream.tapCause((cause) => |
| 365 | options?.onDefect !== undefined && |
| 366 | cause.reasons.some( |
| 367 | (reason) => |
| 368 | reason._tag === "Die" || |
| 369 | (reason._tag === "Fail" && |
| 370 | isRpcClientError(reason.error) && |
| 371 | reason.error.reason._tag === "RpcClientDefect"), |
| 372 | ) |
| 373 | ? options.onDefect(cause) |
| 374 | : Effect.void, |
| 375 | ), |
| 376 | Stream.catchCause((cause) => { |
| 377 | const retryAfter = (base: Duration.Input, retries: number) => |
| 378 | Stream.fromEffect(Effect.sleep(subscriptionRetryDelay(base, retries))).pipe( |
| 379 | Stream.drain, |
| 380 | Stream.concat(subscribeToSession()), |
| 381 | ); |
| 382 | const hasOnlyExpectedFailures = |
| 383 | cause.reasons.length > 0 && |
| 384 | cause.reasons.every((reason) => reason._tag === "Fail"); |
| 385 | const isTransportFailure = |
| 386 | hasOnlyExpectedFailures && |
| 387 | cause.reasons.every( |
| 388 | (reason) => reason._tag === "Fail" && isRpcClientError(reason.error), |
| 389 | ); |
| 390 | // The RPC client dies with a SchemaError when one stream chunk fails to |
| 391 | // decode, ending only that request while the socket stays open. A caller |
| 392 | // with `onDefect` owns its defect recovery. |
| 393 | const isChunkDecodeDefect = |
| 394 | options?.onDefect === undefined && |
| 395 | cause.reasons.length > 0 && |
| 396 | cause.reasons.every( |
| 397 | (reason) => reason._tag === "Die" && Schema.isSchemaError(reason.defect), |
| 398 | ); |
| 399 | // Both end one stream while the session can stay healthy, so nothing else |
| 400 | // would replace it. A dead session is replaced by the supervisor, which |
| 401 | // interrupts this retry through switchMap. A finite search must settle |
| 402 | // rather than restart, so it keeps waiting for the next session. |
| 403 | const resubscribesOnSameSession = |
| 404 | tag !== ORCHESTRATION_V2_WS_METHODS.searchThreadStream; |
| 405 | if (isTransportFailure && !resubscribesOnSameSession) { |
| 406 | return Stream.fromEffect( |
| 407 | Effect.logWarning( |
| 408 | "Durable RPC subscription lost its transport; waiting for the next session.", |
| 409 | { |
| 410 | cause: Cause.pretty(cause), |
| 411 | method: tag, |
| 412 | environmentId: supervisor.target.environmentId, |
| 413 | }, |
| 414 | ), |
| 415 | ).pipe(Stream.drain); |
| 416 | } |
| 417 | if ( |
| 418 | resubscribesOnSameSession && |
| 419 | (isTransportFailure || isChunkDecodeDefect) |
| 420 | ) { |
| 421 | return Stream.fromEffect( |
| 422 | Effect.logWarning( |
| 423 | "Durable RPC subscription stream ended; resubscribing.", |
| 424 | { |
| 425 | cause: Cause.pretty(cause), |
| 426 | method: tag, |
| 427 | environmentId: supervisor.target.environmentId, |
| 428 | }, |
| 429 | ), |
| 430 | ).pipe( |
| 431 | Stream.drain, |
| 432 | Stream.concat( |
| 433 | retryAfter( |
| 434 | options?.retryExpectedFailureAfter ?? STREAM_FAILURE_RETRY_DELAY, |
| 435 | streamFailureRetries++, |
| 436 | ), |
| 437 | ), |
| 438 | ); |
| 439 | } |
| 440 | if (hasOnlyExpectedFailures && options?.onExpectedFailure !== undefined) { |
| 441 | const handled = Stream.fromEffect(options.onExpectedFailure(cause)).pipe( |
| 442 | Stream.drain, |
| 443 | ); |
| 444 | if ( |
| 445 | options.retryExpectedFailureAfter === undefined || |
| 446 | isAuthorizationFailure(cause) |
| 447 | ) { |
| 448 | return handled; |
| 449 | } |
| 450 | return handled.pipe( |
| 451 | Stream.concat( |
| 452 | retryAfter(options.retryExpectedFailureAfter, expectedFailureRetries++), |
| 453 | ), |
| 454 | ); |
| 455 | } |
| 456 | // A reported defect parks until the next session or resubscribe. Failing would |
| 457 | // end the whole subscription, so a mounted screen never syncs again. |
| 458 | if (options?.onDefect !== undefined && Cause.hasDies(cause)) { |
| 459 | return Stream.empty; |
| 460 | } |
| 461 | return Stream.failCause(cause); |
| 462 | }), |
| 463 | ), |
| 464 | ); |
| 465 | return subscribeToSession(); |
| 466 | }, |
| 467 | }), |
| 468 | ), |
| 469 | ); |
| 470 | }), |
| 471 | ).pipe( |
| 472 | Stream.withSpan("EnvironmentRpc.subscribe", { |
| 473 | attributes: { "rpc.method": tag }, |
| 474 | }), |
| 475 | ); |
| 476 | } |
| 477 | |
| 478 | export function subscribeDynamic<TTag extends EnvironmentSubscriptionRpcTag>( |
| 479 | tag: TTag, |
| 480 | makeInput: (session: RpcSession) => Effect.Effect<EnvironmentRpcInput<TTag>>, |
| 481 | options?: SubscriptionOptions<TTag>, |
| 482 | ): Stream.Stream< |
| 483 | EnvironmentRpcStreamValue<TTag>, |
| 484 | EnvironmentRpcStreamFailure<TTag>, |
| 485 | EnvironmentSupervisor.EnvironmentSupervisor |
| 486 | > { |
| 487 | return subscribeDynamicMapped(tag, makeInput, (_session, stream) => stream, options); |
| 488 | } |
| 489 | |
| 490 | /** Tags each value before `switchMap` can buffer it across a session change. */ |
| 491 | export function subscribeDynamicWithSession<TTag extends EnvironmentSubscriptionRpcTag>( |
| 492 | tag: TTag, |
| 493 | makeInput: (session: RpcSession) => Effect.Effect<EnvironmentRpcInput<TTag>>, |
| 494 | options?: SubscriptionOptions<TTag>, |
| 495 | ): Stream.Stream< |
| 496 | readonly [session: RpcSession, value: EnvironmentRpcStreamValue<TTag>], |
| 497 | EnvironmentRpcStreamFailure<TTag>, |
| 498 | EnvironmentSupervisor.EnvironmentSupervisor |
| 499 | > { |
| 500 | return subscribeDynamicMapped( |
| 501 | tag, |
| 502 | makeInput, |
| 503 | (session, stream) => stream.pipe(Stream.map((value) => [session, value] as const)), |
| 504 | options, |
| 505 | ); |
| 506 | } |
| 507 | |
| 508 | export function subscribe<TTag extends EnvironmentSubscriptionRpcTag>( |
| 509 | tag: TTag, |
| 510 | input: EnvironmentRpcInput<TTag>, |
| 511 | options?: SubscriptionOptions<TTag>, |
| 512 | ): Stream.Stream< |
| 513 | EnvironmentRpcStreamValue<TTag>, |
| 514 | EnvironmentRpcStreamFailure<TTag>, |
| 515 | EnvironmentSupervisor.EnvironmentSupervisor |
| 516 | > { |
| 517 | return subscribeDynamic(tag, () => Effect.succeed(input), options); |
| 518 | } |
| 519 | |
| 520 | export const subscribeVcsBranch = ( |
| 521 | input: EnvironmentRpcInput<typeof WS_METHODS.subscribeVcsBranch>, |
| 522 | ) => |
| 523 | subscribeDynamicMapped( |
| 524 | WS_METHODS.subscribeVcsBranch, |
| 525 | () => Effect.succeed(input), |
| 526 | (session, stream) => |
| 527 | Stream.unwrap( |
| 528 | session.initialConfig.pipe( |
| 529 | Effect.mapError( |
| 530 | (error) => |
| 531 | new RpcClientError.RpcClientError({ |
| 532 | reason: new RpcClientError.RpcClientDefect({ |
| 533 | message: error.message, |
| 534 | cause: error, |
| 535 | }), |
| 536 | }), |
| 537 | ), |
| 538 | Effect.map((config) => |
| 539 | config.environment.capabilities.vcsBranchStatus === true |
| 540 | ? stream |
| 541 | : session.client[WS_METHODS.subscribeVcsStatus]({ |
| 542 | ...input, |
| 543 | includeRemote: false, |
| 544 | }).pipe( |
| 545 | Stream.filter((event) => event._tag !== "remoteUpdated"), |
| 546 | Stream.map(({ local }) => ({ refName: local.refName, isRepo: local.isRepo })), |
| 547 | ), |
| 548 | ), |
| 549 | ), |
| 550 | ), |
| 551 | ); |
| 552 | |
| 553 | export const refreshVcsBranch = Effect.fn("EnvironmentRpc.refreshVcsBranch")(function* ( |
| 554 | input: EnvironmentRpcInput<typeof WS_METHODS.vcsRefreshBranch>, |
| 555 | ) { |
| 556 | const supervisor = yield* EnvironmentSupervisor.EnvironmentSupervisor; |
| 557 | const session = yield* currentSession(); |
| 558 | const config = yield* session.initialConfig.pipe( |
| 559 | Effect.mapError( |
| 560 | (error) => |
| 561 | new EnvironmentRpcUnavailableError({ |
| 562 | environmentId: supervisor.target.environmentId, |
| 563 | ...messageFromError(error), |
| 564 | }), |
| 565 | ), |
| 566 | ); |
| 567 | if (config.environment.capabilities.vcsBranchStatus === true) { |
| 568 | return yield* requestInSession(session, WS_METHODS.vcsRefreshBranch, input); |
| 569 | } |
| 570 | // Older hosts retain their existing status stream without adding per-row wake scans. |
| 571 | }); |
| 572 | |
| 573 | export const request = <TTag extends Exclude<EnvironmentUnaryRpcTag, ClientGuardedRpcTag>>( |
| 574 | tag: TTag, |
| 575 | input: EnvironmentRpcInput<TTag>, |
| 576 | ) => requestGuarded(tag, input); |
| 577 | |
| 578 | export const runStream = < |
| 579 | TTag extends Exclude<EnvironmentStreamCommandRpcTag, ClientGuardedRpcTag>, |
| 580 | >( |
| 581 | tag: TTag, |
| 582 | input: EnvironmentRpcInput<TTag>, |
| 583 | ) => runStreamGuarded(tag, input); |