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

main
ts 458 lines 15.1 KB
Raw
1 import * as rtb from "@distilled.cloud/gcp/realtimebidding_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 * as Data from "effect/Data";
7 import * as Effect from "effect/Effect";
8 import { GcpEnvironment } from "../Environment.ts";
9 import type { Providers } from "../Providers.ts";
10 import {
11 configIdOf,
12 encodeDisplayName,
13 expandParent,
14 findOwnedConfig,
15 getConfig,
16 hasOwnershipMarker,
17 ignoreMissing,
18 listOwnedConfigs,
19 mergeSpec,
20 ownedByAlchemy,
21 ownershipLabels,
22 parentOfName,
23 parseDisplayName,
24 replaceOnIdentity,
25 resourceName,
26 specFromRow,
27 specOf,
28 toConfigBody,
29 toDisplayName,
30 updateMaskOf,
31 type AppTargetingValue,
32 type CreativeDimensionsValue,
33 type NumericTargetingDimensionValue,
34 type PretargetingState,
35 type StringTargetingDimensionValue,
36 } from "./internal.ts";
37
38 export type StringTargetingDimension = StringTargetingDimensionValue;
39 export type NumericTargetingDimension = NumericTargetingDimensionValue;
40 export type CreativeDimensions = CreativeDimensionsValue;
41 export type AppTargeting = AppTargetingValue;
42
43 export type BiddersPretargetingConfigProps = {
44 /**
45 * Parent bidder, as `bidders/{bidder}` or the bidder account id.
46 * Immutable — changing it replaces the config.
47 */
48 parent: string;
49 /**
50 * Server-assigned config id (last path segment). Omit on create; pass
51 * the observed id to keep the same config. Immutable — changing it
52 * replaces the config.
53 */
54 configId?: string;
55 /**
56 * Human-readable display name. Must be unique among the bidder's
57 * pretargeting configs. If omitted, a unique name is generated from
58 * the stack, stage, and logical id. Pretargeting configs have no
59 * labels field, so Alchemy stamps ownership into a `[alchemy …]`
60 * prefix and strips it from attributes.
61 */
62 displayName?: string;
63 /**
64 * Desired serving state after create (`ACTIVE` or `SUSPENDED`).
65 * Create always yields `ACTIVE`. `SUSPENDED` is applied with
66 * `pretargetingConfigs.suspend`.
67 */
68 state?: PretargetingState;
69 /**
70 * Creative formats (`HTML`, `VAST`, `NATIVE`). Unset allows every
71 * format.
72 */
73 includedFormats?: string[];
74 /**
75 * Environments (`APP`, `WEB`). Unset includes every environment.
76 */
77 includedEnvironments?: string[];
78 /**
79 * Device platforms (`PERSONAL_COMPUTER`, `PHONE`, `TABLET`,
80 * `CONNECTED_TV`). Unset allows every platform.
81 */
82 includedPlatforms?: string[];
83 /**
84 * User identifier types (`GOOGLE_COOKIE`, `DEVICE_ID`, …). At least
85 * one listed type must be present on a bid request.
86 */
87 includedUserIdTypes?: string[];
88 /**
89 * Language codes to include (AdWords language codes).
90 */
91 includedLanguages?: string[];
92 /**
93 * Mobile OS ids from the Authorized Buyers mobile-os dictionary.
94 */
95 includedMobileOperatingSystemIds?: string[];
96 /**
97 * Sensitive content label ids to exclude.
98 */
99 excludedContentLabelIds?: string[];
100 /**
101 * User targeting modes a bid request must allow (`REMARKETING_ADS`,
102 * `INTEREST_BASED_TARGETING`).
103 */
104 allowedUserTargetingModes?: string[];
105 /**
106 * Interstitial filter (`ONLY_INTERSTITIAL_REQUESTS` or
107 * `ONLY_NON_INTERSTITIAL_REQUESTS`). Unset allows both.
108 */
109 interstitialTargeting?: string;
110 /**
111 * Maximum QPS for this config across bidding endpoints.
112 */
113 maximumQps?: string;
114 /**
115 * Minimum predicted viewability decile (0–10). `5` means 50%.
116 */
117 minimumViewabilityDecile?: number;
118 /**
119 * Included and excluded geo ids.
120 */
121 geoTargeting?: NumericTargetingDimension;
122 /**
123 * Included and excluded remarketing list ids.
124 */
125 userListTargeting?: NumericTargetingDimension;
126 /**
127 * Included and excluded publisher vertical ids.
128 */
129 verticalTargeting?: NumericTargetingDimension;
130 /**
131 * Inclusive or exclusive website targeting.
132 */
133 webTargeting?: StringTargetingDimension;
134 /**
135 * Inclusive or exclusive publisher-id targeting.
136 */
137 publisherTargeting?: StringTargetingDimension;
138 /**
139 * App id and app-category targeting.
140 */
141 appTargeting?: AppTargeting;
142 /**
143 * Creative pixel dimensions (HTML and Native).
144 */
145 includedCreativeDimensions?: CreativeDimensions[];
146 };
147
148 export type BiddersPretargetingConfig = Resource<
149 "GCP.RealTimeBidding.BiddersPretargetingConfig",
150 BiddersPretargetingConfigProps,
151 {
152 /** Full resource name `bidders/{bidder}/pretargetingConfigs/{config}`. */
153 name: string;
154 /** Server-assigned config id (last path segment). */
155 configId: string;
156 /** Parent bidder resource name `bidders/{bidder}`. */
157 parent: string;
158 /** Project id used when the config was reconciled. */
159 project: string;
160 /** Display name with the Alchemy ownership prefix stripped. */
161 displayName: string | undefined;
162 /** Server-reported state (`ACTIVE` or `SUSPENDED`). */
163 state: string | undefined;
164 /** Billing id used to attribute spend. */
165 billingId: string | undefined;
166 /** Previously targeted geos that are no longer valid. */
167 invalidGeoIds: string[] | undefined;
168 /** Creative formats. */
169 includedFormats: string[] | undefined;
170 /** Environments. */
171 includedEnvironments: string[] | undefined;
172 /** Device platforms. */
173 includedPlatforms: string[] | undefined;
174 /** User identifier types. */
175 includedUserIdTypes: string[] | undefined;
176 /** Language codes. */
177 includedLanguages: string[] | undefined;
178 /** Mobile OS ids. */
179 includedMobileOperatingSystemIds: string[] | undefined;
180 /** Excluded content label ids. */
181 excludedContentLabelIds: string[] | undefined;
182 /** Required user targeting modes. */
183 allowedUserTargetingModes: string[] | undefined;
184 /** Interstitial filter. */
185 interstitialTargeting: string | undefined;
186 /** Maximum QPS. */
187 maximumQps: string | undefined;
188 /** Minimum viewability decile. */
189 minimumViewabilityDecile: number | undefined;
190 /** Geo targeting. */
191 geoTargeting: NumericTargetingDimension | undefined;
192 /** Remarketing list targeting. */
193 userListTargeting: NumericTargetingDimension | undefined;
194 /** Vertical targeting. */
195 verticalTargeting: NumericTargetingDimension | undefined;
196 /** Website targeting. */
197 webTargeting: StringTargetingDimension | undefined;
198 /** Publisher targeting. */
199 publisherTargeting: StringTargetingDimension | undefined;
200 /** App targeting. */
201 appTargeting: AppTargeting | undefined;
202 /** Creative dimensions. */
203 includedCreativeDimensions: CreativeDimensions[] | undefined;
204 },
205 never,
206 Providers
207 >;
208
209 /**
210 * An Authorized Buyers Real-time Bidding pretargeting configuration
211 * (`bidders/{bidder}/pretargetingConfigs/{config}`).
212 *
213 * Pretargeting configs have no labels field, so Alchemy stamps ownership
214 * into `displayName` for `list` / nuke. Parent and config id are
215 * identity — changing either replaces the config. Display name and
216 * targeting update in place. Create yields `ACTIVE`; pass `state:
217 * "SUSPENDED"` to suspend. A bidder may own at most 10 configs.
218 *
219 * ### Creating a Pretargeting Config
220 * **Example:** Generated display name
221 * ```typescript
222 * const config = yield* GCP.RealTimeBidding.BiddersPretargetingConfig(
223 * "WebHtml",
224 * { parent: "bidders/123" },
225 * );
226 * ```
227 *
228 * **Example:** Named config for web HTML
229 * ```typescript
230 * const config = yield* GCP.RealTimeBidding.BiddersPretargetingConfig(
231 * "WebHtml",
232 * {
233 * parent: "bidders/123",
234 * displayName: "web-html",
235 * includedEnvironments: ["WEB"],
236 * includedFormats: ["HTML"],
237 * },
238 * );
239 * ```
240 *
241 * ### Updating a Pretargeting Config
242 * Change props on the same logical id; the engine keeps the physical id.
243 *
244 * **Example:** Add Native and suspend
245 * ```typescript
246 * const config = yield* GCP.RealTimeBidding.BiddersPretargetingConfig(
247 * "WebHtml",
248 * {
249 * parent: "bidders/123",
250 * displayName: "web-html-v2",
251 * includedEnvironments: ["WEB"],
252 * includedFormats: ["HTML", "NATIVE"],
253 * state: "SUSPENDED",
254 * },
255 * );
256 * ```
257 *
258 * @resource
259 * @category RealTimeBidding
260 */
261 export const BiddersPretargetingConfig = Resource<BiddersPretargetingConfig>(
262 "GCP.RealTimeBidding.BiddersPretargetingConfig",
263 );
264
265 export class BiddersPretargetingConfigNotResolved extends Data.TaggedError(
266 "GCP.RealTimeBidding.BiddersPretargetingConfigNotResolved",
267 )<{
268 parent: string;
269 resourceName: string;
270 }> {}
271
272 export class BiddersPretargetingConfigParentRequired extends Data.TaggedError(
273 "GCP.RealTimeBidding.BiddersPretargetingConfigParentRequired",
274 )<{
275 message: string;
276 }> {}
277
278 const lookupName = (
279 parent: string,
280 configId: string | undefined,
281 existingName: string | undefined,
282 ) => {
283 if (existingName && existingName.length > 0) return existingName;
284 if (configId && configId.length > 0 && parent.length > 0) {
285 return resourceName(parent, configId);
286 }
287 return "";
288 };
289
290 const specFromProps = (props: BiddersPretargetingConfigProps): ReturnType<typeof specOf> =>
291 specOf({
292 allowedUserTargetingModes: props.allowedUserTargetingModes,
293 excludedContentLabelIds: props.excludedContentLabelIds,
294 includedLanguages: props.includedLanguages,
295 webTargeting: props.webTargeting,
296 includedPlatforms: props.includedPlatforms,
297 includedFormats: props.includedFormats,
298 maximumQps: props.maximumQps,
299 geoTargeting: props.geoTargeting,
300 includedEnvironments: props.includedEnvironments,
301 userListTargeting: props.userListTargeting,
302 publisherTargeting: props.publisherTargeting,
303 includedUserIdTypes: props.includedUserIdTypes,
304 minimumViewabilityDecile: props.minimumViewabilityDecile,
305 verticalTargeting: props.verticalTargeting,
306 includedCreativeDimensions: props.includedCreativeDimensions,
307 interstitialTargeting: props.interstitialTargeting,
308 appTargeting: props.appTargeting,
309 includedMobileOperatingSystemIds: props.includedMobileOperatingSystemIds,
310 });
311
312 const toAttrs = (row: rtb.PretargetingConfig, project: string) => {
313 const name = row.name ?? "";
314 const parent = parentOfName(name);
315 return {
316 name,
317 configId: configIdOf(name),
318 parent,
319 project,
320 displayName: parseDisplayName(row.displayName).displayName,
321 state: row.state,
322 billingId: row.billingId,
323 invalidGeoIds: row.invalidGeoIds,
324 includedFormats: row.includedFormats,
325 includedEnvironments: row.includedEnvironments,
326 includedPlatforms: row.includedPlatforms,
327 includedUserIdTypes: row.includedUserIdTypes,
328 includedLanguages: row.includedLanguages,
329 includedMobileOperatingSystemIds: row.includedMobileOperatingSystemIds,
330 excludedContentLabelIds: row.excludedContentLabelIds,
331 allowedUserTargetingModes: row.allowedUserTargetingModes,
332 interstitialTargeting: row.interstitialTargeting,
333 maximumQps: row.maximumQps,
334 minimumViewabilityDecile: row.minimumViewabilityDecile,
335 geoTargeting: row.geoTargeting,
336 userListTargeting: row.userListTargeting,
337 verticalTargeting: row.verticalTargeting,
338 webTargeting: row.webTargeting,
339 publisherTargeting: row.publisherTargeting,
340 appTargeting: row.appTargeting,
341 includedCreativeDimensions: row.includedCreativeDimensions,
342 };
343 };
344
345 const syncState = (current: rtb.PretargetingConfig, desired: string | undefined) =>
346 Effect.gen(function* () {
347 if (!desired || !current.name) return current;
348 const observed = current.state ?? "";
349 if (observed === desired) return current;
350 if (desired === "ACTIVE" && observed === "SUSPENDED") {
351 return yield* rtb.activateBiddersPretargetingConfigs({
352 name: current.name,
353 });
354 }
355 if (desired === "SUSPENDED" && observed === "ACTIVE") {
356 return yield* rtb.suspendBiddersPretargetingConfigs({
357 name: current.name,
358 });
359 }
360 return current;
361 });
362
363 export const BiddersPretargetingConfigProvider = () =>
364 Provider.succeed(BiddersPretargetingConfig, {
365 stables: ["name", "configId", "parent", "project", "billingId"],
366
367 diff: Effect.fn(function* ({ news, olds, output }) {
368 if (!isResolved(news)) return undefined;
369 return replaceOnIdentity({
370 previousParent: expandParent(olds?.parent ?? output?.parent ?? ""),
371 nextParent: expandParent(news.parent),
372 previousId: olds?.configId ?? output?.configId,
373 nextId: news.configId,
374 });
375 }),
376
377 read: Effect.fn(function* ({ id, olds, output }) {
378 const env = yield* GcpEnvironment.current;
379 const parent = expandParent(olds?.parent ?? output?.parent ?? "");
380 const name = lookupName(parent, olds?.configId ?? output?.configId, output?.name);
381 let existing = yield* getConfig(name);
382 if (existing === undefined) {
383 existing = yield* findOwnedConfig(id, parent, name);
384 }
385 if (existing === undefined) return undefined;
386 const attrs = toAttrs(existing, env.project);
387 return (yield* ownedByAlchemy(id, existing.displayName)) ? attrs : Unowned(attrs);
388 }),
389
390 list: () =>
391 Effect.gen(function* () {
392 const env = yield* GcpEnvironment.current;
393 const rows = yield* listOwnedConfigs();
394 return rows
395 .filter((row) => hasOwnershipMarker(row.displayName))
396 .map((row) => toAttrs(row, env.project));
397 }),
398
399 reconcile: Effect.fn(function* ({ id, news, output }) {
400 const env = yield* GcpEnvironment.current;
401 const parent = expandParent(news.parent);
402 if (parent.length === 0) {
403 return yield* new BiddersPretargetingConfigParentRequired({
404 message: "BiddersPretargetingConfig requires parent (bidders/{bidder})",
405 });
406 }
407 const ownership = yield* ownershipLabels(id);
408 const displayName = yield* toDisplayName(id, news.displayName, output?.displayName);
409 const stamped = encodeDisplayName(ownership, displayName);
410 const name = lookupName(parent, news.configId ?? output?.configId, output?.name);
411
412 let current = yield* getConfig(name);
413 if (current === undefined) {
414 current = yield* findOwnedConfig(id, parent, name, stamped);
415 }
416
417 const desired = mergeSpec(
418 specFromProps(news),
419 current === undefined ? undefined : specFromRow(current),
420 );
421
422 if (current === undefined) {
423 const created = yield* rtb
424 .createBiddersPretargetingConfigs({
425 parent,
426 body: toConfigBody(stamped, desired),
427 })
428 .pipe(Effect.catchTag("Conflict", () => findOwnedConfig(id, parent, name, stamped)));
429 current = created ?? undefined;
430 }
431
432 if (current === undefined) {
433 return yield* new BiddersPretargetingConfigNotResolved({
434 parent,
435 resourceName: name || stamped,
436 });
437 }
438
439 const currentName = current.name ?? name;
440 const updateMask = updateMaskOf(current, desired, stamped);
441 if (updateMask.length > 0) {
442 current = yield* rtb.patchBiddersPretargetingConfigs({
443 name: currentName,
444 updateMask,
445 body: toConfigBody(stamped, desired),
446 });
447 }
448
449 current = yield* syncState(current, news.state);
450
451 return toAttrs(current, env.project);
452 }),
453
454 delete: Effect.fn(function* ({ output }) {
455 if (!output.name) return;
456 yield* ignoreMissing(rtb.deleteBiddersPretargetingConfigs({ name: output.name }));
457 }),
458 });