sailfork / t3code-github / .repos/ alchemy-effect/ packages/ aws/ src/ WAFv2/ RegexPatternSet.ts

import type * as WAFV2 from "@distilled.cloud/aws/wafv2";
import * as wafv2 from "@distilled.cloud/aws/wafv2";
import { Unowned } from "alchemy/AdoptPolicy";
import { deepEqual, isResolved } from "alchemy/Diff";
import { createPhysicalName } from "alchemy/PhysicalName";
import * as Provider from "alchemy/Provider";
import { Resource } from "alchemy/Resource";
import { createInternalTags, createTagsList, hasAlchemyTags } from "alchemy/Tags";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import type { Providers } from "../Providers.ts";
import {
  fetchWafTags,
  retryAssociatedItem,
  retryOptimisticLock,
  syncWafTags,
  type WafScope,
  withWafScope,
} from "./internal.ts";

export class RegexPatternSetUnexpectedResponse extends Data.TaggedError(
  "RegexPatternSetUnexpectedResponse",
)<{
  readonly message: string;
  readonly cause?: unknown;
}> {}

export interface RegexPatternSetProps {
  /**
   * Name of the regex pattern set. Must match `^[\w\-]+

	
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
	.repos/alchemy-effect/packages/aws/src/WAFv2/RegexPatternSet.ts at main · sailfork/t3code-github · Sailfork
	
		
and be 1-128 * characters. Changing the name replaces the regex pattern set. * @default a physical name derived from the app, stage and logical ID */ regexPatternSetName?: string; /** * Scope of the regex pattern set — `REGIONAL` (ambient region) or * `CLOUDFRONT` (pinned to `us-east-1`). Must match the scope of the web * ACLs and rule groups that reference it. Changing the scope replaces the * regex pattern set. * @default "REGIONAL" */ scope?: WafScope; /** * Regular expressions in the set (1-10 patterns, each up to 200 * characters). Mutable — updated in place. */ regularExpressions: string[]; /** * Description of the regex pattern set. */ description?: string; /** * User-defined tags to apply to the regex pattern set. */ tags?: Record<string, string>; } export interface RegexPatternSet extends Resource< "AWS.WAFv2.RegexPatternSet", RegexPatternSetProps, { /** * Name of the regex pattern set. */ regexPatternSetName: string; /** * WAF-assigned unique ID of the regex pattern set. */ regexPatternSetId: string; /** * ARN of the regex pattern set — reference it from a rule's * `RegexPatternSetReferenceStatement`. */ regexPatternSetArn: string; /** * Scope the regex pattern set was created in. */ scope: WafScope; /** * Current regular expressions in the set. */ regularExpressions: string[]; }, never, Providers > {} /** * An AWS WAFv2 regex pattern set — a named collection of regular expressions * referenced from web ACL and rule group rules via * `RegexPatternSetReferenceStatement`. * * ### Creating Regex Pattern Sets * **Example:** Block Requests Matching Bad Path Patterns * ```typescript * const badPaths = yield* AWS.WAFv2.RegexPatternSet("BadPaths", { * regularExpressions: ["^/wp-admin", "\\.php$"], * }); * ``` * * **Example:** Reference from a Web ACL Rule * ```typescript * const acl = yield* AWS.WAFv2.WebACL("Firewall", { * rules: [ * { * Name: "block-bad-paths", * Priority: 0, * Statement: { * RegexPatternSetReferenceStatement: { * ARN: badPaths.regexPatternSetArn, * FieldToMatch: { UriPath: {} }, * TextTransformations: [{ Priority: 0, Type: "NONE" }], * }, * }, * Action: { Block: {} }, * VisibilityConfig: { * SampledRequestsEnabled: true, * CloudWatchMetricsEnabled: true, * MetricName: "block-bad-paths", * }, * }, * ], * }); * ``` * * @resource */ export const RegexPatternSet = Resource<RegexPatternSet>("AWS.WAFv2.RegexPatternSet"); const defaultScope: WafScope = "REGIONAL"; const toExpressionList = (expressions: readonly string[]): WAFV2.Regex[] => expressions.map((RegexString) => ({ RegexString })); const fromExpressionList = (list: readonly WAFV2.Regex[] | undefined): string[] => (list ?? []).flatMap((regex) => (regex.RegexString !== undefined ? [regex.RegexString] : [])); const sorted = (values: readonly string[]) => [...values].sort((a, b) => a.localeCompare(b)); const toAttrs = (set: WAFV2.RegexPatternSet, scope: WafScope) => ({ regexPatternSetName: set.Name ?? "", regexPatternSetId: set.Id ?? "", regexPatternSetArn: set.ARN ?? "", scope, regularExpressions: fromExpressionList(set.RegularExpressionList), }); export const RegexPatternSetProvider = () => Provider.effect( RegexPatternSet, Effect.gen(function* () { const createName = Effect.fn(function* (id: string, props: RegexPatternSetProps) { return props.regexPatternSetName ?? (yield* createPhysicalName({ id, maxLength: 128 })); }); const findSet = Effect.fn(function* ( scope: WafScope, name: string, cachedId: string | undefined, ) { if (cachedId !== undefined) { const byId = yield* withWafScope( scope, wafv2 .getRegexPatternSet({ Name: name, Scope: scope, Id: cachedId }) .pipe(Effect.catchTag("WAFNonexistentItemException", () => Effect.undefined)), ); if (byId?.RegexPatternSet) { return byId; } } let marker: string | undefined; for (let page = 0; page < 20; page++) { const listed = yield* withWafScope( scope, wafv2.listRegexPatternSets({ Scope: scope, NextMarker: marker, Limit: 100, }), ); const summary = listed.RegexPatternSets?.find((s) => s.Name === name); if (summary?.Id !== undefined) { return yield* withWafScope( scope, wafv2 .getRegexPatternSet({ Name: name, Scope: scope, Id: summary.Id, }) .pipe(Effect.catchTag("WAFNonexistentItemException", () => Effect.undefined)), ); } if (!listed.NextMarker || (listed.RegexPatternSets?.length ?? 0) === 0) { break; } marker = listed.NextMarker; } return undefined; }); const listScope = Effect.fn(function* (scope: WafScope) { const rows: ReturnType<typeof toAttrs>[] = []; let marker: string | undefined; for (let page = 0; page < 50; page++) { const listed = yield* withWafScope( scope, wafv2.listRegexPatternSets({ Scope: scope, NextMarker: marker, Limit: 100, }), ); const summaries = listed.RegexPatternSets ?? []; const details = yield* Effect.forEach( summaries, (summary) => summary.Name !== undefined && summary.Id !== undefined ? withWafScope( scope, wafv2 .getRegexPatternSet({ Name: summary.Name, Scope: scope, Id: summary.Id, }) .pipe(Effect.catchTag("WAFNonexistentItemException", () => Effect.undefined)), ) : Effect.undefined, { concurrency: 5 }, ); for (const detail of details) { if (detail?.RegexPatternSet) { rows.push(toAttrs(detail.RegexPatternSet, scope)); } } if (!listed.NextMarker || summaries.length === 0) { break; } marker = listed.NextMarker; } return rows; }); return { stables: ["regexPatternSetName", "regexPatternSetId", "regexPatternSetArn", "scope"], list: () => Effect.gen(function* () { const regional = yield* listScope("REGIONAL"); const cloudfront = yield* listScope("CLOUDFRONT"); return [...regional, ...cloudfront]; }), diff: Effect.fn(function* ({ id, news, olds }) { if (!isResolved(news)) return undefined; const oldName = yield* createName(id, olds ?? { regularExpressions: [] }); const newName = yield* createName(id, news); if ( oldName !== newName || (olds?.scope ?? defaultScope) !== (news.scope ?? defaultScope) ) { return { action: "replace" } as const; } }), read: Effect.fn(function* ({ id, olds, output }) { const scope = output?.scope ?? olds?.scope ?? defaultScope; const name = output?.regexPatternSetName ?? (yield* createName(id, olds ?? { regularExpressions: [] })); const found = yield* findSet(scope, name, output?.regexPatternSetId); if (!found?.RegexPatternSet?.ARN) { return undefined; } const attrs = toAttrs(found.RegexPatternSet, scope); const tags = yield* fetchWafTags(scope, found.RegexPatternSet.ARN); return (yield* hasAlchemyTags(id, tags)) ? attrs : Unowned(attrs); }), reconcile: Effect.fn(function* ({ id, news, output, session }) { const scope = news.scope ?? defaultScope; const name = output?.regexPatternSetName ?? (yield* createName(id, news)); const internalTags = yield* createInternalTags(id); const desiredTags = { ...news.tags, ...internalTags }; // 1. Observe. let observed = yield* findSet(scope, name, output?.regexPatternSetId); // 2. Ensure — tolerate a duplicate-create race and re-read. if (!observed?.RegexPatternSet) { yield* withWafScope( scope, wafv2 .createRegexPatternSet({ Name: name, Scope: scope, RegularExpressionList: toExpressionList(news.regularExpressions), Description: news.description, Tags: createTagsList(desiredTags), }) .pipe(Effect.catchTag("WAFDuplicateItemException", () => Effect.undefined)), ); observed = yield* findSet(scope, name, undefined); } const set = observed?.RegexPatternSet; const arn = set?.ARN; if (set === undefined || arn === undefined) { return yield* new RegexPatternSetUnexpectedResponse({ message: `Failed to observe RegexPatternSet '${name}' after create`, }); } yield* session.note(arn); // 3. Sync expressions + description against OBSERVED state. WAF // may return the list in arbitrary order — compare as sets. const drifted = !deepEqual( { RegularExpressions: sorted(fromExpressionList(set.RegularExpressionList)), Description: set.Description, }, { RegularExpressions: sorted(news.regularExpressions), Description: news.description, }, { stripNullish: true }, ); if (drifted) { yield* retryOptimisticLock( Effect.gen(function* () { const fresh = yield* findSet(scope, name, set.Id); if (!fresh?.RegexPatternSet?.Id || fresh.LockToken === undefined) { return; } yield* withWafScope( scope, wafv2.updateRegexPatternSet({ Name: name, Scope: scope, Id: fresh.RegexPatternSet.Id, RegularExpressionList: toExpressionList(news.regularExpressions), Description: news.description, LockToken: fresh.LockToken, }), ); }), ); } // 3b. Sync tags against OBSERVED cloud tags. yield* syncWafTags(scope, arn, desiredTags); // 4. Return fresh attributes. return { ...toAttrs(set, scope), regularExpressions: [...news.regularExpressions], }; }), delete: Effect.fn(function* ({ output }) { const scope = output.scope; // A pattern set still referenced by a web ACL rule (deletion // propagation) surfaces WAFAssociatedItemException — retry it. yield* Effect.gen(function* () { const found = yield* withWafScope( scope, wafv2 .getRegexPatternSet({ Name: output.regexPatternSetName, Scope: scope, Id: output.regexPatternSetId, }) .pipe(Effect.catchTag("WAFNonexistentItemException", () => Effect.undefined)), ); if (!found?.RegexPatternSet || found.LockToken === undefined) { return; } yield* withWafScope( scope, wafv2 .deleteRegexPatternSet({ Name: output.regexPatternSetName, Scope: scope, Id: output.regexPatternSetId, LockToken: found.LockToken, }) .pipe(Effect.catchTag("WAFNonexistentItemException", () => Effect.void)), ); }).pipe(retryOptimisticLock, retryAssociatedItem); }), }; }), );
.repos/alchemy-effect/packages/aws/src/WAFv2/RegexPatternSet.ts at main · sailfork/t3code-github · Sailfork
and be 1-128\n * characters. Changing the name replaces the regex pattern set.\n * @default a physical name derived from the app, stage and logical ID\n */\n regexPatternSetName?: string;\n /**\n * Scope of the regex pattern set — `REGIONAL` (ambient region) or\n * `CLOUDFRONT` (pinned to `us-east-1`). Must match the scope of the web\n * ACLs and rule groups that reference it. Changing the scope replaces the\n * regex pattern set.\n * @default \"REGIONAL\"\n */\n scope?: WafScope;\n /**\n * Regular expressions in the set (1-10 patterns, each up to 200\n * characters). Mutable — updated in place.\n */\n regularExpressions: string[];\n /**\n * Description of the regex pattern set.\n */\n description?: string;\n /**\n * User-defined tags to apply to the regex pattern set.\n */\n tags?: Record\u003cstring, string>;\n}\n\nexport interface RegexPatternSet extends Resource\u003c\n \"AWS.WAFv2.RegexPatternSet\",\n RegexPatternSetProps,\n {\n /**\n * Name of the regex pattern set.\n */\n regexPatternSetName: string;\n /**\n * WAF-assigned unique ID of the regex pattern set.\n */\n regexPatternSetId: string;\n /**\n * ARN of the regex pattern set — reference it from a rule's\n * `RegexPatternSetReferenceStatement`.\n */\n regexPatternSetArn: string;\n /**\n * Scope the regex pattern set was created in.\n */\n scope: WafScope;\n /**\n * Current regular expressions in the set.\n */\n regularExpressions: string[];\n },\n never,\n Providers\n> {}\n\n/**\n * An AWS WAFv2 regex pattern set — a named collection of regular expressions\n * referenced from web ACL and rule group rules via\n * `RegexPatternSetReferenceStatement`.\n *\n * ### Creating Regex Pattern Sets\n * **Example:** Block Requests Matching Bad Path Patterns\n * ```typescript\n * const badPaths = yield* AWS.WAFv2.RegexPatternSet(\"BadPaths\", {\n * regularExpressions: [\"^/wp-admin\", \"\\\\.php$\"],\n * });\n * ```\n *\n * **Example:** Reference from a Web ACL Rule\n * ```typescript\n * const acl = yield* AWS.WAFv2.WebACL(\"Firewall\", {\n * rules: [\n * {\n * Name: \"block-bad-paths\",\n * Priority: 0,\n * Statement: {\n * RegexPatternSetReferenceStatement: {\n * ARN: badPaths.regexPatternSetArn,\n * FieldToMatch: { UriPath: {} },\n * TextTransformations: [{ Priority: 0, Type: \"NONE\" }],\n * },\n * },\n * Action: { Block: {} },\n * VisibilityConfig: {\n * SampledRequestsEnabled: true,\n * CloudWatchMetricsEnabled: true,\n * MetricName: \"block-bad-paths\",\n * },\n * },\n * ],\n * });\n * ```\n *\n * @resource\n */\nexport const RegexPatternSet = Resource\u003cRegexPatternSet>(\"AWS.WAFv2.RegexPatternSet\");\n\nconst defaultScope: WafScope = \"REGIONAL\";\n\nconst toExpressionList = (expressions: readonly string[]): WAFV2.Regex[] =>\n expressions.map((RegexString) => ({ RegexString }));\n\nconst fromExpressionList = (list: readonly WAFV2.Regex[] | undefined): string[] =>\n (list ?? []).flatMap((regex) => (regex.RegexString !== undefined ? [regex.RegexString] : []));\n\nconst sorted = (values: readonly string[]) => [...values].sort((a, b) => a.localeCompare(b));\n\nconst toAttrs = (set: WAFV2.RegexPatternSet, scope: WafScope) => ({\n regexPatternSetName: set.Name ?? \"\",\n regexPatternSetId: set.Id ?? \"\",\n regexPatternSetArn: set.ARN ?? \"\",\n scope,\n regularExpressions: fromExpressionList(set.RegularExpressionList),\n});\n\nexport const RegexPatternSetProvider = () =>\n Provider.effect(\n RegexPatternSet,\n Effect.gen(function* () {\n const createName = Effect.fn(function* (id: string, props: RegexPatternSetProps) {\n return props.regexPatternSetName ?? (yield* createPhysicalName({ id, maxLength: 128 }));\n });\n\n const findSet = Effect.fn(function* (\n scope: WafScope,\n name: string,\n cachedId: string | undefined,\n ) {\n if (cachedId !== undefined) {\n const byId = yield* withWafScope(\n scope,\n wafv2\n .getRegexPatternSet({ Name: name, Scope: scope, Id: cachedId })\n .pipe(Effect.catchTag(\"WAFNonexistentItemException\", () => Effect.undefined)),\n );\n if (byId?.RegexPatternSet) {\n return byId;\n }\n }\n let marker: string | undefined;\n for (let page = 0; page \u003c 20; page++) {\n const listed = yield* withWafScope(\n scope,\n wafv2.listRegexPatternSets({\n Scope: scope,\n NextMarker: marker,\n Limit: 100,\n }),\n );\n const summary = listed.RegexPatternSets?.find((s) => s.Name === name);\n if (summary?.Id !== undefined) {\n return yield* withWafScope(\n scope,\n wafv2\n .getRegexPatternSet({\n Name: name,\n Scope: scope,\n Id: summary.Id,\n })\n .pipe(Effect.catchTag(\"WAFNonexistentItemException\", () => Effect.undefined)),\n );\n }\n if (!listed.NextMarker || (listed.RegexPatternSets?.length ?? 0) === 0) {\n break;\n }\n marker = listed.NextMarker;\n }\n return undefined;\n });\n\n const listScope = Effect.fn(function* (scope: WafScope) {\n const rows: ReturnType\u003ctypeof toAttrs>[] = [];\n let marker: string | undefined;\n for (let page = 0; page \u003c 50; page++) {\n const listed = yield* withWafScope(\n scope,\n wafv2.listRegexPatternSets({\n Scope: scope,\n NextMarker: marker,\n Limit: 100,\n }),\n );\n const summaries = listed.RegexPatternSets ?? [];\n const details = yield* Effect.forEach(\n summaries,\n (summary) =>\n summary.Name !== undefined && summary.Id !== undefined\n ? withWafScope(\n scope,\n wafv2\n .getRegexPatternSet({\n Name: summary.Name,\n Scope: scope,\n Id: summary.Id,\n })\n .pipe(Effect.catchTag(\"WAFNonexistentItemException\", () => Effect.undefined)),\n )\n : Effect.undefined,\n { concurrency: 5 },\n );\n for (const detail of details) {\n if (detail?.RegexPatternSet) {\n rows.push(toAttrs(detail.RegexPatternSet, scope));\n }\n }\n if (!listed.NextMarker || summaries.length === 0) {\n break;\n }\n marker = listed.NextMarker;\n }\n return rows;\n });\n\n return {\n stables: [\"regexPatternSetName\", \"regexPatternSetId\", \"regexPatternSetArn\", \"scope\"],\n\n list: () =>\n Effect.gen(function* () {\n const regional = yield* listScope(\"REGIONAL\");\n const cloudfront = yield* listScope(\"CLOUDFRONT\");\n return [...regional, ...cloudfront];\n }),\n\n diff: Effect.fn(function* ({ id, news, olds }) {\n if (!isResolved(news)) return undefined;\n const oldName = yield* createName(id, olds ?? { regularExpressions: [] });\n const newName = yield* createName(id, news);\n if (\n oldName !== newName ||\n (olds?.scope ?? defaultScope) !== (news.scope ?? defaultScope)\n ) {\n return { action: \"replace\" } as const;\n }\n }),\n\n read: Effect.fn(function* ({ id, olds, output }) {\n const scope = output?.scope ?? olds?.scope ?? defaultScope;\n const name =\n output?.regexPatternSetName ??\n (yield* createName(id, olds ?? { regularExpressions: [] }));\n const found = yield* findSet(scope, name, output?.regexPatternSetId);\n if (!found?.RegexPatternSet?.ARN) {\n return undefined;\n }\n const attrs = toAttrs(found.RegexPatternSet, scope);\n const tags = yield* fetchWafTags(scope, found.RegexPatternSet.ARN);\n return (yield* hasAlchemyTags(id, tags)) ? attrs : Unowned(attrs);\n }),\n\n reconcile: Effect.fn(function* ({ id, news, output, session }) {\n const scope = news.scope ?? defaultScope;\n const name = output?.regexPatternSetName ?? (yield* createName(id, news));\n const internalTags = yield* createInternalTags(id);\n const desiredTags = { ...news.tags, ...internalTags };\n\n // 1. Observe.\n let observed = yield* findSet(scope, name, output?.regexPatternSetId);\n\n // 2. Ensure — tolerate a duplicate-create race and re-read.\n if (!observed?.RegexPatternSet) {\n yield* withWafScope(\n scope,\n wafv2\n .createRegexPatternSet({\n Name: name,\n Scope: scope,\n RegularExpressionList: toExpressionList(news.regularExpressions),\n Description: news.description,\n Tags: createTagsList(desiredTags),\n })\n .pipe(Effect.catchTag(\"WAFDuplicateItemException\", () => Effect.undefined)),\n );\n observed = yield* findSet(scope, name, undefined);\n }\n\n const set = observed?.RegexPatternSet;\n const arn = set?.ARN;\n if (set === undefined || arn === undefined) {\n return yield* new RegexPatternSetUnexpectedResponse({\n message: `Failed to observe RegexPatternSet '${name}' after create`,\n });\n }\n\n yield* session.note(arn);\n\n // 3. Sync expressions + description against OBSERVED state. WAF\n // may return the list in arbitrary order — compare as sets.\n const drifted = !deepEqual(\n {\n RegularExpressions: sorted(fromExpressionList(set.RegularExpressionList)),\n Description: set.Description,\n },\n {\n RegularExpressions: sorted(news.regularExpressions),\n Description: news.description,\n },\n { stripNullish: true },\n );\n if (drifted) {\n yield* retryOptimisticLock(\n Effect.gen(function* () {\n const fresh = yield* findSet(scope, name, set.Id);\n if (!fresh?.RegexPatternSet?.Id || fresh.LockToken === undefined) {\n return;\n }\n yield* withWafScope(\n scope,\n wafv2.updateRegexPatternSet({\n Name: name,\n Scope: scope,\n Id: fresh.RegexPatternSet.Id,\n RegularExpressionList: toExpressionList(news.regularExpressions),\n Description: news.description,\n LockToken: fresh.LockToken,\n }),\n );\n }),\n );\n }\n\n // 3b. Sync tags against OBSERVED cloud tags.\n yield* syncWafTags(scope, arn, desiredTags);\n\n // 4. Return fresh attributes.\n return {\n ...toAttrs(set, scope),\n regularExpressions: [...news.regularExpressions],\n };\n }),\n\n delete: Effect.fn(function* ({ output }) {\n const scope = output.scope;\n // A pattern set still referenced by a web ACL rule (deletion\n // propagation) surfaces WAFAssociatedItemException — retry it.\n yield* Effect.gen(function* () {\n const found = yield* withWafScope(\n scope,\n wafv2\n .getRegexPatternSet({\n Name: output.regexPatternSetName,\n Scope: scope,\n Id: output.regexPatternSetId,\n })\n .pipe(Effect.catchTag(\"WAFNonexistentItemException\", () => Effect.undefined)),\n );\n if (!found?.RegexPatternSet || found.LockToken === undefined) {\n return;\n }\n yield* withWafScope(\n scope,\n wafv2\n .deleteRegexPatternSet({\n Name: output.regexPatternSetName,\n Scope: scope,\n Id: output.regexPatternSetId,\n LockToken: found.LockToken,\n })\n .pipe(Effect.catchTag(\"WAFNonexistentItemException\", () => Effect.void)),\n );\n }).pipe(retryOptimisticLock, retryAssociatedItem);\n }),\n };\n }),\n );\n","preview":null,"history":null,"version":"05736fd57df92252b9eb7ec6eed4840d1994c184"},"/_session?shell=1":null}