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
| 1 | import * as bigquery from "@distilled.cloud/gcp/bigquery_v2"; |
| 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 Effect from "effect/Effect"; |
| 9 | import * as Stream from "effect/Stream"; |
| 10 | import { GcpEnvironment } from "../Environment.ts"; |
| 11 | import { |
| 12 | ALCHEMY_LABEL_PREFIX, |
| 13 | alchemyLabelKeys, |
| 14 | createInternalLabels, |
| 15 | hasAlchemyLabels, |
| 16 | } from "../Labels.ts"; |
| 17 | import type { Providers } from "../Providers.ts"; |
| 18 | |
| 19 | const MAX_ROUTINE_ID_LENGTH = 256; |
| 20 | const DEFAULT_LANGUAGE = "SQL"; |
| 21 | const DEFAULT_ARGUMENT_KIND = "FIXED_TYPE"; |
| 22 | |
| 23 | export type RoutineType = bigquery.RoutineRoutineTypeEnum | (string & {}); |
| 24 | export type RoutineLanguage = bigquery.RoutineLanguageEnum | (string & {}); |
| 25 | export type RoutineArgument = bigquery.Argument; |
| 26 | export type RoutineDataType = bigquery.StandardSqlDataType; |
| 27 | export type RoutineReturnTableType = bigquery.StandardSqlTableType; |
| 28 | export type RoutineSparkOptions = bigquery.SparkOptions; |
| 29 | export type RoutineRemoteFunctionOptions = bigquery.RemoteFunctionOptions; |
| 30 | export type RoutinePythonOptions = bigquery.PythonOptions; |
| 31 | export type RoutineExternalRuntimeOptions = bigquery.ExternalRuntimeOptions; |
| 32 | export type RoutineDeterminismLevel = bigquery.RoutineDeterminismLevelEnum | (string & {}); |
| 33 | export type RoutineSecurityMode = bigquery.RoutineSecurityModeEnum | (string & {}); |
| 34 | export type RoutineDataGovernanceType = bigquery.RoutineDataGovernanceTypeEnum | (string & {}); |
| 35 | |
| 36 | export type RoutineProps = { |
| 37 | /** |
| 38 | * Dataset id (the `{dataset}` segment of |
| 39 | * `projects/{project}/datasets/{dataset}`) or a full dataset resource |
| 40 | * name. Immutable — changing it replaces the routine. |
| 41 | */ |
| 42 | datasetId: string; |
| 43 | /** |
| 44 | * Routine id (the `{routine}` segment of |
| 45 | * `projects/{project}/datasets/{dataset}/routines/{routine}`). If omitted, |
| 46 | * a unique name is generated from the stack, stage, and logical id. Must |
| 47 | * contain only letters, numbers, and underscores; max 256 characters. |
| 48 | * Immutable — changing it replaces the routine. |
| 49 | */ |
| 50 | routineId?: string; |
| 51 | /** |
| 52 | * Routine kind (`SCALAR_FUNCTION`, `PROCEDURE`, `TABLE_VALUED_FUNCTION`, |
| 53 | * `AGGREGATE_FUNCTION`). Immutable — changing it replaces the routine. |
| 54 | */ |
| 55 | routineType: RoutineType; |
| 56 | /** |
| 57 | * Body of the routine. For SQL functions this is the expression inside |
| 58 | * the `AS (…)` clause, not a full `CREATE FUNCTION` statement. For |
| 59 | * JavaScript, the evaluated string in the `AS` clause. |
| 60 | */ |
| 61 | definitionBody: string; |
| 62 | /** |
| 63 | * Implementation language (`SQL`, `JAVASCRIPT`, `PYTHON`, `JAVA`, |
| 64 | * `SCALA`). Defaults to `SQL` unless `remoteFunctionOptions` is set. |
| 65 | */ |
| 66 | language?: RoutineLanguage; |
| 67 | /** |
| 68 | * Input/output arguments. `mode` is valid on procedures only. |
| 69 | */ |
| 70 | arguments?: RoutineArgument[]; |
| 71 | /** |
| 72 | * Return type for scalar and aggregate functions. Optional for SQL |
| 73 | * (inferred at query time); required for other languages. |
| 74 | */ |
| 75 | returnType?: RoutineDataType; |
| 76 | /** |
| 77 | * Return table schema when `routineType` is `TABLE_VALUED_FUNCTION`. |
| 78 | * Optional for SQL (inferred at query time). |
| 79 | */ |
| 80 | returnTableType?: RoutineReturnTableType; |
| 81 | /** |
| 82 | * User-friendly description of this routine. Alchemy ownership is stored |
| 83 | * in a `[alchemy …]` prefix for `list` / nuke. |
| 84 | */ |
| 85 | description?: string; |
| 86 | /** |
| 87 | * GCS paths of imported JavaScript libraries when `language` is |
| 88 | * `JAVASCRIPT`. |
| 89 | */ |
| 90 | importedLibraries?: string[]; |
| 91 | /** |
| 92 | * Determinism of a JavaScript UDF (`DETERMINISTIC`, |
| 93 | * `NOT_DETERMINISTIC`). |
| 94 | */ |
| 95 | determinismLevel?: RoutineDeterminismLevel; |
| 96 | /** |
| 97 | * Security mode (`DEFINER`, `INVOKER`). If omitted, BigQuery infers it |
| 98 | * from the routine configuration. |
| 99 | */ |
| 100 | securityMode?: RoutineSecurityMode; |
| 101 | /** |
| 102 | * Set to `DATA_MASKING` to register a custom masking function. |
| 103 | */ |
| 104 | dataGovernanceType?: RoutineDataGovernanceType; |
| 105 | /** |
| 106 | * Extra validation for procedure bodies. Default `true`. Recursive |
| 107 | * procedures should set this to `false`. |
| 108 | * @default true |
| 109 | */ |
| 110 | strictMode?: boolean; |
| 111 | /** |
| 112 | * Spark procedure options (`JAVA` / `SCALA` / PySpark). |
| 113 | */ |
| 114 | sparkOptions?: RoutineSparkOptions; |
| 115 | /** |
| 116 | * Remote function endpoint and connection. |
| 117 | */ |
| 118 | remoteFunctionOptions?: RoutineRemoteFunctionOptions; |
| 119 | /** |
| 120 | * Python UDF entry point and packages. |
| 121 | */ |
| 122 | pythonOptions?: RoutinePythonOptions; |
| 123 | /** |
| 124 | * Container limits for Python UDFs. |
| 125 | */ |
| 126 | externalRuntimeOptions?: RoutineExternalRuntimeOptions; |
| 127 | }; |
| 128 | |
| 129 | export type Routine = Resource< |
| 130 | "GCP.BigQuery.Routine", |
| 131 | RoutineProps, |
| 132 | { |
| 133 | /** |
| 134 | * Resource path |
| 135 | * `projects/{project}/datasets/{dataset}/routines/{routine}`. |
| 136 | */ |
| 137 | name: string; |
| 138 | /** Opaque id `project:dataset.routine`. */ |
| 139 | id: string; |
| 140 | /** Routine id (last path segment). */ |
| 141 | routineId: string; |
| 142 | /** Dataset id. */ |
| 143 | datasetId: string; |
| 144 | /** Project id. */ |
| 145 | project: string; |
| 146 | /** Routine kind. */ |
| 147 | routineType: string; |
| 148 | /** Implementation language, if set. */ |
| 149 | language: string | undefined; |
| 150 | /** Routine body. */ |
| 151 | definitionBody: string; |
| 152 | /** Arguments, if set. */ |
| 153 | arguments: RoutineArgument[] | undefined; |
| 154 | /** Scalar/aggregate return type, if set. */ |
| 155 | returnType: RoutineDataType | undefined; |
| 156 | /** TVF return table type, if set. */ |
| 157 | returnTableType: RoutineReturnTableType | undefined; |
| 158 | /** Description, if set. */ |
| 159 | description: string | undefined; |
| 160 | /** Imported JavaScript libraries. */ |
| 161 | importedLibraries: string[] | undefined; |
| 162 | /** JavaScript determinism, if set. */ |
| 163 | determinismLevel: string | undefined; |
| 164 | /** Security mode, if set. */ |
| 165 | securityMode: string | undefined; |
| 166 | /** Data-governance classification, if set. */ |
| 167 | dataGovernanceType: string | undefined; |
| 168 | /** Procedure strict-mode flag. */ |
| 169 | strictMode: boolean | undefined; |
| 170 | /** Spark options, if set. */ |
| 171 | sparkOptions: RoutineSparkOptions | undefined; |
| 172 | /** Remote function options, if set. */ |
| 173 | remoteFunctionOptions: RoutineRemoteFunctionOptions | undefined; |
| 174 | /** Python UDF options, if set. */ |
| 175 | pythonOptions: RoutinePythonOptions | undefined; |
| 176 | /** Python runtime options, if set. */ |
| 177 | externalRuntimeOptions: RoutineExternalRuntimeOptions | undefined; |
| 178 | /** Creation time in milliseconds since epoch. */ |
| 179 | creationTime: string | undefined; |
| 180 | /** Last-modified time in milliseconds since epoch. */ |
| 181 | lastModifiedTime: string | undefined; |
| 182 | /** Server etag. */ |
| 183 | etag: string | undefined; |
| 184 | }, |
| 185 | never, |
| 186 | Providers |
| 187 | >; |
| 188 | |
| 189 | /** |
| 190 | * A Google BigQuery routine — a user-defined function, table-valued |
| 191 | * function, aggregate function, or stored procedure. |
| 192 | * |
| 193 | * Routines have no labels; Alchemy stamps ownership into the description |
| 194 | * (`[alchemy alchemy-stack=… alchemy-stage=… alchemy-id=…]`) so `list` / |
| 195 | * `pnpm nuke:gcp` can find them inside datasets that carry `alchemy-*` |
| 196 | * labels. `datasetId`, `routineId`, and `routineType` are immutable |
| 197 | * (changing them replaces the routine). Body, arguments, description, |
| 198 | * language, and language-specific options update in place via a |
| 199 | * full-resource replace. |
| 200 | * |
| 201 | * ### Creating a Routine |
| 202 | * **Example:** SQL scalar function |
| 203 | * ```typescript |
| 204 | * const dataset = yield* GCP.BigQuery.Dataset("Analytics", { |
| 205 | * forceDestroy: true, |
| 206 | * }); |
| 207 | * const add = yield* GCP.BigQuery.Routine("Add", { |
| 208 | * datasetId: dataset.datasetId, |
| 209 | * routineType: "SCALAR_FUNCTION", |
| 210 | * language: "SQL", |
| 211 | * arguments: [ |
| 212 | * { name: "x", dataType: { typeKind: "INT64" } }, |
| 213 | * { name: "y", dataType: { typeKind: "INT64" } }, |
| 214 | * ], |
| 215 | * returnType: { typeKind: "INT64" }, |
| 216 | * definitionBody: "x + y", |
| 217 | * }); |
| 218 | * ``` |
| 219 | * |
| 220 | * **Example:** SQL stored procedure |
| 221 | * ```typescript |
| 222 | * const proc = yield* GCP.BigQuery.Routine("Seed", { |
| 223 | * datasetId: dataset.datasetId, |
| 224 | * routineType: "PROCEDURE", |
| 225 | * language: "SQL", |
| 226 | * definitionBody: "SELECT 1", |
| 227 | * }); |
| 228 | * ``` |
| 229 | * |
| 230 | * **Example:** JavaScript UDF |
| 231 | * ```typescript |
| 232 | * const multiply = yield* GCP.BigQuery.Routine("Multiply", { |
| 233 | * datasetId: dataset.datasetId, |
| 234 | * routineType: "SCALAR_FUNCTION", |
| 235 | * language: "JAVASCRIPT", |
| 236 | * determinismLevel: "DETERMINISTIC", |
| 237 | * arguments: [ |
| 238 | * { name: "x", dataType: { typeKind: "FLOAT64" } }, |
| 239 | * { name: "y", dataType: { typeKind: "FLOAT64" } }, |
| 240 | * ], |
| 241 | * returnType: { typeKind: "FLOAT64" }, |
| 242 | * definitionBody: "return x * y;", |
| 243 | * }); |
| 244 | * ``` |
| 245 | * |
| 246 | * ### Calling a Routine |
| 247 | * **Example:** Invoke a SQL function with Query |
| 248 | * ```typescript |
| 249 | * const query = yield* GCP.BigQuery.Query(dataset); |
| 250 | * const result = yield* query({ query: "SELECT Add(1, 2) AS n" }); |
| 251 | * ``` |
| 252 | * |
| 253 | * @resource |
| 254 | * @category BigQuery |
| 255 | */ |
| 256 | export const Routine = Resource<Routine>("GCP.BigQuery.Routine"); |
| 257 | |
| 258 | export class RoutineNotResolved extends Data.TaggedError("GCP.BigQuery.RoutineNotResolved")<{ |
| 259 | resourceName: string; |
| 260 | }> {} |
| 261 | |
| 262 | const lastSegment = (value: string) => { |
| 263 | const trimmed = value.replace(/\/+$/, ""); |
| 264 | const parts = trimmed.split("/"); |
| 265 | return parts[parts.length - 1] || trimmed; |
| 266 | }; |
| 267 | |
| 268 | const datasetIdOf = (datasetId: string) => |
| 269 | datasetId.includes("/") ? lastSegment(datasetId) : datasetId; |
| 270 | |
| 271 | const resourceName = (project: string, datasetId: string, routineId: string) => |
| 272 | `projects/${project}/datasets/${datasetId}/routines/${routineId}`; |
| 273 | |
| 274 | const toId = (id: string, routineId: string | undefined, existing?: string) => |
| 275 | Effect.gen(function* () { |
| 276 | if (routineId !== undefined) return routineId; |
| 277 | if (existing !== undefined) return existing; |
| 278 | const generated = yield* createPhysicalName({ |
| 279 | id, |
| 280 | maxLength: MAX_ROUTINE_ID_LENGTH, |
| 281 | lowercase: true, |
| 282 | delimiter: "_", |
| 283 | }); |
| 284 | return generated.replaceAll("-", "_"); |
| 285 | }); |
| 286 | |
| 287 | const stable = (value: unknown): unknown => { |
| 288 | if (Array.isArray(value)) return value.map(stable); |
| 289 | if (value !== null && typeof value === "object") { |
| 290 | return Object.fromEntries( |
| 291 | Object.entries(value as Record<string, unknown>) |
| 292 | .filter(([, nested]) => nested !== undefined) |
| 293 | .sort(([left], [right]) => left.localeCompare(right)) |
| 294 | .map(([key, nested]) => [key, stable(nested)]), |
| 295 | ); |
| 296 | } |
| 297 | return value; |
| 298 | }; |
| 299 | |
| 300 | const jsonEqual = (left: unknown, right: unknown) => |
| 301 | JSON.stringify(stable(left ?? null)) === JSON.stringify(stable(right ?? null)); |
| 302 | |
| 303 | const canonType = (type: RoutineDataType | undefined): RoutineDataType | undefined => { |
| 304 | if (type === undefined) return undefined; |
| 305 | return { |
| 306 | typeKind: type.typeKind, |
| 307 | arrayElementType: canonType(type.arrayElementType), |
| 308 | rangeElementType: canonType(type.rangeElementType), |
| 309 | structType: type.structType |
| 310 | ? { |
| 311 | fields: (type.structType.fields ?? []).map((field) => ({ |
| 312 | name: field.name, |
| 313 | type: canonType(field.type), |
| 314 | })), |
| 315 | } |
| 316 | : undefined, |
| 317 | }; |
| 318 | }; |
| 319 | |
| 320 | const canonArguments = (args: RoutineArgument[] | undefined) => |
| 321 | (args ?? []).map((argument) => ({ |
| 322 | name: argument.name ?? "", |
| 323 | argumentKind: argument.argumentKind ?? DEFAULT_ARGUMENT_KIND, |
| 324 | mode: argument.mode, |
| 325 | isAggregate: argument.isAggregate, |
| 326 | dataType: canonType(argument.dataType), |
| 327 | })); |
| 328 | |
| 329 | const encodeDescription = ( |
| 330 | labels: Record<string, string>, |
| 331 | description: string | undefined, |
| 332 | ): string => { |
| 333 | const marker = `[alchemy ${alchemyLabelKeys.stack}=${labels[alchemyLabelKeys.stack]} ${alchemyLabelKeys.stage}=${labels[alchemyLabelKeys.stage]} ${alchemyLabelKeys.id}=${labels[alchemyLabelKeys.id]}]`; |
| 334 | return description ? `${marker}\n${description}` : marker; |
| 335 | }; |
| 336 | |
| 337 | const parseDescription = ( |
| 338 | description: string | undefined, |
| 339 | ): { |
| 340 | labels: Record<string, string>; |
| 341 | description: string | undefined; |
| 342 | } => { |
| 343 | if (!description?.startsWith("[alchemy ")) { |
| 344 | return { labels: {}, description }; |
| 345 | } |
| 346 | const end = description.indexOf("]"); |
| 347 | if (end < 0) return { labels: {}, description }; |
| 348 | const labels: Record<string, string> = {}; |
| 349 | for (const part of description.slice("[alchemy ".length, end).split(/\s+/)) { |
| 350 | const eq = part.indexOf("="); |
| 351 | if (eq > 0) { |
| 352 | labels[part.slice(0, eq)] = part.slice(eq + 1); |
| 353 | } |
| 354 | } |
| 355 | const rest = description.slice(end + 1).replace(/^\n/, ""); |
| 356 | return { labels, description: rest.length > 0 ? rest : undefined }; |
| 357 | }; |
| 358 | |
| 359 | const hasOwnershipMarker = (description: string | undefined) => |
| 360 | Object.keys(parseDescription(description).labels).some((key) => |
| 361 | key.startsWith(ALCHEMY_LABEL_PREFIX), |
| 362 | ); |
| 363 | |
| 364 | const toAttrs = (routine: bigquery.Routine, project: string) => { |
| 365 | const ref = routine.routineReference; |
| 366 | const routineId = ref?.routineId ?? ""; |
| 367 | const datasetId = ref?.datasetId ?? ""; |
| 368 | const projectId = ref?.projectId ?? project; |
| 369 | return { |
| 370 | name: resourceName(projectId, datasetId, routineId), |
| 371 | id: `${projectId}:${datasetId}.${routineId}`, |
| 372 | routineId, |
| 373 | datasetId, |
| 374 | project: projectId, |
| 375 | routineType: routine.routineType ?? "", |
| 376 | language: routine.language, |
| 377 | definitionBody: routine.definitionBody ?? "", |
| 378 | arguments: routine.arguments, |
| 379 | returnType: routine.returnType, |
| 380 | returnTableType: routine.returnTableType, |
| 381 | description: parseDescription(routine.description).description, |
| 382 | importedLibraries: routine.importedLibraries, |
| 383 | determinismLevel: routine.determinismLevel, |
| 384 | securityMode: routine.securityMode, |
| 385 | dataGovernanceType: routine.dataGovernanceType, |
| 386 | strictMode: routine.strictMode, |
| 387 | sparkOptions: routine.sparkOptions, |
| 388 | remoteFunctionOptions: routine.remoteFunctionOptions, |
| 389 | pythonOptions: routine.pythonOptions, |
| 390 | externalRuntimeOptions: routine.externalRuntimeOptions, |
| 391 | creationTime: routine.creationTime, |
| 392 | lastModifiedTime: routine.lastModifiedTime, |
| 393 | etag: routine.etag, |
| 394 | }; |
| 395 | }; |
| 396 | |
| 397 | const getByRef = (projectId: string, datasetId: string, routineId: string) => |
| 398 | bigquery |
| 399 | .getRoutines({ projectId, datasetId, routineId }) |
| 400 | .pipe(Effect.catchTag("NotFound", () => Effect.undefined)); |
| 401 | |
| 402 | const defaultLanguage = (news: RoutineProps, observed?: bigquery.Routine) => { |
| 403 | if (news.language !== undefined) return news.language; |
| 404 | if (observed?.language !== undefined) return observed.language; |
| 405 | if (news.remoteFunctionOptions !== undefined || observed?.remoteFunctionOptions !== undefined) { |
| 406 | return undefined; |
| 407 | } |
| 408 | return DEFAULT_LANGUAGE; |
| 409 | }; |
| 410 | |
| 411 | const pick = <T>(news: T | undefined, observed: T | undefined) => |
| 412 | news !== undefined ? news : observed; |
| 413 | |
| 414 | const toRoutineBody = ( |
| 415 | projectId: string, |
| 416 | datasetId: string, |
| 417 | routineId: string, |
| 418 | news: RoutineProps, |
| 419 | encodedDescription: string, |
| 420 | observed?: bigquery.Routine, |
| 421 | ): bigquery.Routine => { |
| 422 | const body: bigquery.Routine = { |
| 423 | routineReference: { projectId, datasetId, routineId }, |
| 424 | routineType: news.routineType, |
| 425 | definitionBody: news.definitionBody, |
| 426 | description: encodedDescription, |
| 427 | }; |
| 428 | const language = defaultLanguage(news, observed); |
| 429 | if (language !== undefined) body.language = language; |
| 430 | const args = pick(news.arguments, observed?.arguments); |
| 431 | if (args !== undefined) body.arguments = args; |
| 432 | const returnType = pick(news.returnType, observed?.returnType); |
| 433 | if (returnType !== undefined) body.returnType = returnType; |
| 434 | const returnTableType = pick(news.returnTableType, observed?.returnTableType); |
| 435 | if (returnTableType !== undefined) body.returnTableType = returnTableType; |
| 436 | const importedLibraries = pick(news.importedLibraries, observed?.importedLibraries); |
| 437 | if (importedLibraries !== undefined) { |
| 438 | body.importedLibraries = importedLibraries; |
| 439 | } |
| 440 | const determinismLevel = pick(news.determinismLevel, observed?.determinismLevel); |
| 441 | if (determinismLevel !== undefined) body.determinismLevel = determinismLevel; |
| 442 | const securityMode = pick(news.securityMode, observed?.securityMode); |
| 443 | if (securityMode !== undefined) body.securityMode = securityMode; |
| 444 | const dataGovernanceType = pick(news.dataGovernanceType, observed?.dataGovernanceType); |
| 445 | if (dataGovernanceType !== undefined) { |
| 446 | body.dataGovernanceType = dataGovernanceType; |
| 447 | } |
| 448 | const strictMode = pick(news.strictMode, observed?.strictMode); |
| 449 | if (strictMode !== undefined) body.strictMode = strictMode; |
| 450 | const sparkOptions = pick(news.sparkOptions, observed?.sparkOptions); |
| 451 | if (sparkOptions !== undefined) body.sparkOptions = sparkOptions; |
| 452 | const remoteFunctionOptions = pick(news.remoteFunctionOptions, observed?.remoteFunctionOptions); |
| 453 | if (remoteFunctionOptions !== undefined) { |
| 454 | body.remoteFunctionOptions = remoteFunctionOptions; |
| 455 | } |
| 456 | const pythonOptions = pick(news.pythonOptions, observed?.pythonOptions); |
| 457 | if (pythonOptions !== undefined) body.pythonOptions = pythonOptions; |
| 458 | const externalRuntimeOptions = pick( |
| 459 | news.externalRuntimeOptions, |
| 460 | observed?.externalRuntimeOptions, |
| 461 | ); |
| 462 | if (externalRuntimeOptions !== undefined) { |
| 463 | body.externalRuntimeOptions = externalRuntimeOptions; |
| 464 | } |
| 465 | return body; |
| 466 | }; |
| 467 | |
| 468 | const inputSnapshot = (routine: bigquery.Routine) => ({ |
| 469 | routineType: (routine.routineType ?? "").toUpperCase(), |
| 470 | language: routine.language, |
| 471 | definitionBody: routine.definitionBody ?? "", |
| 472 | arguments: canonArguments(routine.arguments), |
| 473 | returnType: canonType(routine.returnType), |
| 474 | returnTableType: routine.returnTableType |
| 475 | ? { |
| 476 | columns: (routine.returnTableType.columns ?? []).map((column) => ({ |
| 477 | name: column.name, |
| 478 | type: canonType(column.type), |
| 479 | })), |
| 480 | } |
| 481 | : undefined, |
| 482 | description: routine.description ?? "", |
| 483 | importedLibraries: routine.importedLibraries ?? [], |
| 484 | determinismLevel: routine.determinismLevel, |
| 485 | securityMode: routine.securityMode, |
| 486 | dataGovernanceType: routine.dataGovernanceType, |
| 487 | strictMode: routine.strictMode, |
| 488 | sparkOptions: routine.sparkOptions, |
| 489 | remoteFunctionOptions: routine.remoteFunctionOptions, |
| 490 | pythonOptions: routine.pythonOptions, |
| 491 | externalRuntimeOptions: routine.externalRuntimeOptions, |
| 492 | }); |
| 493 | |
| 494 | const hasAlchemyDatasetLabels = (labels: Record<string, string | undefined> | null | undefined) => |
| 495 | Object.keys(labels ?? {}).some((key) => key.startsWith(ALCHEMY_LABEL_PREFIX)); |
| 496 | |
| 497 | export const RoutineProvider = () => |
| 498 | Provider.succeed(Routine, { |
| 499 | stables: ["name", "id", "routineId", "datasetId", "project", "routineType", "creationTime"], |
| 500 | |
| 501 | diff: Effect.fn(function* ({ news, olds, output }) { |
| 502 | if (!isResolved(news)) return undefined; |
| 503 | const previousRoutineId = olds?.routineId ?? output?.routineId; |
| 504 | const nextRoutineId = news.routineId ?? previousRoutineId; |
| 505 | const routineIdChanged = |
| 506 | news.routineId !== undefined && |
| 507 | previousRoutineId !== undefined && |
| 508 | news.routineId !== previousRoutineId; |
| 509 | |
| 510 | const previousDataset = olds?.datasetId ?? output?.datasetId; |
| 511 | const nextDataset = datasetIdOf(news.datasetId); |
| 512 | const datasetChanged = |
| 513 | previousDataset !== undefined && datasetIdOf(previousDataset) !== nextDataset; |
| 514 | |
| 515 | const previousType = (olds?.routineType ?? output?.routineType ?? "").toUpperCase(); |
| 516 | const typeChanged = |
| 517 | previousType.length > 0 && news.routineType.toUpperCase() !== previousType; |
| 518 | |
| 519 | if (!routineIdChanged && !datasetChanged && !typeChanged) { |
| 520 | return undefined; |
| 521 | } |
| 522 | return { |
| 523 | action: "replace" as const, |
| 524 | deleteFirst: |
| 525 | !routineIdChanged && |
| 526 | !datasetChanged && |
| 527 | nextRoutineId !== undefined && |
| 528 | previousRoutineId !== undefined && |
| 529 | nextRoutineId === previousRoutineId, |
| 530 | }; |
| 531 | }), |
| 532 | |
| 533 | read: Effect.fn(function* ({ id, olds, output }) { |
| 534 | const env = yield* GcpEnvironment.current; |
| 535 | const routineId = yield* toId(id, olds?.routineId, output?.routineId); |
| 536 | const datasetId = datasetIdOf(olds?.datasetId ?? output?.datasetId ?? ""); |
| 537 | if (datasetId.length === 0) return undefined; |
| 538 | const existing = yield* getByRef(env.project, datasetId, routineId); |
| 539 | if (existing === undefined) return undefined; |
| 540 | const attrs = toAttrs(existing, env.project); |
| 541 | return (yield* hasAlchemyLabels(id, parseDescription(existing.description).labels)) |
| 542 | ? attrs |
| 543 | : Unowned(attrs); |
| 544 | }), |
| 545 | |
| 546 | list: () => |
| 547 | Effect.gen(function* () { |
| 548 | const env = yield* GcpEnvironment.current; |
| 549 | const datasets = yield* bigquery.listDatasets |
| 550 | .pages({ |
| 551 | projectId: env.project, |
| 552 | maxResults: 1000, |
| 553 | all: true, |
| 554 | }) |
| 555 | .pipe( |
| 556 | Stream.flatMap((page) => Stream.fromIterable(page.datasets ?? [])), |
| 557 | Stream.filter((dataset) => hasAlchemyDatasetLabels(dataset.labels)), |
| 558 | Stream.runCollect, |
| 559 | Effect.map((chunk) => Array.from(chunk)), |
| 560 | Effect.catchTag("NotFound", () => |
| 561 | Effect.succeed([] as bigquery.DatasetListDatasetsItem[]), |
| 562 | ), |
| 563 | ); |
| 564 | const pages = yield* Effect.forEach( |
| 565 | datasets, |
| 566 | (dataset) => { |
| 567 | const datasetId = dataset.datasetReference?.datasetId; |
| 568 | if (datasetId === undefined) { |
| 569 | return Effect.succeed([] as ReturnType<typeof toAttrs>[]); |
| 570 | } |
| 571 | return bigquery.listRoutines |
| 572 | .pages({ |
| 573 | projectId: env.project, |
| 574 | datasetId, |
| 575 | maxResults: 1000, |
| 576 | readMask: "description,routineType,language", |
| 577 | }) |
| 578 | .pipe( |
| 579 | Stream.flatMap((page) => Stream.fromIterable(page.routines ?? [])), |
| 580 | Stream.filter((routine) => hasOwnershipMarker(routine.description)), |
| 581 | Stream.map((routine) => toAttrs(routine, env.project)), |
| 582 | Stream.runCollect, |
| 583 | Effect.map((chunk) => Array.from(chunk)), |
| 584 | Effect.catchTag("NotFound", () => |
| 585 | Effect.succeed([] as ReturnType<typeof toAttrs>[]), |
| 586 | ), |
| 587 | ); |
| 588 | }, |
| 589 | { concurrency: 4 }, |
| 590 | ); |
| 591 | return pages.flat(); |
| 592 | }), |
| 593 | |
| 594 | reconcile: Effect.fn(function* ({ id, news, output }) { |
| 595 | const env = yield* GcpEnvironment.current; |
| 596 | const routineId = yield* toId(id, news.routineId, output?.routineId); |
| 597 | const datasetId = datasetIdOf(news.datasetId); |
| 598 | const name = resourceName(env.project, datasetId, routineId); |
| 599 | const internalLabels = yield* createInternalLabels(id); |
| 600 | |
| 601 | let current = yield* getByRef(env.project, datasetId, routineId); |
| 602 | const userDescription = |
| 603 | news.description !== undefined |
| 604 | ? news.description |
| 605 | : parseDescription(current?.description).description; |
| 606 | const encodedDescription = encodeDescription(internalLabels, userDescription); |
| 607 | const bodyOf = (observed?: bigquery.Routine) => |
| 608 | toRoutineBody(env.project, datasetId, routineId, news, encodedDescription, observed); |
| 609 | |
| 610 | if (current === undefined) { |
| 611 | const created = yield* bigquery |
| 612 | .insertRoutines({ |
| 613 | projectId: env.project, |
| 614 | datasetId, |
| 615 | body: bodyOf(), |
| 616 | }) |
| 617 | .pipe(Effect.catchTag("Conflict", () => getByRef(env.project, datasetId, routineId))); |
| 618 | current = created ?? undefined; |
| 619 | } |
| 620 | |
| 621 | if (current === undefined) { |
| 622 | return yield* new RoutineNotResolved({ resourceName: name }); |
| 623 | } |
| 624 | |
| 625 | const desired = bodyOf(current); |
| 626 | const metadataChanged = !jsonEqual(inputSnapshot(desired), inputSnapshot(current)); |
| 627 | |
| 628 | if (metadataChanged) { |
| 629 | current = yield* bigquery |
| 630 | .updateRoutines({ |
| 631 | projectId: env.project, |
| 632 | datasetId, |
| 633 | routineId, |
| 634 | body: desired, |
| 635 | }) |
| 636 | .pipe( |
| 637 | Effect.catchTag("NotFound", () => |
| 638 | bigquery |
| 639 | .insertRoutines({ |
| 640 | projectId: env.project, |
| 641 | datasetId, |
| 642 | body: bodyOf(), |
| 643 | }) |
| 644 | .pipe( |
| 645 | Effect.catchTag("Conflict", () => getByRef(env.project, datasetId, routineId)), |
| 646 | ), |
| 647 | ), |
| 648 | ); |
| 649 | if (current === undefined) { |
| 650 | return yield* new RoutineNotResolved({ resourceName: name }); |
| 651 | } |
| 652 | } |
| 653 | |
| 654 | return toAttrs(current, env.project); |
| 655 | }), |
| 656 | |
| 657 | delete: Effect.fn(function* ({ output }) { |
| 658 | yield* bigquery |
| 659 | .deleteRoutines({ |
| 660 | projectId: output.project, |
| 661 | datasetId: output.datasetId, |
| 662 | routineId: output.routineId, |
| 663 | }) |
| 664 | .pipe(Effect.catchTag("NotFound", () => Effect.void)); |
| 665 | }), |
| 666 | }); |