The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as documentai from "@distilled.cloud/gcp/documentai_v1"; |
| 2 | import { Unowned } from "alchemy/AdoptPolicy"; |
| 3 | import { isResolved } from "alchemy/Diff"; |
| 4 | import * as Provider from "alchemy/Provider"; |
| 5 | import { Resource } from "alchemy/Resource"; |
| 6 | import { tagRecord } from "alchemy/Tags"; |
| 7 | import * as Effect from "effect/Effect"; |
| 8 | import { GcpEnvironment } from "../Environment.ts"; |
| 9 | import { createInternalLabels, diffLabels, hasAlchemyLabels, toLabels } from "../Labels.ts"; |
| 10 | import type { Providers } from "../Providers.ts"; |
| 11 | import { |
| 12 | DEFAULT_LOCATION, |
| 13 | ResourceNotResolved, |
| 14 | findOwnedByLabels, |
| 15 | hasAlchemyLabelMap, |
| 16 | listProjectSchemas, |
| 17 | listSchemasAt, |
| 18 | locationParent, |
| 19 | normalizeLocation, |
| 20 | parseResourceName, |
| 21 | replaceOnIdentity, |
| 22 | retryTransient, |
| 23 | sameText, |
| 24 | toPhysicalId, |
| 25 | updateMaskOf, |
| 26 | userLabels, |
| 27 | waitUntilGone, |
| 28 | } from "./internal.ts"; |
| 29 | import { waitForOperation } from "./operations.ts"; |
| 30 | |
| 31 | export type SchemaProps = { |
| 32 | /** |
| 33 | * Schema id (the `{schema}` segment of |
| 34 | * `projects/{project}/locations/{location}/schemas/{schema}`). Assigned |
| 35 | * by the API on create. Immutable — changing it replaces the schema. |
| 36 | * Supply it to adopt an existing schema. |
| 37 | */ |
| 38 | schemaId?: string; |
| 39 | /** |
| 40 | * Multi-region location (`us` or `eu`). Immutable — changing it |
| 41 | * replaces the schema. |
| 42 | * @default "us" |
| 43 | */ |
| 44 | location?: string; |
| 45 | /** |
| 46 | * User-defined display name. Defaults to a generated id. |
| 47 | */ |
| 48 | displayName?: string; |
| 49 | /** |
| 50 | * User labels. Alchemy ownership labels are merged in automatically. |
| 51 | */ |
| 52 | labels?: Record<string, string>; |
| 53 | }; |
| 54 | |
| 55 | export type Schema = Resource< |
| 56 | "GCP.DocumentAI.Schema", |
| 57 | SchemaProps, |
| 58 | { |
| 59 | /** Full resource name `projects/{project}/locations/{location}/schemas/{schema}`. */ |
| 60 | name: string; |
| 61 | /** Schema id (last path segment). */ |
| 62 | schemaId: string; |
| 63 | /** Project id. */ |
| 64 | project: string; |
| 65 | /** Location id. */ |
| 66 | location: string; |
| 67 | /** User-defined display name. */ |
| 68 | displayName: string | undefined; |
| 69 | /** User labels (Alchemy ownership labels stripped). */ |
| 70 | labels: Record<string, string>; |
| 71 | /** RFC3339 creation timestamp. */ |
| 72 | createTime: string | undefined; |
| 73 | /** RFC3339 last-update timestamp. */ |
| 74 | updateTime: string | undefined; |
| 75 | }, |
| 76 | never, |
| 77 | Providers |
| 78 | >; |
| 79 | |
| 80 | /** |
| 81 | * A Document AI schema — a collection of schema versions describing |
| 82 | * extraction output. |
| 83 | * |
| 84 | * Schemas are location-scoped. The API assigns the schema id. Location is |
| 85 | * immutable; display name and labels update in place. |
| 86 | * |
| 87 | * ### Creating a Schema |
| 88 | * **Example:** Generated id |
| 89 | * ```typescript |
| 90 | * const schema = yield* GCP.DocumentAI.Schema("Invoice", { |
| 91 | * displayName: "invoice", |
| 92 | * labels: { env: "test" }, |
| 93 | * }); |
| 94 | * ``` |
| 95 | * |
| 96 | * ### Updating a Schema |
| 97 | * **Example:** Rename and relabel |
| 98 | * ```typescript |
| 99 | * // Same logical id, changed props: the engine updates it in place. |
| 100 | * const schema = yield* GCP.DocumentAI.Schema("Invoice", { |
| 101 | * displayName: "invoice-v2", |
| 102 | * labels: { env: "prod" }, |
| 103 | * }); |
| 104 | * ``` |
| 105 | * |
| 106 | * @resource |
| 107 | * @category DocumentAI |
| 108 | */ |
| 109 | export const Schema = Resource<Schema>("GCP.DocumentAI.Schema"); |
| 110 | |
| 111 | const resourceName = (project: string, location: string, schemaId: string) => |
| 112 | `${locationParent(project, location)}/schemas/${schemaId}`; |
| 113 | |
| 114 | const toAttrs = (schema: documentai.GoogleCloudDocumentaiV1NextSchema, project: string) => { |
| 115 | const name = schema.name ?? ""; |
| 116 | const parsed = parseResourceName(name, "schemas"); |
| 117 | return { |
| 118 | name, |
| 119 | schemaId: parsed.id, |
| 120 | project: parsed.project || project, |
| 121 | location: parsed.location, |
| 122 | displayName: schema.displayName, |
| 123 | labels: userLabels(schema.labels), |
| 124 | createTime: schema.createTime, |
| 125 | updateTime: schema.updateTime, |
| 126 | }; |
| 127 | }; |
| 128 | |
| 129 | const getByName = (name: string) => |
| 130 | name.length === 0 |
| 131 | ? Effect.undefined |
| 132 | : documentai |
| 133 | .getProjectsLocationsSchemas({ name }) |
| 134 | .pipe(Effect.catchTag("NotFound", () => Effect.undefined)); |
| 135 | |
| 136 | const findOwned = (id: string, project: string, parent: string, hinted?: string) => |
| 137 | Effect.gen(function* () { |
| 138 | if (hinted !== undefined && hinted.length > 0) { |
| 139 | const existing = yield* getByName(hinted); |
| 140 | if (existing !== undefined) return existing; |
| 141 | } |
| 142 | const local = yield* findOwnedByLabels(id, yield* listSchemasAt(parent)); |
| 143 | if (local !== undefined) return local; |
| 144 | return yield* findOwnedByLabels(id, yield* listProjectSchemas(project)); |
| 145 | }); |
| 146 | |
| 147 | export const SchemaProvider = () => |
| 148 | Provider.succeed(Schema, { |
| 149 | stables: ["name", "schemaId", "project", "location", "createTime"], |
| 150 | |
| 151 | diff: Effect.fn(function* ({ news, olds, output }) { |
| 152 | if (!isResolved(news)) return undefined; |
| 153 | return replaceOnIdentity({ |
| 154 | previousId: olds?.schemaId ?? output?.schemaId, |
| 155 | nextId: news.schemaId, |
| 156 | previousLocation: olds?.location ?? output?.location, |
| 157 | nextLocation: news.location ?? olds?.location ?? output?.location, |
| 158 | }); |
| 159 | }), |
| 160 | |
| 161 | read: Effect.fn(function* ({ id, olds, output }) { |
| 162 | const env = yield* GcpEnvironment.current; |
| 163 | const location = normalizeLocation(olds?.location ?? output?.location); |
| 164 | const schemaId = olds?.schemaId ?? output?.schemaId; |
| 165 | const name = output?.name ?? (schemaId ? resourceName(env.project, location, schemaId) : ""); |
| 166 | const parent = locationParent(env.project, location); |
| 167 | const existing = yield* findOwned(id, env.project, parent, name); |
| 168 | if (existing === undefined) return undefined; |
| 169 | const attrs = toAttrs(existing, env.project); |
| 170 | return (yield* hasAlchemyLabels(id, tagRecord(existing.labels))) ? attrs : Unowned(attrs); |
| 171 | }), |
| 172 | |
| 173 | list: () => |
| 174 | Effect.gen(function* () { |
| 175 | const env = yield* GcpEnvironment.current; |
| 176 | const schemas = yield* listProjectSchemas(env.project); |
| 177 | return schemas |
| 178 | .filter((schema) => hasAlchemyLabelMap(schema.labels)) |
| 179 | .map((schema) => toAttrs(schema, env.project)); |
| 180 | }), |
| 181 | |
| 182 | reconcile: Effect.fn(function* ({ id, news, output }) { |
| 183 | const env = yield* GcpEnvironment.current; |
| 184 | const location = normalizeLocation(news.location ?? output?.location ?? DEFAULT_LOCATION); |
| 185 | const parent = locationParent(env.project, location); |
| 186 | const desiredLabels = { |
| 187 | ...toLabels(news.labels), |
| 188 | ...(yield* createInternalLabels(id)), |
| 189 | }; |
| 190 | const fallbackName = yield* toPhysicalId( |
| 191 | id, |
| 192 | undefined, |
| 193 | output?.displayName ?? output?.schemaId, |
| 194 | ); |
| 195 | const displayName = news.displayName ?? fallbackName; |
| 196 | const hinted = |
| 197 | output?.name ?? (news.schemaId ? resourceName(env.project, location, news.schemaId) : ""); |
| 198 | |
| 199 | let current = yield* findOwned(id, env.project, parent, hinted); |
| 200 | |
| 201 | if (current === undefined) { |
| 202 | current = yield* retryTransient( |
| 203 | documentai.createProjectsLocationsSchemas({ |
| 204 | parent, |
| 205 | body: { |
| 206 | displayName, |
| 207 | labels: desiredLabels, |
| 208 | }, |
| 209 | }), |
| 210 | ).pipe( |
| 211 | Effect.catchTag("Conflict", (error) => |
| 212 | findOwned(id, env.project, parent, hinted).pipe( |
| 213 | Effect.flatMap((found) => |
| 214 | found !== undefined ? Effect.succeed(found) : Effect.fail(error), |
| 215 | ), |
| 216 | ), |
| 217 | ), |
| 218 | ); |
| 219 | } |
| 220 | |
| 221 | if (current === undefined) { |
| 222 | return yield* new ResourceNotResolved({ |
| 223 | resourceName: hinted || `${parent}/schemas`, |
| 224 | }); |
| 225 | } |
| 226 | |
| 227 | const currentName = current.name ?? hinted; |
| 228 | const observedLabels = tagRecord(current.labels); |
| 229 | const { upsert, removed } = diffLabels(observedLabels, desiredLabels); |
| 230 | const labelsChanged = upsert.length > 0 || removed.length > 0; |
| 231 | const displayChanged = !sameText(current.displayName, displayName); |
| 232 | |
| 233 | if (labelsChanged || displayChanged) { |
| 234 | current = yield* retryTransient( |
| 235 | documentai.patchProjectsLocationsSchemas({ |
| 236 | name: currentName, |
| 237 | updateMask: updateMaskOf( |
| 238 | displayChanged ? "displayName" : undefined, |
| 239 | labelsChanged ? "labels" : undefined, |
| 240 | ), |
| 241 | body: { |
| 242 | displayName, |
| 243 | labels: desiredLabels, |
| 244 | }, |
| 245 | }), |
| 246 | ); |
| 247 | } |
| 248 | |
| 249 | return toAttrs(current, env.project); |
| 250 | }), |
| 251 | |
| 252 | delete: Effect.fn(function* ({ output }) { |
| 253 | if (!output.name) return; |
| 254 | const operation = yield* retryTransient( |
| 255 | documentai.deleteProjectsLocationsSchemas({ |
| 256 | name: output.name, |
| 257 | force: true, |
| 258 | }), |
| 259 | ).pipe(Effect.catchTag("NotFound", () => Effect.undefined)); |
| 260 | if (operation !== undefined) { |
| 261 | // NOT_FOUND (5): already gone. |
| 262 | yield* waitForOperation(operation).pipe( |
| 263 | Effect.catchTag("GCP.OperationFailed", (error) => |
| 264 | error.code === 5 ? Effect.void : Effect.fail(error), |
| 265 | ), |
| 266 | ); |
| 267 | } |
| 268 | yield* waitUntilGone(getByName(output.name), output.name); |
| 269 | }), |
| 270 | }); |