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, 06:00 UTC
| 1 | import * as scheduler from "@distilled.cloud/gcp/cloudscheduler_v1"; |
| 2 | import { Unowned } from "alchemy/AdoptPolicy"; |
| 3 | import { isResolved } from "alchemy/Diff"; |
| 4 | import { createPhysicalName } from "alchemy/PhysicalName"; |
| 5 | import * as Provider from "alchemy/Provider"; |
| 6 | import { Resource } from "alchemy/Resource"; |
| 7 | import * as Data from "effect/Data"; |
| 8 | import * as Duration from "effect/Duration"; |
| 9 | import * as Effect from "effect/Effect"; |
| 10 | import * as Schedule from "effect/Schedule"; |
| 11 | import { GcpEnvironment } from "../Environment.ts"; |
| 12 | import type { Providers } from "../Providers.ts"; |
| 13 | |
| 14 | const DEFAULT_TIME_ZONE = "UTC"; |
| 15 | const DEFAULT_HTTP_METHOD = "POST"; |
| 16 | const MAX_NAME_LENGTH = 63; |
| 17 | |
| 18 | const backoff = Schedule.min([ |
| 19 | Schedule.exponential(Duration.millis(300), 1.5), |
| 20 | Schedule.spaced(Duration.seconds(2)), |
| 21 | ]); |
| 22 | |
| 23 | export type HttpMethod = "POST" | "GET" | "HEAD" | "PUT" | "DELETE" | "PATCH" | "OPTIONS"; |
| 24 | |
| 25 | export type OidcToken = { |
| 26 | /** |
| 27 | * Service account email used to mint the OIDC token. Must be in the same |
| 28 | * project as the job. The caller needs `iam.serviceAccounts.actAs`. |
| 29 | */ |
| 30 | serviceAccountEmail?: string; |
| 31 | /** |
| 32 | * Audience claimed in the token. Defaults to the HTTP target URI. |
| 33 | */ |
| 34 | audience?: string; |
| 35 | }; |
| 36 | |
| 37 | export type OAuthToken = { |
| 38 | /** |
| 39 | * Service account email used to mint the OAuth token. Must be in the same |
| 40 | * project as the job. The caller needs `iam.serviceAccounts.actAs`. |
| 41 | */ |
| 42 | serviceAccountEmail?: string; |
| 43 | /** |
| 44 | * OAuth scope. Defaults to `https://www.googleapis.com/auth/cloud-platform`. |
| 45 | */ |
| 46 | scope?: string; |
| 47 | }; |
| 48 | |
| 49 | export type HttpTarget = { |
| 50 | /** |
| 51 | * Full URI the job POSTs (or GETs, …) to. Must start with `http://` or |
| 52 | * `https://`. |
| 53 | */ |
| 54 | uri: string; |
| 55 | /** |
| 56 | * HTTP method. |
| 57 | * @default "POST" |
| 58 | */ |
| 59 | httpMethod?: HttpMethod; |
| 60 | /** |
| 61 | * Request headers. Cloud Scheduler overwrites Host, Content-Length, |
| 62 | * User-Agent, and `X-Google-*` / `X-CloudScheduler*` headers. |
| 63 | */ |
| 64 | headers?: Record<string, string>; |
| 65 | /** |
| 66 | * UTF-8 request body. Allowed for POST, PUT, and PATCH. Alchemy |
| 67 | * base64-encodes this for the API. |
| 68 | */ |
| 69 | body?: string; |
| 70 | /** |
| 71 | * Attach an OIDC token as `Authorization`. |
| 72 | */ |
| 73 | oidcToken?: OidcToken; |
| 74 | /** |
| 75 | * Attach an OAuth token as `Authorization` (typically for |
| 76 | * `*.googleapis.com` targets). |
| 77 | */ |
| 78 | oauthToken?: OAuthToken; |
| 79 | }; |
| 80 | |
| 81 | export type PubsubTarget = { |
| 82 | /** |
| 83 | * Pub/Sub topic to publish to, as |
| 84 | * `projects/{project}/topics/{topic}`. Must be in the same project. |
| 85 | */ |
| 86 | topicName: string; |
| 87 | /** |
| 88 | * UTF-8 message payload. Alchemy base64-encodes this for the API. |
| 89 | * Either `data` or `attributes` is required. |
| 90 | */ |
| 91 | data?: string; |
| 92 | /** |
| 93 | * Message attributes. Either `data` or `attributes` is required. |
| 94 | */ |
| 95 | attributes?: Record<string, string>; |
| 96 | }; |
| 97 | |
| 98 | export type AppEngineRouting = { |
| 99 | /** App Engine service. Empty uses the default service. */ |
| 100 | service?: string; |
| 101 | /** App Engine version. Empty uses the default version. */ |
| 102 | version?: string; |
| 103 | /** App Engine instance. Empty uses any available instance. */ |
| 104 | instance?: string; |
| 105 | }; |
| 106 | |
| 107 | export type AppEngineHttpTarget = { |
| 108 | /** |
| 109 | * Relative URI beginning with `/`. Empty uses `/`. |
| 110 | */ |
| 111 | relativeUri?: string; |
| 112 | /** |
| 113 | * HTTP method. PATCH and OPTIONS are not permitted. |
| 114 | * @default "POST" |
| 115 | */ |
| 116 | httpMethod?: HttpMethod; |
| 117 | /** |
| 118 | * Request headers. |
| 119 | */ |
| 120 | headers?: Record<string, string>; |
| 121 | /** |
| 122 | * UTF-8 request body. Allowed for POST and PUT. Alchemy base64-encodes |
| 123 | * this for the API. |
| 124 | */ |
| 125 | body?: string; |
| 126 | /** |
| 127 | * App Engine service / version / instance routing. |
| 128 | */ |
| 129 | appEngineRouting?: AppEngineRouting; |
| 130 | }; |
| 131 | |
| 132 | export type RetryConfig = { |
| 133 | /** |
| 134 | * Retry attempts after a failed execution (0–5). |
| 135 | * @default 0 |
| 136 | */ |
| 137 | retryCount?: number; |
| 138 | /** |
| 139 | * Time limit for retrying a failed job (e.g. `"3600s"`). Zero means |
| 140 | * unlimited, unless `retryCount` is also 0. |
| 141 | */ |
| 142 | maxRetryDuration?: string; |
| 143 | /** |
| 144 | * Times the backoff doubles before increasing linearly. |
| 145 | * @default 5 |
| 146 | */ |
| 147 | maxDoublings?: number; |
| 148 | /** |
| 149 | * Maximum backoff between retries. |
| 150 | * @default "3600s" |
| 151 | */ |
| 152 | maxBackoffDuration?: string; |
| 153 | /** |
| 154 | * Minimum backoff between retries. |
| 155 | * @default "5s" |
| 156 | */ |
| 157 | minBackoffDuration?: string; |
| 158 | }; |
| 159 | |
| 160 | export type JobProps = { |
| 161 | /** |
| 162 | * Job id (the `{job}` segment of |
| 163 | * `projects/{project}/locations/{location}/jobs/{job}`). If omitted, a |
| 164 | * unique name is generated from the stack, stage, and logical id. Must |
| 165 | * match `[A-Za-z0-9_-]{1,500}`. Immutable — changing it replaces the job. |
| 166 | */ |
| 167 | jobId?: string; |
| 168 | /** |
| 169 | * Cloud Scheduler location (`us-central1`, `us-east1`, …). Immutable — |
| 170 | * changing it replaces the job. `US-CENTRAL1` is accepted and normalized |
| 171 | * to `us-central1`. |
| 172 | * @default the stack's GCP region (`GCP.Region`, profile region, `us-central1`) |
| 173 | */ |
| 174 | location?: string; |
| 175 | /** |
| 176 | * Cron or english-like schedule (e.g. `"0 0 * * *"` or |
| 177 | * `"every 24 hours"`). Required on create. |
| 178 | */ |
| 179 | schedule: string; |
| 180 | /** |
| 181 | * tz-database time zone used to interpret `schedule`. |
| 182 | * @default "UTC" |
| 183 | */ |
| 184 | timeZone?: string; |
| 185 | /** |
| 186 | * Human-readable description (single line, max 499 characters). |
| 187 | */ |
| 188 | description?: string; |
| 189 | /** |
| 190 | * Deadline for a single attempt (e.g. `"180s"`). HTTP targets default to |
| 191 | * 3 minutes and must be in `[15s, 30m]`. |
| 192 | */ |
| 193 | attemptDeadline?: string; |
| 194 | /** |
| 195 | * Retry behavior after a failed attempt. |
| 196 | */ |
| 197 | retryConfig?: RetryConfig; |
| 198 | /** |
| 199 | * HTTP/HTTPS target. Exactly one of `httpTarget`, `pubsubTarget`, or |
| 200 | * `appEngineHttpTarget` must be set. |
| 201 | */ |
| 202 | httpTarget?: HttpTarget; |
| 203 | /** |
| 204 | * Pub/Sub target. Exactly one of `httpTarget`, `pubsubTarget`, or |
| 205 | * `appEngineHttpTarget` must be set. |
| 206 | */ |
| 207 | pubsubTarget?: PubsubTarget; |
| 208 | /** |
| 209 | * App Engine HTTP target. Exactly one of `httpTarget`, `pubsubTarget`, |
| 210 | * or `appEngineHttpTarget` must be set. |
| 211 | */ |
| 212 | appEngineHttpTarget?: AppEngineHttpTarget; |
| 213 | /** |
| 214 | * When true, the job exists but is not scheduled (`Job.State.PAUSED`). |
| 215 | * Synced via `jobs.pause` / `jobs.resume`. |
| 216 | * @default false |
| 217 | */ |
| 218 | paused?: boolean; |
| 219 | }; |
| 220 | |
| 221 | export type Job = Resource< |
| 222 | "GCP.CloudScheduler.Job", |
| 223 | JobProps, |
| 224 | { |
| 225 | /** Full resource name `projects/{project}/locations/{location}/jobs/{job}`. */ |
| 226 | name: string; |
| 227 | /** Job id (last path segment). */ |
| 228 | jobId: string; |
| 229 | /** Location id (`us-central1`, …). */ |
| 230 | location: string; |
| 231 | /** Project id. */ |
| 232 | project: string; |
| 233 | /** Job description. */ |
| 234 | description: string | undefined; |
| 235 | /** Cron or english-like schedule. */ |
| 236 | schedule: string | undefined; |
| 237 | /** Time zone used to interpret the schedule. */ |
| 238 | timeZone: string | undefined; |
| 239 | /** Server-reported job state. */ |
| 240 | state: string | undefined; |
| 241 | /** Whether the job is paused. */ |
| 242 | paused: boolean; |
| 243 | /** Attempt deadline. */ |
| 244 | attemptDeadline: string | undefined; |
| 245 | /** Retry configuration. */ |
| 246 | retryConfig: RetryConfig | undefined; |
| 247 | /** HTTP target, if set. Body is the API's base64 payload. */ |
| 248 | httpTarget: scheduler.HttpTarget | undefined; |
| 249 | /** Pub/Sub target, if set. */ |
| 250 | pubsubTarget: scheduler.PubsubTarget | undefined; |
| 251 | /** App Engine HTTP target, if set. */ |
| 252 | appEngineHttpTarget: scheduler.AppEngineHttpTarget | undefined; |
| 253 | /** Next scheduled attempt (RFC3339). */ |
| 254 | scheduleTime: string | undefined; |
| 255 | /** Last attempt start (RFC3339). */ |
| 256 | lastAttemptTime: string | undefined; |
| 257 | /** Last user update (RFC3339). */ |
| 258 | userUpdateTime: string | undefined; |
| 259 | /** Last attempt status. */ |
| 260 | status: scheduler.Status | undefined; |
| 261 | /** Whether the job satisfies physical zone separation. */ |
| 262 | satisfiesPzs: boolean | undefined; |
| 263 | }, |
| 264 | never, |
| 265 | Providers |
| 266 | >; |
| 267 | |
| 268 | /** |
| 269 | * A Cloud Scheduler job that invokes an HTTP, Pub/Sub, or App Engine |
| 270 | * target on a cron schedule. |
| 271 | * |
| 272 | * Jobs have no labels field, so ownership rests on the deterministic job |
| 273 | * name: `read` reports a job it finds without prior state as unowned |
| 274 | * (adopt it with `--adopt`). Name and location are immutable; changing |
| 275 | * either replaces the job. |
| 276 | * |
| 277 | * ### Creating a Job |
| 278 | * **Example:** Generated name, yearly HTTP GET |
| 279 | * ```typescript |
| 280 | * const ping = yield* GCP.CloudScheduler.Job("Ping", { |
| 281 | * schedule: "0 0 1 1 *", |
| 282 | * paused: true, |
| 283 | * httpTarget: { |
| 284 | * uri: "https://example.com/", |
| 285 | * httpMethod: "GET", |
| 286 | * }, |
| 287 | * }); |
| 288 | * ``` |
| 289 | * |
| 290 | * **Example:** Named job with retries and a POST body |
| 291 | * ```typescript |
| 292 | * const notify = yield* GCP.CloudScheduler.Job("Notify", { |
| 293 | * jobId: "order-notify", |
| 294 | * location: "us-central1", |
| 295 | * schedule: "every 15 minutes", |
| 296 | * timeZone: "America/Chicago", |
| 297 | * description: "fan out order events", |
| 298 | * retryConfig: { retryCount: 3, minBackoffDuration: "10s" }, |
| 299 | * httpTarget: { |
| 300 | * uri: "https://example.com/hooks/orders", |
| 301 | * httpMethod: "POST", |
| 302 | * headers: { "Content-Type": "application/json" }, |
| 303 | * body: JSON.stringify({ source: "scheduler" }), |
| 304 | * }, |
| 305 | * }); |
| 306 | * ``` |
| 307 | * |
| 308 | * **Example:** Pub/Sub target |
| 309 | * ```typescript |
| 310 | * const tick = yield* GCP.CloudScheduler.Job("Tick", { |
| 311 | * schedule: "0 * * * *", |
| 312 | * pubsubTarget: { |
| 313 | * topicName: topic.name, |
| 314 | * data: "tick", |
| 315 | * }, |
| 316 | * }); |
| 317 | * ``` |
| 318 | * |
| 319 | * @resource |
| 320 | * @category CloudScheduler |
| 321 | */ |
| 322 | export const Job = Resource<Job>("GCP.CloudScheduler.Job"); |
| 323 | |
| 324 | export class JobNotResolved extends Data.TaggedError("GCP.CloudScheduler.JobNotResolved")<{ |
| 325 | resourceName: string; |
| 326 | }> {} |
| 327 | |
| 328 | export class SchedulerJobNotReady extends Data.TaggedError("GCP.CloudScheduler.JobNotReady")<{ |
| 329 | resourceName: string; |
| 330 | state: string | undefined; |
| 331 | }> {} |
| 332 | |
| 333 | export class JobStateFailed extends Data.TaggedError("GCP.CloudScheduler.JobStateFailed")<{ |
| 334 | resourceName: string; |
| 335 | state: string; |
| 336 | message: string; |
| 337 | }> {} |
| 338 | |
| 339 | export class JobTargetMissing extends Data.TaggedError("GCP.CloudScheduler.JobTargetMissing")<{ |
| 340 | resourceName: string; |
| 341 | message: string; |
| 342 | }> {} |
| 343 | |
| 344 | const lastSegment = (value: string) => { |
| 345 | const trimmed = value.replace(/\/+$/, ""); |
| 346 | const parts = trimmed.split("/"); |
| 347 | return parts[parts.length - 1] || trimmed; |
| 348 | }; |
| 349 | |
| 350 | const normalizeLocation = (location: string | undefined, fallback: string) => |
| 351 | lastSegment(location ?? fallback).toLowerCase(); |
| 352 | |
| 353 | const resourceName = (project: string, location: string, jobId: string) => |
| 354 | `projects/${project}/locations/${location}/jobs/${jobId}`; |
| 355 | |
| 356 | const parentOf = (project: string, location: string) => `projects/${project}/locations/${location}`; |
| 357 | |
| 358 | const parseName = (name: string, fallbackLocation: string) => { |
| 359 | const parts = name.split("/").filter((part) => part.length > 0); |
| 360 | const jobsAt = parts.lastIndexOf("jobs"); |
| 361 | const locationsAt = parts.lastIndexOf("locations"); |
| 362 | const projectsAt = parts.lastIndexOf("projects"); |
| 363 | return { |
| 364 | project: projectsAt >= 0 && parts[projectsAt + 1] ? parts[projectsAt + 1]! : "", |
| 365 | location: |
| 366 | locationsAt >= 0 && parts[locationsAt + 1] ? parts[locationsAt + 1]! : fallbackLocation, |
| 367 | jobId: jobsAt >= 0 && parts[jobsAt + 1] ? parts[jobsAt + 1]! : lastSegment(name), |
| 368 | }; |
| 369 | }; |
| 370 | |
| 371 | const toId = (id: string, jobId: string | undefined, existing?: string) => |
| 372 | Effect.gen(function* () { |
| 373 | return ( |
| 374 | jobId ?? |
| 375 | existing ?? |
| 376 | (yield* createPhysicalName({ |
| 377 | id, |
| 378 | maxLength: MAX_NAME_LENGTH, |
| 379 | lowercase: true, |
| 380 | })) |
| 381 | ); |
| 382 | }); |
| 383 | |
| 384 | const encodeUtf8 = (value: string | undefined) => |
| 385 | value === undefined |
| 386 | ? Effect.succeed(undefined as string | undefined) |
| 387 | : Effect.sync(() => Buffer.from(value, "utf8").toString("base64")); |
| 388 | |
| 389 | const methodOf = (value: string | undefined) => |
| 390 | value && value !== "HTTP_METHOD_UNSPECIFIED" ? value : DEFAULT_HTTP_METHOD; |
| 391 | |
| 392 | const timeZoneOf = (value: string | undefined) => |
| 393 | value && value.length > 0 ? value : DEFAULT_TIME_ZONE; |
| 394 | |
| 395 | const compact = <T extends Record<string, unknown>>(value: T): T => |
| 396 | Object.fromEntries(Object.entries(value).filter(([, item]) => item !== undefined)) as T; |
| 397 | |
| 398 | const toAttrs = (job: scheduler.Job, project: string, region: string) => { |
| 399 | const name = job.name ?? ""; |
| 400 | const parsed = parseName(name, region); |
| 401 | return { |
| 402 | name, |
| 403 | jobId: parsed.jobId, |
| 404 | location: parsed.location, |
| 405 | project: parsed.project || project, |
| 406 | description: job.description, |
| 407 | schedule: job.schedule, |
| 408 | timeZone: job.timeZone, |
| 409 | state: job.state, |
| 410 | paused: job.state === "PAUSED", |
| 411 | attemptDeadline: job.attemptDeadline, |
| 412 | retryConfig: job.retryConfig, |
| 413 | httpTarget: job.httpTarget, |
| 414 | pubsubTarget: job.pubsubTarget, |
| 415 | appEngineHttpTarget: job.appEngineHttpTarget, |
| 416 | scheduleTime: job.scheduleTime, |
| 417 | lastAttemptTime: job.lastAttemptTime, |
| 418 | userUpdateTime: job.userUpdateTime, |
| 419 | status: job.status, |
| 420 | satisfiesPzs: job.satisfiesPzs, |
| 421 | }; |
| 422 | }; |
| 423 | |
| 424 | const getByName = (name: string) => |
| 425 | scheduler |
| 426 | .getProjectsLocationsJobs({ name }) |
| 427 | .pipe(Effect.catchTag("NotFound", () => Effect.undefined)); |
| 428 | |
| 429 | /** Poll until Cloud Scheduler reports the job in the desired ENABLED/PAUSED state. */ |
| 430 | const waitForJobState = (name: string, paused: boolean) => |
| 431 | getByName(name).pipe( |
| 432 | Effect.flatMap((job): Effect.Effect<scheduler.Job, JobStateFailed | SchedulerJobNotReady> => { |
| 433 | const desired = paused ? "PAUSED" : "ENABLED"; |
| 434 | if (job?.state === desired) return Effect.succeed(job); |
| 435 | if (job?.state === "UPDATE_FAILED" || job?.state === "DISABLED") { |
| 436 | return Effect.fail( |
| 437 | new JobStateFailed({ |
| 438 | resourceName: name, |
| 439 | state: job.state, |
| 440 | message: job.status?.message ?? `job is ${job.state}`, |
| 441 | }), |
| 442 | ); |
| 443 | } |
| 444 | return Effect.fail(new SchedulerJobNotReady({ resourceName: name, state: job?.state })); |
| 445 | }), |
| 446 | Effect.retry({ |
| 447 | while: (error) => error._tag === "GCP.CloudScheduler.JobNotReady", |
| 448 | times: 30, |
| 449 | schedule: Schedule.spaced("2 seconds"), |
| 450 | }), |
| 451 | ); |
| 452 | |
| 453 | const headersMatch = ( |
| 454 | observed: scheduler.StringMap | undefined, |
| 455 | desired: Record<string, string> | undefined, |
| 456 | ) => { |
| 457 | if (desired === undefined) return true; |
| 458 | const current = observed ?? {}; |
| 459 | for (const [key, value] of Object.entries(desired)) { |
| 460 | const found = Object.entries(current).find( |
| 461 | ([header]) => header.toLowerCase() === key.toLowerCase(), |
| 462 | ); |
| 463 | if ((found?.[1] ?? "") !== value) return false; |
| 464 | } |
| 465 | return true; |
| 466 | }; |
| 467 | |
| 468 | const tokenEqual = ( |
| 469 | observed: { serviceAccountEmail?: string; audience?: string; scope?: string } | undefined, |
| 470 | desired: { serviceAccountEmail?: string; audience?: string; scope?: string } | undefined, |
| 471 | ) => { |
| 472 | if (desired === undefined) return true; |
| 473 | return ( |
| 474 | (observed?.serviceAccountEmail ?? "") === (desired.serviceAccountEmail ?? "") && |
| 475 | (observed?.audience ?? "") === (desired.audience ?? "") && |
| 476 | (observed?.scope ?? "") === (desired.scope ?? "") |
| 477 | ); |
| 478 | }; |
| 479 | |
| 480 | const subsetEqual = ( |
| 481 | observed: Record<string, unknown> | undefined, |
| 482 | desired: Record<string, unknown> | undefined, |
| 483 | ) => { |
| 484 | if (desired === undefined) return true; |
| 485 | const current = observed ?? {}; |
| 486 | for (const [key, value] of Object.entries(desired)) { |
| 487 | if (value === undefined) continue; |
| 488 | if (current[key] !== value) return false; |
| 489 | } |
| 490 | return true; |
| 491 | }; |
| 492 | |
| 493 | const toApiHttpTarget = Effect.fn(function* (target: HttpTarget) { |
| 494 | return compact({ |
| 495 | uri: target.uri, |
| 496 | httpMethod: target.httpMethod, |
| 497 | headers: target.headers, |
| 498 | body: yield* encodeUtf8(target.body), |
| 499 | oidcToken: target.oidcToken, |
| 500 | oauthToken: target.oauthToken, |
| 501 | }) as scheduler.HttpTarget; |
| 502 | }); |
| 503 | |
| 504 | const toApiPubsubTarget = Effect.fn(function* (target: PubsubTarget) { |
| 505 | return compact({ |
| 506 | topicName: target.topicName, |
| 507 | data: yield* encodeUtf8(target.data), |
| 508 | attributes: target.attributes, |
| 509 | }) as scheduler.PubsubTarget; |
| 510 | }); |
| 511 | |
| 512 | const toApiAppEngineHttpTarget = Effect.fn(function* (target: AppEngineHttpTarget) { |
| 513 | return compact({ |
| 514 | relativeUri: target.relativeUri, |
| 515 | httpMethod: target.httpMethod, |
| 516 | headers: target.headers, |
| 517 | body: yield* encodeUtf8(target.body), |
| 518 | appEngineRouting: target.appEngineRouting, |
| 519 | }) as scheduler.AppEngineHttpTarget; |
| 520 | }); |
| 521 | |
| 522 | const httpTargetDrift = ( |
| 523 | observed: scheduler.HttpTarget | undefined, |
| 524 | desired: scheduler.HttpTarget | undefined, |
| 525 | news: HttpTarget | undefined, |
| 526 | ) => { |
| 527 | if (news === undefined || desired === undefined) return false; |
| 528 | if ((observed?.uri ?? "") !== (desired.uri ?? "")) return true; |
| 529 | if (methodOf(observed?.httpMethod) !== methodOf(desired.httpMethod)) { |
| 530 | return true; |
| 531 | } |
| 532 | if ((observed?.body ?? "") !== (desired.body ?? "")) return true; |
| 533 | if (!headersMatch(observed?.headers, news.headers)) return true; |
| 534 | if (!tokenEqual(observed?.oidcToken, news.oidcToken)) return true; |
| 535 | if (!tokenEqual(observed?.oauthToken, news.oauthToken)) return true; |
| 536 | return false; |
| 537 | }; |
| 538 | |
| 539 | const pubsubTargetDrift = ( |
| 540 | observed: scheduler.PubsubTarget | undefined, |
| 541 | desired: scheduler.PubsubTarget | undefined, |
| 542 | ) => { |
| 543 | if (desired === undefined) return false; |
| 544 | if ((observed?.topicName ?? "") !== (desired.topicName ?? "")) return true; |
| 545 | if ((observed?.data ?? "") !== (desired.data ?? "")) return true; |
| 546 | return !subsetEqual(observed?.attributes, desired.attributes); |
| 547 | }; |
| 548 | |
| 549 | const appEngineTargetDrift = ( |
| 550 | observed: scheduler.AppEngineHttpTarget | undefined, |
| 551 | desired: scheduler.AppEngineHttpTarget | undefined, |
| 552 | news: AppEngineHttpTarget | undefined, |
| 553 | ) => { |
| 554 | if (news === undefined || desired === undefined) return false; |
| 555 | if ((observed?.relativeUri ?? "") !== (desired.relativeUri ?? "")) { |
| 556 | return true; |
| 557 | } |
| 558 | if (methodOf(observed?.httpMethod) !== methodOf(desired.httpMethod)) { |
| 559 | return true; |
| 560 | } |
| 561 | if ((observed?.body ?? "") !== (desired.body ?? "")) return true; |
| 562 | if (!headersMatch(observed?.headers, news.headers)) return true; |
| 563 | return !subsetEqual( |
| 564 | observed?.appEngineRouting as Record<string, unknown> | undefined, |
| 565 | news.appEngineRouting as Record<string, unknown> | undefined, |
| 566 | ); |
| 567 | }; |
| 568 | |
| 569 | const hasTarget = (news: JobProps) => |
| 570 | news.httpTarget !== undefined || |
| 571 | news.pubsubTarget !== undefined || |
| 572 | news.appEngineHttpTarget !== undefined; |
| 573 | |
| 574 | const retryTransient = <A, E extends { _tag: string }, R>(effect: Effect.Effect<A, E, R>) => |
| 575 | effect.pipe( |
| 576 | Effect.retry({ |
| 577 | while: (error) => error._tag === "NotFound" || error._tag === "Conflict", |
| 578 | times: 8, |
| 579 | schedule: backoff, |
| 580 | }), |
| 581 | ); |
| 582 | |
| 583 | const syncPaused = Effect.fn(function* (name: string, current: scheduler.Job, paused: boolean) { |
| 584 | if (paused && current.state === "ENABLED") { |
| 585 | const pausedJob = yield* retryTransient( |
| 586 | scheduler.pauseProjectsLocationsJobs({ name, body: {} }), |
| 587 | ).pipe( |
| 588 | Effect.catchTag(["BadRequest", "Conflict", "NotFound"], () => |
| 589 | getByName(name).pipe( |
| 590 | Effect.flatMap((job) => |
| 591 | job !== undefined && job.state === "PAUSED" |
| 592 | ? Effect.succeed(job) |
| 593 | : new JobNotResolved({ resourceName: name }), |
| 594 | ), |
| 595 | ), |
| 596 | ), |
| 597 | ); |
| 598 | return pausedJob ?? current; |
| 599 | } |
| 600 | if (!paused && current.state === "PAUSED") { |
| 601 | const resumed = yield* retryTransient( |
| 602 | scheduler.resumeProjectsLocationsJobs({ name, body: {} }), |
| 603 | ).pipe( |
| 604 | Effect.catchTag(["BadRequest", "Conflict", "NotFound"], () => |
| 605 | getByName(name).pipe( |
| 606 | Effect.flatMap((job) => |
| 607 | job !== undefined && job.state === "ENABLED" |
| 608 | ? Effect.succeed(job) |
| 609 | : new JobNotResolved({ resourceName: name }), |
| 610 | ), |
| 611 | ), |
| 612 | ), |
| 613 | ); |
| 614 | return resumed ?? current; |
| 615 | } |
| 616 | return current; |
| 617 | }); |
| 618 | |
| 619 | export const JobProvider = () => |
| 620 | Provider.succeed(Job, { |
| 621 | stables: ["name", "jobId", "location", "project"], |
| 622 | |
| 623 | diff: Effect.fn(function* ({ news, olds, output }) { |
| 624 | if (!isResolved(news)) return undefined; |
| 625 | const env = yield* GcpEnvironment.current; |
| 626 | const previousId = olds?.jobId ?? output?.jobId; |
| 627 | const nextId = news.jobId ?? previousId; |
| 628 | const idChanged = previousId !== undefined && nextId !== undefined && nextId !== previousId; |
| 629 | |
| 630 | const previousLocation = normalizeLocation(olds?.location ?? output?.location, env.region); |
| 631 | const nextLocation = normalizeLocation(news.location ?? output?.location, env.region); |
| 632 | const locationChanged = previousLocation !== nextLocation; |
| 633 | |
| 634 | if (idChanged || locationChanged) { |
| 635 | return { action: "replace" as const, deleteFirst: false }; |
| 636 | } |
| 637 | return undefined; |
| 638 | }), |
| 639 | |
| 640 | read: Effect.fn(function* ({ id, olds, output }) { |
| 641 | const env = yield* GcpEnvironment.current; |
| 642 | const jobId = yield* toId(id, olds?.jobId, output?.jobId); |
| 643 | const location = normalizeLocation(olds?.location ?? output?.location, env.region); |
| 644 | const name = output?.name ?? resourceName(env.project, location, jobId); |
| 645 | const existing = yield* getByName(name); |
| 646 | if (existing === undefined) return undefined; |
| 647 | const attrs = toAttrs(existing, env.project, env.region); |
| 648 | // No labels field: without prior state the job may not be ours. |
| 649 | return output !== undefined ? attrs : Unowned(attrs); |
| 650 | }), |
| 651 | |
| 652 | reconcile: Effect.fn(function* ({ id, news, output }) { |
| 653 | const env = yield* GcpEnvironment.current; |
| 654 | const jobId = yield* toId(id, news.jobId, output?.jobId); |
| 655 | const location = normalizeLocation(news.location ?? output?.location, env.region); |
| 656 | const name = resourceName(env.project, location, jobId); |
| 657 | const parent = parentOf(env.project, location); |
| 658 | if (!hasTarget(news)) { |
| 659 | return yield* new JobTargetMissing({ |
| 660 | resourceName: name, |
| 661 | message: "Cloud Scheduler jobs require httpTarget, pubsubTarget, or appEngineHttpTarget", |
| 662 | }); |
| 663 | } |
| 664 | |
| 665 | // Descriptions are a single RE2 line (`^.{1,499}$`). |
| 666 | const desiredDescription = |
| 667 | news.description |
| 668 | ?.replace(/[\r\n]+/g, " ") |
| 669 | .trim() |
| 670 | .slice(0, 499) || undefined; |
| 671 | const desiredTimeZone = timeZoneOf(news.timeZone); |
| 672 | const desiredPaused = news.paused === true; |
| 673 | const httpTarget = |
| 674 | news.httpTarget !== undefined ? yield* toApiHttpTarget(news.httpTarget) : undefined; |
| 675 | const pubsubTarget = |
| 676 | news.pubsubTarget !== undefined ? yield* toApiPubsubTarget(news.pubsubTarget) : undefined; |
| 677 | const appEngineHttpTarget = |
| 678 | news.appEngineHttpTarget !== undefined |
| 679 | ? yield* toApiAppEngineHttpTarget(news.appEngineHttpTarget) |
| 680 | : undefined; |
| 681 | |
| 682 | const desiredBody: scheduler.Job = compact({ |
| 683 | name, |
| 684 | description: desiredDescription, |
| 685 | schedule: news.schedule, |
| 686 | timeZone: desiredTimeZone, |
| 687 | attemptDeadline: news.attemptDeadline, |
| 688 | retryConfig: news.retryConfig, |
| 689 | httpTarget, |
| 690 | pubsubTarget, |
| 691 | appEngineHttpTarget, |
| 692 | }); |
| 693 | |
| 694 | let current = yield* getByName(name); |
| 695 | |
| 696 | if (current === undefined) { |
| 697 | const created = yield* scheduler |
| 698 | .createProjectsLocationsJobs({ |
| 699 | parent, |
| 700 | body: desiredBody, |
| 701 | }) |
| 702 | .pipe(Effect.catchTag("Conflict", () => getByName(name))); |
| 703 | current = created ?? undefined; |
| 704 | } |
| 705 | |
| 706 | if (current === undefined) { |
| 707 | return yield* new JobNotResolved({ resourceName: name }); |
| 708 | } |
| 709 | |
| 710 | const mask: string[] = []; |
| 711 | if ((current.description ?? "") !== (desiredDescription ?? "")) { |
| 712 | mask.push("description"); |
| 713 | } |
| 714 | if ((current.schedule ?? "") !== news.schedule) { |
| 715 | mask.push("schedule"); |
| 716 | } |
| 717 | if (timeZoneOf(current.timeZone) !== desiredTimeZone) { |
| 718 | mask.push("timeZone"); |
| 719 | } |
| 720 | if ( |
| 721 | news.attemptDeadline !== undefined && |
| 722 | (current.attemptDeadline ?? "") !== news.attemptDeadline |
| 723 | ) { |
| 724 | mask.push("attemptDeadline"); |
| 725 | } |
| 726 | if ( |
| 727 | news.retryConfig !== undefined && |
| 728 | !subsetEqual( |
| 729 | current.retryConfig as Record<string, unknown> | undefined, |
| 730 | news.retryConfig as Record<string, unknown>, |
| 731 | ) |
| 732 | ) { |
| 733 | mask.push("retryConfig"); |
| 734 | } |
| 735 | if (httpTargetDrift(current.httpTarget, httpTarget, news.httpTarget)) { |
| 736 | mask.push("httpTarget"); |
| 737 | } |
| 738 | if (pubsubTargetDrift(current.pubsubTarget, pubsubTarget)) { |
| 739 | mask.push("pubsubTarget"); |
| 740 | } |
| 741 | if ( |
| 742 | appEngineTargetDrift( |
| 743 | current.appEngineHttpTarget, |
| 744 | appEngineHttpTarget, |
| 745 | news.appEngineHttpTarget, |
| 746 | ) |
| 747 | ) { |
| 748 | mask.push("appEngineHttpTarget"); |
| 749 | } |
| 750 | |
| 751 | if (mask.length > 0) { |
| 752 | current = yield* retryTransient( |
| 753 | scheduler.patchProjectsLocationsJobs({ |
| 754 | name, |
| 755 | updateMask: mask.join(","), |
| 756 | body: desiredBody, |
| 757 | }), |
| 758 | ); |
| 759 | current = (yield* getByName(name)) ?? current; |
| 760 | } |
| 761 | |
| 762 | current = yield* syncPaused(name, current, desiredPaused); |
| 763 | current = yield* waitForJobState(name, desiredPaused); |
| 764 | return toAttrs(current, env.project, env.region); |
| 765 | }), |
| 766 | |
| 767 | delete: Effect.fn(function* ({ output }) { |
| 768 | yield* scheduler.deleteProjectsLocationsJobs({ name: output.name }).pipe( |
| 769 | Effect.retry({ |
| 770 | while: (error) => error._tag === "Conflict", |
| 771 | times: 10, |
| 772 | schedule: Schedule.spaced("3 seconds"), |
| 773 | }), |
| 774 | Effect.catchTag("NotFound", () => Effect.void), |
| 775 | ); |
| 776 | }), |
| 777 | }); |