import * as synthetics from "@distilled.cloud/aws/synthetics";
import { Unowned } from "alchemy/AdoptPolicy";
import { isResolved } from "alchemy/Diff";
import { createPhysicalName } from "alchemy/PhysicalName";
import * as Provider from "alchemy/Provider";
import { Resource } from "alchemy/Resource";
import { createInternalTags, diffTags, hasAlchemyTags } from "alchemy/Tags";
import * as Effect from "effect/Effect";
import * as Schedule from "effect/Schedule";
import * as Stream from "effect/Stream";
import type { Providers } from "../Providers.ts";
export interface GroupProps {
/**
* Name of the group. Must match `^[0-9a-zA-Z_-]+
.repos/alchemy-effect/packages/aws/src/Synthetics/Group.ts at main · sailfork/t3code-github · Sailfork
and be at most 64
* characters. Group names must be unique in the account (groups are
* global resources visible from every Region).
* @default ${app}-${id}-${stage}-${suffix}
*/
groupName?: string;
/**
* ARNs of the canaries associated with this group (as many as 10). The
* canaries must exist in the Region the group is managed from; membership
* is converged on every deploy (canaries added here are associated,
* canaries removed are disassociated).
*/
members?: string[];
/**
* Tags to apply to the group. Merged with internal Alchemy tags.
*/
tags?: Record<string, string>;
}
export interface Group extends Resource<
"AWS.Synthetics.Group",
GroupProps,
{
/**
* Physical name of the group.
*/
groupName: string;
/**
* ARN of the group. The ARN reflects the home Region the group was
* created in, but the group itself is a global resource.
*/
groupArn: string;
/**
* Service-assigned unique ID of the group.
*/
groupId: string;
},
never,
Providers
> {}
/**
* A CloudWatch Synthetics group — associates canaries (including
* cross-Region canaries) so you can view aggregated run results and manage
* them as a unit. A group can hold as many as 10 canaries, and an account
* can have as many as 20 groups.
* ### Creating Groups
* **Example:** Group of Canaries
* ```typescript
* import * as Synthetics from "@alchemy.run/aws/Synthetics";
*
* const group = yield* Synthetics.Group("ApiCanaries", {
* members: [checkoutCanary.canaryArn, searchCanary.canaryArn],
* });
* ```
*
* **Example:** Empty Group with Tags
* ```typescript
* const group = yield* Synthetics.Group("Fleet", {
* tags: { team: "platform" },
* });
* ```
*
* @resource
*/
export const Group = Resource<Group>("AWS.Synthetics.Group");
export const GroupProvider = () =>
Provider.effect(
Group,
Effect.gen(function* () {
const createGroupName = Effect.fn(function* (
id: string,
props: { groupName?: string | undefined },
) {
if (props.groupName) return props.groupName;
return yield* createPhysicalName({ id, maxLength: 64 });
});
const getGroupOrUndefined = Effect.fn(function* (identifier: string) {
return yield* synthetics.getGroup({ GroupIdentifier: identifier }).pipe(
Effect.map((r) => r.Group),
Effect.catchTag("ResourceNotFoundException", () => Effect.undefined),
);
});
const listMembers = Effect.fn(function* (identifier: string) {
const pages = yield* synthetics.listGroupResources
.pages({ GroupIdentifier: identifier })
.pipe(Stream.runCollect);
return Array.from(pages).flatMap((page) => page.Resources ?? []);
});
const filterTags = (
tags: { [key: string]: string | undefined } | undefined,
): Record<string, string> =>
Object.fromEntries(
Object.entries(tags ?? {}).filter(
(entry): entry is [string, string] => entry[1] !== undefined,
),
);
const toAttributes = (groupName: string, group: synthetics.Group): Group["Attributes"] => ({
groupName,
groupArn: group.Arn ?? "",
groupId: group.Id ?? "",
});
return Group.Provider.of({
stables: ["groupName", "groupArn", "groupId"],
list: () =>
Effect.gen(function* () {
const pages = yield* synthetics.listGroups.pages({}).pipe(Stream.runCollect);
return Array.from(pages)
.flatMap((page) => page.Groups ?? [])
.filter((group) => group.Name !== undefined)
.map((group) => ({
groupName: group.Name!,
groupArn: group.Arn ?? "",
groupId: group.Id ?? "",
}));
}),
read: Effect.fn(function* ({ id, olds, output }) {
const groupName = output?.groupName ?? (yield* createGroupName(id, olds ?? {}));
const group = yield* getGroupOrUndefined(groupName);
if (group === undefined) return undefined;
const attrs = toAttributes(groupName, group);
const tags = filterTags(group.Tags);
return (yield* hasAlchemyTags(id, tags)) ? attrs : Unowned(attrs);
}),
diff: Effect.fn(function* ({ id, news, olds }) {
if (!isResolved(news)) return undefined;
const oldName = yield* createGroupName(id, olds);
const newName = yield* createGroupName(id, news);
if (oldName !== newName) {
return { action: "replace" } as const;
}
// members and tags converge through reconcile
}),
reconcile: Effect.fn(function* ({ id, news, output, session }) {
const groupName = output?.groupName ?? (yield* createGroupName(id, news));
const internalTags = yield* createInternalTags(id);
const desiredTags = { ...news.tags, ...internalTags };
// 1. OBSERVE — cloud state is authoritative.
let observed = yield* getGroupOrUndefined(groupName);
// 2. ENSURE — create if missing; tolerate a concurrent-create race.
if (observed === undefined) {
yield* synthetics
.createGroup({ Name: groupName, Tags: desiredTags })
.pipe(Effect.catchTag("ConflictException", () => Effect.void));
observed = yield* getGroupOrUndefined(groupName);
yield* session.note(`created group ${groupName}`);
}
const groupArn = observed?.Arn ?? "";
// 3. SYNC members — diff observed canary associations against the
// desired members and apply only the delta. Association calls are
// idempotent per (group, canary) pair.
const observedMembers = yield* listMembers(groupName);
const desiredMembers = news.members ?? [];
const toAssociate = desiredMembers.filter((arn) => !observedMembers.includes(arn));
const toDisassociate = observedMembers.filter((arn) => !desiredMembers.includes(arn));
for (const ResourceArn of toAssociate) {
yield* synthetics.associateResource({ GroupIdentifier: groupName, ResourceArn }).pipe(
Effect.retry({
while: (e): boolean => e._tag === "ConflictException",
schedule: Schedule.max([Schedule.fixed("2 seconds"), Schedule.recurs(8)]),
}),
);
}
for (const ResourceArn of toDisassociate) {
yield* synthetics
.disassociateResource({
GroupIdentifier: groupName,
ResourceArn,
})
.pipe(
Effect.catchTag("ResourceNotFoundException", () => Effect.void),
Effect.retry({
while: (e): boolean => e._tag === "ConflictException",
schedule: Schedule.max([Schedule.fixed("2 seconds"), Schedule.recurs(8)]),
}),
);
}
if (toAssociate.length > 0 || toDisassociate.length > 0) {
yield* session.note(
`synced group ${groupName} members (+${toAssociate.length}/-${toDisassociate.length})`,
);
}
// 4. SYNC tags — diff against OBSERVED cloud tags so adoption
// converges (create already applied them).
const currentTags = filterTags(observed?.Tags);
const { upsert, removed } = diffTags(currentTags, desiredTags);
if (upsert.length > 0) {
yield* synthetics.tagResource({
ResourceArn: groupArn,
Tags: Object.fromEntries(upsert.map((t) => [t.Key, t.Value])),
});
}
if (removed.length > 0) {
yield* synthetics.untagResource({
ResourceArn: groupArn,
TagKeys: removed,
});
}
yield* session.note(groupName);
return {
groupName,
groupArn,
groupId: observed?.Id ?? "",
};
}),
delete: Effect.fn(function* ({ output }) {
// The group does not need to be emptied first — deleting a group
// never deletes its canaries.
yield* synthetics.deleteGroup({ GroupIdentifier: output.groupName }).pipe(
Effect.retry({
while: (e): boolean => e._tag === "ConflictException",
schedule: Schedule.max([Schedule.fixed("2 seconds"), Schedule.recurs(8)]),
}),
Effect.catchTag("ResourceNotFoundException", () => Effect.void),
);
}),
});
}),
);
.repos/alchemy-effect/packages/aws/src/Synthetics/Group.ts at main · sailfork/t3code-github · Sailfork
and be at most 64\n * characters. Group names must be unique in the account (groups are\n * global resources visible from every Region).\n * @default ${app}-${id}-${stage}-${suffix}\n */\n groupName?: string;\n /**\n * ARNs of the canaries associated with this group (as many as 10). The\n * canaries must exist in the Region the group is managed from; membership\n * is converged on every deploy (canaries added here are associated,\n * canaries removed are disassociated).\n */\n members?: string[];\n /**\n * Tags to apply to the group. Merged with internal Alchemy tags.\n */\n tags?: Record\u003cstring, string>;\n}\n\nexport interface Group extends Resource\u003c\n \"AWS.Synthetics.Group\",\n GroupProps,\n {\n /**\n * Physical name of the group.\n */\n groupName: string;\n /**\n * ARN of the group. The ARN reflects the home Region the group was\n * created in, but the group itself is a global resource.\n */\n groupArn: string;\n /**\n * Service-assigned unique ID of the group.\n */\n groupId: string;\n },\n never,\n Providers\n> {}\n\n/**\n * A CloudWatch Synthetics group — associates canaries (including\n * cross-Region canaries) so you can view aggregated run results and manage\n * them as a unit. A group can hold as many as 10 canaries, and an account\n * can have as many as 20 groups.\n * ### Creating Groups\n * **Example:** Group of Canaries\n * ```typescript\n * import * as Synthetics from \"@alchemy.run/aws/Synthetics\";\n *\n * const group = yield* Synthetics.Group(\"ApiCanaries\", {\n * members: [checkoutCanary.canaryArn, searchCanary.canaryArn],\n * });\n * ```\n *\n * **Example:** Empty Group with Tags\n * ```typescript\n * const group = yield* Synthetics.Group(\"Fleet\", {\n * tags: { team: \"platform\" },\n * });\n * ```\n *\n * @resource\n */\nexport const Group = Resource\u003cGroup>(\"AWS.Synthetics.Group\");\n\nexport const GroupProvider = () =>\n Provider.effect(\n Group,\n Effect.gen(function* () {\n const createGroupName = Effect.fn(function* (\n id: string,\n props: { groupName?: string | undefined },\n ) {\n if (props.groupName) return props.groupName;\n return yield* createPhysicalName({ id, maxLength: 64 });\n });\n\n const getGroupOrUndefined = Effect.fn(function* (identifier: string) {\n return yield* synthetics.getGroup({ GroupIdentifier: identifier }).pipe(\n Effect.map((r) => r.Group),\n Effect.catchTag(\"ResourceNotFoundException\", () => Effect.undefined),\n );\n });\n\n const listMembers = Effect.fn(function* (identifier: string) {\n const pages = yield* synthetics.listGroupResources\n .pages({ GroupIdentifier: identifier })\n .pipe(Stream.runCollect);\n return Array.from(pages).flatMap((page) => page.Resources ?? []);\n });\n\n const filterTags = (\n tags: { [key: string]: string | undefined } | undefined,\n ): Record\u003cstring, string> =>\n Object.fromEntries(\n Object.entries(tags ?? {}).filter(\n (entry): entry is [string, string] => entry[1] !== undefined,\n ),\n );\n\n const toAttributes = (groupName: string, group: synthetics.Group): Group[\"Attributes\"] => ({\n groupName,\n groupArn: group.Arn ?? \"\",\n groupId: group.Id ?? \"\",\n });\n\n return Group.Provider.of({\n stables: [\"groupName\", \"groupArn\", \"groupId\"],\n\n list: () =>\n Effect.gen(function* () {\n const pages = yield* synthetics.listGroups.pages({}).pipe(Stream.runCollect);\n return Array.from(pages)\n .flatMap((page) => page.Groups ?? [])\n .filter((group) => group.Name !== undefined)\n .map((group) => ({\n groupName: group.Name!,\n groupArn: group.Arn ?? \"\",\n groupId: group.Id ?? \"\",\n }));\n }),\n\n read: Effect.fn(function* ({ id, olds, output }) {\n const groupName = output?.groupName ?? (yield* createGroupName(id, olds ?? {}));\n const group = yield* getGroupOrUndefined(groupName);\n if (group === undefined) return undefined;\n const attrs = toAttributes(groupName, group);\n const tags = filterTags(group.Tags);\n return (yield* hasAlchemyTags(id, tags)) ? attrs : Unowned(attrs);\n }),\n\n diff: Effect.fn(function* ({ id, news, olds }) {\n if (!isResolved(news)) return undefined;\n const oldName = yield* createGroupName(id, olds);\n const newName = yield* createGroupName(id, news);\n if (oldName !== newName) {\n return { action: \"replace\" } as const;\n }\n // members and tags converge through reconcile\n }),\n\n reconcile: Effect.fn(function* ({ id, news, output, session }) {\n const groupName = output?.groupName ?? (yield* createGroupName(id, news));\n const internalTags = yield* createInternalTags(id);\n const desiredTags = { ...news.tags, ...internalTags };\n\n // 1. OBSERVE — cloud state is authoritative.\n let observed = yield* getGroupOrUndefined(groupName);\n\n // 2. ENSURE — create if missing; tolerate a concurrent-create race.\n if (observed === undefined) {\n yield* synthetics\n .createGroup({ Name: groupName, Tags: desiredTags })\n .pipe(Effect.catchTag(\"ConflictException\", () => Effect.void));\n observed = yield* getGroupOrUndefined(groupName);\n yield* session.note(`created group ${groupName}`);\n }\n const groupArn = observed?.Arn ?? \"\";\n\n // 3. SYNC members — diff observed canary associations against the\n // desired members and apply only the delta. Association calls are\n // idempotent per (group, canary) pair.\n const observedMembers = yield* listMembers(groupName);\n const desiredMembers = news.members ?? [];\n const toAssociate = desiredMembers.filter((arn) => !observedMembers.includes(arn));\n const toDisassociate = observedMembers.filter((arn) => !desiredMembers.includes(arn));\n for (const ResourceArn of toAssociate) {\n yield* synthetics.associateResource({ GroupIdentifier: groupName, ResourceArn }).pipe(\n Effect.retry({\n while: (e): boolean => e._tag === \"ConflictException\",\n schedule: Schedule.max([Schedule.fixed(\"2 seconds\"), Schedule.recurs(8)]),\n }),\n );\n }\n for (const ResourceArn of toDisassociate) {\n yield* synthetics\n .disassociateResource({\n GroupIdentifier: groupName,\n ResourceArn,\n })\n .pipe(\n Effect.catchTag(\"ResourceNotFoundException\", () => Effect.void),\n Effect.retry({\n while: (e): boolean => e._tag === \"ConflictException\",\n schedule: Schedule.max([Schedule.fixed(\"2 seconds\"), Schedule.recurs(8)]),\n }),\n );\n }\n if (toAssociate.length > 0 || toDisassociate.length > 0) {\n yield* session.note(\n `synced group ${groupName} members (+${toAssociate.length}/-${toDisassociate.length})`,\n );\n }\n\n // 4. SYNC tags — diff against OBSERVED cloud tags so adoption\n // converges (create already applied them).\n const currentTags = filterTags(observed?.Tags);\n const { upsert, removed } = diffTags(currentTags, desiredTags);\n if (upsert.length > 0) {\n yield* synthetics.tagResource({\n ResourceArn: groupArn,\n Tags: Object.fromEntries(upsert.map((t) => [t.Key, t.Value])),\n });\n }\n if (removed.length > 0) {\n yield* synthetics.untagResource({\n ResourceArn: groupArn,\n TagKeys: removed,\n });\n }\n\n yield* session.note(groupName);\n return {\n groupName,\n groupArn,\n groupId: observed?.Id ?? \"\",\n };\n }),\n\n delete: Effect.fn(function* ({ output }) {\n // The group does not need to be emptied first — deleting a group\n // never deletes its canaries.\n yield* synthetics.deleteGroup({ GroupIdentifier: output.groupName }).pipe(\n Effect.retry({\n while: (e): boolean => e._tag === \"ConflictException\",\n schedule: Schedule.max([Schedule.fixed(\"2 seconds\"), Schedule.recurs(8)]),\n }),\n Effect.catchTag(\"ResourceNotFoundException\", () => Effect.void),\n );\n }),\n });\n }),\n );\n","preview":null,"history":null,"version":"30d1187d136690fa9b80ddd71bde9d11f2da083a"},"/_session?shell=1":null}