@mark1russell7/stack-spend 0.1.9 → 0.1.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -445,6 +445,7 @@ The rules of the stop:
445
445
  - A request that fails gives the result `failed` and an error in the log. The next notification tries again.
446
446
  - The result of the function holds no token.
447
447
  - The identity also has the role Service Usage Consumer, because Eventarc examines that the identity of a trigger can use the project.
448
+ - The last step of the script reads the JSON result of a test with a cost of 0. It tells "The stop is live." only for `kept` with `ready`, and else it stops with an error.
448
449
  - A change of IAM comes into force after a delay. The script tries each grant and the deploy again while the error is such a delay, at most 16 times, 20 seconds apart. Each other error stops the script.
449
450
 
450
451
  The limits of the stop:
package/build/gcp-stop.js CHANGED
@@ -366,10 +366,26 @@ if [ -z "$(gcloud billing budgets list --billing-account="$ACCOUNT" --billing-pr
366
366
  fi
367
367
 
368
368
  echo "7/7 Test the function with a cost of 0. This test does not stop the project."
369
+ SENT="$(date -u +%Y-%m-%dT%H:%M:%SZ)"
369
370
  gcloud pubsub topics publish "$NAME" --message="{\\"budgetDisplayName\\":\\"$DISPLAY test\\",\\"costAmount\\":0,\\"budgetAmount\\":$AMOUNT,\\"currencyCode\\":\\"$CURRENCY\\",\\"costIntervalStart\\":\\"$(date -u +%Y-%m-01T00:00:00Z)\\"}"
370
- sleep 90
371
- gcloud functions logs read "$NAME" --gen2 --region="$REGION" --limit=10
372
- echo "The stop is live when a line of the log has \\"action\\":\\"kept\\" and \\"ready\\":true."
371
+ # The function writes its result as a JSON line. "gcloud functions logs read" does not show such a line, so the script reads it with "gcloud logging read".
372
+ # The result can come to the log some minutes late. Thus the script reads the log at most 15 times, 20 seconds apart.
373
+ FILTER="resource.type=\\"cloud_run_revision\\" AND resource.labels.service_name=\\"$NAME\\" AND jsonPayload.action:* AND timestamp>=\\"$SENT\\""
374
+ RESULT=""
375
+ for try in $(seq 1 15); do
376
+ sleep 20
377
+ RESULT="$(gcloud logging read "$FILTER" --limit=1 --format='value(jsonPayload.action,jsonPayload.ready)')"
378
+ if [ -n "$RESULT" ]; then break; fi
379
+ done
380
+ if [ -z "$RESULT" ]; then RESULT="no result"; fi
381
+ echo "The result of the test: $RESULT"
382
+ case "$RESULT" in
383
+ kept*True)
384
+ echo "The stop is live." ;;
385
+ *)
386
+ echo "The stop is not live. The log of the function: gcloud functions logs read $NAME --gen2 --region=$REGION --limit=20" >&2
387
+ exit 1 ;;
388
+ esac
373
389
  `;
374
390
  }
375
391
  export { BILLING_URL, FRAMEWORK_RANGE, METADATA_URL, RESOURCE_MANAGER_URL, STOP_ENTRY_POINT, STOP_PERMISSION, STOP_RUNTIME, billingInfoRequest, decideStop, detachRequest, isProjectId, permissionRequest, projectRequest, readNotification, stopBilling, stopScript, stopSource, tokenRequest };
@@ -1 +1 @@
1
- {"version":3,"file":"gcp-stop.js","names":[],"sources":["../src/gcp-stop.ts"],"sourcesContent":["/**\n * The entry `@mark1russell7/stack-spend/gcp-stop`: a stop by code for a project of Google Cloud.\n *\n * A budget of the project sends a notification to a Pub/Sub topic some times each day. A function reads each notification.\n * When the cost of the month is at the amount of the budget, the function removes the billing account of the project.\n * Then Google stops the paid services of the project. This is the limit of the kind `code`, with the function as its `stop`.\n *\n * The entry has no dependencies and no clock. The caller gives the `fetch`, so a test gives a fake.\n */\n\n/** The fields of a budget notification that the stop uses. */\nexport interface BudgetNotification {\n /** The name of the budget. */\n readonly budgetDisplayName: string;\n /** The cost of the period of the budget, up to the time of the notification. */\n readonly costAmount: number;\n /** The amount of the budget. */\n readonly budgetAmount: number;\n /** The currency of the two amounts, for example `USD`. */\n readonly currencyCode: string;\n /** The start of the period of the budget, as an ISO 8601 time. */\n readonly costIntervalStart: string;\n}\n\n/** The result of a read of a notification: the notification, or the reason that the read failed. */\nexport type NotificationRead = { readonly ok: true; readonly notification: BudgetNotification } | { readonly ok: false; readonly error: string };\n\n/** The decision of the stop for one notification. */\nexport interface StopDecision {\n /** `true` when the cost is at the amount of the budget or above it. */\n readonly stop: boolean;\n /** The decision in words, with the two amounts. */\n readonly reason: string;\n}\n\n/** One request of the stop, as data. The headers can hold a token, so do not write a request to a log. */\nexport interface StopRequest {\n readonly method: \"GET\" | \"POST\" | \"PUT\";\n readonly url: string;\n readonly headers: Readonly<Record<string, string>>;\n readonly body?: string;\n}\n\n/** The answer of a request, with only the parts that the stop reads. The global `fetch` gives this form. */\nexport interface StopAnswer {\n readonly status: number;\n text(): Promise<string>;\n}\n\n/** The function that sends a request. The global `fetch` is such a function. */\nexport type StopFetch = (url: string, init: { method: string; headers: Record<string, string>; body?: string }) => Promise<StopAnswer>;\n\n/**\n * The result of the stop for one notification. It holds no token.\n *\n * - `refused`: the notification has a fault of form, so the stop does nothing.\n * - `kept`: the cost is below the amount. `ready` tells if the identity of the function can remove the billing account.\n * - `stopped`: the stop removed the billing account of the project.\n * - `already`: the project had no billing account.\n * - `failed`: a request failed. The next notification tries again.\n */\nexport type StopOutcome =\n | { readonly action: \"refused\"; readonly reason: string }\n | { readonly action: \"kept\"; readonly reason: string; readonly project: string; readonly ready: boolean }\n | { readonly action: \"stopped\" | \"already\"; readonly reason: string; readonly project: string }\n | { readonly action: \"failed\"; readonly reason: string };\n\n/** The root of the metadata server of Google Cloud. A function gets its token and its project from it. */\nexport const METADATA_URL = \"http://metadata.google.internal/computeMetadata/v1\";\n\n/** The root of the Cloud Billing API. */\nexport const BILLING_URL = \"https://cloudbilling.googleapis.com/v1\";\n\n/** The root of the Cloud Resource Manager API. */\nexport const RESOURCE_MANAGER_URL = \"https://cloudresourcemanager.googleapis.com/v1\";\n\n/** The permission that lets the identity of the function remove the billing account of the project. */\nexport const STOP_PERMISSION = \"resourcemanager.projects.deleteBillingAssignment\";\n\n/** The rule of a project id of Google Cloud: 6 to 30 characters, lowercase letters, digits and hyphens, and a letter first. */\nconst PROJECT_ID = /^[a-z][a-z0-9-]{4,28}[a-z0-9]$/;\n\n/** This function tells if a text is a project id of Google Cloud. A request puts the id in its path, so the stop examines it. */\nexport function isProjectId(value: string): boolean {\n return PROJECT_ID.test(value);\n}\n\n// The build of the package is for each platform, so its types have no DOM and no Node. Node, Deno and each browser have these two globals.\ndeclare const atob: (data: string) => string;\ndeclare const TextDecoder: new (label: string, options: { fatal: boolean }) => { decode(input: Uint8Array): string };\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\n\n/** This function decodes base64 text to UTF-8 text, or gives `undefined` for text that is not base64. */\nfunction fromBase64(text: string): string | undefined {\n try {\n const bytes = Uint8Array.from(atob(text), (character: string) => character.charCodeAt(0));\n return new TextDecoder(\"utf-8\", { fatal: true }).decode(bytes);\n } catch {\n return undefined;\n }\n}\n\n/**\n * This function reads a budget notification from the data of a CloudEvent of Pub/Sub. The data has the form\n * `{ message: { data } }`, and `data` is the notification as base64 JSON.\n */\nexport function readNotification(data: unknown): NotificationRead {\n const message = isRecord(data) && isRecord(data[\"message\"]) ? data[\"message\"] : undefined;\n const encoded = message?.[\"data\"];\n if (typeof encoded !== \"string\") return { ok: false, error: \"The event has no message data.\" };\n const text = fromBase64(encoded);\n if (text === undefined) return { ok: false, error: \"The message data is not base64 UTF-8 text.\" };\n let value: unknown;\n try {\n value = JSON.parse(text);\n } catch {\n return { ok: false, error: \"The message data is not JSON.\" };\n }\n if (!isRecord(value)) return { ok: false, error: \"The notification is not an object.\" };\n const { costAmount, budgetAmount } = value;\n if (typeof costAmount !== \"number\" || !Number.isFinite(costAmount) || costAmount < 0) return { ok: false, error: \"The field costAmount is not a number of 0 or more.\" };\n if (typeof budgetAmount !== \"number\" || !Number.isFinite(budgetAmount) || budgetAmount <= 0) return { ok: false, error: \"The field budgetAmount is not a number above 0.\" };\n // The stop needs only the two amounts. A text field that is not there does not stop the stop: it becomes an empty text.\n const record = value;\n const textOf = (field: string): string => {\n const found = record[field];\n return typeof found === \"string\" ? found : \"\";\n };\n return {\n ok: true,\n notification: { budgetDisplayName: textOf(\"budgetDisplayName\"), costAmount, budgetAmount, currencyCode: textOf(\"currencyCode\"), costIntervalStart: textOf(\"costIntervalStart\") },\n };\n}\n\n/** This function decides the stop: the stop acts when the cost is at the amount of the budget or above it. */\nexport function decideStop(notification: BudgetNotification): StopDecision {\n const { costAmount, budgetAmount, currencyCode, budgetDisplayName } = notification;\n const amounts = `${String(costAmount)} ${currencyCode} of ${String(budgetAmount)} ${currencyCode}`;\n return costAmount >= budgetAmount\n ? { stop: true, reason: `The cost of the budget \"${budgetDisplayName}\" is at its amount: ${amounts}.` }\n : { stop: false, reason: `The cost of the budget \"${budgetDisplayName}\" is below its amount: ${amounts}.` };\n}\n\n/** This function gives the request of the token of the identity of the function, to the metadata server. */\nexport function tokenRequest(): StopRequest {\n return { method: \"GET\", url: `${METADATA_URL}/instance/service-accounts/default/token`, headers: { \"metadata-flavor\": \"Google\" } };\n}\n\n/** This function gives the request of the id of the project of the function, to the metadata server. */\nexport function projectRequest(): StopRequest {\n return { method: \"GET\", url: `${METADATA_URL}/project/project-id`, headers: { \"metadata-flavor\": \"Google\" } };\n}\n\nfunction checkedProject(project: string): string {\n if (!isProjectId(project)) throw new Error(\"The project id is not a project id of Google Cloud.\");\n return project;\n}\n\n/** This function gives the request that reads the billing state of a project. */\nexport function billingInfoRequest(project: string, token: string): StopRequest {\n return { method: \"GET\", url: `${BILLING_URL}/projects/${checkedProject(project)}/billingInfo`, headers: { authorization: `Bearer ${token}` } };\n}\n\n/** This function gives the request that removes the billing account of a project: a billing account name that is empty. */\nexport function detachRequest(project: string, token: string): StopRequest {\n return {\n method: \"PUT\",\n url: `${BILLING_URL}/projects/${checkedProject(project)}/billingInfo`,\n headers: { authorization: `Bearer ${token}`, \"content-type\": \"application/json\" },\n body: JSON.stringify({ billingAccountName: \"\" }),\n };\n}\n\n/** This function gives the request that tells if the identity of the function holds the permission of the stop. */\nexport function permissionRequest(project: string, token: string): StopRequest {\n return {\n method: \"POST\",\n url: `${RESOURCE_MANAGER_URL}/projects/${checkedProject(project)}:testIamPermissions`,\n headers: { authorization: `Bearer ${token}`, \"content-type\": \"application/json\" },\n body: JSON.stringify({ permissions: [STOP_PERMISSION] }),\n };\n}\n\n/** A failed request, with a reason that holds no token. */\nclass RequestFailure extends Error {}\n\nasync function send(fetch: StopFetch, request: StopRequest, what: string): Promise<string> {\n const init = { method: request.method, headers: { ...request.headers }, ...(request.body === undefined ? {} : { body: request.body }) };\n let answer: StopAnswer;\n try {\n answer = await fetch(request.url, init);\n } catch (error) {\n throw new RequestFailure(`The request of ${what} failed: ${error instanceof Error ? error.name : \"an error\"}.`);\n }\n const text = await answer.text();\n if (answer.status !== 200) throw new RequestFailure(`The request of ${what} gave the status ${String(answer.status)}.`);\n return text;\n}\n\nfunction json(text: string, what: string): Record<string, unknown> {\n try {\n const value: unknown = JSON.parse(text);\n if (isRecord(value)) return value;\n } catch {\n // The text is not JSON. The next line gives the failure.\n }\n throw new RequestFailure(`The answer of ${what} is not a JSON object.`);\n}\n\n/**\n * This function is the stop. It reads the notification, and it decides. Below the amount, it examines that the identity of\n * the function holds the permission of the stop. At the amount, it removes the billing account of the project, if the\n * project has one.\n *\n * @param data - The data of the CloudEvent of Pub/Sub\n * @param fetch - The function that sends a request, for example the global `fetch`\n */\nexport async function stopBilling(data: unknown, fetch: StopFetch): Promise<StopOutcome> {\n const read = readNotification(data);\n if (!read.ok) return { action: \"refused\", reason: read.error };\n const decision = decideStop(read.notification);\n try {\n const project = (await send(fetch, projectRequest(), \"the project id\")).trim();\n if (!isProjectId(project)) return { action: \"failed\", reason: \"The metadata server gave a text that is not a project id.\" };\n const tokenText = await send(fetch, tokenRequest(), \"the token\");\n const token = json(tokenText, \"the token\")[\"access_token\"];\n if (typeof token !== \"string\" || token === \"\") return { action: \"failed\", reason: \"The answer of the token has no access_token.\" };\n if (!decision.stop) {\n const held = json(await send(fetch, permissionRequest(project, token), \"the permissions\"), \"the permissions\")[\"permissions\"];\n const ready = Array.isArray(held) && held.includes(STOP_PERMISSION);\n return { action: \"kept\", reason: decision.reason, project, ready };\n }\n // The read of the billing state only prevents a write that is not necessary. The stop must not depend on it: when the\n // read fails, for example because the identity cannot read the project, the function sends the removal all the same.\n let enabled: boolean | undefined;\n try {\n enabled = json(await send(fetch, billingInfoRequest(project, token), \"the billing state\"), \"the billing state\")[\"billingEnabled\"] === true;\n } catch (error) {\n if (!(error instanceof RequestFailure)) throw error;\n }\n if (enabled === false) return { action: \"already\", reason: `${decision.reason} The project has no billing account.`, project };\n await send(fetch, detachRequest(project, token), \"the removal of the billing account\");\n return { action: \"stopped\", reason: `${decision.reason} The stop removed the billing account of the project.`, project };\n } catch (error) {\n if (error instanceof RequestFailure) return { action: \"failed\", reason: error.message };\n throw error;\n }\n}\n\n/** The options of the script that makes the stop of a project. */\nexport interface StopScriptOptions {\n /** The id of the project. */\n readonly project: string;\n /** The amount of the budget for each month. */\n readonly amount: number;\n /** The currency of the billing account, for example `USD`. */\n readonly currency: string;\n /** The version range of this package in the source of the function, for example `^0.1.8`. */\n readonly version: string;\n /** The region of the function. The default is `us-central1`. */\n readonly region?: string;\n /** The name of the topic, of the function and of its identity. The default is `billing-stop`. */\n readonly name?: string;\n}\n\n/** The version range of the Functions Framework in the source of the function. */\nexport const FRAMEWORK_RANGE = \"^5.0.5\";\n\n/** The runtime of the function. */\nexport const STOP_RUNTIME = \"nodejs22\";\n\n/** The name of the entry point of the function. */\nexport const STOP_ENTRY_POINT = \"billingStop\";\n\n/** This function gives the source of the function: its `package.json` and its `index.js`. */\nexport function stopSource(version: string): { readonly packageJson: string; readonly indexJs: string } {\n if (!/^[\\^~]?\\d+\\.\\d+\\.\\d+$/.test(version)) throw new Error(\"The version is not a version range of the form ^1.2.3.\");\n const packageJson = JSON.stringify(\n {\n name: \"billing-stop\",\n private: true,\n type: \"module\",\n main: \"index.js\",\n dependencies: { \"@google-cloud/functions-framework\": FRAMEWORK_RANGE, \"@mark1russell7/stack-spend\": version },\n },\n null,\n 2,\n );\n const indexJs = [\n 'import functions from \"@google-cloud/functions-framework\";',\n 'import { stopBilling } from \"@mark1russell7/stack-spend/gcp-stop\";',\n \"\",\n \"// The function gets each budget notification. A failure or an identity with no permission gives an error in the log.\",\n `functions.cloudEvent(\"${STOP_ENTRY_POINT}\", async (event) => {`,\n \" const outcome = await stopBilling(event.data, fetch);\",\n \" console.log(JSON.stringify(outcome));\",\n ' if (outcome.action === \"failed\") throw new Error(outcome.reason);',\n ' if (outcome.action === \"kept\" && !outcome.ready) throw new Error(\"The identity of the function cannot remove the billing account.\");',\n \"});\",\n ].join(\"\\n\");\n return { packageJson, indexJs };\n}\n\n/**\n * This function gives a Bash script for Cloud Shell. The script makes the stop of a project: a budget for each month, a\n * Pub/Sub topic, the identity of the function, and the function. Then it tests the function with a cost of 0.\n *\n * The script has no key and makes no key. It reads the billing account of the project when it starts, so the text does not\n * hold the account id. A second run changes nothing that is already made.\n */\nexport function stopScript(options: StopScriptOptions): string {\n const { project, amount, currency, version } = options;\n const region = options.region ?? \"us-central1\";\n const name = options.name ?? \"billing-stop\";\n if (!isProjectId(project)) throw new Error(\"The project id is not a project id of Google Cloud.\");\n if (!Number.isFinite(amount) || amount <= 0) throw new Error(\"The amount is not a number above 0.\");\n if (!/^[A-Z]{3}$/.test(currency)) throw new Error(\"The currency is not a code of three letters.\");\n if (!/^[a-z]+-[a-z]+\\d+$/.test(region)) throw new Error(\"The region is not a region of Google Cloud.\");\n if (!isProjectId(name)) throw new Error(\"The name is not 6 to 30 lowercase letters, digits and hyphens.\");\n const source = stopSource(version);\n const money = `${String(amount)} ${currency}`;\n return `#!/usr/bin/env bash\n# The stop of the cost of the project ${project}: a budget of ${money} for each month, a Pub/Sub topic and a function.\n# When the cost of a month gets to ${money}, the function removes the billing account of the project.\n#\n# What a stop does:\n# - Google stops the paid services of the project. A server stops, also a server in the free tier.\n# - Google keeps the disks and the data for a time. It can delete the resources of a project with no billing account.\n# - The cost data of Google comes some hours late. Thus the cost can go a little above ${money} before the stop.\n#\n# How to undo a stop:\n# 1. Raise the amount of the budget, or wait for the next month. Else the next notification stops the project again.\n# 2. Link the billing account again: gcloud billing projects link ${project} --billing-account=<the account id>\n# 3. Start each server again: gcloud compute instances start <the server> --zone=<its zone>\n#\n# Run this script in Cloud Shell, as the owner of the project and of its billing account.\nset -euo pipefail\n\nPROJECT=\"${project}\"\nNAME=\"${name}\"\nREGION=\"${region}\"\nAMOUNT=\"${String(amount)}\"\nCURRENCY=\"${currency}\"\nSA=\"$NAME@$PROJECT.iam.gserviceaccount.com\"\nDISPLAY=\"$NAME $AMOUNT $CURRENCY\"\n\ngcloud config set project \"$PROJECT\"\n\necho \"1/7 Read the billing account of the project.\"\n# Cloud Shell signs in as a user, so each billing command uses the project for its quota (--billing-project).\ngcloud services enable cloudbilling.googleapis.com\nACCOUNT=\"$(gcloud billing projects describe \"$PROJECT\" --billing-project=\"$PROJECT\" --format='value(billingAccountName)')\"\nACCOUNT=\"\\${ACCOUNT#billingAccounts/}\"\nif [ -z \"$ACCOUNT\" ]; then\n echo \"The project $PROJECT has no billing account. Link it, then run this script again.\"\n exit 1\nfi\n\necho \"2/7 Turn on the APIs.\"\ngcloud services enable cloudfunctions.googleapis.com cloudbuild.googleapis.com artifactregistry.googleapis.com run.googleapis.com eventarc.googleapis.com pubsub.googleapis.com billingbudgets.googleapis.com cloudresourcemanager.googleapis.com\n\necho \"3/7 Make the identity of the function.\"\ngcloud iam service-accounts describe \"$SA\" > /dev/null 2>&1 || gcloud iam service-accounts create \"$NAME\" --display-name=\"The stop of the cost\"\n# A change of IAM comes into force after a delay. A new service account or a new role can be missing for some minutes.\n# Thus try_again runs a command again while its error is one of these delays, at most 16 times, 20 seconds apart.\n# Each other error stops the script.\ntry_again() {\n local try out\n out=\"$(mktemp)\"\n for try in $(seq 1 16); do\n if \"$@\" 2>&1 | tee \"$out\"; then rm -f \"$out\"; return 0; fi\n if ! grep -qE \"Service account [^ ]+ does not exist|does not have required permission|Propagation of the new permission\" \"$out\"; then rm -f \"$out\"; return 1; fi\n echo \"A new identity or role is not in force yet. Wait 20 seconds (try $try of 16).\"\n sleep 20\n done\n rm -f \"$out\"\n return 1\n}\ngrant() {\n try_again gcloud projects add-iam-policy-binding \"$PROJECT\" --member=\"serviceAccount:$SA\" --role=\"$1\" --condition=None --format=none\n}\n# The role Project Billing Manager lets the function remove the billing account of this project only.\ngrant \"roles/billing.projectManager\"\n# The trigger calls the function with the same identity.\ngrant \"roles/run.invoker\"\n# Eventarc examines that the identity of the trigger can use the project (serviceusage.services.use).\ngrant \"roles/serviceusage.serviceUsageConsumer\"\n\necho \"4/7 Make the topic.\"\ngcloud pubsub topics describe \"$NAME\" > /dev/null 2>&1 || gcloud pubsub topics create \"$NAME\"\n\necho \"5/7 Deploy the function.\"\nSOURCE=\"$(mktemp -d)\"\ncat > \"$SOURCE/package.json\" <<'JSON'\n${source.packageJson}\nJSON\ncat > \"$SOURCE/index.js\" <<'JS'\n${source.indexJs}\nJS\ntry_again gcloud functions deploy \"$NAME\" --gen2 --runtime=${STOP_RUNTIME} --region=\"$REGION\" --source=\"$SOURCE\" --entry-point=${STOP_ENTRY_POINT} --trigger-topic=\"$NAME\" --service-account=\"$SA\" --trigger-service-account=\"$SA\" --max-instances=1 --memory=256Mi --quiet\n\necho \"6/7 Make the budget.\"\nif [ -z \"$(gcloud billing budgets list --billing-account=\"$ACCOUNT\" --billing-project=\"$PROJECT\" --filter=\"displayName='$DISPLAY'\" --format='value(name)')\" ]; then\n gcloud billing budgets create --billing-account=\"$ACCOUNT\" --billing-project=\"$PROJECT\" --display-name=\"$DISPLAY\" --budget-amount=\"$AMOUNT$CURRENCY\" --calendar-period=month --filter-projects=\"projects/$PROJECT\" --threshold-rule=percent=0.5 --threshold-rule=percent=0.8 --threshold-rule=percent=1.0 --notifications-rule-pubsub-topic=\"projects/$PROJECT/topics/$NAME\"\nfi\n\necho \"7/7 Test the function with a cost of 0. This test does not stop the project.\"\ngcloud pubsub topics publish \"$NAME\" --message=\"{\\\\\"budgetDisplayName\\\\\":\\\\\"$DISPLAY test\\\\\",\\\\\"costAmount\\\\\":0,\\\\\"budgetAmount\\\\\":$AMOUNT,\\\\\"currencyCode\\\\\":\\\\\"$CURRENCY\\\\\",\\\\\"costIntervalStart\\\\\":\\\\\"$(date -u +%Y-%m-01T00:00:00Z)\\\\\"}\"\nsleep 90\ngcloud functions logs read \"$NAME\" --gen2 --region=\"$REGION\" --limit=10\necho \"The stop is live when a line of the log has \\\\\"action\\\\\":\\\\\"kept\\\\\" and \\\\\"ready\\\\\":true.\"\n`;\n}\n"],"mappings":";;AAoEA,MAAa,eAAe;;AAG5B,MAAa,cAAc;;AAG3B,MAAa,uBAAuB;;AAGpC,MAAa,kBAAkB;;AAG/B,MAAM,aAAa;;AAGnB,SAAgB,YAAY,OAAwB;CAClD,OAAO,WAAW,KAAK,KAAK;AAC9B;AAMA,SAAS,SAAS,OAAkD;CAClE,OAAO,UAAU,QAAQ,OAAO,UAAU,YAAY,CAAC,MAAM,QAAQ,KAAK;AAC5E;;AAGA,SAAS,WAAW,MAAkC;CACpD,IAAI;EACF,MAAM,QAAQ,WAAW,KAAK,KAAK,IAAI,IAAI,cAAsB,UAAU,WAAW,CAAC,CAAC;EACxF,OAAO,IAAI,YAAY,SAAS,EAAE,OAAO,KAAK,CAAC,CAAC,CAAC,OAAO,KAAK;CAC/D,QAAQ;EACN;CACF;AACF;;;;;AAMA,SAAgB,iBAAiB,MAAiC;CAEhE,MAAM,WADU,SAAS,IAAI,KAAK,SAAS,KAAK,UAAU,IAAI,KAAK,aAAa,KAAA,EAAA,GACtD;CAC1B,IAAI,OAAO,YAAY,UAAU,OAAO;EAAE,IAAI;EAAO,OAAO;CAAiC;CAC7F,MAAM,OAAO,WAAW,OAAO;CAC/B,IAAI,SAAS,KAAA,GAAW,OAAO;EAAE,IAAI;EAAO,OAAO;CAA6C;CAChG,IAAI;CACJ,IAAI;EACF,QAAQ,KAAK,MAAM,IAAI;CACzB,QAAQ;EACN,OAAO;GAAE,IAAI;GAAO,OA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,GAAG,OAAO,MAAM,EAAE,GAAG;CACnC,OAAO;wCAC+B,QAAQ,gBAAgB,MAAM;qCACjC,MAAM;;;;;yFAK8C,MAAM;;;;oEAI3B,QAAQ;;;;;;WAMjE,QAAQ;QACX,KAAK;UACH,OAAO;UACP,OAAO,MAAM,EAAE;YACb,SAAS;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAoDnB,OAAO,YAAY;;;EAGnB,OAAO,QAAQ;;6DAE4C,aAAa,uDAAuD,iBAAiB;;;;;;;;;;;;;AAalJ"}
1
+ {"version":3,"file":"gcp-stop.js","names":[],"sources":["../src/gcp-stop.ts"],"sourcesContent":["/**\n * The entry `@mark1russell7/stack-spend/gcp-stop`: a stop by code for a project of Google Cloud.\n *\n * A budget of the project sends a notification to a Pub/Sub topic some times each day. A function reads each notification.\n * When the cost of the month is at the amount of the budget, the function removes the billing account of the project.\n * Then Google stops the paid services of the project. This is the limit of the kind `code`, with the function as its `stop`.\n *\n * The entry has no dependencies and no clock. The caller gives the `fetch`, so a test gives a fake.\n */\n\n/** The fields of a budget notification that the stop uses. */\nexport interface BudgetNotification {\n /** The name of the budget. */\n readonly budgetDisplayName: string;\n /** The cost of the period of the budget, up to the time of the notification. */\n readonly costAmount: number;\n /** The amount of the budget. */\n readonly budgetAmount: number;\n /** The currency of the two amounts, for example `USD`. */\n readonly currencyCode: string;\n /** The start of the period of the budget, as an ISO 8601 time. */\n readonly costIntervalStart: string;\n}\n\n/** The result of a read of a notification: the notification, or the reason that the read failed. */\nexport type NotificationRead = { readonly ok: true; readonly notification: BudgetNotification } | { readonly ok: false; readonly error: string };\n\n/** The decision of the stop for one notification. */\nexport interface StopDecision {\n /** `true` when the cost is at the amount of the budget or above it. */\n readonly stop: boolean;\n /** The decision in words, with the two amounts. */\n readonly reason: string;\n}\n\n/** One request of the stop, as data. The headers can hold a token, so do not write a request to a log. */\nexport interface StopRequest {\n readonly method: \"GET\" | \"POST\" | \"PUT\";\n readonly url: string;\n readonly headers: Readonly<Record<string, string>>;\n readonly body?: string;\n}\n\n/** The answer of a request, with only the parts that the stop reads. The global `fetch` gives this form. */\nexport interface StopAnswer {\n readonly status: number;\n text(): Promise<string>;\n}\n\n/** The function that sends a request. The global `fetch` is such a function. */\nexport type StopFetch = (url: string, init: { method: string; headers: Record<string, string>; body?: string }) => Promise<StopAnswer>;\n\n/**\n * The result of the stop for one notification. It holds no token.\n *\n * - `refused`: the notification has a fault of form, so the stop does nothing.\n * - `kept`: the cost is below the amount. `ready` tells if the identity of the function can remove the billing account.\n * - `stopped`: the stop removed the billing account of the project.\n * - `already`: the project had no billing account.\n * - `failed`: a request failed. The next notification tries again.\n */\nexport type StopOutcome =\n | { readonly action: \"refused\"; readonly reason: string }\n | { readonly action: \"kept\"; readonly reason: string; readonly project: string; readonly ready: boolean }\n | { readonly action: \"stopped\" | \"already\"; readonly reason: string; readonly project: string }\n | { readonly action: \"failed\"; readonly reason: string };\n\n/** The root of the metadata server of Google Cloud. A function gets its token and its project from it. */\nexport const METADATA_URL = \"http://metadata.google.internal/computeMetadata/v1\";\n\n/** The root of the Cloud Billing API. */\nexport const BILLING_URL = \"https://cloudbilling.googleapis.com/v1\";\n\n/** The root of the Cloud Resource Manager API. */\nexport const RESOURCE_MANAGER_URL = \"https://cloudresourcemanager.googleapis.com/v1\";\n\n/** The permission that lets the identity of the function remove the billing account of the project. */\nexport const STOP_PERMISSION = \"resourcemanager.projects.deleteBillingAssignment\";\n\n/** The rule of a project id of Google Cloud: 6 to 30 characters, lowercase letters, digits and hyphens, and a letter first. */\nconst PROJECT_ID = /^[a-z][a-z0-9-]{4,28}[a-z0-9]$/;\n\n/** This function tells if a text is a project id of Google Cloud. A request puts the id in its path, so the stop examines it. */\nexport function isProjectId(value: string): boolean {\n return PROJECT_ID.test(value);\n}\n\n// The build of the package is for each platform, so its types have no DOM and no Node. Node, Deno and each browser have these two globals.\ndeclare const atob: (data: string) => string;\ndeclare const TextDecoder: new (label: string, options: { fatal: boolean }) => { decode(input: Uint8Array): string };\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\n\n/** This function decodes base64 text to UTF-8 text, or gives `undefined` for text that is not base64. */\nfunction fromBase64(text: string): string | undefined {\n try {\n const bytes = Uint8Array.from(atob(text), (character: string) => character.charCodeAt(0));\n return new TextDecoder(\"utf-8\", { fatal: true }).decode(bytes);\n } catch {\n return undefined;\n }\n}\n\n/**\n * This function reads a budget notification from the data of a CloudEvent of Pub/Sub. The data has the form\n * `{ message: { data } }`, and `data` is the notification as base64 JSON.\n */\nexport function readNotification(data: unknown): NotificationRead {\n const message = isRecord(data) && isRecord(data[\"message\"]) ? data[\"message\"] : undefined;\n const encoded = message?.[\"data\"];\n if (typeof encoded !== \"string\") return { ok: false, error: \"The event has no message data.\" };\n const text = fromBase64(encoded);\n if (text === undefined) return { ok: false, error: \"The message data is not base64 UTF-8 text.\" };\n let value: unknown;\n try {\n value = JSON.parse(text);\n } catch {\n return { ok: false, error: \"The message data is not JSON.\" };\n }\n if (!isRecord(value)) return { ok: false, error: \"The notification is not an object.\" };\n const { costAmount, budgetAmount } = value;\n if (typeof costAmount !== \"number\" || !Number.isFinite(costAmount) || costAmount < 0) return { ok: false, error: \"The field costAmount is not a number of 0 or more.\" };\n if (typeof budgetAmount !== \"number\" || !Number.isFinite(budgetAmount) || budgetAmount <= 0) return { ok: false, error: \"The field budgetAmount is not a number above 0.\" };\n // The stop needs only the two amounts. A text field that is not there does not stop the stop: it becomes an empty text.\n const record = value;\n const textOf = (field: string): string => {\n const found = record[field];\n return typeof found === \"string\" ? found : \"\";\n };\n return {\n ok: true,\n notification: { budgetDisplayName: textOf(\"budgetDisplayName\"), costAmount, budgetAmount, currencyCode: textOf(\"currencyCode\"), costIntervalStart: textOf(\"costIntervalStart\") },\n };\n}\n\n/** This function decides the stop: the stop acts when the cost is at the amount of the budget or above it. */\nexport function decideStop(notification: BudgetNotification): StopDecision {\n const { costAmount, budgetAmount, currencyCode, budgetDisplayName } = notification;\n const amounts = `${String(costAmount)} ${currencyCode} of ${String(budgetAmount)} ${currencyCode}`;\n return costAmount >= budgetAmount\n ? { stop: true, reason: `The cost of the budget \"${budgetDisplayName}\" is at its amount: ${amounts}.` }\n : { stop: false, reason: `The cost of the budget \"${budgetDisplayName}\" is below its amount: ${amounts}.` };\n}\n\n/** This function gives the request of the token of the identity of the function, to the metadata server. */\nexport function tokenRequest(): StopRequest {\n return { method: \"GET\", url: `${METADATA_URL}/instance/service-accounts/default/token`, headers: { \"metadata-flavor\": \"Google\" } };\n}\n\n/** This function gives the request of the id of the project of the function, to the metadata server. */\nexport function projectRequest(): StopRequest {\n return { method: \"GET\", url: `${METADATA_URL}/project/project-id`, headers: { \"metadata-flavor\": \"Google\" } };\n}\n\nfunction checkedProject(project: string): string {\n if (!isProjectId(project)) throw new Error(\"The project id is not a project id of Google Cloud.\");\n return project;\n}\n\n/** This function gives the request that reads the billing state of a project. */\nexport function billingInfoRequest(project: string, token: string): StopRequest {\n return { method: \"GET\", url: `${BILLING_URL}/projects/${checkedProject(project)}/billingInfo`, headers: { authorization: `Bearer ${token}` } };\n}\n\n/** This function gives the request that removes the billing account of a project: a billing account name that is empty. */\nexport function detachRequest(project: string, token: string): StopRequest {\n return {\n method: \"PUT\",\n url: `${BILLING_URL}/projects/${checkedProject(project)}/billingInfo`,\n headers: { authorization: `Bearer ${token}`, \"content-type\": \"application/json\" },\n body: JSON.stringify({ billingAccountName: \"\" }),\n };\n}\n\n/** This function gives the request that tells if the identity of the function holds the permission of the stop. */\nexport function permissionRequest(project: string, token: string): StopRequest {\n return {\n method: \"POST\",\n url: `${RESOURCE_MANAGER_URL}/projects/${checkedProject(project)}:testIamPermissions`,\n headers: { authorization: `Bearer ${token}`, \"content-type\": \"application/json\" },\n body: JSON.stringify({ permissions: [STOP_PERMISSION] }),\n };\n}\n\n/** A failed request, with a reason that holds no token. */\nclass RequestFailure extends Error {}\n\nasync function send(fetch: StopFetch, request: StopRequest, what: string): Promise<string> {\n const init = { method: request.method, headers: { ...request.headers }, ...(request.body === undefined ? {} : { body: request.body }) };\n let answer: StopAnswer;\n try {\n answer = await fetch(request.url, init);\n } catch (error) {\n throw new RequestFailure(`The request of ${what} failed: ${error instanceof Error ? error.name : \"an error\"}.`);\n }\n const text = await answer.text();\n if (answer.status !== 200) throw new RequestFailure(`The request of ${what} gave the status ${String(answer.status)}.`);\n return text;\n}\n\nfunction json(text: string, what: string): Record<string, unknown> {\n try {\n const value: unknown = JSON.parse(text);\n if (isRecord(value)) return value;\n } catch {\n // The text is not JSON. The next line gives the failure.\n }\n throw new RequestFailure(`The answer of ${what} is not a JSON object.`);\n}\n\n/**\n * This function is the stop. It reads the notification, and it decides. Below the amount, it examines that the identity of\n * the function holds the permission of the stop. At the amount, it removes the billing account of the project, if the\n * project has one.\n *\n * @param data - The data of the CloudEvent of Pub/Sub\n * @param fetch - The function that sends a request, for example the global `fetch`\n */\nexport async function stopBilling(data: unknown, fetch: StopFetch): Promise<StopOutcome> {\n const read = readNotification(data);\n if (!read.ok) return { action: \"refused\", reason: read.error };\n const decision = decideStop(read.notification);\n try {\n const project = (await send(fetch, projectRequest(), \"the project id\")).trim();\n if (!isProjectId(project)) return { action: \"failed\", reason: \"The metadata server gave a text that is not a project id.\" };\n const tokenText = await send(fetch, tokenRequest(), \"the token\");\n const token = json(tokenText, \"the token\")[\"access_token\"];\n if (typeof token !== \"string\" || token === \"\") return { action: \"failed\", reason: \"The answer of the token has no access_token.\" };\n if (!decision.stop) {\n const held = json(await send(fetch, permissionRequest(project, token), \"the permissions\"), \"the permissions\")[\"permissions\"];\n const ready = Array.isArray(held) && held.includes(STOP_PERMISSION);\n return { action: \"kept\", reason: decision.reason, project, ready };\n }\n // The read of the billing state only prevents a write that is not necessary. The stop must not depend on it: when the\n // read fails, for example because the identity cannot read the project, the function sends the removal all the same.\n let enabled: boolean | undefined;\n try {\n enabled = json(await send(fetch, billingInfoRequest(project, token), \"the billing state\"), \"the billing state\")[\"billingEnabled\"] === true;\n } catch (error) {\n if (!(error instanceof RequestFailure)) throw error;\n }\n if (enabled === false) return { action: \"already\", reason: `${decision.reason} The project has no billing account.`, project };\n await send(fetch, detachRequest(project, token), \"the removal of the billing account\");\n return { action: \"stopped\", reason: `${decision.reason} The stop removed the billing account of the project.`, project };\n } catch (error) {\n if (error instanceof RequestFailure) return { action: \"failed\", reason: error.message };\n throw error;\n }\n}\n\n/** The options of the script that makes the stop of a project. */\nexport interface StopScriptOptions {\n /** The id of the project. */\n readonly project: string;\n /** The amount of the budget for each month. */\n readonly amount: number;\n /** The currency of the billing account, for example `USD`. */\n readonly currency: string;\n /** The version range of this package in the source of the function, for example `^0.1.8`. */\n readonly version: string;\n /** The region of the function. The default is `us-central1`. */\n readonly region?: string;\n /** The name of the topic, of the function and of its identity. The default is `billing-stop`. */\n readonly name?: string;\n}\n\n/** The version range of the Functions Framework in the source of the function. */\nexport const FRAMEWORK_RANGE = \"^5.0.5\";\n\n/** The runtime of the function. */\nexport const STOP_RUNTIME = \"nodejs22\";\n\n/** The name of the entry point of the function. */\nexport const STOP_ENTRY_POINT = \"billingStop\";\n\n/** This function gives the source of the function: its `package.json` and its `index.js`. */\nexport function stopSource(version: string): { readonly packageJson: string; readonly indexJs: string } {\n if (!/^[\\^~]?\\d+\\.\\d+\\.\\d+$/.test(version)) throw new Error(\"The version is not a version range of the form ^1.2.3.\");\n const packageJson = JSON.stringify(\n {\n name: \"billing-stop\",\n private: true,\n type: \"module\",\n main: \"index.js\",\n dependencies: { \"@google-cloud/functions-framework\": FRAMEWORK_RANGE, \"@mark1russell7/stack-spend\": version },\n },\n null,\n 2,\n );\n const indexJs = [\n 'import functions from \"@google-cloud/functions-framework\";',\n 'import { stopBilling } from \"@mark1russell7/stack-spend/gcp-stop\";',\n \"\",\n \"// The function gets each budget notification. A failure or an identity with no permission gives an error in the log.\",\n `functions.cloudEvent(\"${STOP_ENTRY_POINT}\", async (event) => {`,\n \" const outcome = await stopBilling(event.data, fetch);\",\n \" console.log(JSON.stringify(outcome));\",\n ' if (outcome.action === \"failed\") throw new Error(outcome.reason);',\n ' if (outcome.action === \"kept\" && !outcome.ready) throw new Error(\"The identity of the function cannot remove the billing account.\");',\n \"});\",\n ].join(\"\\n\");\n return { packageJson, indexJs };\n}\n\n/**\n * This function gives a Bash script for Cloud Shell. The script makes the stop of a project: a budget for each month, a\n * Pub/Sub topic, the identity of the function, and the function. Then it tests the function with a cost of 0.\n *\n * The script has no key and makes no key. It reads the billing account of the project when it starts, so the text does not\n * hold the account id. A second run changes nothing that is already made.\n */\nexport function stopScript(options: StopScriptOptions): string {\n const { project, amount, currency, version } = options;\n const region = options.region ?? \"us-central1\";\n const name = options.name ?? \"billing-stop\";\n if (!isProjectId(project)) throw new Error(\"The project id is not a project id of Google Cloud.\");\n if (!Number.isFinite(amount) || amount <= 0) throw new Error(\"The amount is not a number above 0.\");\n if (!/^[A-Z]{3}$/.test(currency)) throw new Error(\"The currency is not a code of three letters.\");\n if (!/^[a-z]+-[a-z]+\\d+$/.test(region)) throw new Error(\"The region is not a region of Google Cloud.\");\n if (!isProjectId(name)) throw new Error(\"The name is not 6 to 30 lowercase letters, digits and hyphens.\");\n const source = stopSource(version);\n const money = `${String(amount)} ${currency}`;\n return `#!/usr/bin/env bash\n# The stop of the cost of the project ${project}: a budget of ${money} for each month, a Pub/Sub topic and a function.\n# When the cost of a month gets to ${money}, the function removes the billing account of the project.\n#\n# What a stop does:\n# - Google stops the paid services of the project. A server stops, also a server in the free tier.\n# - Google keeps the disks and the data for a time. It can delete the resources of a project with no billing account.\n# - The cost data of Google comes some hours late. Thus the cost can go a little above ${money} before the stop.\n#\n# How to undo a stop:\n# 1. Raise the amount of the budget, or wait for the next month. Else the next notification stops the project again.\n# 2. Link the billing account again: gcloud billing projects link ${project} --billing-account=<the account id>\n# 3. Start each server again: gcloud compute instances start <the server> --zone=<its zone>\n#\n# Run this script in Cloud Shell, as the owner of the project and of its billing account.\nset -euo pipefail\n\nPROJECT=\"${project}\"\nNAME=\"${name}\"\nREGION=\"${region}\"\nAMOUNT=\"${String(amount)}\"\nCURRENCY=\"${currency}\"\nSA=\"$NAME@$PROJECT.iam.gserviceaccount.com\"\nDISPLAY=\"$NAME $AMOUNT $CURRENCY\"\n\ngcloud config set project \"$PROJECT\"\n\necho \"1/7 Read the billing account of the project.\"\n# Cloud Shell signs in as a user, so each billing command uses the project for its quota (--billing-project).\ngcloud services enable cloudbilling.googleapis.com\nACCOUNT=\"$(gcloud billing projects describe \"$PROJECT\" --billing-project=\"$PROJECT\" --format='value(billingAccountName)')\"\nACCOUNT=\"\\${ACCOUNT#billingAccounts/}\"\nif [ -z \"$ACCOUNT\" ]; then\n echo \"The project $PROJECT has no billing account. Link it, then run this script again.\"\n exit 1\nfi\n\necho \"2/7 Turn on the APIs.\"\ngcloud services enable cloudfunctions.googleapis.com cloudbuild.googleapis.com artifactregistry.googleapis.com run.googleapis.com eventarc.googleapis.com pubsub.googleapis.com billingbudgets.googleapis.com cloudresourcemanager.googleapis.com\n\necho \"3/7 Make the identity of the function.\"\ngcloud iam service-accounts describe \"$SA\" > /dev/null 2>&1 || gcloud iam service-accounts create \"$NAME\" --display-name=\"The stop of the cost\"\n# A change of IAM comes into force after a delay. A new service account or a new role can be missing for some minutes.\n# Thus try_again runs a command again while its error is one of these delays, at most 16 times, 20 seconds apart.\n# Each other error stops the script.\ntry_again() {\n local try out\n out=\"$(mktemp)\"\n for try in $(seq 1 16); do\n if \"$@\" 2>&1 | tee \"$out\"; then rm -f \"$out\"; return 0; fi\n if ! grep -qE \"Service account [^ ]+ does not exist|does not have required permission|Propagation of the new permission\" \"$out\"; then rm -f \"$out\"; return 1; fi\n echo \"A new identity or role is not in force yet. Wait 20 seconds (try $try of 16).\"\n sleep 20\n done\n rm -f \"$out\"\n return 1\n}\ngrant() {\n try_again gcloud projects add-iam-policy-binding \"$PROJECT\" --member=\"serviceAccount:$SA\" --role=\"$1\" --condition=None --format=none\n}\n# The role Project Billing Manager lets the function remove the billing account of this project only.\ngrant \"roles/billing.projectManager\"\n# The trigger calls the function with the same identity.\ngrant \"roles/run.invoker\"\n# Eventarc examines that the identity of the trigger can use the project (serviceusage.services.use).\ngrant \"roles/serviceusage.serviceUsageConsumer\"\n\necho \"4/7 Make the topic.\"\ngcloud pubsub topics describe \"$NAME\" > /dev/null 2>&1 || gcloud pubsub topics create \"$NAME\"\n\necho \"5/7 Deploy the function.\"\nSOURCE=\"$(mktemp -d)\"\ncat > \"$SOURCE/package.json\" <<'JSON'\n${source.packageJson}\nJSON\ncat > \"$SOURCE/index.js\" <<'JS'\n${source.indexJs}\nJS\ntry_again gcloud functions deploy \"$NAME\" --gen2 --runtime=${STOP_RUNTIME} --region=\"$REGION\" --source=\"$SOURCE\" --entry-point=${STOP_ENTRY_POINT} --trigger-topic=\"$NAME\" --service-account=\"$SA\" --trigger-service-account=\"$SA\" --max-instances=1 --memory=256Mi --quiet\n\necho \"6/7 Make the budget.\"\nif [ -z \"$(gcloud billing budgets list --billing-account=\"$ACCOUNT\" --billing-project=\"$PROJECT\" --filter=\"displayName='$DISPLAY'\" --format='value(name)')\" ]; then\n gcloud billing budgets create --billing-account=\"$ACCOUNT\" --billing-project=\"$PROJECT\" --display-name=\"$DISPLAY\" --budget-amount=\"$AMOUNT$CURRENCY\" --calendar-period=month --filter-projects=\"projects/$PROJECT\" --threshold-rule=percent=0.5 --threshold-rule=percent=0.8 --threshold-rule=percent=1.0 --notifications-rule-pubsub-topic=\"projects/$PROJECT/topics/$NAME\"\nfi\n\necho \"7/7 Test the function with a cost of 0. This test does not stop the project.\"\nSENT=\"$(date -u +%Y-%m-%dT%H:%M:%SZ)\"\ngcloud pubsub topics publish \"$NAME\" --message=\"{\\\\\"budgetDisplayName\\\\\":\\\\\"$DISPLAY test\\\\\",\\\\\"costAmount\\\\\":0,\\\\\"budgetAmount\\\\\":$AMOUNT,\\\\\"currencyCode\\\\\":\\\\\"$CURRENCY\\\\\",\\\\\"costIntervalStart\\\\\":\\\\\"$(date -u +%Y-%m-01T00:00:00Z)\\\\\"}\"\n# The function writes its result as a JSON line. \"gcloud functions logs read\" does not show such a line, so the script reads it with \"gcloud logging read\".\n# The result can come to the log some minutes late. Thus the script reads the log at most 15 times, 20 seconds apart.\nFILTER=\"resource.type=\\\\\"cloud_run_revision\\\\\" AND resource.labels.service_name=\\\\\"$NAME\\\\\" AND jsonPayload.action:* AND timestamp>=\\\\\"$SENT\\\\\"\"\nRESULT=\"\"\nfor try in $(seq 1 15); do\n sleep 20\n RESULT=\"$(gcloud logging read \"$FILTER\" --limit=1 --format='value(jsonPayload.action,jsonPayload.ready)')\"\n if [ -n \"$RESULT\" ]; then break; fi\ndone\nif [ -z \"$RESULT\" ]; then RESULT=\"no result\"; fi\necho \"The result of the test: $RESULT\"\ncase \"$RESULT\" in\n kept*True)\n echo \"The stop is live.\" ;;\n *)\n echo \"The stop is not live. The log of the function: gcloud functions logs read $NAME --gen2 --region=$REGION --limit=20\" >&2\n exit 1 ;;\nesac\n`;\n}\n"],"mappings":";;AAoEA,MAAa,eAAe;;AAG5B,MAAa,cAAc;;AAG3B,MAAa,uBAAuB;;AAGpC,MAAa,kBAAkB;;AAG/B,MAAM,aAAa;;AAGnB,SAAgB,YAAY,OAAwB;CAClD,OAAO,WAAW,KAAK,KAAK;AAC9B;AAMA,SAAS,SAAS,OAAkD;CAClE,OAAO,UAAU,QAAQ,OAAO,UAAU,YAAY,CAAC,MAAM,QAAQ,KAAK;AAC5E;;AAGA,SAAS,WAAW,MAAkC;CACpD,IAAI;EACF,MAAM,QAAQ,WAAW,KAAK,KAAK,IAAI,IAAI,cAAsB,UAAU,WAAW,CAAC,CAAC;EACxF,OAAO,IAAI,YAAY,SAAS,EAAE,OAAO,KAAK,CAAC,CAAC,CAAC,OAAO,KAAK;CAC/D,QAAQ;EACN;CACF;AACF;;;;;AAMA,SAAgB,iBAAiB,MAAiC;CAEhE,MAAM,WADU,S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DAAqD;CAChG,IAAI,CAAC,OAAO,SAAS,MAAM,KAAK,UAAU,GAAG,MAAM,IAAI,MAAM,qCAAqC;CAClG,IAAI,CAAC,aAAa,KAAK,QAAQ,GAAG,MAAM,IAAI,MAAM,8CAA8C;CAChG,IAAI,CAAC,qBAAqB,KAAK,MAAM,GAAG,MAAM,IAAI,MAAM,6CAA6C;CACrG,IAAI,CAAC,YAAY,IAAI,GAAG,MAAM,IAAI,MAAM,gEAAgE;CACxG,MAAM,SAAS,WAAW,OAAO;CACjC,MAAM,QAAQ,GAAG,OAAO,MAAM,EAAE,GAAG;CACnC,OAAO;wCAC+B,QAAQ,gBAAgB,MAAM;qCACjC,MAAM;;;;;yFAK8C,MAAM;;;;oEAI3B,QAAQ;;;;;;WAMjE,QAAQ;QACX,KAAK;UACH,OAAO;UACP,OAAO,MAAM,EAAE;YACb,SAAS;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAoDnB,OAAO,YAAY;;;EAGnB,OAAO,QAAQ;;6DAE4C,aAAa,uDAAuD,iBAAiB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6BlJ"}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "$schema": "https://json.schemastore.org/package",
3
3
  "name": "@mark1russell7/stack-spend",
4
- "version": "0.1.9",
4
+ "version": "0.1.11",
5
5
  "description": "The cost of each part of a system stack as data: plans, prices and hard monthly limits, a gate, and the largest cost of a month as Vex programs. An add-on of system-stack.",
6
6
  "license": "MIT",
7
7
  "repository": {
@@ -54,7 +54,7 @@
54
54
  "build"
55
55
  ],
56
56
  "dependencies": {
57
- "@mark1russell7/system-stack": "0.1.5",
57
+ "@mark1russell7/system-stack": "0.1.6",
58
58
  "@mark1russell7/vex": "^0.19.1",
59
59
  "@mark1russell7/vex-domains": "^0.19.1",
60
60
  "zod": "^4.6.7"