Public: anyone can read this; the crew can change it.
Show which app a cloud resource is part of, and find by it with app: #17642
Merged 20h 49m ago, live in production
sold/part-of → main 0 commits
17 files
changed +528
−49
- docs/CLOUD.md
- docs/features/infra.md
- src/cloud/aws_call.ts
- src/cloud/aws_part_of.ts
- src/cloud/aws_read.ts
- src/cloud/inventory.ts
- src/cloud/projects.ts
- src/cloud/tree.ts
- src/core/migration-pins/20261202200219-cloud-part-of.pin
- src/core/migrations/20261202200219-cloud-part-of.ts
- src/http/mcp/tools/infra.ts
- src/tui/screens/cloudtree.ts
- src/web/pages/cloud_tree.ts
- test/cloud-inventory.test.ts
- test/cloud-part-of.test.ts
- test/cloud-tree.test.ts
- test/helpers/recorded-aws.ts
docs/CLOUD.md +2 −1
| @@ -75,7 +75,7 @@ an agent's own vendor calls beyond the hand-out are not metered. A forge admin r | ||
| 75 | 75 | |
| 76 | 76 | ## What is read of an account (#17532) |
| 77 | 77 | |
| 78 | A duty reads DigitalOcean and Hetzner every 5 minutes, and AWS and Cloudflare every 6 hours (about 250 audited calls for a whole AWS account); **Read now** on /infra reads all of them at once. Every call is a read through the gate. `src/cloud/projects.ts` keeps it, and every page and tool reads what was kept. | |
| 78 | A duty reads DigitalOcean and Hetzner every 5 minutes, and AWS and Cloudflare every 6 hours (about 320 audited calls for a whole AWS account, and one more for each CloudFormation stack); **Read now** on /infra reads all of them at once. Every call is a read through the gate. `src/cloud/projects.ts` keeps it, and every page and tool reads what was kept. | |
| 79 | 79 | |
| 80 | 80 | - **AWS** (`src/cloud/aws_read.ts`). Attach `ACCESS_KEY_ID:SECRET_ACCESS_KEY`, or with `:SESSION_TOKEN` for a temporary key, of an IAM user that holds only the AWS managed policies ViewOnlyAccess and AWSBillingReadOnlyAccess. A project is a region the account has enabled, plus `global`. Read in each region: EC2 instances, EBS volumes, own snapshots and AMIs, Elastic IPs, NAT gateways, load balancers, RDS instances and snapshots (instance and cluster), log groups, Lambda functions, DynamoDB tables, ECR repositories, ECS clusters, services and running tasks (a task's launch type, vCPU and memory, and the service it is of; its environment overrides are not kept). In `global`: S3 buckets and Route 53 zones. Each keeps its state and what uses it. GovCloud and China are not read. |
| 81 | 81 | - **Cloudflare** (`src/cloud/cloudflare_read.ts`). A project is a Cloudflare account: zones, R2 buckets (the default jurisdiction), Workers and Pages projects, as the token's permissions allow (Zone Read, Workers R2 Storage Read, Workers Scripts Read, Pages Read; Account Settings Read to list the accounts). R2's code 10042 (no R2 subscription) is a fact about the account with no buckets, not a gap, unless buckets were seen there before: those are kept, as a gap. |
| @@ -85,6 +85,7 @@ A duty reads DigitalOcean and Hetzner every 5 minutes, and AWS and Cloudflare ev | ||
| 85 | 85 | - **Where those prices are from.** Files AWS serves without a key, so none is sent: the documented price list (`pricing.us-east-1.amazonaws.com`) for public IPv4, load balancers and RDS, and the files AWS's own pricing pages draw from (`b0.p.awsstatic.com`, **not documented**, so AWS may change them) for EBS, NAT gateways and Linux instances, since the price list's EC2 file is over 300 MB. A region's name in them is read from the documented list. The documented alternative is the signed `GetProducts` of AWS's Price List Query API: a read that needs one more IAM permission, `pricing:GetProducts`, which neither managed policy holds. AWS has said it is free ("at no charge", AWS News Blog, 2017-11-06; "all pricing API calls are free of charge", AWS Cloud Financial Management blog, 2025-07-15); no current AWS pricing page was found that says so. It is not built. A file is read only for a region with something it prices, and again after 7 days (a failed one after an hour at the soonest); what was kept stays, with its age and the failure (`listed.failing`), and is null 30 days after it was read, whether or not the account has been read since. The inventory waits 60 seconds at most for all of them. RDS's file is 5 to 20 MB a region and is read a line at a time. `forge.json` names neither host, so a forge in a cell has no AWS list prices: its gate refuses both at once, and each resource says so (`unpricedWhy`). |
| 86 | 86 | - **What an undocumented figure is checked for.** US dollars, the region's name, the on-demand term, and its size: an EBS or NAT rate within three times the lowest and highest of AWS's regions on 2026-12-02, and a Linux instance's price a vCPU within bounds for its type and for the file's middle. A figure that fails one is null, with the reason in `CloudResource.unpricedWhy`, and the file's others stand. A file with no figure left is a failed read. A wrong figure within those bounds is not caught: no documented file small enough to read prices the same things. `listed.source` names whose file a price is from. |
| 87 | 87 | - **Names.** A project's or resource's name is kept as its owner wrote it, 120 characters at most, with control, bidi and other unseen characters as U+FFFD (`nameText`, `src/cloud/watch.ts`). Pages escape it, a talk fences it, and a sentence quotes it. The hourly watch's names go into issue bodies and notifications, so those keep plain characters alone. |
| 88 | - **Part of** (`src/cloud/aws_part_of.ts`). The app an AWS resource is part of, and how that is known (`partOf: { app, by }`, null when it is not). First the CloudFormation stack that lists it (ListStacks and ListStackResources, 200 calls a region at most; a nested stack's things are the topmost's), then its tags (`sst:app` and `sst:stage`, else `aws:cloudformation:stack-name`), then what it serves, only when all of that is known and agrees: a disk its machines, a snapshot its volume, an address its machine, NAT gateway, task or balancer, a task its service, a cluster or balancer its services. `by` then says "through its balancer". Two stacks that claim one thing, or a name that only looks alike, are not known. ViewOnlyAccess has every call; it lacks the tag reads for balancers, buckets, functions and log groups, so those have an app from a stack (or a balancer through its services) alone. Being part of an app is never a reason to delete: a stack can hold data meant to outlive it. **What it cannot see** (read from the code, not tested on a live account): what a machine serves, since instance targets and ECS container instances are not read, so a machine behind an app's balancer can have no app here, and so can its disks and addresses. Nor does it see what a stack kept when it let go of it or was deleted, a thing a stack is still making, tags other than SST's and CloudFormation's (EKS, Karpenter, Elastic Beanstalk or a person's own), whose an address is that AWS manages for a service, the images that use a snapshot, or a snapshot's volume once it is gone. A kind that could not be read keeps its older answer, so no app found never means that nothing uses a thing. | |
| 88 | 89 | - **Hosts.** `src/cloud/aws_call.ts` builds each AWS host from a fixed list of services and a checked region name, refuses a redirect, and refuses any operation not named Describe, List or Get. `forge.json` names three exact AWS hosts and no `*.amazonaws.com`, since strangers' machines, buckets and load balancers are below that name. So a forge running in a cell (a preview) can check a key, list its regions, and read us-east-1's EC2 and the bill; every other read there is refused and kept as a gap. A forge that is not in a cell is not held by `forge.json`. |
| 89 | 90 | |
| 90 | 91 | ## OVHcloud US as a pinned-forge target (#16556) |
docs/features/infra.md +3 −3
| @@ -96,10 +96,10 @@ Every DigitalOcean and Hetzner account is read into provider ▸ account ▸ pro | ||
| 96 | 96 | |
| 97 | 97 | /infra leads with what every cloud costs a month and draws one tree: cloud ▸ account ▸ project or region ▸ resource, the costliest first, the cost rolled up at each level (`src/cloud/tree.ts`, pure; `src/web/pages/cloud_tree.ts`). It is the code browser's column and script. A page reads the database alone, never a provider, and nothing in it changes a resource. |
| 98 | 98 | |
| 99 | - **Cost.** An AWS region, account and cloud show the last whole month billed; everything else is a list price. A bill stands in for its resources' prices and is never added to them. The total says it in words ("November's AWS bill, list prices for the rest, 2 things without a price"). In a row a bill is unmarked, `list` is a list price, `≥` means part has no price, and `–` means no price of its own: never $0. A screen reader hears each in full. Under a filter the headline is what was found ("10 unused volumes") and only resources' own prices are added. | |
| 99 | - **Cost.** An AWS region, account and cloud show the last whole month billed; everything else is a list price. A bill stands in for its resources' prices and is never added to them. The total says it in words ("November's AWS bill, list prices for the rest, 2 things without a price"). In a row a bill is unmarked, `list` is a list price, `≥` means part has no price, and `–` means no price of its own: never $0. A screen reader hears each in full. Under a filter the headline is what was found ("10 unattached volumes") and only resources' own prices are added. | |
| 100 | 100 | - **With nothing open** the pane is where the money goes, then what the forge runs; under a filter it is the matches. **Build** (`c`) is `/infra/build`: the compose form, a build's progress (`?plan=`), a DNS record, the code it is kept as and the pinned forges. `/pinned` redirects there, and so does `/infra?plan=`. |
| 101 | - **Filter.** `/`, then `kind:volume cloud:aws attached:no cost:>10 text`. Properties: kind, cloud, account, project, region, size, name, state, attached, made, for, cost. `!` negates, a comma means any of, `cost:unknown` is a value. It is in the URL as `?q=`. | |
| 102 | - **A resource** is at `/infra/-/<cloud>/<account>/<project>/<id>`, beside the tree, or full width on a phone: cost, state, what it is attached to and what it holds, an AWS list price's day, what it leaves out and whose file it is (or why there is none), what it was made from, who made it, when it was read, and Ask about this (a talk with those facts, fenced as data). | |
| 101 | - **Filter.** `/`, then `kind:volume cloud:aws attached:no cost:>10 text`. Properties: kind, cloud, account, project, region, size, name, state, attached, made, for, app, cost. `!` negates, a comma means any of, `cost:unknown` is a value, and `app:unknown` finds what has no app known, on any cloud, which does not mean nothing uses it. It is in the URL as `?q=`. | |
| 102 | - **A resource** is at `/infra/-/<cloud>/<account>/<project>/<id>`, beside the tree, or full width on a phone: cost, state, what it is attached to and what it holds, an AWS list price's day, what it leaves out and whose file it is (or why there is none), the app an AWS resource is part of and how that is known (nothing when it is not), what it was made from, who made it, when it was read, and Ask about this (a talk with those facts, fenced as data). | |
| 103 | 103 | - **Keys.** j and k move, Enter opens, h and l (or the arrows) close and open, `/` filters and Enter goes to the first match. |
| 104 | 104 | - **States.** No account (a link to /settings/cloud), not read yet, a failed read (one line: when, why, and how old what is shown is), a kind that could not be read with its reason (on its project and on the account, which says where; under the headline's sum, "Not everything is listed: 1 kind not read" links to that account, and text doors name it; a billed account's gaps count too, and change no sum), and a reading older than three of its duty's intervals. A project's note ("R2 is not switched on for this account") is a plain line and no trouble, on its account too when that has one project. |
| 105 | 105 | - **Terminal.** `:` then Cloud resources, or `/` in Infra (`src/tui/screens/cloudtree.ts`): the same list, filter and facts, the List price, Old price, Price from and No price lines among them (both read `factsOf`); `tab` changes pane, `w` opens the web page, `P` reads every account. |
src/cloud/aws_call.ts +1
| @@ -24,6 +24,7 @@ const HOST = { | ||
| 24 | 24 | lambda: (r: string) => `lambda.${r}.amazonaws.com`, |
| 25 | 25 | dynamodb: (r: string) => `dynamodb.${r}.amazonaws.com`, |
| 26 | 26 | ecr: (r: string) => `api.ecr.${r}.amazonaws.com`, |
| 27 | cloudformation: (r: string) => `cloudformation.${r}.amazonaws.com`, | |
| 27 | 28 | ecs: (r: string) => `ecs.${r}.amazonaws.com`, |
| 28 | 29 | s3: (r: string) => `s3.${r}.amazonaws.com`, |
| 29 | 30 | sts: () => "sts.amazonaws.com", |
src/cloud/aws_part_of.ts added +171
| @@ -0,0 +1,171 @@ | ||
| 1 | /** | |
| 2 | * Which app an AWS resource is part of (#17532), from what AWS states and never from how a name | |
| 3 | * looks. In this order: the CloudFormation stack that lists it, the tags SST and CloudFormation put | |
| 4 | * on it, then what it serves (a disk its machine, an address its balancer), only when every one of | |
| 5 | * those is known and they agree. Anything else is not known. `by` says which, so what was only | |
| 6 | * reached through a neighbour never reads as stated of the thing itself. | |
| 7 | * | |
| 8 | * It is never a reason to delete: a stack can hold data that was meant to outlive it. | |
| 9 | */ | |
| 10 | ||
| 11 | import type { Call } from "./aws_read.ts"; | |
| 12 | import { items, listed, parseXml, val, type Xml } from "./aws_xml.ts"; | |
| 13 | import { Reasoned, exactId, reasonOf, type Found, type PartOf } from "./inventory.ts"; | |
| 14 | import { nameText } from "./watch.ts"; | |
| 15 | ||
| 16 | /** What a thing's own answer says towards its app, beside what is kept of it. */ | |
| 17 | export interface Clues { | |
| 18 | /** From its tags; empty when they name none. */ | |
| 19 | readonly app?: string; | |
| 20 | /** The network interfaces that are its own. */ | |
| 21 | readonly cards?: readonly string[]; | |
| 22 | /** The target groups a service fills. */ | |
| 23 | readonly groups?: readonly string[]; | |
| 24 | } | |
| 25 | export type Clued = Omit<Found, "project"> & { readonly clues?: Clues }; | |
| 26 | ||
| 27 | /** The app a thing's tags name: SST's app and stage, else its CloudFormation stack. */ | |
| 28 | export function taggedApp(tag: (key: string) => string): string { | |
| 29 | const [app, stage] = [tag("sst:app"), tag("sst:stage")]; | |
| 30 | return nameText(app === "" ? tag("aws:cloudformation:stack-name") : stage === "" ? app : `${app}/${stage}`); | |
| 31 | } | |
| 32 | ||
| 33 | /** The most calls a region's stacks are read with: one lists them, and each is asked what it owns. */ | |
| 34 | const STACK_CALLS = 200; | |
| 35 | const CFN = "2010-05-15"; | |
| 36 | ||
| 37 | /** A thing a stack lists, as the forge names it, for each type whose id CloudFormation gives whole. */ | |
| 38 | const OWNED: Readonly<Record<string, (id: string, region: string) => string>> = { | |
| 39 | "AWS::EC2::Instance": (id) => `machine:${id}`, | |
| 40 | "AWS::EC2::Volume": (id) => `volume:${id}`, | |
| 41 | "AWS::EC2::NatGateway": (id) => `nat:${id}`, | |
| 42 | // Its public address, not its allocation. | |
| 43 | "AWS::EC2::EIP": (id) => `address:${id}`, | |
| 44 | "AWS::ElasticLoadBalancingV2::LoadBalancer": (id) => `balancer:${id}`, | |
| 45 | "AWS::ElasticLoadBalancing::LoadBalancer": (id, r) => `balancer:${r}/${id}`, | |
| 46 | "AWS::RDS::DBInstance": (id, r) => `database:${r}/${id.toLowerCase()}`, | |
| 47 | "AWS::Logs::LogGroup": (id, r) => `logs:${r}/${id}`, | |
| 48 | "AWS::Lambda::Function": (id, r) => `function:${r}/${id}`, | |
| 49 | "AWS::DynamoDB::Table": (id, r) => `table:${r}/${id}`, | |
| 50 | "AWS::DynamoDB::GlobalTable": (id, r) => `table:${r}/${id}`, | |
| 51 | "AWS::ECR::Repository": (id, r) => `registry:${r}/${id}`, | |
| 52 | "AWS::ECS::Cluster": (id, r) => `cluster:${r}/${id}`, | |
| 53 | // An ARN, which names the cluster only in its long form. | |
| 54 | "AWS::ECS::Service": (id, r) => `service:${r}/${/:service\/([^/]+\/[^/]+)$/.exec(id)?.[1] ?? ""}`, | |
| 55 | "AWS::S3::Bucket": (id) => `bucket:${id}`, | |
| 56 | "AWS::Route53::HostedZone": (id) => `zone:${id}`, | |
| 57 | }; | |
| 58 | ||
| 59 | export interface Owned { | |
| 60 | readonly id: string; | |
| 61 | readonly app: string; | |
| 62 | } | |
| 63 | ||
| 64 | /** | |
| 65 | * What a region's stacks own. A nested stack's things are its topmost stack's. What was read before | |
| 66 | * a refusal or the cap still stands, and `short` says why there is no more; a thing the stack no | |
| 67 | * longer manages (deleted, or kept when it was dropped) is not its own. | |
| 68 | */ | |
| 69 | export async function readStacks(call: Call, region: string): Promise<{ readonly owned: Owned[]; readonly short: string }> { | |
| 70 | let left = STACK_CALLS; | |
| 71 | const every = async (action: string, list: string, params: Record<string, string>): Promise<Xml[]> => { | |
| 72 | const out: Xml[] = []; | |
| 73 | for (let token = ""; ; ) { | |
| 74 | if (left-- <= 0) throw new Reasoned(`more than ${STACK_CALLS} calls to list what CloudFormation stacks own: the rest were not read`); | |
| 75 | const x = parseXml(await call("cloudformation", region, { action, version: CFN, params: { ...params, ...(token === "" ? {} : { NextToken: token }) } })); | |
| 76 | out.push(...listed(x, `${action}Result/${list}`)); | |
| 77 | token = val(x, `${action}Result/NextToken`); | |
| 78 | if (token === "") return out; | |
| 79 | } | |
| 80 | }; | |
| 81 | const owned: Owned[] = []; | |
| 82 | try { | |
| 83 | for (const s of await every("ListStacks", "StackSummaries", {})) { | |
| 84 | if (val(s, "StackStatus") === "DELETE_COMPLETE") continue; | |
| 85 | const app = nameText(val(s, "RootId").split("/")[1] ?? val(s, "StackName")); | |
| 86 | for (const r of await every("ListStackResources", "StackResourceSummaries", { StackName: val(s, "StackId") })) { | |
| 87 | const [id, name] = [val(r, "PhysicalResourceId"), OWNED[val(r, "ResourceType")]]; | |
| 88 | if (id !== "" && name !== undefined && !/^DELETE_(COMPLETE|SKIPPED)$/.test(val(r, "ResourceStatus"))) owned.push({ id: exactId(name(id, region)), app }); | |
| 89 | } | |
| 90 | } | |
| 91 | return { owned, short: "" }; | |
| 92 | } catch (e) { | |
| 93 | return { owned, short: reasonOf(e, "cloudformation:ListStacks and cloudformation:ListStackResources") }; | |
| 94 | } | |
| 95 | } | |
| 96 | ||
| 97 | /** Each target group's balancers, by ARN. */ | |
| 98 | export const groupsOf = (groups: readonly Xml[]): Map<string, string[]> => | |
| 99 | new Map(groups.map((g) => [val(g, "TargetGroupArn"), items(g, "LoadBalancerArns").map((a) => a.text.trim())])); | |
| 100 | ||
| 101 | /** | |
| 102 | * The balancer each of AWS's own interfaces is for. AWS writes "ELB app/<name>/<id>" in their | |
| 103 | * description, which its reference does not promise, so it counts only where it is the end of a | |
| 104 | * balancer's own ARN, id and all; a description a person wrote never does. | |
| 105 | */ | |
| 106 | export function balancerCards(cards: readonly Xml[], balancers: readonly string[]): Map<string, string> { | |
| 107 | const ends = new Map(balancers.map((arn) => [`ELB ${arn.split(":loadbalancer/")[1] ?? ""}`, `balancer:${exactId(arn)}`])); | |
| 108 | return new Map( | |
| 109 | cards.flatMap((c) => { | |
| 110 | const to = val(c, "requesterManaged") === "true" ? ends.get(val(c, "description")) : undefined; | |
| 111 | return to === undefined ? [] : [[val(c, "networkInterfaceId"), to] as const]; | |
| 112 | }), | |
| 113 | ); | |
| 114 | } | |
| 115 | ||
| 116 | const WORD: Readonly<Record<string, string>> = { nat: "NAT gateway" }; | |
| 117 | const keyOf = (t: Clued): string => `${t.kind}:${t.id}`; | |
| 118 | ||
| 119 | /** | |
| 120 | * Each thing's app, by its `<kind>:<id>`; one that is not known is not in it. `groups` and `cards` | |
| 121 | * are what was read of target groups and of balancers' interfaces. | |
| 122 | */ | |
| 123 | export function partsOf(things: readonly Clued[], owned: readonly Owned[], groups: ReadonlyMap<string, readonly string[]>, cards: ReadonlyMap<string, string>): Map<string, PartOf> { | |
| 124 | const stacks = new Map<string, Set<string>>(); | |
| 125 | for (const o of owned) stacks.set(o.id, (stacks.get(o.id) ?? new Set()).add(o.app)); | |
| 126 | const out = new Map<string, PartOf>(); | |
| 127 | const open = new Map<string, readonly string[]>(); | |
| 128 | ||
| 129 | const holder = new Map(cards); | |
| 130 | const fills = new Map<string, string[]>(); | |
| 131 | for (const t of things) { | |
| 132 | for (const c of t.clues?.cards ?? []) holder.set(c, keyOf(t)); | |
| 133 | for (const g of t.clues?.groups ?? []) fills.set(g, [...(fills.get(g) ?? []), keyOf(t)]); | |
| 134 | } | |
| 135 | const behind = new Map<string, string[]>(); | |
| 136 | const add = (of: string, ids: readonly string[]): void => void behind.set(of, [...(behind.get(of) ?? []), ...ids]); | |
| 137 | // A target group no service fills sends traffic to something not read: an end that is not known. | |
| 138 | for (const [group, arns] of groups) for (const arn of arns) add(`balancer:${exactId(arn)}`, fills.get(group) ?? [group]); | |
| 139 | for (const t of things) if (t.kind === "service" || t.kind === "task") add(`cluster:${t.id.slice(0, t.id.lastIndexOf("/"))}`, [keyOf(t)]); | |
| 140 | ||
| 141 | for (const t of things) { | |
| 142 | const own = stacks.get(keyOf(t)) ?? (t.kind === "address" ? stacks.get(`address:${t.size}`) : undefined); | |
| 143 | const tagged = t.clues?.app ?? ""; | |
| 144 | if (own !== undefined) { | |
| 145 | // Two stacks that both claim it settle nothing, and no neighbour may settle it for them. | |
| 146 | if (own.size === 1) out.set(keyOf(t), { app: [...own][0]!, by: "its CloudFormation stack" }); | |
| 147 | } else if (tagged !== "") out.set(keyOf(t), { app: tagged, by: "its tags" }); | |
| 148 | else { | |
| 149 | const on = t.kind === "snapshot" || t.kind === "database-snapshot" ? [t.madeFrom].filter((m) => m !== "") : t.kind === "image" ? [] : (t.attachedTo ?? []); | |
| 150 | const ends = [...on.map((id) => (id.startsWith("interface:") ? (holder.get(id.slice("interface:".length)) ?? id) : id)), ...(behind.get(keyOf(t)) ?? [])]; | |
| 151 | if (ends.length > 0) open.set(keyOf(t), ends); | |
| 152 | } | |
| 153 | } | |
| 154 | // An address is its balancer's, which is its service's: each round sees only the one before it. | |
| 155 | for (let found = 1; found > 0; ) { | |
| 156 | const next: [string, PartOf][] = []; | |
| 157 | for (const [id, ends] of open) { | |
| 158 | const apps = new Set(ends.map((e) => out.get(e)?.app)); | |
| 159 | const app = [...apps][0]; | |
| 160 | if (apps.size !== 1 || app === undefined) continue; | |
| 161 | const kinds = [...new Set(ends.map((e) => e.slice(0, e.indexOf(":"))))].map((k) => `${WORD[k] ?? k}${ends.filter((e) => e.startsWith(`${k}:`)).length > 1 ? "s" : ""}`); | |
| 162 | next.push([id, { app, by: `through its ${kinds.join(" and ")}` }]); | |
| 163 | } | |
| 164 | for (const [id, p] of next) { | |
| 165 | out.set(id, p); | |
| 166 | open.delete(id); | |
| 167 | } | |
| 168 | found = next.length; | |
| 169 | } | |
| 170 | return out; | |
| 171 | } |
src/cloud/aws_read.ts +54 −14
| @@ -11,10 +11,11 @@ | ||
| 11 | 11 | */ |
| 12 | 12 | |
| 13 | 13 | import { AWS_REGION, AwsRefused, awsCall, type AwsAsk, type AwsService } from "./aws_call.ts"; |
| 14 | import { balancerCards, groupsOf, partsOf, readStacks, taggedApp, type Clued, type Clues, type Owned } from "./aws_part_of.ts"; | |
| 14 | 15 | import type { AwsKey } from "./aws_sign.ts"; |
| 15 | 16 | import { addressTerms, balancerTerms, databaseTerms, machineTerms, natTerms, volumeTerms, zonesOf } from "./aws_terms.ts"; |
| 16 | 17 | import { items, listed, parseXml, val, type Xml } from "./aws_xml.ts"; |
| 17 | import { Reasoned, exactId, reasonOf, type Found, type Gap, type Inventory, type ResourceKind } from "./inventory.ts"; | |
| 18 | import { Reasoned, exactId, reasonOf, type Gap, type Inventory, type ResourceKind } from "./inventory.ts"; | |
| 18 | 19 | import type { Fetch } from "./providers.ts"; |
| 19 | 20 | import { nameText, text } from "./watch.ts"; |
| 20 | 21 | |
| @@ -25,9 +26,9 @@ const MAX_PAGES = 100; | ||
| 25 | 26 | /** The key itself is refused, so no other call would answer differently. */ |
| 26 | 27 | const BAD_KEY = /^(AuthFailure|InvalidClientTokenId|UnrecognizedClientException|ExpiredToken|ExpiredTokenException|RequestExpired|SignatureDoesNotMatch)$/; |
| 27 | 28 | |
| 28 | type Call = (service: AwsService, region: string, ask: AwsAsk) => Promise<string>; | |
| 29 | export type Call = (service: AwsService, region: string, ask: AwsAsk) => Promise<string>; | |
| 29 | 30 | /** A thing before its region's links are drawn: an image also names the snapshots it stands on. */ |
| 30 | type Part = Omit<Found, "project"> & { readonly on?: readonly string[] }; | |
| 31 | type Part = Clued & { readonly on?: readonly string[] }; | |
| 31 | 32 | |
| 32 | 33 | const EC2 = "2016-11-15"; |
| 33 | 34 | const RDS = "2014-10-31"; |
| @@ -86,7 +87,11 @@ const tagOf = (x: Xml, key: string): string => { | ||
| 86 | 87 | const value = val(items(x, "tagSet").find((t) => val(t, "key") === key) ?? x, "value"); |
| 87 | 88 | return key === "Name" ? nameText(value) : text(value, 40); |
| 88 | 89 | }; |
| 89 | const ec2Tags = (x: Xml): { name: string; label: string } => ({ name: tagOf(x, "Name"), label: tagOf(x, "forge") }); | |
| 90 | /** The app a thing's tags name, from a list of key and value: `tagSet` in EC2, `TagList` in RDS. */ | |
| 91 | const xmlApp = (x: Xml, list: string, key: string, value: string): string => taggedApp((k) => val(items(x, list).find((t) => val(t, key) === k) ?? x, value)); | |
| 92 | const ec2Tags = (x: Xml): { name: string; label: string; clues: Clues } => ({ name: tagOf(x, "Name"), label: tagOf(x, "forge"), clues: { app: xmlApp(x, "tagSet", "key", "value") } }); | |
| 93 | /** The same from ECS, whose tags are JSON. */ | |
| 94 | const ecsApp = (x: any): string => taggedApp((k) => String((Array.isArray(x.tags) ? x.tags : []).find((t: any) => t?.key === k)?.value ?? "")); | |
| 90 | 95 | |
| 91 | 96 | const binary = (bytes: number): string => { |
| 92 | 97 | const units = ["B", "KiB", "MiB", "GiB", "TiB"]; |
| @@ -156,7 +161,7 @@ async function ecsAll(call: Call, region: string, what: "cluster" | "service" | | ||
| 156 | 161 | const arns = await json((t) => ecs(call, region, `List${operation}`, { ...inside, maxResults: 100, ...t }), `${what}Arns`, "nextToken", "nextToken"); |
| 157 | 162 | const out: any[] = []; |
| 158 | 163 | for (let i = 0; i < arns.length; i += most) { |
| 159 | const body: any = JSON.parse(await ecs(call, region, `Describe${operation}`, { ...inside, [many]: arns.slice(i, i + most) })); | |
| 164 | const body: any = JSON.parse(await ecs(call, region, `Describe${operation}`, { ...inside, include: ["TAGS"], [many]: arns.slice(i, i + most) })); | |
| 160 | 165 | if (!Array.isArray(body?.[many])) throw new Error(`the answer held no ${many}`); |
| 161 | 166 | if ((body.failures ?? []).some((x: any) => x?.reason !== "MISSING")) throw new Error("ECS could not describe all it listed: not read whole"); |
| 162 | 167 | out.push(...body[many]); |
| @@ -193,7 +198,7 @@ const REGIONAL: readonly { readonly kind: ResourceKind; readonly needs: string; | ||
| 193 | 198 | read: async (call, region) => |
| 194 | 199 | (await ec2(call, region, "DescribeNatGateways", "natGatewaySet")) |
| 195 | 200 | .filter((x) => val(x, "state") !== "deleted") |
| 196 | .map((x): Part => ({ ...none, ...ec2Tags(x), kind: "nat", region, id: exactId(val(x, "natGatewayId")), state: text(val(x, "state")), createdAt: text(val(x, "createTime")), terms: natTerms(x) })), | |
| 201 | .map((x): Part => ({ ...none, ...ec2Tags(x), kind: "nat", region, id: exactId(val(x, "natGatewayId")), state: text(val(x, "state")), createdAt: text(val(x, "createTime")), terms: natTerms(x), clues: { ...ec2Tags(x).clues, cards: items(x, "natGatewayAddressSet").map((a) => val(a, "networkInterfaceId")) } })), | |
| 197 | 202 | }, |
| 198 | 203 | { |
| 199 | 204 | kind: "address", needs: "ec2:DescribeAddresses", |
| @@ -206,7 +211,7 @@ const REGIONAL: readonly { readonly kind: ResourceKind; readonly needs: string; | ||
| 206 | 211 | const free = held.length === 0 && val(x, "associationId") === ""; |
| 207 | 212 | return { |
| 208 | 213 | ...none, kind: "address", region, id: exactId(val(x, "allocationId") || val(x, "publicIp")), label: tagOf(x, "forge"), name: tagOf(x, "Name") || nameText(val(x, "publicIp")), |
| 209 | size: text(val(x, "publicIp")), state: free ? "unattached" : "attached", attachedTo: held.length === 0 && !free ? null : held, terms: addressTerms(x, region), | |
| 214 | size: text(val(x, "publicIp")), state: free ? "unattached" : "attached", attachedTo: held.length === 0 && !free ? null : held, terms: addressTerms(x, region), clues: ec2Tags(x).clues, | |
| 210 | 215 | }; |
| 211 | 216 | }), |
| 212 | 217 | }, |
| @@ -215,7 +220,7 @@ const REGIONAL: readonly { readonly kind: ResourceKind; readonly needs: string; | ||
| 215 | 220 | read: async (call, region) => |
| 216 | 221 | (await ec2(call, region, "DescribeImages", "imagesSet", { "Owner.1": "self" })).map((x): Part => { |
| 217 | 222 | const tags = ec2Tags(x); |
| 218 | return { ...none, kind: "image", region, label: tags.label, name: nameText(val(x, "name")) || tags.name, id: exactId(val(x, "imageId")), state: text(val(x, "imageState")), createdAt: text(val(x, "creationDate")), on: items(x, "blockDeviceMapping").map((d) => exactId(val(d, "ebs/snapshotId"))) }; | |
| 223 | return { ...none, kind: "image", region, label: tags.label, clues: tags.clues, name: nameText(val(x, "name")) || tags.name, id: exactId(val(x, "imageId")), state: text(val(x, "imageState")), createdAt: text(val(x, "creationDate")), on: items(x, "blockDeviceMapping").map((d) => exactId(val(d, "ebs/snapshotId"))) }; | |
| 219 | 224 | }), |
| 220 | 225 | }, |
| 221 | 226 | { |
| @@ -224,7 +229,7 @@ const REGIONAL: readonly { readonly kind: ResourceKind; readonly needs: string; | ||
| 224 | 229 | (await ec2(call, region, "DescribeSnapshots", "snapshotSet", { "Owner.1": "self" })).map((x): Part => { |
| 225 | 230 | const tags = ec2Tags(x); |
| 226 | 231 | return { |
| 227 | ...none, kind: "snapshot", region, label: tags.label, name: tags.name || nameText(val(x, "description")), id: exactId(val(x, "snapshotId")), state: text(val(x, "status")), createdAt: text(val(x, "startTime")), | |
| 232 | ...none, kind: "snapshot", region, label: tags.label, clues: tags.clues, name: tags.name || nameText(val(x, "description")), id: exactId(val(x, "snapshotId")), state: text(val(x, "status")), createdAt: text(val(x, "startTime")), | |
| 228 | 233 | size: words(gib(val(x, "volumeSize")), val(x, "storageTier") === "archive" ? "archived" : ""), madeFrom: val(x, "volumeId") === "" ? "" : `volume:${exactId(val(x, "volumeId"))}`, |
| 229 | 234 | }; |
| 230 | 235 | }), |
| @@ -236,7 +241,7 @@ const REGIONAL: readonly { readonly kind: ResourceKind; readonly needs: string; | ||
| 236 | 241 | (await wrapped(call, "rds", region, "DescribeDBInstances", RDS, "DBInstances", { MaxRecords: "100" }, "Marker")).map( |
| 237 | 242 | (x): Part => ({ |
| 238 | 243 | ...none, kind: "database", region, id: exactId(`${region}/${val(x, "DBInstanceIdentifier")}`), name: nameText(val(x, "DBInstanceIdentifier")), state: text(val(x, "DBInstanceStatus")), createdAt: text(val(x, "InstanceCreateTime")), |
| 239 | size: words(val(x, "DBInstanceClass"), val(x, "Engine"), gib(val(x, "AllocatedStorage")), val(x, "MultiAZ") === "true" ? "two zones" : ""), terms: databaseTerms(x, region), | |
| 244 | size: words(val(x, "DBInstanceClass"), val(x, "Engine"), gib(val(x, "AllocatedStorage")), val(x, "MultiAZ") === "true" ? "two zones" : ""), terms: databaseTerms(x, region), clues: { app: xmlApp(x, "TagList", "Key", "Value") }, | |
| 240 | 245 | }), |
| 241 | 246 | ), |
| 242 | 247 | }, |
| @@ -279,7 +284,7 @@ const REGIONAL: readonly { readonly kind: ResourceKind; readonly needs: string; | ||
| 279 | 284 | kind: "cluster", needs: "ecs:ListClusters and ecs:DescribeClusters", |
| 280 | 285 | read: async (call, region) => |
| 281 | 286 | (await clusters(call, region)).map( |
| 282 | (x): Part => ({ ...none, kind: "cluster", region, id: exactId(`${region}/${String(x.clusterName)}`), name: nameText(x.clusterName), state: text(x.status), size: typeof x.runningTasksCount === "number" ? `${x.runningTasksCount} running tasks` : "" }), | |
| 287 | (x): Part => ({ ...none, kind: "cluster", region, id: exactId(`${region}/${String(x.clusterName)}`), name: nameText(x.clusterName), state: text(x.status), size: typeof x.runningTasksCount === "number" ? `${x.runningTasksCount} running tasks` : "", clues: { app: ecsApp(x) } }), | |
| 283 | 288 | ), |
| 284 | 289 | }, |
| 285 | 290 | { |
| @@ -289,6 +294,7 @@ const REGIONAL: readonly { readonly kind: ResourceKind; readonly needs: string; | ||
| 289 | 294 | ({ x, cluster }): Part => ({ |
| 290 | 295 | ...none, kind: "service", region, id: exactId(`${cluster}/${String(x.serviceName)}`), name: nameText(x.serviceName), state: text(x.status), createdAt: since(x.createdAt), |
| 291 | 296 | size: words(text(x.launchType ?? x.capacityProviderStrategy?.[0]?.capacityProvider), typeof x.runningCount === "number" && typeof x.desiredCount === "number" ? `${x.runningCount} of ${x.desiredCount} running` : ""), |
| 297 | clues: { app: ecsApp(x), groups: (x.loadBalancers ?? []).flatMap((b: any) => (typeof b?.targetGroupArn === "string" ? [b.targetGroupArn] : [])) }, | |
| 292 | 298 | }), |
| 293 | 299 | ), |
| 294 | 300 | }, |
| @@ -303,6 +309,7 @@ const REGIONAL: readonly { readonly kind: ResourceKind; readonly needs: string; | ||
| 303 | 309 | ...none, kind: "task", region, id: exactId(`${cluster}/${lastOf(x.taskArn)}`), name: nameText(name), state: text(x.lastStatus), createdAt: since(x.createdAt), |
| 304 | 310 | size: words(text(x.capacityProviderName ?? x.launchType), of1024(x.cpu, "vCPU"), of1024(x.memory, "GiB")), |
| 305 | 311 | attachedTo: by === "service" ? [exactId(`service:${cluster}/${name}`)] : null, |
| 312 | clues: { app: ecsApp(x), cards: (x.attachments ?? []).flatMap((a: any) => a?.details ?? []).flatMap((d: any) => (d?.name === "networkInterfaceId" ? [String(d.value)] : [])) }, | |
| 306 | 313 | }; |
| 307 | 314 | }), |
| 308 | 315 | }, |
| @@ -353,7 +360,7 @@ async function atMost<T>(all: readonly T[], most: number, work: (x: T) => Promis | ||
| 353 | 360 | * on it, and by nothing when the images were read and none is. An image no machine runs may still |
| 354 | 361 | * be a launch template's, which is not read, so it is not known to be unused. |
| 355 | 362 | */ |
| 356 | function linked(things: readonly Part[], imagesRead: boolean): Omit<Found, "project">[] { | |
| 363 | function linked(things: readonly Part[], imagesRead: boolean): Clued[] { | |
| 357 | 364 | const users = new Map<string, string[]>(); |
| 358 | 365 | const use = (of: string, by: string): unknown => users.set(of, [...(users.get(of) ?? []), by]); |
| 359 | 366 | for (const t of things) { |
| @@ -372,8 +379,10 @@ function linked(things: readonly Part[], imagesRead: boolean): Omit<Found, "proj | ||
| 372 | 379 | * account's failure, and everything kept stays. |
| 373 | 380 | */ |
| 374 | 381 | export async function readAws(f: Fetch, key: AwsKey, known: readonly string[]): Promise<Inventory> { |
| 375 | const things: Found[] = []; | |
| 382 | const things: (Clued & { readonly project: string })[] = []; | |
| 376 | 383 | const gaps: Gap[] = []; |
| 384 | const owned: Owned[] = []; | |
| 385 | const [groups, cards] = [new Map<string, string[]>(), new Map<string, string>()]; | |
| 377 | 386 | let answered = 0; |
| 378 | 387 | const call: Call = (service, region, ask) => awsCall(f, key, service, region, ask); |
| 379 | 388 | let regions: string[]; |
| @@ -405,12 +414,43 @@ export async function readAws(f: Fetch, key: AwsKey, known: readonly string[]): | ||
| 405 | 414 | } |
| 406 | 415 | const imagesRead = !gaps.some((g) => g.project === project && g.kind === "image"); |
| 407 | 416 | things.push(...linked(mine, imagesRead).map((t) => ({ ...t, project }))); |
| 417 | if (project !== AWS_GLOBAL) await apps(project, mine, silent); | |
| 418 | }; | |
| 419 | /** What says which app a region's things are part of; asked only where it can settle one. */ | |
| 420 | const apps = async (region: string, mine: readonly Part[], silent: string): Promise<void> => { | |
| 421 | if (silent !== "") return void gaps.push({ project: region, kind: "stack", reason: silent }); | |
| 422 | const stacks = await readStacks(call, region); | |
| 423 | owned.push(...stacks.owned); | |
| 424 | if (stacks.short !== "") gaps.push({ project: region, kind: "stack", reason: stacks.short }); | |
| 425 | const arns = mine.filter((t) => t.kind === "balancer" && t.id.startsWith("arn:")).map((t) => t.id); | |
| 426 | if (arns.length === 0) return; | |
| 427 | const side = async (kind: "target-group" | "interface", needs: string, of: () => Promise<void>): Promise<void> => { | |
| 428 | try { | |
| 429 | await of(); | |
| 430 | } catch (e) { | |
| 431 | gaps.push({ project: region, kind, reason: reasonOf(e, needs) }); | |
| 432 | } | |
| 433 | }; | |
| 434 | if (mine.some((t) => (t.clues?.groups ?? []).length > 0)) | |
| 435 | await side("target-group", "elasticloadbalancing:DescribeTargetGroups", async () => { | |
| 436 | for (const [g, to] of groupsOf(await wrapped(call, "elasticloadbalancing", region, "DescribeTargetGroups", "2015-12-01", "TargetGroups", { PageSize: "400" }, "NextMarker"))) groups.set(g, to); | |
| 437 | }); | |
| 438 | const held = new Set(mine.flatMap((t) => t.clues?.cards ?? [])); | |
| 439 | if (mine.some((t) => t.kind === "address" && t.attachedTo?.some((a) => a.startsWith("interface:") && !held.has(a.slice("interface:".length))))) | |
| 440 | await side("interface", "ec2:DescribeNetworkInterfaces", async () => { | |
| 441 | for (const [c, to] of balancerCards(await ec2(call, region, "DescribeNetworkInterfaces", "networkInterfaceSet"), arns)) cards.set(c, to); | |
| 442 | }); | |
| 408 | 443 | }; |
| 409 | 444 | await atMost([AWS_GLOBAL, ...regions], REGIONS_AT_ONCE, (p) => read(p, p === AWS_GLOBAL ? GLOBAL : REGIONAL)); |
| 410 | 445 | if (answered === 0) throw new Reasoned(gaps.find((g) => g.kind !== "project")?.reason ?? "nothing could be read"); |
| 446 | // Over the whole account, since a region's stack can own a bucket or a zone. | |
| 447 | const parts = partsOf(things, owned, groups, cards); | |
| 411 | 448 | return { |
| 412 | 449 | projects: [{ id: AWS_GLOBAL, name: AWS_GLOBAL, isDefault: true }, ...regions.map((r) => ({ id: r, name: r, isDefault: false }))], |
| 413 | things, | |
| 450 | things: things.map(({ clues: _clues, ...t }) => { | |
| 451 | const partOf = parts.get(`${t.kind}:${t.id}`); | |
| 452 | return partOf === undefined ? t : { ...t, partOf }; | |
| 453 | }), | |
| 414 | 454 | gaps, |
| 415 | 455 | }; |
| 416 | 456 | } |
src/cloud/inventory.ts +13 −2
| @@ -32,6 +32,12 @@ export type ResourceKind = | ||
| 32 | 32 | | "worker" |
| 33 | 33 | | "site"; |
| 34 | 34 | |
| 35 | /** An app, and how it is known: "its CloudFormation stack", "its tags", "through its balancer". */ | |
| 36 | export interface PartOf { | |
| 37 | readonly app: string; | |
| 38 | readonly by: string; | |
| 39 | } | |
| 40 | ||
| 35 | 41 | export interface Found { |
| 36 | 42 | readonly kind: ResourceKind; |
| 37 | 43 | /** The provider's id, or `<region>/<name>` for a thing whose name is only its region's own. */ |
| @@ -56,14 +62,19 @@ export interface Found { | ||
| 56 | 62 | */ |
| 57 | 63 | readonly madeFrom: string; |
| 58 | 64 | readonly createdAt: string; |
| 65 | /** The app it is part of, as AWS states it; absent when that is not known. */ | |
| 66 | readonly partOf?: PartOf; | |
| 59 | 67 | /** What an AWS thing is billed by; null or absent when that is not known. */ |
| 60 | 68 | readonly terms?: Terms; |
| 61 | 69 | } |
| 62 | 70 | |
| 63 | 71 | export interface Gap { |
| 64 | 72 | readonly project: string; |
| 65 | /** The kind that could not be read; `project` when the list of projects itself could not be. */ | |
| 66 | readonly kind: ResourceKind | "project"; | |
| 73 | /** | |
| 74 | * The kind that could not be read; `project` when the list of projects itself could not be, and | |
| 75 | * `stack`, `target-group` or `interface` for what only says which app a thing is part of. | |
| 76 | */ | |
| 77 | readonly kind: ResourceKind | "project" | "stack" | "target-group" | "interface"; | |
| 67 | 78 | readonly reason: string; |
| 68 | 79 | } |
| 69 | 80 |
src/cloud/projects.ts +11 −4
| @@ -30,7 +30,7 @@ import { AWS_GLOBAL, readAws } from "./aws_read.ts"; | ||
| 30 | 30 | import { leftOut, sourceOf, type Priced } from "./aws_terms.ts"; |
| 31 | 31 | import { priced } from "./ceiling.ts"; |
| 32 | 32 | import { readCloudflare } from "./cloudflare_read.ts"; |
| 33 | import { reasonOf, type Found, type Gap, type Inventory, type ResourceKind } from "./inventory.ts"; | |
| 33 | import { reasonOf, type Found, type Gap, type Inventory, type PartOf, type ResourceKind } from "./inventory.ts"; | |
| 34 | 34 | import { VOLUME_GIB } from "./places.ts"; |
| 35 | 35 | import { dollars } from "./prices.ts"; |
| 36 | 36 | import type { Fetch } from "./providers.ts"; |
| @@ -96,6 +96,8 @@ export interface CloudResource { | ||
| 96 | 96 | * What it was made from (`volume:vol-1`), whether or not that still stands; empty when not known. |
| 97 | 97 | */ |
| 98 | 98 | readonly madeFrom: string; |
| 99 | /** The app it is part of and how that is known; null when it is not. Never a reason to delete. */ | |
| 100 | readonly partOf: PartOf | null; | |
| 99 | 101 | readonly createdAt: string; |
| 100 | 102 | /** |
| 101 | 103 | * When it was last seen: older than its project's reading when its kind could not be read since. |
| @@ -112,7 +114,7 @@ type Thing = Omit<Seen, "kind"> & { readonly kind: ResourceKind; readonly projec | ||
| 112 | 114 | /** What was read of an account before it is judged: its projects and each thing, with its project. */ |
| 113 | 115 | interface Read { |
| 114 | 116 | readonly projects: Inventory["projects"]; |
| 115 | readonly things: readonly (Thing & Partial<Pick<Found, "state" | "attachedTo" | "madeFrom" | "terms">>)[]; | |
| 117 | readonly things: readonly (Thing & Partial<Pick<Found, "state" | "attachedTo" | "madeFrom" | "terms" | "partOf">>)[]; | |
| 116 | 118 | readonly gaps: readonly Gap[]; |
| 117 | 119 | } |
| 118 | 120 | |
| @@ -285,8 +287,8 @@ export async function readProjects( | ||
| 285 | 287 | ); |
| 286 | 288 | for (const p of read.projects) project.run(provider, account, p.id, p.name, p.isDefault ? 1 : 0, at, p.note ?? ""); |
| 287 | 289 | const thing = db.query( |
| 288 | `INSERT OR REPLACE INTO cloud_resource (cloud_provider, cloud_account_id, cloud_resource_id, cloud_project_id, kind, name, cloud_region, host_type, label, made_by, cents, created_at, read_at, state, attached_to, made_from, priced_at, price_note) | |
| 289 | VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15, ?16, ?17, ?18)`, | |
| 290 | `INSERT OR REPLACE INTO cloud_resource (cloud_provider, cloud_account_id, cloud_resource_id, cloud_project_id, kind, name, cloud_region, host_type, label, made_by, cents, created_at, read_at, state, attached_to, made_from, priced_at, price_note, part_of, part_of_how) | |
| 291 | VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15, ?16, ?17, ?18, ?19, ?20)`, | |
| 290 | 292 | ); |
| 291 | 293 | for (const t of read.things) { |
| 292 | 294 | const j = verdict.get(`${t.kind}:${t.id}`); |
| @@ -311,6 +313,8 @@ export async function readProjects( | ||
| 311 | 313 | t.madeFrom ?? "", |
| 312 | 314 | list === undefined || list.cents === null ? "" : list.readAt, |
| 313 | 315 | list?.note ?? "", |
| 316 | t.partOf?.app ?? "", | |
| 317 | t.partOf?.by ?? "", | |
| 314 | 318 | ); |
| 315 | 319 | } |
| 316 | 320 | })(); |
| @@ -466,6 +470,8 @@ export function projectsOf(db: Database, now = new Date()): ProjectView[] { | ||
| 466 | 470 | made_from: string; |
| 467 | 471 | priced_at: string; |
| 468 | 472 | price_note: string; |
| 473 | part_of: string; | |
| 474 | part_of_how: string; | |
| 469 | 475 | }, |
| 470 | 476 | [] |
| 471 | 477 | >("SELECT * FROM cloud_resource ORDER BY made_by, kind, name") |
| @@ -491,6 +497,7 @@ export function projectsOf(db: Database, now = new Date()): ProjectView[] { | ||
| 491 | 497 | state: r.state, |
| 492 | 498 | attachedTo: r.attached_to === "" ? null : (JSON.parse(r.attached_to) as string[]), |
| 493 | 499 | madeFrom: r.made_from, |
| 500 | partOf: r.part_of === "" ? null : { app: r.part_of, by: r.part_of_how }, | |
| 494 | 501 | createdAt: r.created_at, |
| 495 | 502 | readAt: r.read_at, |
| 496 | 503 | }), |
src/cloud/tree.ts +18 −11
| @@ -217,10 +217,14 @@ const groupBy = <T>(all: readonly T[], key: (x: T) => string): Map<string, T[]> | ||
| 217 | 217 | |
| 218 | 218 | /** The kinds a read could not see, one sentence a reason. */ |
| 219 | 219 | const unreadTrouble = (unread: AccountRead["unread"], href: string, where: (own: AccountRead["unread"]) => string = () => ""): Trouble[] => |
| 220 | [...groupBy(unread, (u) => u.reason)].map(([reason, own]) => ({ says: `Not read: ${[...new Set(own.map((u) => u.kind))].join(", ")}${where(own)}. ${reason}`, href, label: "Check the account", gap: "here" })); | |
| 220 | [...groupBy(unread, (u) => u.reason)].map(([reason, own]) => ({ says: `Not read: ${[...new Set(own.map((u) => u.kind))].join(", ")}${where(own)}${listGaps(own).length === 0 ? ", so the app some things are part of is not known" : ""}. ${reason}`, href, label: "Check the account", gap: "here" })); | |
| 221 | ||
| 222 | /** Read only for the app a thing is part of: without them the list and its sum are as whole. */ | |
| 223 | const PART_OF_ONLY: ReadonlySet<string> = new Set(["stack", "target-group", "interface"]); | |
| 224 | const listGaps = (unread: AccountRead["unread"]): AccountRead["unread"] => unread.filter((u) => !PART_OF_ONLY.has(u.kind)); | |
| 221 | 225 | |
| 222 | 226 | /** How many kinds a list of gaps is about, however many regions refused each. */ |
| 223 | const kindsOf = (unread: AccountRead["unread"]): number => new Set(unread.map((u) => u.kind)).size; | |
| 227 | const kindsOf = (unread: AccountRead["unread"]): number => new Set(listGaps(unread).map((u) => u.kind)).size; | |
| 224 | 228 | |
| 225 | 229 | |
| 226 | 230 | /** |
| @@ -244,7 +248,7 @@ export function cloudTree(projects: readonly ProjectView[], reads: readonly Acco | ||
| 244 | 248 | const n = { ...branch("project", path, p.name, things, p.readAt, unreadTrouble(p.unread, href)), note: p.note }; |
| 245 | 249 | // A bill is the whole project's, so it stands in for its resources' prices, known or not. |
| 246 | 250 | if (!filtering && p.cost.costFrom === "billed" && p.cost.cents !== null) return { ...n, money: { ...NOTHING, cents: p.cost.cents, billed: 1 }, month: { from: p.cost.from, to: p.cost.to }, gaps: kindsOf(p.unread) }; |
| 247 | return filtering ? n : { ...n, gaps: kindsOf(p.unread), money: { ...n.money, unread: p.unread.length } }; | |
| 251 | return filtering ? n : { ...n, gaps: kindsOf(p.unread), money: { ...n.money, unread: listGaps(p.unread).length } }; | |
| 248 | 252 | }); |
| 249 | 253 | const shown = kids.filter((k) => k.count > 0 || (!filtering && (k.money.cents > 0 || k.alert || k.note !== ""))); |
| 250 | 254 | const readAt = oldest(kids); |
| @@ -326,6 +330,7 @@ const PROPS = { | ||
| 326 | 330 | attached: (r) => (r.attachedTo === null || r.kind === "snapshot" ? "unknown" : r.attachedTo.length === 0 ? "no" : "yes"), |
| 327 | 331 | made: (r) => r.madeBy, |
| 328 | 332 | for: (r) => r.label, |
| 333 | app: (r) => r.partOf?.app ?? "", | |
| 329 | 334 | } as const satisfies Record<string, (r: CloudResource, project: string) => string>; |
| 330 | 335 | |
| 331 | 336 | type Prop = keyof typeof PROPS; |
| @@ -405,14 +410,14 @@ function costHolds(r: CloudResource, t: CloudTerm): boolean { | ||
| 405 | 410 | function termHolds(t: CloudTerm, r: CloudResource, project: string): boolean { |
| 406 | 411 | if (t.field === "cost") return costHolds(r, t) !== t.negate; |
| 407 | 412 | const have = PROPS[t.field as Prop](r, project).toLowerCase(); |
| 408 | const hit = t.values.some((v) => (EXACT.has(t.field) ? have === v : v === "none" ? have === "" : t.field === "state" ? have.startsWith(v) : have.includes(v))); | |
| 413 | const hit = t.values.some((v) => (EXACT.has(t.field) ? have === v : v === (t.field === "app" ? "unknown" : "none") ? have === "" : t.field === "state" ? have.startsWith(v) : have.includes(v))); | |
| 409 | 414 | return hit !== t.negate; |
| 410 | 415 | } |
| 411 | 416 | |
| 412 | 417 | function matches(q: CloudQuery, r: CloudResource, project: string): boolean { |
| 413 | 418 | if (!q.terms.every((t) => termHolds(t, r, project))) return false; |
| 414 | 419 | if (q.words.length === 0) return true; |
| 415 | const hay = [r.id, r.name, r.kind, r.provider, r.account, project, r.region, r.size, r.label, r.state].join(" ").toLowerCase(); | |
| 420 | const hay = [r.id, r.name, r.kind, r.provider, r.account, project, r.region, r.size, r.label, r.state, r.partOf?.app ?? ""].join(" ").toLowerCase(); | |
| 416 | 421 | return q.words.every((w) => hay.includes(w)); |
| 417 | 422 | } |
| 418 | 423 | |
| @@ -503,6 +508,7 @@ export function linkedFacts(root: CloudNode, n: CloudNode): Fact[] { | ||
| 503 | 508 | ...ties.filter((f) => !origin(f)), |
| 504 | 509 | { label: "Region", value: r.region }, |
| 505 | 510 | ...priceFacts(r), |
| 511 | { label: "Part of", value: r.partOf === null ? "" : `${r.partOf.app}, ${r.partOf.by}` }, | |
| 506 | 512 | { label: "Project", value: project === r.region ? "" : project }, |
| 507 | 513 | { label: "Account", value: `${cloudName(r.provider)} / ${r.account}` }, |
| 508 | 514 | { label: "Made by", value: r.madeBy === "forge" ? `the forge${r.label === "" ? "" : `, for ${r.label}`}` : "not the forge" }, |
| @@ -572,8 +578,8 @@ function priceFacts(r: CloudResource): Fact[] { | ||
| 572 | 578 | const PLURAL = new Map([["address", "addresses"], ["registry", "registries"], ["logs", "log groups"], ["nat", "NAT gateways"], ["balancer", "load balancers"], ["database-snapshot", "database snapshots"]]); |
| 573 | 579 | const SINGULAR = new Map([["logs", "log group"], ["nat", "NAT gateway"], ["balancer", "load balancer"], ["database-snapshot", "database snapshot"]]); |
| 574 | 580 | |
| 575 | /** What a filter found, and what is known of its cost: "10 unused volumes". */ | |
| 576 | export function findingOf(v: CloudView): { readonly found: string; readonly cost: string } { | |
| 581 | /** What a filter found, and what is known of its cost: "10 unattached volumes". */ | |
| 582 | export function findingOf(v: CloudView): { readonly found: string; readonly cost: string; readonly caveat: string } { | |
| 577 | 583 | const { root, q } = v; |
| 578 | 584 | const only = (field: string): string => { |
| 579 | 585 | const own = q.terms.filter((t) => t.field === field); |
| @@ -584,12 +590,13 @@ export function findingOf(v: CloudView): { readonly found: string; readonly cost | ||
| 584 | 590 | const said = [...(kind === "" ? [] : ["kind"]), ...(idle ? ["attached"] : []), ...(only("state") === "" ? [] : ["state"]), ...(only("cloud") === "" ? [] : ["cloud"]), ...(only("region") === "" ? [] : ["region"])]; |
| 585 | 591 | const noun = kind === "" ? (root.count === 1 ? "resource" : "resources") : root.count === 1 ? (SINGULAR.get(kind) ?? kind) : (PLURAL.get(kind) ?? `${kind}s`); |
| 586 | 592 | const rest = q.words.length > 0 || q.terms.some((t) => !said.includes(t.field)); |
| 587 | const found = [root.count === 0 ? "No" : root.count.toLocaleString("en-US"), idle ? "unused" : "", only("state"), only("cloud") === "" ? "" : cloudName(only("cloud")), noun, only("region") === "" ? "" : `in ${only("region")}`, rest ? "matching" : ""].filter((x) => x !== "").join(" "); | |
| 588 | if (root.count === 0) return { found, cost: "" }; | |
| 593 | const found = [root.count === 0 ? "No" : root.count.toLocaleString("en-US"), idle ? "unattached" : "", only("state"), only("cloud") === "" ? "" : cloudName(only("cloud")), noun, only("region") === "" ? "" : `in ${only("region")}`, rest ? "matching" : ""].filter((x) => x !== "").join(" "); | |
| 594 | if (root.count === 0) return { found, cost: "", caveat: "" }; | |
| 595 | const caveat = q.terms.some((t) => t.field === "app" && !t.negate && t.values.every((x) => x === "unknown")) ? "No app found for these. That does not mean nothing uses them." : ""; | |
| 589 | 596 | const m = root.money; |
| 590 | if (m.list + m.billed > 0) return { found, cost: costLine(root) }; | |
| 597 | if (m.list + m.billed > 0) return { found, cost: costLine(root), caveat }; | |
| 591 | 598 | // With no price of their own, they may still be inside a bill that was read. |
| 592 | 599 | const billed = root.children.flatMap((c) => c.children).map((a) => nodeAt(v.whole, a.path)).filter((a) => a !== undefined); |
| 593 | 600 | const inside = billed.length > 0 && billed.every((a) => a.month !== undefined) ? `, inside ${billSays(v.whole)}` : ""; |
| 594 | return { found, cost: `${root.count === 1 ? "No price of its own" : "No prices of their own"}${inside}.` }; | |
| 601 | return { found, cost: `${root.count === 1 ? "No price of its own" : "No prices of their own"}${inside}.`, caveat }; | |
| 595 | 602 | } |
src/core/migration-pins/20261202200219-cloud-part-of.pin added +1
| @@ -0,0 +1,1 @@ | ||
| 1 | 5d9b5dbc50223dddab4f008f431c2fb69d7541e280619a40c21a176b59f18c56 |
src/core/migrations/20261202200219-cloud-part-of.ts added +6
| @@ -0,0 +1,6 @@ | ||
| 1 | // The app a cloud resource is part of, and how that is known (#17532). Additive: two columns, empty | |
| 2 | // when it is not known. | |
| 3 | export default ` | |
| 4 | ALTER TABLE cloud_resource ADD COLUMN part_of TEXT NOT NULL DEFAULT ''; | |
| 5 | ALTER TABLE cloud_resource ADD COLUMN part_of_how TEXT NOT NULL DEFAULT ''; | |
| 6 | `; |
src/http/mcp/tools/infra.ts +1 −1
| @@ -54,7 +54,7 @@ export const tool: Tool = { | ||
| 54 | 54 | if (!v.ok) return bad("not_found", "no such tool here"); |
| 55 | 55 | const all = costliestOf(v.value.root); |
| 56 | 56 | const f = findingOf(v.value); |
| 57 | const says = [f.found, f.cost, ...v.value.q.problems].filter((x) => x !== "").join(". "); | |
| 57 | const says = [f.found, f.cost, f.caveat, ...v.value.q.problems].filter((x) => x !== "").map((x, i, all) => (i < all.length - 1 ? x.replace(/\.$/, "") : x)).join(". "); | |
| 58 | 58 | return good({ says, resources: all.slice(0, 50).map((n) => ({ id: n.path.join("/"), name: n.name, kind: n.resource!.kind, state: n.resource!.state, cost: moneyWords(n.money), readAt: n.readAt })) }); |
| 59 | 59 | } |
| 60 | 60 | if (action === "list") { |
src/tui/screens/cloudtree.ts +3 −3
| @@ -51,7 +51,7 @@ export function cloudLines(v: CloudView, n: CloudNode): string[] { | ||
| 51 | 51 | ...trouble, |
| 52 | 52 | ...(n.note === "" ? [] : [`${n.note}.`]), |
| 53 | 53 | ...(goes.length === 0 ? [] : ["", "Where it goes", ...goes.map((c) => line(dollars(c.cents), `${c.says} · ${c.where}${c.hint === "" ? "" : ` · ${c.hint}`}`))]), |
| 54 | ...(n.count === 0 ? [] : ["", `${n.count} ${n.count === 1 ? "resource" : "resources"}`, ...costliestOf(n).slice(0, 200).map((c) => line(markOf(c), `${c.name} · ${[c.resource!.kind, unused(c.resource!) ? "unused" : c.resource!.state].filter((x) => x !== "").join(" · ")}`))]), | |
| 54 | ...(n.count === 0 ? [] : ["", `${n.count} ${n.count === 1 ? "resource" : "resources"}`, ...costliestOf(n).slice(0, 200).map((c) => line(markOf(c), `${c.name} · ${[c.resource!.kind, unused(c.resource!) ? "unattached" : c.resource!.state].filter((x) => x !== "").join(" · ")}`))]), | |
| 55 | 55 | ]; |
| 56 | 56 | } |
| 57 | 57 | |
| @@ -117,9 +117,9 @@ export function cloudTreeScreen(f: Session, ctx: Ctx): Screen { | ||
| 117 | 117 | return; |
| 118 | 118 | } |
| 119 | 119 | const f = findingOf(v); |
| 120 | const total = v.q.text === "" ? costLine(v.root) || (v.root.count === 0 ? "" : [`${v.root.count} resources, no price known`, unreadLine(v.root)].filter((x) => x !== "").join(", ")) : [f.found, f.cost].filter((x) => x !== "").join(" · "); | |
| 120 | const total = v.q.text === "" ? costLine(v.root) || (v.root.count === 0 ? "" : [`${v.root.count} resources, no price known`, unreadLine(v.root)].filter((x) => x !== "").join(", ")) : [f.found, f.caveat, f.cost].filter((x) => x !== "").join(" · "); | |
| 121 | 121 | const says = note !== "" ? note : v.held === 0 ? "No cloud account is attached: press I on Cloud accounts, or open /settings/cloud." : total === "" ? "Nothing read yet: press P to read every account now." : total; |
| 122 | const said = wrap(v.q.problems[0] ?? says, area.w).slice(0, 2); | |
| 122 | const said = wrap(v.q.problems[0] ?? says, area.w).slice(0, f.caveat === "" ? 2 : 3); | |
| 123 | 123 | const [head, box, body] = split(area, "v", [len(said.length), len(1), fill(1)]); |
| 124 | 124 | said.forEach((l, i) => s.text(head!.x, head!.y + i, truncate(l, head!.w), style(c.fg, c.bg), head!.x + head!.w)); |
| 125 | 125 | const caret = filter.render(s, box!, c, "/ kind:volume cloud:aws cost:>10"); |
src/web/pages/cloud_tree.ts +3 −3
| @@ -94,7 +94,7 @@ function level(v: CloudView, n: CloudNode, current: readonly string[], openAll: | ||
| 94 | 94 | const at = c.path.every((p, i) => current[i] === p); |
| 95 | 95 | const here = at && current.length === c.path.length; |
| 96 | 96 | if (c.level === "resource") |
| 97 | return html`<li><a class="ex-file" data-ex-file data-nav tabindex="-1" href="${href}" ${here ? raw('aria-current="page"') : null}><span class="truncate">${c.name}</span><span class="ex-kind">${c.resource!.kind}${unused(c.resource!) ? " · unused" : ""}</span>${cost(c)}</a></li>`; | |
| 97 | return html`<li><a class="ex-file" data-ex-file data-nav tabindex="-1" href="${href}" ${here ? raw('aria-current="page"') : null}><span class="truncate">${c.name}</span><span class="ex-kind">${c.resource!.kind}${unused(c.resource!) ? " · unattached" : ""}</span>${cost(c)}</a></li>`; | |
| 98 | 98 | const open = at || openAll || c.level === "cloud" || (c.level === "account" && c.children.length <= OPEN_ACCOUNT); |
| 99 | 99 | return html`<li><details class="ex-dir" data-url="${href}" ${open ? raw("open") : null}> |
| 100 | 100 | <summary data-nav ${here ? raw('data-current=""') : null}>${icon("chevronRight")}<span class="truncate">${c.name}</span>${c.alert ? html`<span data-trouble title="Something here needs a look">${icon("alert")}</span>` : null}</summary> |
| @@ -163,7 +163,7 @@ function totalOf(v: CloudView): Html { | ||
| 163 | 163 | if (v.held === 0 && root.count === 0) return emptySection("cloudResources", { action: btn("Attach an account", { href: "/settings/cloud" }) }); |
| 164 | 164 | if (v.q.text !== "") { |
| 165 | 165 | const f = findingOf(v); |
| 166 | return html`<p class="cloud-total"><strong>${f.found}</strong></p><p class="muted">${f.cost}</p>`; | |
| 166 | return html`<p class="cloud-total"><strong>${f.found}</strong></p><p class="muted">${f.cost}${f.caveat === "" ? null : html`<br />${f.caveat}`}</p>`; | |
| 167 | 167 | } |
| 168 | 168 | if (root.count === 0 && root.money.cents === 0) return html`<p>${root.readAt === "" ? "Nothing is read yet." : "The accounts hold nothing the forge reads."}${unreadLinks(v, root)}</p>`; |
| 169 | 169 | if (root.money.billed + root.money.list === 0) return html`<p class="cloud-total"><strong>${root.count.toLocaleString("en-US")} ${root.count === 1 ? "resource" : "resources"}</strong></p><p class="muted">None has a price the forge knows.${unreadLinks(v, root)}</p>`; |
| @@ -205,7 +205,7 @@ function listed(v: CloudView, n: CloudNode): Html { | ||
| 205 | 205 | row({ |
| 206 | 206 | href: cloudHref(c.path, v.q), |
| 207 | 207 | title: c.name, |
| 208 | meta: html`${[c.resource!.kind, unused(c.resource!) ? "unused" : c.resource!.state, c.resource!.size, c.resource!.region].filter((x) => x !== "").join(" · ")}`, | |
| 208 | meta: html`${[c.resource!.kind, unused(c.resource!) ? "unattached" : c.resource!.state, c.resource!.size, c.resource!.region].filter((x) => x !== "").join(" · ")}`, | |
| 209 | 209 | trail: cost(c), |
| 210 | 210 | }), |
| 211 | 211 | ), |
test/cloud-inventory.test.ts +2 −2
| @@ -110,7 +110,7 @@ describe("AWS", () => { | ||
| 110 | 110 | const hosts = new Set(calls.map((c) => c.split(" ")[1]!)); |
| 111 | 111 | // AWS's public price files, asked for unsigned (aws-prices.test.ts). |
| 112 | 112 | for (const open of ["b0.p.awsstatic.com", "pricing.us-east-1.amazonaws.com"]) hosts.delete(open); |
| 113 | for (const h of hosts) expect(h).toMatch(/^((ec2|elasticloadbalancing|rds|logs|lambda|dynamodb|api\.ecr|ecs)\.(us-east-1|eu-west-1)|s3\.us-east-1|ce\.us-east-1|route53)\.amazonaws\.com$/); | |
| 113 | for (const h of hosts) expect(h).toMatch(/^((ec2|elasticloadbalancing|rds|logs|lambda|dynamodb|api\.ecr|ecs|cloudformation)\.(us-east-1|eu-west-1)|s3\.us-east-1|ce\.us-east-1|route53)\.amazonaws\.com$/); | |
| 114 | 114 | expect(auditToday(app.db, Date.now(), 1000)).toHaveLength(calls.length); |
| 115 | 115 | }); |
| 116 | 116 | |
| @@ -174,7 +174,7 @@ describe("AWS", () => { | ||
| 174 | 174 | expect((await aws(now)).failed).toEqual([]); |
| 175 | 175 | expect(calls.filter((c) => c.includes("eu-west-1"))).toHaveLength(1); |
| 176 | 176 | const west = projectsOf(app.db).find((p) => p.id === "eu-west-1")!; |
| 177 | expect(west.unread).toHaveLength(16); | |
| 177 | expect(west.unread).toHaveLength(17); | |
| 178 | 178 | expect(west.unread[0]!.reason).toContain("no answer in 10 seconds"); |
| 179 | 179 | }); |
| 180 | 180 |
test/cloud-part-of.test.ts added +177
| @@ -0,0 +1,177 @@ | ||
| 1 | /** | |
| 2 | * Which app an AWS resource is part of (#17532): its CloudFormation stack first, then its tags, then | |
| 3 | * what it serves when all of that agrees, and not known otherwise. Invented accounts, in the shapes | |
| 4 | * of the AWS API reference (read 2026-12-02); no live account was asked. | |
| 5 | */ | |
| 6 | import { afterEach, describe, expect, test } from "bun:test"; | |
| 7 | import { mkdtempSync, rmSync } from "node:fs"; | |
| 8 | import { tmpdir } from "node:os"; | |
| 9 | import { join } from "node:path"; | |
| 10 | import { createApp } from "../src/app.ts"; | |
| 11 | import { readAws } from "../src/cloud/aws_read.ts"; | |
| 12 | import { projectsOf, readProjects } from "../src/cloud/projects.ts"; | |
| 13 | import type { Inventory } from "../src/cloud/inventory.ts"; | |
| 14 | import { denied, ec2, query, recordedAws, timeout, type AwsAccount } from "./helpers/recorded-aws.ts"; | |
| 15 | ||
| 16 | const E1 = "us-east-1.amazonaws.com"; | |
| 17 | const ARN = "arn:aws:elasticloadbalancing:us-east-1:123456789012"; | |
| 18 | const LB = `${ARN}:loadbalancer/app/front/50dc6c495c0c9188`; | |
| 19 | const ECS = "arn:aws:ecs:us-east-1:123456789012"; | |
| 20 | const stackId = (name: string): string => `arn:aws:cloudformation:us-east-1:123456789012:stack/${name}/aaaa`; | |
| 21 | const stacks = (...all: [name: string, status?: string, root?: string][]) => | |
| 22 | query("ListStacks", `<StackSummaries>${all.map(([n, s, root]) => `<member><StackId>${stackId(n)}</StackId><StackName>${n}</StackName><StackStatus>${s ?? "CREATE_COMPLETE"}</StackStatus>${root === undefined ? "" : `<RootId>${stackId(root)}</RootId>`}</member>`).join("")}</StackSummaries>`); | |
| 23 | const owns = (...all: [type: string, id: string, status?: string][]) => | |
| 24 | query("ListStackResources", `<StackResourceSummaries>${all.map(([t, id, s]) => `<member><ResourceType>AWS::${t}</ResourceType><PhysicalResourceId>${id}</PhysicalResourceId><ResourceStatus>${s ?? "CREATE_COMPLETE"}</ResourceStatus></member>`).join("")}</StackResourceSummaries>`); | |
| 25 | const own = (name: string): string => `cloudformation.${E1} ListStackResources/${stackId(name)}`; | |
| 26 | const tagged = (tags: Record<string, string>): string => `<tagSet>${Object.entries(tags).map(([k, v]) => `<item><key>${k}</key><value>${v}</value></item>`).join("")}</tagSet>`; | |
| 27 | const machines = (...all: [id: string, tags?: Record<string, string>][]) => | |
| 28 | ec2("DescribeInstances", `<reservationSet><item><instancesSet>${all.map(([id, t]) => `<item><instanceId>${id}</instanceId><instanceState><name>running</name></instanceState>${tagged(t ?? {})}</item>`).join("")}</instancesSet></item></reservationSet>`); | |
| 29 | const volume = (id: string, ...on: string[]): string => | |
| 30 | `<item><volumeId>${id}</volumeId><status>${on.length === 0 ? "available" : "in-use"}</status><attachmentSet>${on.map((m) => `<item><instanceId>${m}</instanceId></item>`).join("")}</attachmentSet></item>`; | |
| 31 | const regions = (...names: string[]) => ec2("DescribeRegions", `<regionInfo>${names.map((r) => `<item><regionName>${r}</regionName></item>`).join("")}</regionInfo>`); | |
| 32 | ||
| 33 | /** Buckets and zones that the base account has none of. */ | |
| 34 | const bare: AwsAccount = { | |
| 35 | [`ec2.${E1} DescribeRegions`]: regions("us-east-1"), | |
| 36 | [`s3.${E1} /`]: { body: "<ListAllMyBucketsResult><Buckets><Bucket><Name>shop-uploads</Name></Bucket><Bucket><Name>shop-lookalike</Name></Bucket></Buckets></ListAllMyBucketsResult>" }, | |
| 37 | "route53.amazonaws.com /2013-04-01/hostedzone": { body: "<ListHostedZonesResponse><HostedZones/><IsTruncated>false</IsTruncated></ListHostedZonesResponse>" }, | |
| 38 | }; | |
| 39 | let calls: string[] = []; | |
| 40 | afterEach(() => void (calls = [])); | |
| 41 | const read = (of: AwsAccount): Promise<Inventory> => readAws(recordedAws({ ...bare, ...of }, calls), { id: "AKIDEXAMPLE", secret: "example" }, []); | |
| 42 | const app = (i: Inventory, id: string): string => { | |
| 43 | const t = i.things.find((x) => `${x.kind}:${x.id}` === id); | |
| 44 | if (t === undefined) throw new Error(`no ${id}`); | |
| 45 | return t.partOf === undefined ? "not known" : `${t.partOf.app}, ${t.partOf.by}`; | |
| 46 | }; | |
| 47 | ||
| 48 | describe("stacks", () => { | |
| 49 | test("a stack's things are its own, in any project, and a nested stack's are the topmost's", async () => { | |
| 50 | const i = await read({ | |
| 51 | [`ec2.${E1} DescribeInstances`]: machines(["i-1", { "sst:app": "other" }], ["i-2"]), | |
| 52 | [`lambda.${E1} /2015-03-31/functions`]: { body: JSON.stringify({ Functions: [{ FunctionName: "resize" }] }) }, | |
| 53 | [`logs.${E1} DescribeLogGroups`]: { body: JSON.stringify({ logGroups: [{ logGroupName: "/x/resize" }] }) }, | |
| 54 | [`rds.${E1} DescribeDBInstances`]: query("DescribeDBInstances", "<DBInstances><DBInstance><DBInstanceIdentifier>shopdb</DBInstanceIdentifier></DBInstance></DBInstances>"), | |
| 55 | [`ec2.${E1} DescribeAddresses`]: ec2("DescribeAddresses", "<addressesSet><item><publicIp>203.0.113.4</publicIp><allocationId>eipalloc-9</allocationId></item></addressesSet>"), | |
| 56 | [`cloudformation.${E1} ListStacks`]: stacks(["shop"], ["shop-Nested-1", "UPDATE_COMPLETE", "shop"], ["old", "DELETE_COMPLETE"]), | |
| 57 | [own("shop")]: owns(["EC2::Instance", "i-1"], ["S3::Bucket", "shop-uploads"], ["RDS::DBInstance", "ShopDB"], ["EC2::EIP", "203.0.113.4"], ["SNS::Topic", "x"]), | |
| 58 | [own("shop-Nested-1")]: owns(["Lambda::Function", "resize"], ["Logs::LogGroup", "/x/resize"]), | |
| 59 | }); | |
| 60 | // What the stack lists outranks a tag. | |
| 61 | for (const id of ["machine:i-1", "bucket:shop-uploads", "database:us-east-1/shopdb", "address:eipalloc-9", "function:us-east-1/resize", "logs:us-east-1//x/resize"]) | |
| 62 | expect([id, app(i, id)]).toEqual([id, "shop, its CloudFormation stack"]); | |
| 63 | // Alike in name alone. | |
| 64 | expect(app(i, "bucket:shop-lookalike")).toBe("not known"); | |
| 65 | expect(app(i, "machine:i-2")).toBe("not known"); | |
| 66 | expect(calls.filter((c) => c.includes("/arn:") && c.includes("stack/old/"))).toEqual([]); | |
| 67 | expect(i.gaps).toEqual([]); | |
| 68 | }); | |
| 69 | ||
| 70 | test("a thing a stack let go of is not its own; two stacks that claim one settle nothing", async () => { | |
| 71 | const i = await read({ | |
| 72 | [`ec2.${E1} DescribeInstances`]: machines(["i-1", { "sst:app": "shop" }]), | |
| 73 | [`cloudformation.${E1} ListStacks`]: stacks(["a"], ["b"]), | |
| 74 | [own("a")]: owns(["S3::Bucket", "shop-uploads", "DELETE_SKIPPED"], ["EC2::Instance", "i-1"]), | |
| 75 | [own("b")]: owns(["EC2::Instance", "i-1"]), | |
| 76 | }); | |
| 77 | expect(app(i, "bucket:shop-uploads")).toBe("not known"); | |
| 78 | expect(app(i, "machine:i-1")).toBe("not known"); | |
| 79 | }); | |
| 80 | ||
| 81 | test("refused, cut off or silent: a gap with its reason, what was read stands, and tags still count", async () => { | |
| 82 | const tag = { [`ec2.${E1} DescribeInstances`]: machines(["i-1", { "sst:app": "shop", "sst:stage": "prod" }]) }; | |
| 83 | const refused = await read({ ...tag, [`cloudformation.${E1} ListStacks`]: denied("AccessDenied") }); | |
| 84 | expect(refused.gaps).toEqual([{ project: "us-east-1", kind: "stack", reason: `cloudformation.${E1} answered 403 AccessDenied: the key needs cloudformation:ListStacks and cloudformation:ListStackResources` }]); | |
| 85 | expect(app(refused, "machine:i-1")).toBe("shop/prod, its tags"); | |
| 86 | ||
| 87 | calls = []; | |
| 88 | const names = Array.from({ length: 250 }, (_, n) => `s${n}`); | |
| 89 | const many = await read({ [`cloudformation.${E1} ListStacks`]: stacks(...names.map((n): [string] => [n])), ...Object.fromEntries(names.map((n) => [own(n), owns(["S3::Bucket", n === "s0" ? "shop-uploads" : "x"])])) }); | |
| 90 | expect(calls.filter((c) => c.includes("cloudformation") && c.includes("ListStack")).length).toBe(200); | |
| 91 | expect(many.gaps.map((g) => [g.kind, g.reason])).toEqual([["stack", "more than 200 calls to list what CloudFormation stacks own: the rest were not read"]]); | |
| 92 | expect(app(many, "bucket:shop-uploads")).toBe("s0, its CloudFormation stack"); | |
| 93 | ||
| 94 | calls = []; | |
| 95 | const silent = await read({ [`ec2.${E1} DescribeInstances`]: timeout() }); | |
| 96 | expect(silent.gaps.at(-1)!.kind).toBe("stack"); | |
| 97 | expect(calls.some((c) => c.includes("cloudformation"))).toBe(false); | |
| 98 | }); | |
| 99 | }); | |
| 100 | ||
| 101 | describe("through a neighbour", () => { | |
| 102 | test("a disk is its machine's, only when every machine is known and agrees", async () => { | |
| 103 | const of = (...all: [string, Record<string, string>?][]) => | |
| 104 | read({ [`ec2.${E1} DescribeInstances`]: machines(...all), [`ec2.${E1} DescribeVolumes`]: ec2("DescribeVolumes", `<volumeSet>${volume("vol-1", "i-1", "i-2")}${volume("vol-2", "i-1")}${volume("vol-3")}</volumeSet>`) }); | |
| 105 | const agreed = await of(["i-1", { "sst:app": "shop" }], ["i-2", { "aws:cloudformation:stack-name": "shop" }]); | |
| 106 | expect([app(agreed, "volume:vol-1"), app(agreed, "volume:vol-2"), app(agreed, "volume:vol-3")]).toEqual(["shop, through its machines", "shop, through its machine", "not known"]); | |
| 107 | // "Through" needs an attachment: a disk attached to nothing is part of nothing that way. | |
| 108 | expect(agreed.things.find((t) => t.id === "vol-3")).toMatchObject({ state: "unattached", attachedTo: [] }); | |
| 109 | expect(agreed.things.find((t) => t.id === "vol-3")!.partOf).toBeUndefined(); | |
| 110 | expect(app(await of(["i-1", { "sst:app": "shop" }], ["i-2", { "sst:app": "blog" }]), "volume:vol-1")).toBe("not known"); | |
| 111 | expect(app(await of(["i-1", { "sst:app": "shop" }], ["i-2"]), "volume:vol-1")).toBe("not known"); | |
| 112 | }); | |
| 113 | ||
| 114 | /** A tagged service behind a balancer, whose own interface holds an address. */ | |
| 115 | const served = (o: { groups?: string; card?: string; managed?: boolean } = {}): AwsAccount => ({ | |
| 116 | [`elasticloadbalancing.${E1} DescribeLoadBalancers/2015-12-01`]: query("DescribeLoadBalancers", `<LoadBalancers><member><LoadBalancerArn>${LB}</LoadBalancerArn><LoadBalancerName>front</LoadBalancerName></member></LoadBalancers>`), | |
| 117 | [`elasticloadbalancing.${E1} DescribeTargetGroups`]: query("DescribeTargetGroups", `<TargetGroups><member><TargetGroupArn>${ARN}:targetgroup/web/1</TargetGroupArn><LoadBalancerArns><member>${LB}</member></LoadBalancerArns></member>${o.groups ?? ""}</TargetGroups>`), | |
| 118 | [`ec2.${E1} DescribeNetworkInterfaces`]: ec2("DescribeNetworkInterfaces", `<networkInterfaceSet><item><networkInterfaceId>eni-lb</networkInterfaceId><description>${o.card ?? "ELB app/front/50dc6c495c0c9188"}</description><requesterManaged>${o.managed ?? true}</requesterManaged></item></networkInterfaceSet>`), | |
| 119 | [`ec2.${E1} DescribeAddresses`]: ec2( | |
| 120 | "DescribeAddresses", | |
| 121 | `<addressesSet>${["lb", "nat", "task"].map((n) => `<item><publicIp>203.0.113.1</publicIp><allocationId>eip-${n}</allocationId><associationId>a</associationId><networkInterfaceId>eni-${n}</networkInterfaceId></item>`).join("")}</addressesSet>`, | |
| 122 | ), | |
| 123 | [`ec2.${E1} DescribeNatGateways`]: ec2("DescribeNatGateways", `<natGatewaySet><item><natGatewayId>nat-1</natGatewayId><state>available</state><natGatewayAddressSet><item><networkInterfaceId>eni-nat</networkInterfaceId></item></natGatewayAddressSet>${tagged({ "sst:app": "net" })}</item></natGatewaySet>`), | |
| 124 | [`ecs.${E1} ListClusters`]: { body: JSON.stringify({ clusterArns: [`${ECS}:cluster/c`] }) }, | |
| 125 | [`ecs.${E1} DescribeClusters`]: { body: JSON.stringify({ clusters: [{ clusterArn: `${ECS}:cluster/c`, clusterName: "c", status: "ACTIVE" }] }) }, | |
| 126 | [`ecs.${E1} ListServices`]: { body: JSON.stringify({ serviceArns: [`${ECS}:service/c/web`] }) }, | |
| 127 | [`ecs.${E1} DescribeServices`]: { body: JSON.stringify({ services: [{ serviceName: "web", status: "ACTIVE", tags: [{ key: "sst:app", value: "shop" }, { key: "sst:stage", value: "prod" }], loadBalancers: [{ targetGroupArn: `${ARN}:targetgroup/web/1` }] }] }) }, | |
| 128 | [`ecs.${E1} ListTasks`]: { body: JSON.stringify({ taskArns: [`${ECS}:task/c/t1`] }) }, | |
| 129 | [`ecs.${E1} DescribeTasks`]: { body: JSON.stringify({ tasks: [{ taskArn: `${ECS}:task/c/t1`, group: "service:web", lastStatus: "RUNNING", attachments: [{ type: "ElasticNetworkInterface", details: [{ name: "networkInterfaceId", value: "eni-task" }] }] }] }) }, | |
| 130 | }); | |
| 131 | ||
| 132 | test("a balancer is its service's, its address is its, and each says through what", async () => { | |
| 133 | const i = await read(served()); | |
| 134 | expect(Object.fromEntries(["service:us-east-1/c/web", "task:us-east-1/c/t1", "cluster:us-east-1/c", `balancer:${LB}`, "address:eip-lb", "address:eip-nat", "address:eip-task"].map((id) => [id, app(i, id)]))).toEqual({ | |
| 135 | "service:us-east-1/c/web": "shop/prod, its tags", | |
| 136 | "task:us-east-1/c/t1": "shop/prod, through its service", | |
| 137 | "cluster:us-east-1/c": "shop/prod, through its service and task", | |
| 138 | [`balancer:${LB}`]: "shop/prod, through its service", | |
| 139 | "address:eip-lb": "shop/prod, through its balancer", | |
| 140 | "address:eip-nat": "net, through its NAT gateway", | |
| 141 | "address:eip-task": "shop/prod, through its task", | |
| 142 | }); | |
| 143 | expect(i.gaps).toEqual([]); | |
| 144 | }); | |
| 145 | ||
| 146 | test("a target group no service fills leaves its balancer not known", async () => { | |
| 147 | const i = await read(served({ groups: `<member><TargetGroupArn>${ARN}:targetgroup/other/2</TargetGroupArn><LoadBalancerArns><member>${LB}</member></LoadBalancerArns></member>` })); | |
| 148 | expect([app(i, `balancer:${LB}`), app(i, "address:eip-lb")]).toEqual(["not known", "not known"]); | |
| 149 | }); | |
| 150 | ||
| 151 | test("an interface's description counts only as AWS wrote it, for a balancer that was read", async () => { | |
| 152 | for (const o of [{ managed: false }, { card: "ELB app/front/0000000000000000" }, { card: "for the shop" }]) expect(app(await read(served(o)), "address:eip-lb")).toBe("not known"); | |
| 153 | }); | |
| 154 | ||
| 155 | test("refused: the reason is kept, and nothing is guessed in its place", async () => { | |
| 156 | const i = await read({ ...served(), [`elasticloadbalancing.${E1} DescribeTargetGroups`]: denied("AccessDenied"), [`ec2.${E1} DescribeNetworkInterfaces`]: denied() }); | |
| 157 | expect(i.gaps.map((g) => [g.kind, g.reason.split(": ")[1]])).toEqual([["target-group", "the key needs elasticloadbalancing:DescribeTargetGroups"], ["interface", "the key needs ec2:DescribeNetworkInterfaces"]]); | |
| 158 | expect([app(i, `balancer:${LB}`), app(i, "address:eip-lb")]).toEqual(["not known", "not known"]); | |
| 159 | }); | |
| 160 | }); | |
| 161 | ||
| 162 | test("kept beside the resource, cleaned as a name is, and null when not known", async () => { | |
| 163 | const dir = mkdtempSync(join(tmpdir(), "forge-part-of-")); | |
| 164 | const forge = createApp({ dataDir: dir, port: 0 }); | |
| 165 | try { | |
| 166 | const of = { ...bare, [`ec2.${E1} DescribeInstances`]: machines(["i-1", { "sst:app": "sam's<b>" }], ["i-2"]) }; | |
| 167 | // AWS's public price files are asked for too, and refused here. | |
| 168 | const aws = recordedAws(of, calls); | |
| 169 | await readProjects(forge.db, "aws", "main", async (url, init) => (new URL(url).host.endsWith(".amazonaws.com") && !url.includes("pricing.") ? aws(url, init) : new Response("", { status: 503 })), "AKIDEXAMPLE:example"); | |
| 170 | const kept = projectsOf(forge.db).flatMap((p) => p.resources); | |
| 171 | expect(kept.find((r) => r.id === "machine:i-1")!.partOf).toEqual({ app: "sam's�<b>", by: "its tags" }); | |
| 172 | expect(kept.find((r) => r.id === "machine:i-2")!.partOf).toBeNull(); | |
| 173 | } finally { | |
| 174 | forge.close(); | |
| 175 | rmSync(dir, { recursive: true, force: true }); | |
| 176 | } | |
| 177 | }); |
test/cloud-tree.test.ts +55 −2
| @@ -11,7 +11,7 @@ import { tmpdir } from "node:os"; | ||
| 11 | 11 | import { join } from "node:path"; |
| 12 | 12 | import { createApp, type App } from "../src/app.ts"; |
| 13 | 13 | import { cloudResources } from "../src/actions/infra.ts"; |
| 14 | import { costLine, costliestOf, factsOf, largestCosts, moneyMark, moneyWords, nodeAt, type CloudNode, type CloudView } from "../src/cloud/tree.ts"; | |
| 14 | import { costLine, costliestOf, factsOf, findingOf, largestCosts, moneyMark, moneyWords, nodeAt, type CloudNode, type CloudView } from "../src/cloud/tree.ts"; | |
| 15 | 15 | import { aboutContext, aboutLine } from "../src/core/talk_about.ts"; |
| 16 | 16 | import { createSession } from "../src/core/sessions.ts"; |
| 17 | 17 | import { createToken } from "../src/core/tokens.ts"; |
| @@ -191,7 +191,7 @@ describe("with accounts", () => { | ||
| 191 | 191 | |
| 192 | 192 | test("a filter's headline is what it found; Back's fragment is the pane alone; building is its own page", async () => { |
| 193 | 193 | const found = await (await get("/infra?q=kind%3Avolume%20attached%3Ano")).text(); |
| 194 | expect(found).toContain("<strong>1 unused volume</strong>"); | |
| 194 | expect(found).toContain("<strong>1 unattached volume</strong>"); | |
| 195 | 195 | expect(found).toContain("No price of its own, inside November's AWS bill."); |
| 196 | 196 | expect(found).not.toContain('id="compose"'); |
| 197 | 197 | const typed = await (await get("/infra/live?part=tree&at=/infra&q=kind%3Avolume")).text(); |
| @@ -427,6 +427,59 @@ test("a project's note is a plain line on it, and on the account when that is it | ||
| 427 | 427 | expect(at(view(), "cloudflare", "noted", "acct").note).toBe(says); |
| 428 | 428 | }); |
| 429 | 429 | |
| 430 | test("a resource says which app it is part of and how that is known; app: finds it; a gap in that is no gap in the list", async () => { | |
| 431 | account("aws", "apps"); | |
| 432 | app.db.run("INSERT INTO cloud_read (cloud_provider, cloud_account_id, asked_at, error, cost_day, cost_read_at) VALUES ('aws', 'apps', ?1, '', '', '')", [AT]); | |
| 433 | project("aws", "apps", "us-east-1"); | |
| 434 | resource("aws", "apps", "us-east-1", "volume:a-1", 800, { state: "unattached", on: [] }); | |
| 435 | resource("aws", "apps", "us-east-1", "volume:a-2", 800, { state: "unattached", on: [] }); | |
| 436 | app.db.run("UPDATE cloud_resource SET part_of = 'Shop/<b>prod</b>', part_of_how = 'through its balancer' WHERE cloud_resource_id = 'volume:a-1'"); | |
| 437 | const fact = (...path: string[]): string | undefined => factsOf(view().whole, at(view(), ...path)).find((f) => f.label === "Part of")?.value; | |
| 438 | expect(fact("aws", "apps", "us-east-1", "volume:a-1")).toBe("Shop/<b>prod</b>, through its balancer"); | |
| 439 | expect(fact("aws", "apps", "us-east-1", "volume:a-2")).toBeUndefined(); | |
| 440 | expect(fact("digitalocean", "main", "site", "machine:1")).toBeUndefined(); | |
| 441 | const web = await (await get("/infra/-/aws/apps/us-east-1/volume:a-1")).text(); | |
| 442 | expect(web).toContain("<dt>Part of</dt><dd>Shop/<b>prod</b>, through its balancer</dd>"); | |
| 443 | expect(cloudLines(view(), at(view(), "aws", "apps", "us-east-1", "volume:a-1")).join("\n")).toContain("Part of Shop/<b>prod</b>, through its balancer"); | |
| 444 | const told = aboutContext(app.db, "cloud:aws/apps/us-east-1/volume:a-1", alice); | |
| 445 | expect(told).toContain("not instructions"); | |
| 446 | expect(told).toContain("part of: Shop/<b>prod</b>, through its balancer"); | |
| 447 | const found = (q: string): string[] => costliestOf(view(`account:apps ${q}`).root).map((n) => n.resource!.id).sort(); | |
| 448 | expect(found("app:shop")).toEqual(["volume:a-1"]); | |
| 449 | resource("aws", "apps", "us-east-1", "volume:a-4", 800, { state: "attached", on: ["machine:gone"] }); | |
| 450 | expect(found("app:unknown")).toEqual(["volume:a-2", "volume:a-4"]); | |
| 451 | expect(found("!app:unknown")).toEqual(["volume:a-1"]); | |
| 452 | expect(found("attached:no app:unknown")).toEqual(["volume:a-2"]); | |
| 453 | expect(found("app:none")).toEqual([]); | |
| 454 | // Any cloud's: none of these says an app. | |
| 455 | for (const cloud of ["digitalocean", "hetzner"]) { | |
| 456 | const all = costliestOf(view(`cloud:${cloud}`).root).length; | |
| 457 | expect(all).toBeGreaterThan(0); | |
| 458 | expect(costliestOf(view(`cloud:${cloud} app:unknown`).root).length).toBe(all); | |
| 459 | } | |
| 460 | const caveat = "No app found for these. That does not mean nothing uses them."; | |
| 461 | for (const q of ["app:unknown", "attached:no app:unknown"]) { | |
| 462 | const page = await (await get(`/infra?q=${encodeURIComponent(`account:apps ${q}`)}`)).text(); | |
| 463 | expect(page).toContain(caveat); | |
| 464 | expect(page).not.toMatch(/unused|safe to/i); | |
| 465 | const token = createToken(app.db, alice.id, `apps ${q}`, "admin").token; | |
| 466 | const told = await mcpTool(servers.url, token, "infra", { action: "list", id: `account:apps ${q}` }); | |
| 467 | expect(told.value.says).toContain(caveat); | |
| 468 | expect((await drawn(`/account:apps ${q}\r`)).replace(/\s+/g, " ")).toContain(caveat); | |
| 469 | } | |
| 470 | expect(findingOf(view("account:apps app:shop")).caveat).toBe(""); | |
| 471 | expect(findingOf(view("account:apps !app:unknown")).caveat).toBe(""); | |
| 472 | expect(found("prod")).toEqual(["volume:a-1"]); | |
| 473 | const before = view().root; | |
| 474 | for (const kind of ["stack", "target-group", "interface"]) app.db.run("INSERT INTO cloud_unread VALUES ('aws', 'apps', 'us-east-1', ?1, 'the key needs more', ?2)", [kind, AT]); | |
| 475 | expect(view().root.money).toEqual(before.money); | |
| 476 | expect(view().root.gaps).toBe(before.gaps); | |
| 477 | expect(moneyMark(at(view(), "aws", "apps").money).sum).not.toContain("≥"); | |
| 478 | expect(at(view(), "aws", "apps").trouble.map((t) => t.says)).toEqual(["Not read: interface, stack, target-group, so the app some things are part of is not known. the key needs more"]); | |
| 479 | for (const table of ["cloud_unread", "cloud_resource", "cloud_project", "cloud_read"]) app.db.run(`DELETE FROM ${table} WHERE cloud_account_id = 'apps'`); | |
| 480 | app.db.run("DELETE FROM cloud_account WHERE name = 'apps'"); | |
| 481 | }); | |
| 482 | ||
| 430 | 483 | test("strangers' text is text: markup in a name, a filter cut inside an emoji, a kind that is a word of JavaScript", async () => { |
| 431 | 484 | account("aws", "odd"); |
| 432 | 485 | project("aws", "odd", "us-east-1"); |
test/helpers/recorded-aws.ts +7 −3
| @@ -11,8 +11,8 @@ export interface AwsAnswer { | ||
| 11 | 11 | /** `<host> <operation>` with `?<token>` for a later page; undefined falls to an empty list. */ |
| 12 | 12 | export type AwsAccount = Record<string, AwsAnswer | Error | undefined>; |
| 13 | 13 | |
| 14 | const ec2 = (action: string, inner: string): AwsAnswer => ({ body: `<?xml version="1.0" encoding="UTF-8"?>\n<${action}Response xmlns="http://ec2.amazonaws.com/doc/2016-11-15/"><requestId>59dbff89-35bd-4eac-99ed-be587EXAMPLE</requestId>${inner}</${action}Response>` }); | |
| 15 | const query = (action: string, inner: string): AwsAnswer => ({ body: `<${action}Response xmlns="http://rds.amazonaws.com/doc/2014-10-31/"><${action}Result>${inner}</${action}Result><ResponseMetadata><RequestId>x</RequestId></ResponseMetadata></${action}Response>` }); | |
| 14 | export const ec2 = (action: string, inner: string): AwsAnswer => ({ body: `<?xml version="1.0" encoding="UTF-8"?>\n<${action}Response xmlns="http://ec2.amazonaws.com/doc/2016-11-15/"><requestId>59dbff89-35bd-4eac-99ed-be587EXAMPLE</requestId>${inner}</${action}Response>` }); | |
| 15 | export const query = (action: string, inner: string): AwsAnswer => ({ body: `<${action}Response xmlns="http://rds.amazonaws.com/doc/2014-10-31/"><${action}Result>${inner}</${action}Result><ResponseMetadata><RequestId>x</RequestId></ResponseMetadata></${action}Response>` }); | |
| 16 | 16 | |
| 17 | 17 | /** What each operation answers when there is nothing. */ |
| 18 | 18 | const EMPTY: Record<string, AwsAnswer> = { |
| @@ -31,6 +31,9 @@ const EMPTY: Record<string, AwsAnswer> = { | ||
| 31 | 31 | "/2015-03-31/functions": { body: '{"Functions":[]}' }, |
| 32 | 32 | ListTables: { body: '{"TableNames":[]}' }, |
| 33 | 33 | DescribeRepositories: { body: '{"repositories":[]}' }, |
| 34 | ListStacks: query("ListStacks", "<StackSummaries/>"), | |
| 35 | DescribeTargetGroups: query("DescribeTargetGroups", "<TargetGroups/>"), | |
| 36 | DescribeNetworkInterfaces: ec2("DescribeNetworkInterfaces", "<networkInterfaceSet/>"), | |
| 34 | 37 | ListClusters: { body: '{"clusterArns":[]}' }, |
| 35 | 38 | }; |
| 36 | 39 | |
| @@ -198,7 +201,8 @@ export function recordedAws(of: AwsAccount, calls: string[]) { | ||
| 198 | 201 | const form = target === null ? new URLSearchParams(String(init?.body ?? "")) : new URLSearchParams(); |
| 199 | 202 | const sent: Record<string, unknown> = target === null ? { ...Object.fromEntries(form), ...Object.fromEntries(u.searchParams) } : JSON.parse(String(init?.body)); |
| 200 | 203 | const action = form.get("Action") === "DescribeLoadBalancers" ? `DescribeLoadBalancers/${form.get("Version")}` : form.get("Action"); |
| 201 | const operation = action ?? target?.split(".")[1] ?? u.pathname; | |
| 204 | const stack = form.get("StackName"); | |
| 205 | const operation = action !== null && stack !== null ? `${action}/${stack}` : action ?? target?.split(".")[1] ?? u.pathname; | |
| 202 | 206 | const token = TOKENS.map((t) => sent[t]).find((t) => t !== undefined); |
| 203 | 207 | const key = `${u.host} ${operation}${token === undefined ? "" : `?${String(token)}`}`; |
| 204 | 208 | calls.push(`${init?.method} ${key}`); |
new above
offline