The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 04:45 UTC
| 1 | import * as mm from "@distilled.cloud/aws/mailmanager"; |
| 2 | import { Unowned } from "alchemy/AdoptPolicy"; |
| 3 | import { isResolved } from "alchemy/Diff"; |
| 4 | import { createPhysicalName } from "alchemy/PhysicalName"; |
| 5 | import * as Provider from "alchemy/Provider"; |
| 6 | import { Resource } from "alchemy/Resource"; |
| 7 | import { createInternalTags, createTagsList, hasAlchemyTags } from "alchemy/Tags"; |
| 8 | import * as Data from "effect/Data"; |
| 9 | import * as Effect from "effect/Effect"; |
| 10 | import * as Stream from "effect/Stream"; |
| 11 | import type { Providers } from "../Providers.ts"; |
| 12 | import { |
| 13 | readMailManagerTags, |
| 14 | retryWhileMailManagerConflict, |
| 15 | syncMailManagerTags, |
| 16 | } from "./internal.ts"; |
| 17 | |
| 18 | export class MailManagerArchiveUnexpectedResponse extends Data.TaggedError( |
| 19 | "MailManagerArchiveUnexpectedResponse", |
| 20 | )<{ |
| 21 | readonly message: string; |
| 22 | readonly cause?: unknown; |
| 23 | }> {} |
| 24 | |
| 25 | export interface ArchiveProps { |
| 26 | /** |
| 27 | * Name of the archive. If omitted, a deterministic physical name is |
| 28 | * generated from the app, stage, and logical ID. Renames apply in place. |
| 29 | */ |
| 30 | archiveName?: string; |
| 31 | /** |
| 32 | * How long archived emails are retained before automatic deletion, as a |
| 33 | * Mail Manager retention enum (`THREE_MONTHS` ... `TEN_YEARS`, |
| 34 | * `PERMANENT`). The wire values are calendar periods, not arbitrary |
| 35 | * durations. Updates apply in place. |
| 36 | * @default PERMANENT |
| 37 | */ |
| 38 | retentionPeriod?: mm.RetentionPeriod; |
| 39 | /** |
| 40 | * ARN of the KMS key used to encrypt the archived emails. Immutable — |
| 41 | * changing it replaces the archive. |
| 42 | * @default an AWS-owned key |
| 43 | */ |
| 44 | kmsKeyArn?: string; |
| 45 | /** |
| 46 | * Tags applied to the archive. Alchemy ownership tags are merged in |
| 47 | * automatically. |
| 48 | */ |
| 49 | tags?: Record<string, string>; |
| 50 | } |
| 51 | |
| 52 | export interface Archive extends Resource< |
| 53 | "AWS.MailManager.Archive", |
| 54 | ArchiveProps, |
| 55 | { |
| 56 | /** Server-assigned ID of the archive. */ |
| 57 | archiveId: string; |
| 58 | /** ARN of the archive. */ |
| 59 | archiveArn: string; |
| 60 | /** Name of the archive. */ |
| 61 | archiveName: string; |
| 62 | /** Current state (ACTIVE or PENDING_DELETION). */ |
| 63 | archiveState: string | undefined; |
| 64 | }, |
| 65 | never, |
| 66 | Providers |
| 67 | > {} |
| 68 | |
| 69 | /** |
| 70 | * An SES Mail Manager email archive — durable storage for emails captured |
| 71 | * by an `Archive` rule action, searchable and exportable for compliance. |
| 72 | * |
| 73 | * Deleting an archive puts it into `PENDING_DELETION` for 30 days before |
| 74 | * its contents are permanently removed; the archive cannot be revived, so |
| 75 | * the provider treats a pending-deletion archive as gone. |
| 76 | * ### Creating Archives |
| 77 | * **Example:** Compliance Archive |
| 78 | * ```typescript |
| 79 | * import * as MailManager from "@alchemy.run/aws/MailManager"; |
| 80 | * |
| 81 | * const archive = yield* MailManager.Archive("Compliance", { |
| 82 | * retentionPeriod: "ONE_YEAR", |
| 83 | * }); |
| 84 | * |
| 85 | * const ruleSet = yield* MailManager.RuleSet("Inbound", { |
| 86 | * rules: [ |
| 87 | * { |
| 88 | * Name: "ArchiveAll", |
| 89 | * Actions: [{ Archive: { TargetArchive: archive.archiveId } }], |
| 90 | * }, |
| 91 | * ], |
| 92 | * }); |
| 93 | * ``` |
| 94 | * |
| 95 | * ### Searching the Archive at Runtime |
| 96 | * **Example:** Search Archived Mail from a Lambda |
| 97 | * ```typescript |
| 98 | * // init — bind the search capabilities to the archive |
| 99 | * const startSearch = yield* MailManager.StartArchiveSearch(archive); |
| 100 | * const getSearchResults = yield* MailManager.GetArchiveSearchResults(archive); |
| 101 | * |
| 102 | * // runtime |
| 103 | * const { SearchId } = yield* startSearch({ |
| 104 | * FromTimestamp: new Date(Date.now() - 86_400_000), |
| 105 | * ToTimestamp: new Date(), |
| 106 | * MaxResults: 100, |
| 107 | * }); |
| 108 | * ``` |
| 109 | * |
| 110 | * @resource |
| 111 | */ |
| 112 | export const Archive = Resource<Archive>("AWS.MailManager.Archive"); |
| 113 | |
| 114 | export const ArchiveProvider = () => |
| 115 | Provider.effect( |
| 116 | Archive, |
| 117 | Effect.gen(function* () { |
| 118 | const createName = Effect.fn(function* (id: string, props: { archiveName?: string }) { |
| 119 | return props.archiveName ?? (yield* createPhysicalName({ id, maxLength: 64 })); |
| 120 | }); |
| 121 | |
| 122 | // A PENDING_DELETION archive is irrevocably deleted (contents already |
| 123 | // inaccessible) — treat it as gone everywhere. |
| 124 | const getById = (archiveId: string) => |
| 125 | mm.getArchive({ ArchiveId: archiveId }).pipe( |
| 126 | Effect.map((a) => (a.ArchiveState === "PENDING_DELETION" ? undefined : a)), |
| 127 | Effect.catchTag("ResourceNotFoundException", () => Effect.undefined), |
| 128 | ); |
| 129 | |
| 130 | // Archives have no name-keyed Get — enumerate and match, skipping |
| 131 | // tombstones in PENDING_DELETION. |
| 132 | const findByName = (name: string) => |
| 133 | mm.listArchives.pages({}).pipe( |
| 134 | Stream.runCollect, |
| 135 | Effect.map((chunk) => |
| 136 | Array.from(chunk) |
| 137 | .flatMap((page) => page.Archives ?? []) |
| 138 | .find((a) => a.ArchiveName === name && a.ArchiveState !== "PENDING_DELETION"), |
| 139 | ), |
| 140 | ); |
| 141 | |
| 142 | const observe = Effect.fn(function* ( |
| 143 | output: Archive["Attributes"] | undefined, |
| 144 | name: string, |
| 145 | ) { |
| 146 | if (output?.archiveId !== undefined) { |
| 147 | const found = yield* getById(output.archiveId); |
| 148 | if (found !== undefined) return found; |
| 149 | } |
| 150 | const summary = yield* findByName(name); |
| 151 | if (summary?.ArchiveId === undefined) return undefined; |
| 152 | return yield* getById(summary.ArchiveId); |
| 153 | }); |
| 154 | |
| 155 | const toAttrs = (archive: mm.GetArchiveResponse) => ({ |
| 156 | archiveId: archive.ArchiveId, |
| 157 | archiveArn: archive.ArchiveArn, |
| 158 | archiveName: archive.ArchiveName, |
| 159 | archiveState: archive.ArchiveState, |
| 160 | }); |
| 161 | |
| 162 | return Archive.Provider.of({ |
| 163 | stables: ["archiveId", "archiveArn"], |
| 164 | |
| 165 | list: () => |
| 166 | mm.listArchives.pages({}).pipe( |
| 167 | Stream.runCollect, |
| 168 | Effect.flatMap((chunk) => |
| 169 | Effect.forEach( |
| 170 | Array.from(chunk) |
| 171 | .flatMap((page) => page.Archives ?? []) |
| 172 | .filter((a) => a.ArchiveState !== "PENDING_DELETION") |
| 173 | .map((a) => a.ArchiveId), |
| 174 | (archiveId) => getById(archiveId), |
| 175 | ), |
| 176 | ), |
| 177 | Effect.map((results) => results.flatMap((a) => (a === undefined ? [] : [toAttrs(a)]))), |
| 178 | ), |
| 179 | |
| 180 | read: Effect.fn(function* ({ id, olds, output }) { |
| 181 | const name = output?.archiveName ?? (yield* createName(id, olds ?? {})); |
| 182 | const archive = yield* observe(output, name); |
| 183 | if (archive === undefined) return undefined; |
| 184 | const attrs = toAttrs(archive); |
| 185 | const tags = yield* readMailManagerTags(attrs.archiveArn); |
| 186 | return (yield* hasAlchemyTags(id, tags)) ? attrs : Unowned(attrs); |
| 187 | }), |
| 188 | |
| 189 | // The KMS key is create-only — changing it replaces the archive. |
| 190 | // Name and retention update in place via UpdateArchive. |
| 191 | diff: Effect.fn(function* ({ news, olds }) { |
| 192 | if (!isResolved(news)) return undefined; |
| 193 | if (olds === undefined) return undefined; |
| 194 | if (olds.kmsKeyArn !== news.kmsKeyArn) { |
| 195 | return { action: "replace" } as const; |
| 196 | } |
| 197 | }), |
| 198 | |
| 199 | reconcile: Effect.fn(function* ({ id, news, output, session }) { |
| 200 | const name = yield* createName(id, news); |
| 201 | const internalTags = yield* createInternalTags(id); |
| 202 | const desiredTags = { ...news.tags, ...internalTags }; |
| 203 | const desiredRetention: mm.RetentionPeriod = news.retentionPeriod ?? "PERMANENT"; |
| 204 | |
| 205 | // 1. OBSERVE — cloud state is authoritative; output is an id cache. |
| 206 | let archive = yield* observe(output, name); |
| 207 | |
| 208 | // 2. ENSURE — create if missing; a Conflict race re-observes by |
| 209 | // name instead of failing. |
| 210 | if (archive === undefined) { |
| 211 | yield* session.note(`creating archive ${name}`); |
| 212 | const created = yield* mm |
| 213 | .createArchive({ |
| 214 | ArchiveName: name, |
| 215 | Retention: { RetentionPeriod: desiredRetention }, |
| 216 | KmsKeyArn: news.kmsKeyArn, |
| 217 | Tags: createTagsList(desiredTags), |
| 218 | }) |
| 219 | .pipe(Effect.catchTag("ConflictException", () => Effect.undefined)); |
| 220 | archive = |
| 221 | created !== undefined |
| 222 | ? yield* getById(created.ArchiveId) |
| 223 | : yield* observe(undefined, name); |
| 224 | } |
| 225 | if (archive === undefined) { |
| 226 | return yield* new MailManagerArchiveUnexpectedResponse({ |
| 227 | message: `Mail Manager archive '${name}' not found after create`, |
| 228 | }); |
| 229 | } |
| 230 | |
| 231 | // 3. SYNC — diff OBSERVED name/retention against desired; apply |
| 232 | // only the delta. |
| 233 | if ( |
| 234 | archive.ArchiveName !== name || |
| 235 | archive.Retention?.RetentionPeriod !== desiredRetention |
| 236 | ) { |
| 237 | yield* mm.updateArchive({ |
| 238 | ArchiveId: archive.ArchiveId, |
| 239 | ArchiveName: name, |
| 240 | Retention: { RetentionPeriod: desiredRetention }, |
| 241 | }); |
| 242 | archive = (yield* getById(archive.ArchiveId)) ?? archive; |
| 243 | } |
| 244 | |
| 245 | // 3b. SYNC TAGS — against observed cloud tags. |
| 246 | yield* syncMailManagerTags(archive.ArchiveArn, desiredTags); |
| 247 | |
| 248 | yield* session.note(archive.ArchiveId); |
| 249 | return { ...toAttrs(archive), archiveName: name }; |
| 250 | }), |
| 251 | |
| 252 | delete: Effect.fn(function* ({ output }) { |
| 253 | // DeleteArchive's error union carries no not-found tag — deletion |
| 254 | // is natively idempotent (the archive moves to PENDING_DELETION). |
| 255 | // An in-flight search or export reports Conflict — retry through. |
| 256 | yield* retryWhileMailManagerConflict( |
| 257 | mm.deleteArchive({ ArchiveId: output.archiveId }), |
| 258 | ).pipe(Effect.asVoid); |
| 259 | }), |
| 260 | }); |
| 261 | }), |
| 262 | ); |