import * as lexm from "@distilled.cloud/aws/lex-models-v2";
import { diffTags } from "alchemy/Tags";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import * as Schedule from "effect/Schedule";
/** A Lex V2 resource ended in a terminal `Failed` state (or never settled). */
export class LexOperationFailed extends Data.TaggedError("LexOperationFailed")<{
readonly resourceId: string;
readonly status: string;
readonly reasons: readonly string[];
}> {}
/**
* Coerce a generated physical name into Lex's name pattern
* `^([0-9a-zA-Z][_-]?){1,100}
.repos/alchemy-effect/packages/aws/src/LexV2/internal.ts at main · sailfork/t3code-github · Sailfork
— every `-`/`_` must be preceded by an
* alphanumeric (no leading or consecutive separators).
*/
export const toLexName = (name: string): string =>
name
.replace(/[^0-9a-zA-Z_-]/g, "-")
.replace(/[-_]{2,}/g, "-")
.replace(/^[-_]+/, "")
.slice(0, 100);
/** Convert a Lex wire tag map (values may be undefined) into a plain record. */
export const toTagRecord = (
tags: { [key: string]: string | undefined } | undefined,
): Record<string, string> =>
Object.fromEntries(
Object.entries(tags ?? {}).filter((entry): entry is [string, string] => entry[1] !== undefined),
);
/**
* Retry `ConflictException`s on a bounded schedule. Lex serializes most
* mutations per bot — a concurrent build/version/update surfaces as a
* transient conflict.
*
* The explicit `Effect.Effect<A, E, R>` return annotation is load-bearing:
* inlining retry/repeat combinators in provider lifecycle code lets their
* conditional return types survive into declaration emit and widen the
* provider layer to `unknown` (see `../EC2/VolumeAttachment.ts`).
*/
export const retryWhileConflict = <A, E extends { readonly _tag: string }, R>(
self: Effect.Effect<A, E, R>,
): Effect.Effect<A, E, R> =>
Effect.retry(self, {
while: (e) => e._tag === "ConflictException",
schedule: Schedule.max([Schedule.fixed(2000), Schedule.recurs(10)]),
});
/**
* Repeat a describe poll until `done` holds (bounded). Explicitly typed for
* the declaration-emit reason above.
*/
const untilConverged = <A, E, R>(
self: Effect.Effect<A, E, R>,
done: (a: A) => boolean,
options?: { intervalSeconds?: number; times?: number },
): Effect.Effect<A, E, R> =>
Effect.repeat(self, {
schedule: Schedule.spaced(`${options?.intervalSeconds ?? 2} seconds`),
until: done,
times: options?.times ?? 40,
});
const transientBotStatuses = new Set(["Creating", "Versioning", "Updating", "Importing"]);
/**
* Poll `describeBot` until the bot leaves its transient statuses
* (`Creating`/`Versioning`/`Updating`/`Importing`). Fails typed on `Failed`.
* Bot mutations settle in seconds — budget ~80s.
*/
export const waitForBotSettled = Effect.fn("AWS.LexV2.waitForBotSettled")(function* (
botId: string,
) {
const bot = yield* untilConverged(
lexm.describeBot({ botId }),
(b) => !transientBotStatuses.has(b.botStatus ?? ""),
);
if (bot.botStatus === "Failed" || transientBotStatuses.has(bot.botStatus ?? "")) {
return yield* new LexOperationFailed({
resourceId: botId,
status: bot.botStatus ?? "unknown",
reasons: bot.failureReasons ?? [],
});
}
return bot;
});
const transientLocaleStatuses = new Set(["Creating", "Processing", "Importing", "Deleting"]);
/**
* Poll `describeBotLocale` until the DRAFT locale leaves its create-time
* transient statuses (settles at `NotBuilt`/`Built`/`ReadyExpressTesting`).
* Fails typed on `Failed`.
*/
export const waitForLocaleSettled = Effect.fn("AWS.LexV2.waitForLocaleSettled")(function* (
botId: string,
localeId: string,
) {
const locale = yield* untilConverged(
lexm.describeBotLocale({ botId, botVersion: "DRAFT", localeId }),
(l) => !transientLocaleStatuses.has(l.botLocaleStatus ?? ""),
);
if (
locale.botLocaleStatus === "Failed" ||
transientLocaleStatuses.has(locale.botLocaleStatus ?? "")
) {
return yield* new LexOperationFailed({
resourceId: `${botId}/${localeId}`,
status: locale.botLocaleStatus ?? "unknown",
reasons: locale.failureReasons ?? [],
});
}
return locale;
});
/**
* Poll `describeBotLocale` until a triggered build lands on `Built`.
* `Building` and `ReadyExpressTesting` are intermediate build states. A tiny
* bot normally builds in under a minute; keep the poll bounded to ~90 seconds
* so a stalled AWS build fails promptly.
*/
export const waitForLocaleBuilt = Effect.fn("AWS.LexV2.waitForLocaleBuilt")(function* (
botId: string,
localeId: string,
) {
const locale = yield* untilConverged(
lexm.describeBotLocale({ botId, botVersion: "DRAFT", localeId }),
(l) => l.botLocaleStatus === "Built" || l.botLocaleStatus === "Failed",
{ intervalSeconds: 5, times: 18 },
);
if (locale.botLocaleStatus !== "Built") {
return yield* new LexOperationFailed({
resourceId: `${botId}/${localeId}`,
status: locale.botLocaleStatus ?? "unknown",
reasons: locale.failureReasons ?? [],
});
}
return locale;
});
/**
* Poll `describeBotAlias` until the alias leaves `Creating`. Fails typed on
* `Failed`.
*/
export const waitForAliasSettled = Effect.fn("AWS.LexV2.waitForAliasSettled")(function* (
botId: string,
botAliasId: string,
) {
const alias = yield* untilConverged(
lexm.describeBotAlias({ botId, botAliasId }),
(a) => a.botAliasStatus !== "Creating",
);
if (alias.botAliasStatus === "Failed" || alias.botAliasStatus === "Creating") {
return yield* new LexOperationFailed({
resourceId: `${botId}/${botAliasId}`,
status: alias.botAliasStatus ?? "unknown",
reasons: [],
});
}
return alias;
});
/**
* Read the observed tags of a Lex resource by ARN. Best-effort — a race with
* deletion reports no tags.
*/
export const readLexTags = Effect.fn("AWS.LexV2.readLexTags")(function* (arn: string) {
const response = yield* lexm
.listTagsForResource({ resourceARN: arn })
.pipe(Effect.orElseSucceed(() => undefined));
return toTagRecord(response?.tags);
});
/**
* Sync tags on a Lex resource: diff OBSERVED cloud tags against the desired
* set and apply only the delta.
*/
export const syncLexTags = Effect.fn("AWS.LexV2.syncLexTags")(function* (
arn: string,
observed: Record<string, string>,
desired: Record<string, string>,
) {
const { removed, upsert } = diffTags(observed, desired);
if (upsert.length > 0) {
yield* lexm.tagResource({
resourceARN: arn,
tags: Object.fromEntries(upsert.map((tag) => [tag.Key, tag.Value])),
});
}
if (removed.length > 0) {
yield* lexm.untagResource({ resourceARN: arn, tagKeys: removed });
}
});
.repos/alchemy-effect/packages/aws/src/LexV2/internal.ts at main · sailfork/t3code-github · Sailfork
— every `-`/`_` must be preceded by an\n * alphanumeric (no leading or consecutive separators).\n */\nexport const toLexName = (name: string): string =>\n name\n .replace(/[^0-9a-zA-Z_-]/g, \"-\")\n .replace(/[-_]{2,}/g, \"-\")\n .replace(/^[-_]+/, \"\")\n .slice(0, 100);\n\n/** Convert a Lex wire tag map (values may be undefined) into a plain record. */\nexport const toTagRecord = (\n tags: { [key: string]: string | undefined } | undefined,\n): Record\u003cstring, string> =>\n Object.fromEntries(\n Object.entries(tags ?? {}).filter((entry): entry is [string, string] => entry[1] !== undefined),\n );\n\n/**\n * Retry `ConflictException`s on a bounded schedule. Lex serializes most\n * mutations per bot — a concurrent build/version/update surfaces as a\n * transient conflict.\n *\n * The explicit `Effect.Effect\u003cA, E, R>` return annotation is load-bearing:\n * inlining retry/repeat combinators in provider lifecycle code lets their\n * conditional return types survive into declaration emit and widen the\n * provider layer to `unknown` (see `../EC2/VolumeAttachment.ts`).\n */\nexport const retryWhileConflict = \u003cA, E extends { readonly _tag: string }, R>(\n self: Effect.Effect\u003cA, E, R>,\n): Effect.Effect\u003cA, E, R> =>\n Effect.retry(self, {\n while: (e) => e._tag === \"ConflictException\",\n schedule: Schedule.max([Schedule.fixed(2000), Schedule.recurs(10)]),\n });\n\n/**\n * Repeat a describe poll until `done` holds (bounded). Explicitly typed for\n * the declaration-emit reason above.\n */\nconst untilConverged = \u003cA, E, R>(\n self: Effect.Effect\u003cA, E, R>,\n done: (a: A) => boolean,\n options?: { intervalSeconds?: number; times?: number },\n): Effect.Effect\u003cA, E, R> =>\n Effect.repeat(self, {\n schedule: Schedule.spaced(`${options?.intervalSeconds ?? 2} seconds`),\n until: done,\n times: options?.times ?? 40,\n });\n\nconst transientBotStatuses = new Set([\"Creating\", \"Versioning\", \"Updating\", \"Importing\"]);\n\n/**\n * Poll `describeBot` until the bot leaves its transient statuses\n * (`Creating`/`Versioning`/`Updating`/`Importing`). Fails typed on `Failed`.\n * Bot mutations settle in seconds — budget ~80s.\n */\nexport const waitForBotSettled = Effect.fn(\"AWS.LexV2.waitForBotSettled\")(function* (\n botId: string,\n) {\n const bot = yield* untilConverged(\n lexm.describeBot({ botId }),\n (b) => !transientBotStatuses.has(b.botStatus ?? \"\"),\n );\n if (bot.botStatus === \"Failed\" || transientBotStatuses.has(bot.botStatus ?? \"\")) {\n return yield* new LexOperationFailed({\n resourceId: botId,\n status: bot.botStatus ?? \"unknown\",\n reasons: bot.failureReasons ?? [],\n });\n }\n return bot;\n});\n\nconst transientLocaleStatuses = new Set([\"Creating\", \"Processing\", \"Importing\", \"Deleting\"]);\n\n/**\n * Poll `describeBotLocale` until the DRAFT locale leaves its create-time\n * transient statuses (settles at `NotBuilt`/`Built`/`ReadyExpressTesting`).\n * Fails typed on `Failed`.\n */\nexport const waitForLocaleSettled = Effect.fn(\"AWS.LexV2.waitForLocaleSettled\")(function* (\n botId: string,\n localeId: string,\n) {\n const locale = yield* untilConverged(\n lexm.describeBotLocale({ botId, botVersion: \"DRAFT\", localeId }),\n (l) => !transientLocaleStatuses.has(l.botLocaleStatus ?? \"\"),\n );\n if (\n locale.botLocaleStatus === \"Failed\" ||\n transientLocaleStatuses.has(locale.botLocaleStatus ?? \"\")\n ) {\n return yield* new LexOperationFailed({\n resourceId: `${botId}/${localeId}`,\n status: locale.botLocaleStatus ?? \"unknown\",\n reasons: locale.failureReasons ?? [],\n });\n }\n return locale;\n});\n\n/**\n * Poll `describeBotLocale` until a triggered build lands on `Built`.\n * `Building` and `ReadyExpressTesting` are intermediate build states. A tiny\n * bot normally builds in under a minute; keep the poll bounded to ~90 seconds\n * so a stalled AWS build fails promptly.\n */\nexport const waitForLocaleBuilt = Effect.fn(\"AWS.LexV2.waitForLocaleBuilt\")(function* (\n botId: string,\n localeId: string,\n) {\n const locale = yield* untilConverged(\n lexm.describeBotLocale({ botId, botVersion: \"DRAFT\", localeId }),\n (l) => l.botLocaleStatus === \"Built\" || l.botLocaleStatus === \"Failed\",\n { intervalSeconds: 5, times: 18 },\n );\n if (locale.botLocaleStatus !== \"Built\") {\n return yield* new LexOperationFailed({\n resourceId: `${botId}/${localeId}`,\n status: locale.botLocaleStatus ?? \"unknown\",\n reasons: locale.failureReasons ?? [],\n });\n }\n return locale;\n});\n\n/**\n * Poll `describeBotAlias` until the alias leaves `Creating`. Fails typed on\n * `Failed`.\n */\nexport const waitForAliasSettled = Effect.fn(\"AWS.LexV2.waitForAliasSettled\")(function* (\n botId: string,\n botAliasId: string,\n) {\n const alias = yield* untilConverged(\n lexm.describeBotAlias({ botId, botAliasId }),\n (a) => a.botAliasStatus !== \"Creating\",\n );\n if (alias.botAliasStatus === \"Failed\" || alias.botAliasStatus === \"Creating\") {\n return yield* new LexOperationFailed({\n resourceId: `${botId}/${botAliasId}`,\n status: alias.botAliasStatus ?? \"unknown\",\n reasons: [],\n });\n }\n return alias;\n});\n\n/**\n * Read the observed tags of a Lex resource by ARN. Best-effort — a race with\n * deletion reports no tags.\n */\nexport const readLexTags = Effect.fn(\"AWS.LexV2.readLexTags\")(function* (arn: string) {\n const response = yield* lexm\n .listTagsForResource({ resourceARN: arn })\n .pipe(Effect.orElseSucceed(() => undefined));\n return toTagRecord(response?.tags);\n});\n\n/**\n * Sync tags on a Lex resource: diff OBSERVED cloud tags against the desired\n * set and apply only the delta.\n */\nexport const syncLexTags = Effect.fn(\"AWS.LexV2.syncLexTags\")(function* (\n arn: string,\n observed: Record\u003cstring, string>,\n desired: Record\u003cstring, string>,\n) {\n const { removed, upsert } = diffTags(observed, desired);\n if (upsert.length > 0) {\n yield* lexm.tagResource({\n resourceARN: arn,\n tags: Object.fromEntries(upsert.map((tag) => [tag.Key, tag.Value])),\n });\n }\n if (removed.length > 0) {\n yield* lexm.untagResource({ resourceARN: arn, tagKeys: removed });\n }\n});\n","preview":null,"history":null,"version":"8203abb9e5a6f669fd8e2e342bcd5ef7a7719f70"},"/_session?shell=1":null}