diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..261eeb9 --- /dev/null +++ b/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/README.md b/README.md index a3bfa4a..06ffcd6 100644 --- a/README.md +++ b/README.md @@ -1,117 +1,118 @@ # insta-cli InstaCloud CLI (`insta`) — a thin client of the [platform](../platform) control-plane API. -管理 project / branch / secrets / deploy / governance,面向开发者与 agent。 +Manages project / branch / secrets / deploy / governance — built for developers and agents. -技术栈:Node 20 + TypeScript(ESM)+ commander。所有命令都是平台 API 的封装。 +Tech stack: Node 20 + TypeScript (ESM) + commander. Every command is a wrapper around the platform API. -## 安装 +## Installation -**一键装(原生二进制,无需 node)** — macOS / Linux / WSL: +**One-line install (native binary, no node required)** — macOS / Linux / WSL: ```bash curl -fsSL https://raw.githubusercontent.com/InsForge/insta-cli/main/install.sh | sh -# 装到 ~/.insta/bin/insta(可 INSTA_INSTALL_DIR 覆盖);校验 SHA256SUMS。 -# 固定版本:curl -fsSL .../install.sh | INSTA_VERSION=v0.1.0 sh -# Windows:从 releases 页下载 insta-windows-x64.exe。 +# Installs to ~/.insta/bin/insta (override with INSTA_INSTALL_DIR); verifies SHA256SUMS. +# Pin a version: curl -fsSL .../install.sh | INSTA_VERSION=v0.1.0 sh +# Windows: download insta-windows-x64.exe from the releases page. ``` -**从源码构建(需 node):** +**Build from source (requires node):** ```bash npm install -npm run build # -> dist/index.js(bin: insta;纯 JS,运行需 node) +npm run build # -> dist/index.js (bin: insta; pure JS, requires node to run) node dist/index.js --help ``` -### 自己出二进制(Bun 交叉编译) +### Build your own binaries (Bun cross-compilation) -`install.sh` 装的二进制由 CI(tag `v*` → `.github/workflows/release.yml`)用 Bun 交叉编译并发到 GitHub -releases。本地也可出:需 [Bun](https://bun.sh)。npm 包仍发布 JS(`dist/index.js`)——二进制是另一条渠道。 +The binaries that `install.sh` installs are cross-compiled with Bun by CI (tag `v*` → `.github/workflows/release.yml`) +and published to GitHub releases. You can also build them locally: requires [Bun](https://bun.sh). The npm package still +ships JS (`dist/index.js`) — binaries are a separate distribution channel. ```bash -npm run compile # 只编译当前平台 -> dist/bin/insta -npm run build:binaries # 交叉编译全平台 -> dist/bin/insta--(.exe) + SHA256SUMS -# 版本号(baked 进 `insta --version`)默认取 package.json,也可传参:bash scripts/build-binaries.sh 1.2.3 +npm run compile # compile for the current platform only -> dist/bin/insta +npm run build:binaries # cross-compile all platforms -> dist/bin/insta--(.exe) + SHA256SUMS +# The version (baked into `insta --version`) defaults to package.json, or pass it: bash scripts/build-binaries.sh 1.2.3 ``` -产物形如 `insta-darwin-arm64` / `insta-linux-x64` / `insta-windows-x64.exe`(`file` 显示 Mach-O/ELF/PE 原生可执行)。 -`dist/` 已 gitignore;二进制不入库,交给 CI 发到 releases。 +Artifacts look like `insta-darwin-arm64` / `insta-linux-x64` / `insta-windows-x64.exe` (`file` reports native Mach-O/ELF/PE executables). +`dist/` is gitignored; binaries are not committed — CI publishes them to releases. ## Quickstart ```bash -# 指向控制面(默认 http://localhost:8080,可用 $INSTA_API_URL 或 --api-url 覆盖) +# Point at the control plane (defaults to http://localhost:8080; override with $INSTA_API_URL or --api-url) insta login --email you@example.com --password ****** --api-url http://localhost:8080 -insta project create my-app # 新建空 project 并 link 当前目录(默认不含 service) -insta services add postgres db # 按需添加 service(postgres/storage/compute) -insta services add compute api # compute 用于部署镜像 -insta secrets # 把当前 branch 的凭证写入 ./.env(secret seam) -insta deploy --image # 部署容器镜像到当前 branch 的 compute service -insta status # 登录态 + 已 link 的 project/branch +insta project create my-app # create an empty project and link the current directory (no services by default) +insta services add postgres db # add services on demand (postgres/storage/compute) +insta services add compute api # compute is used to deploy images +insta secrets # write the current branch's credentials to ./.env (secret seam) +insta deploy --image # deploy a container image to the current branch's compute service +insta status # login state + linked project/branch ``` -## 命令 +## Commands -| 命令 | 说明 | +| Command | Description | |------|------| -| `insta login [--email --password --api-url]` | 登录(email/password;token 自动 refresh) | -| `insta login --oauth ` | 浏览器 OAuth 登录(启本地回环端口,浏览器授权后自动带回 token) | -| `insta logout` / `insta status [--json]` | 登出 / 查看状态 | -| `insta org list [--json]` / `org create ` | 组织(每个用户仅可拥有一个 free org) | -| `insta project create [--org]` | 新建空 project 并 link(默认不含任何 service) | -| `insta project list [--org] [--json]` / `link ` / `delete` | 项目管理 | -| `insta services add ` | 按需 provision 一个 service(postgres/compute 分配默认访问域名) | -| `insta services list [--json]` / `services remove ` | 列出 / 删除 service | -| `insta services scale compute [region]` | 设置 compute 机器数(付费档;free 拒绝) | -| `insta services upgrade ` | 升级 spec(付费档;只升不降) | -| `insta branch create [--from]` | 新建分支环境(物化 project 当前的 services;每 project 上限 10 个 branch) | -| `insta branch list [--json]` / `switch ` / `delete ` | 分支管理 | -| `insta secrets [--branch -o --print --json]` | secret seam:凭证写入 `.env` | -| `insta secrets list [--branch]` | 仅列出 secret 名 | -| `insta deploy --image [--branch --group --port]` | 部署镜像 | -| `insta manifest [--json]` | agent 可读的环境清单 | -| `insta metrics [group] [--branch --from --to --step --json]` | 资源指标(compute=Fly;db 受限) | -| `insta logs [group] [--branch --limit --region --instance --json]` | 运行时日志(compute=Fly;db 受限) | -| `insta events [--branch --limit --json]` | 审计 + agent 事件时间线 | -| `insta usage [--from --to --json]` | 按 meter 聚合的资源用量(含 costUsd) | -| `insta billing [--org --json]` | 当前计费周期摘要(tier / 额度 / 已用 / overage / 状态) | -| `insta billing upgrade [--org --no-open --json]` | Stripe Checkout 订阅付费档,返回并打开支付链接 | -| `insta billing portal [--org --no-open --json]` | 打开 Stripe Customer Portal(改套餐 / 卡 / 取消) | -| `insta approvals list [--status] [--json]` | 治理审批列表 | -| `insta approvals approve [--always]` / `deny ` | 批准 / 拒绝(admin) | -| `insta policy get [--json]` / `policy set ` | 治理策略(action 含 `service.add/remove/scale/upgrade`) | - -被 governance gate 的操作(`secrets.read`/`deploy`/`project.delete`/`branch.delete`/`service.add`/`service.remove`/`service.scale`/`service.upgrade`)命中审批时, -CLI 会提示 `approval required — run: insta approvals approve `。 - -## 配置位置 - -- 全局:`~/.insta/config.json`(apiUrl + access/refresh token + user) -- 项目:`./.insta/project.json`(projectId / orgId / 当前 branch) - -## 本地端到端跑通 - -平台提供 `dev:fake` 模式(fake provider adapters,无需 Neon/Fly/Tigris 凭证): +| `insta login [--email --password --api-url]` | Log in (email/password; tokens auto-refresh) | +| `insta login --oauth ` | Browser OAuth login (starts a local loopback port; the token is carried back automatically after browser authorization) | +| `insta logout` / `insta status [--json]` | Log out / show status | +| `insta org list [--json]` / `org create ` | Organizations (each user may own only one free org) | +| `insta project create [--org]` | Create an empty project and link it (no services by default) | +| `insta project list [--org] [--json]` / `link ` / `delete` | Project management | +| `insta services add ` | Provision a service on demand (postgres/compute get a default access domain) | +| `insta services list [--json]` / `services remove ` | List / remove services | +| `insta services scale compute [region]` | Set the compute machine count (paid tiers; rejected on free) | +| `insta services upgrade ` | Upgrade the spec (paid tiers; upgrade only, no downgrade) | +| `insta branch create [--from]` | Create a branch environment (materializes the project's current services; up to 10 branches per project) | +| `insta branch list [--json]` / `switch ` / `delete ` | Branch management | +| `insta secrets [--branch -o --print --json]` | Secret seam: write credentials to `.env` | +| `insta secrets list [--branch]` | List secret names only | +| `insta deploy --image [--branch --group --port]` | Deploy an image | +| `insta manifest [--json]` | Agent-readable environment manifest | +| `insta metrics [group] [--branch --from --to --step --json]` | Resource metrics (compute=Fly; db limited) | +| `insta logs [group] [--branch --limit --region --instance --json]` | Runtime logs (compute=Fly; db limited) | +| `insta events [--branch --limit --json]` | Audit + agent event timeline | +| `insta usage [--from --to --json]` | Resource usage aggregated by meter (includes costUsd) | +| `insta billing [--org --json]` | Current billing-cycle summary (tier / quota / used / overage / status) | +| `insta billing upgrade [--org --no-open --json]` | Subscribe to a paid tier via Stripe Checkout; returns and opens the payment link | +| `insta billing portal [--org --no-open --json]` | Open the Stripe Customer Portal (change plan / card / cancel) | +| `insta approvals list [--status] [--json]` | Governance approval list | +| `insta approvals approve [--always]` / `deny ` | Approve / deny (admin) | +| `insta policy get [--json]` / `policy set ` | Governance policy (actions include `service.add/remove/scale/upgrade`) | + +When a governance-gated operation (`secrets.read`/`deploy`/`project.delete`/`branch.delete`/`service.add`/`service.remove`/`service.scale`/`service.upgrade`) hits an approval, +the CLI prompts `approval required — run: insta approvals approve `. + +## Configuration locations + +- Global: `~/.insta/config.json` (apiUrl + access/refresh token + user) +- Project: `./.insta/project.json` (projectId / orgId / current branch) + +## Local end-to-end run + +The platform provides a `dev:fake` mode (fake provider adapters, no Neon/Fly/Tigris credentials required): ```bash -# 1) 起 Postgres + 平台 dev 服务(见 ../platform) +# 1) Start Postgres + the platform dev server (see ../platform) docker run -d --name pg -e POSTGRES_PASSWORD=insta -e POSTGRES_DB=insta_dev -p 55432:5432 postgres:16-alpine cd ../platform && DATABASE_URL='postgres://postgres:insta@localhost:55432/insta_dev' PORT=8899 npm run dev:fake -# 2) 用 CLI 跑全流程(注册走 /auth/signup + /auth/verify-email,dev 模式验证码打印在服务端日志) +# 2) Run the full flow with the CLI (signup goes through /auth/signup + /auth/verify-email; in dev mode the verification code is printed in the server logs) INSTA_API_URL=http://localhost:8899 insta login --email you@x.com --password ... ``` -## OAuth 浏览器登录 +## OAuth browser login ```bash -insta login --oauth github # 或 google -# CLI 起本地回环端口 → 打开浏览器到 /auth/cli/authorize → Better Auth 走 provider 授权 → -# 平台读会话 cookie 换出 bearer token → 带回回环端口 → CLI 存为登录态 +insta login --oauth github # or google +# CLI starts a local loopback port → opens the browser to /auth/cli/authorize → Better Auth runs provider authorization → +# the platform reads the session cookie to exchange for a bearer token → carries it back to the loopback port → CLI stores it as login state ``` -> 平台侧需配置该 provider 的 OAuth 应用(`GITHUB_OAUTH_CLIENT_ID/SECRET` 或 `GOOGLE_*`), -> 且应用的回调 URL 必须是 **`{INSTA_API_BASE_URL}/api/auth/callback/`**(不是回环地址)。 +> The platform must have an OAuth app configured for that provider (`GITHUB_OAUTH_CLIENT_ID/SECRET` or `GOOGLE_*`), +> and the app's callback URL must be **`{INSTA_API_BASE_URL}/api/auth/callback/`** (not the loopback address). -> `metrics` / `logs` / `usage` 已支持(usage 为采集层聚合)。多 compute service(`services add compute`)、`services scale/upgrade` 已实现;镜像构建后续加入。多 postgres/storage service(每 project >1 个)暂受 credential-seam 限制,为后续工作。 +> `metrics` / `logs` / `usage` are supported (usage is aggregated at the collection layer). Multiple compute services (`services add compute`) and `services scale/upgrade` are implemented; image building will come later. Multiple postgres/storage services (>1 per project) are currently constrained by the credential seam and remain future work. diff --git a/package.json b/package.json index 6573ea7..8daf671 100644 --- a/package.json +++ b/package.json @@ -1,18 +1,25 @@ { - "name": "insta-cli", - "version": "0.0.1", - "private": true, + "name": "insta", + "version": "0.0.3", "type": "module", "description": "InstaCloud CLI — a thin client of the platform control-plane API.", + "keywords": ["insta", "insforge", "cli", "backend", "baas", "platform"], + "license": "Apache-2.0", + "homepage": "https://github.com/InsForge/insta-cli#readme", + "repository": { "type": "git", "url": "git+https://github.com/InsForge/insta-cli.git" }, + "bugs": { "url": "https://github.com/InsForge/insta-cli/issues" }, "bin": { "insta": "dist/index.js" }, - "files": ["dist"], + "files": ["dist/**/*.js"], + "engines": { "node": ">=18" }, + "publishConfig": { "access": "public" }, "scripts": { "build": "tsc -p tsconfig.json", "typecheck": "tsc -p tsconfig.json --noEmit", "dev": "tsx src/index.ts", "test": "vitest run", "compile": "bun build ./src/index.ts --compile --minify --outfile dist/bin/insta", - "build:binaries": "bash scripts/build-binaries.sh" + "build:binaries": "bash scripts/build-binaries.sh", + "prepublishOnly": "npm run build" }, "dependencies": { "commander": "^12.1.0" diff --git a/src/commands/compute.ts b/src/commands/compute.ts new file mode 100644 index 0000000..2da33ac --- /dev/null +++ b/src/commands/compute.ts @@ -0,0 +1,43 @@ +import { ApiClient, requireProject } from '../api.js' +import { info, printJson, handleApproval } from '../util.js' + +type Opts = { branch?: string; group?: string; json?: boolean } + +// Attach a developer-owned custom domain to a branch's compute service. Fly issues the cert + routes +// it; the platform returns the DNS records to set in your OWN zone. +export async function setDomain(host: string, opts: Opts): Promise { + const api = await ApiClient.load() + const p = await requireProject() + const res = await api.rawRequest('POST', `/projects/${p.projectId}/compute/domain`, { hostname: host, branch: opts.branch ?? p.branch, group: opts.group }) + if (handleApproval(res)) return + printDomain(res.body, opts.json) +} + +// Re-check a custom domain's cert status + required DNS records. +export async function checkDomain(host: string, opts: Opts): Promise { + const api = await ApiClient.load() + const p = await requireProject() + const qs = new URLSearchParams({ hostname: host }) + if (opts.branch ?? p.branch) qs.set('branch', opts.branch ?? p.branch) + if (opts.group) qs.set('group', opts.group) + printDomain(await api.request('GET', `/projects/${p.projectId}/compute/domain?${qs}`), opts.json) +} + +export async function removeDomain(host: string, opts: Opts): Promise { + const api = await ApiClient.load() + const p = await requireProject() + const res = await api.rawRequest('DELETE', `/projects/${p.projectId}/compute/domain`, { hostname: host, branch: opts.branch ?? p.branch, group: opts.group }) + if (handleApproval(res)) return + info(`removed custom domain ${res.body.hostname} from ${res.body.flyApp}`) +} + +function printDomain(r: any, json?: boolean): void { + if (json) return printJson(r) + info(`${r.hostname} → ${r.flyApp}`) + info(` status: ${r.status}${r.configured ? ' ✓ configured' : ''}`) + if (r.dns?.length) { + info(' set these DNS records at your domain registrar:') + for (const d of r.dns) info(` ${String(d.type).padEnd(5)} ${d.name} → ${d.value}${d.note ? ` # ${d.note}` : ''}`) + } + if (!r.configured) info(' once DNS propagates, Fly issues the cert — re-check with `insta compute check-domain`') +} diff --git a/src/commands/deploy.ts b/src/commands/deploy.ts index 2c5e2eb..cb688e8 100644 --- a/src/commands/deploy.ts +++ b/src/commands/deploy.ts @@ -1,16 +1,46 @@ +import { resolve, join } from 'node:path' +import { existsSync } from 'node:fs' import { ApiClient, requireProject } from '../api.js' import { info, die, handleApproval } from '../util.js' +import { flyctlBuildAndPush, ensureFlyctl } from '../flyctl-build.js' + +type DeployOpts = { image?: string; branch?: string; group?: string; port?: string } + +// Deploy either a prebuilt image (`--image`) or a source directory (positional ``, built +// remotely on Fly and pushed with a short-lived platform-minted token). Exactly one mode. +export async function deploy(dir: string | undefined, opts: DeployOpts): Promise { + if (dir && opts.image) die('pick one: a source OR --image , not both') + if (!dir && !opts.image) die('usage: insta deploy | --image [--branch ] [--group ] [--port ]') -export async function deploy(opts: { image?: string; branch?: string; group?: string; port?: string }): Promise { const api = await ApiClient.load() const p = await requireProject() - if (!opts.image) die('--image is required') + const branch = opts.branch ?? p.branch + + const image = dir ? await buildFromSource(api, p.projectId, dir, branch, opts) : opts.image! const res = await api.rawRequest('POST', `/projects/${p.projectId}/deploy`, { - image: opts.image, - branch: opts.branch ?? p.branch, + image, + branch, group: opts.group, port: opts.port ? Number(opts.port) : undefined, }) if (handleApproval(res)) return - info(`deployed ${opts.image} -> ${res.body.url} (branch ${res.body.branch}, group ${res.body.group})`) + info(`deployed ${image} -> ${res.body.url} (branch ${res.body.branch}, group ${res.body.group})`) +} + +// Source mode: mint a scoped Fly deploy token from the platform, then build+push (needs a +// Dockerfile) with flyctl's remote builder, returning the pushed image ref to deploy. +async function buildFromSource(api: ApiClient, projectId: string, dir: string, branch: string, opts: DeployOpts): Promise { + const absDir = resolve(process.cwd(), dir) + if (!existsSync(join(absDir, 'Dockerfile'))) die(`no Dockerfile at ${join(absDir, 'Dockerfile')} — add one, or use --image `) + await ensureFlyctl() + const port = opts.port ? Number(opts.port) : 8080 + + const tok = await api.rawRequest('POST', `/projects/${projectId}/deploy-token`, { branch, group: opts.group }) + if (handleApproval(tok)) die('deploy requires approval — get it approved, then re-run') + const { token, flyApp } = tok.body + + info(`building ${dir} for ${flyApp} (remote builder)…`) + const { imageRef } = await flyctlBuildAndPush({ dir: absDir, flyApp, imageLabel: `insta-${Date.now()}`, token, port }) + info(` pushed ${imageRef}`) + return imageRef } diff --git a/src/commands/metrics.ts b/src/commands/metrics.ts index 444220b..e761a05 100644 --- a/src/commands/metrics.ts +++ b/src/commands/metrics.ts @@ -22,22 +22,54 @@ export async function metrics(component: string, group: string | undefined, opts } } -// insta usage — aggregated usage by meter over a window -export async function usage(opts: { from?: string; to?: string; json?: boolean }): Promise { +// Customer-facing name for each internal billing dimension (the platform stores RAM as `ram`). +const DIMENSION_LABEL: Record = { ram: 'memory' } + +type Dim = { dimension: string; quantity: number; unit: string; costUsd?: number } + +// Window line. Defaults to the current billing cycle; `to` is the exclusive next-cycle start, so +// show the inclusive last day (to − 1 day) — e.g. an org created on the 5th reads "…-05 → …next-04". +function cycleLine(res: { from: number; to: number }): string { + const day = (sec: number) => new Date(sec * 1000).toISOString().slice(0, 10) + return `billing cycle ${day(res.from)} → ${day(res.to - 86400)}` +} + +function printDimensions(dims: Dim[]): void { + for (const d of dims) { + const label = DIMENSION_LABEL[d.dimension] ?? d.dimension + const cost = d.costUsd != null ? ` ($${Number(d.costUsd).toFixed(4)})` : '' + info(`${label}: ${d.quantity} ${d.unit}${cost}`) + } +} + +// insta usage — usage across the 5 billing dimensions (cpu/memory/volume/egress/storage) for the +// current billing cycle. Shows the whole ORG by default (with a per-project breakdown); pass --proj +// [id] for a single project (the linked one, or a given id). Billed dimensions, not raw fly/neon meters. +export async function usage(opts: { from?: string; to?: string; json?: boolean; proj?: string | boolean }): Promise { const api = await ApiClient.load() const p = await requireProject() - const res = await api.request('GET', `/projects/${p.projectId}/usage${qs({ from: opts.from, to: opts.to })}`) + + if (opts.proj !== undefined && opts.proj !== false) { + const projectId = typeof opts.proj === 'string' ? opts.proj : p.projectId + const res = await api.request('GET', `/projects/${projectId}/usage${qs({ from: opts.from, to: opts.to })}`) + if (opts.json) return printJson(res) + info(cycleLine(res)) + if (!res.dimensions?.length) return info('(no usage recorded)') + printDimensions(res.dimensions) + return info(`total: $${Number(res.totalCostUsd ?? 0).toFixed(4)}`) + } + + // Default: the whole org (the linked project's org), with a per-project cost breakdown. + const res = await api.request('GET', `/orgs/${p.orgId}/usage${qs({ from: opts.from, to: opts.to })}`) if (opts.json) return printJson(res) - info(`usage ${new Date(res.from * 1000).toISOString().slice(0, 10)} → ${new Date(res.to * 1000).toISOString().slice(0, 10)}`) - if (!res.usage?.length) return info('(no usage recorded)') - let total = 0 - for (const u of res.usage) { - const dims = u.dimensions && Object.keys(u.dimensions).length ? ` ${JSON.stringify(u.dimensions)}` : '' - const cost = u.costUsd != null ? ` ($${Number(u.costUsd).toFixed(4)})` : '' - total += Number(u.costUsd ?? 0) - info(`${u.meter}${dims}: ${u.quantity} ${u.unit}${cost}`) + info(cycleLine(res)) + if (!res.org?.dimensions?.length) return info('(no usage recorded)') + printDimensions(res.org.dimensions) + info(`total: $${Number(res.org.totalCostUsd ?? 0).toFixed(4)}`) + if (res.projects?.length) { + info('by project:') + for (const pr of res.projects) info(` ${pr.name}: $${Number(pr.totalCostUsd ?? 0).toFixed(4)}`) } - info(`total: $${total.toFixed(4)}`) } // insta logs [group] diff --git a/src/flyctl-build.ts b/src/flyctl-build.ts new file mode 100644 index 0000000..bfcf468 --- /dev/null +++ b/src/flyctl-build.ts @@ -0,0 +1,90 @@ +// Build a source directory into an image and push it to Fly's registry, using a short-lived, +// app-scoped deploy token minted by the platform (the CLI never holds a standing Fly credential). +// Shells out to `flyctl deploy --build-only --push` (remote builder). Ported from firth. +import { spawn } from 'node:child_process' +import { existsSync, writeFileSync, unlinkSync } from 'node:fs' +import { join } from 'node:path' +import { info } from './util.js' + +export type BuildRunner = ( + cmd: string, + args: string[], + opts: { cwd: string; env: Record }, +) => Promise<{ code: number; output: string }> + +// Spawn flyctl, tee its output to the user (so they see buildkit progress) AND capture it for digest +// parsing. +export const defaultBuildRunner: BuildRunner = (cmd, args, opts) => + new Promise((resolve) => { + const child = spawn(cmd, args, { cwd: opts.cwd, env: opts.env, stdio: ['inherit', 'pipe', 'pipe'] }) + let output = '' + child.stdout?.on('data', (b) => { const s = b.toString(); output += s; process.stdout.write(s) }) + child.stderr?.on('data', (b) => { const s = b.toString(); output += s; process.stderr.write(s) }) + child.on('error', (err) => resolve({ code: -1, output: `${output}\n${err.message}` })) + child.on('close', (code) => resolve({ code: code ?? -1, output })) + }) + +// buildkit prints "pushing manifest for registry.fly.io/: