feat: renumber lib reference into 4-pillar anatomy
Renumber the 15 reference docs into pillar groups (recipe -> anatomy): - 01 Build Recipe (entry), 02 Composition Root - domains: 10 Layering Rules - contract: 20 Spec-First Routing, 21 CRUD Template, 22 Auth Integration - interfaces/infra: 30 Infra Adapters - UI: 40 UI: Auto-Rendered Admin & Custom Pages (new; @aetoskia packages, client template, x- catalog via react-openapi MCP module) - pipelines: 50 Pipeline Scaffold, 51 Worker & Progress, 52 Human-in-the-Loop - delivery/meta: 90 Drone Pipelines, 91 Versioning & Changelog, 92 Genericity Matrix, 93 Library Registry, 94 Repository Inventory MCP module names are unchanged (NN_ prefix stripped); all cross-references (wiki, templates, hooks, registry) updated; lib index rewritten pillar-first; build recipe bootstraps the client template. Bundle + HTML sites regenerated.
This commit is contained in:
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"project": "standards",
|
||||
"type": "standards",
|
||||
"modules_count": 23,
|
||||
"modules_count": 24,
|
||||
"source": "hand-authored"
|
||||
}
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -2,7 +2,7 @@
|
||||
"module": "index",
|
||||
"content": {
|
||||
"path": "index",
|
||||
"docstring": "# Standards Reference\n\nThe reference half of the Standards description: the enforceable rules,\npatterns, and the internal library catalog that agents consult while coding.\n\n- **Build Recipe** — the ordered, agentic checklist for a new app.\n- **Layering Rules** — the strict request → domain → repository layering and\n the rules that enforce it.\n- **Composition Root** — a single composition point wiring the whole app.\n- **Spec-First Routing** — the OpenAPI contract as the routing source of truth.\n- **CRUD Template** — the standardized generic resource endpoint scaffold.\n- **Pipeline Scaffold** — the deterministic pipeline skeleton for multi-stage\n jobs.\n- **Worker & Progress** — queued work, progress reporting, and visibility.\n- **Human-in-the-Loop** — guardrails and approvals inside automations.\n- **Infra Adapters** — how infrastructure connects without leaking into domain.\n- **Drone Pipelines** — the two CI shapes: a PyPI package or a Docker deployment.\n- **Versioning & Changelog** — SemVer, the tag↔version contract, and the release\n changelog.\n- **Repository Inventory** — every covered repo, its type, version source, and\n Drone shape.\n- **Genericity Matrix** — what is library-backed, template-provided, or authored.\n- **Auth Integration** — consuming the shared auth-server service (spec-driven,\n no auth code).\n- **Library Registry** — the catalog of internal libraries behind all of it.\n\nRead the **Wiki** for the philosophy and rationale; these pages are the\nreference that mirrors the `standards` MCP bundle.\n",
|
||||
"docstring": "# Standards Reference\n\nThe reference half of the Standards description: the enforceable rules,\npatterns, and the internal library catalog that agents consult while coding.\n\nThe reference is organized as an **anatomy** — one entry checklist and four\npillars describing what an application is made of, plus delivery/meta pages\nand an optional pipelines layer.\n\n## Anatomy\n\n- **Build Recipe** — the ordered, agentic checklist for a new app; the entry\n point that walks the whole anatomy.\n\n## Pillar 1 — Domains\n\n- **Layering Rules** — the strict request → domain → repository layering and\n the rules that enforce it.\n\n## Pillar 2 — OpenAPI Spec (the contract)\n\n- **Composition Root** — a single composition point wiring the whole app.\n- **Spec-First Routing** — the OpenAPI contract as the routing source of truth.\n- **CRUD Template** — the standardized generic resource endpoint scaffold.\n- **Auth Integration** — consuming the shared auth-server service (spec-driven,\n no auth code).\n\n## Pillar 3 — Interfaces & Infra\n\n- **Infra Adapters** — how infrastructure connects without leaking into domain.\n\n## Pillar 4 — UI\n\n- **UI: Auto-Rendered Admin & Custom Pages** — the `@aetoskia/react-openapi`\n admin rendered from the spec's x- extensions, and `@aetoskia/react-auth`\n for auth pages; the client template scaffold.\n\n## Pipelines (optional layer)\n\n- **Pipeline Scaffold** — the deterministic pipeline skeleton for multi-stage\n jobs.\n- **Worker & Progress** — queued work, progress reporting, and visibility.\n- **Human-in-the-Loop** — guardrails and approvals inside automations.\n\n## Delivery & Meta\n\n- **Drone Pipelines** — the two CI shapes: a PyPI/npm package or a Docker\n deployment.\n- **Versioning & Changelog** — SemVer, the tag↔version contract, and the\n release changelog.\n- **Repository Inventory** — every covered repo, its type, version source, and\n Drone shape.\n- **Genericity Matrix** — what is library-backed, template-provided, or\n authored.\n- **Library Registry** — the catalog of internal libraries behind all of it.\n\nRead the **Wiki** for the philosophy and rationale; these pages are the\nreference that mirrors the `standards` MCP bundle.\n",
|
||||
"objects": {}
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,7 @@
|
||||
"module": "repository_inventory",
|
||||
"content": {
|
||||
"path": "repository_inventory",
|
||||
"docstring": "# Repository Inventory\n\n## Summary\n\nThe canonical list of Aetos repositories covered by the CI and versioning\nstandards, with the artifact each one produces, its version source, and its\nDrone shape. Every entry maps to the contract in\n[11 – Versioning & Changelog](11_versioning_and_changelog.md) and the two CI\nfiles in [10 – Drone Pipelines](10_drone_pipelines.md).\n\nThe same data is published machine-readably as the `registry://repos` MCP\nresource (and the `list_repos` tool), sourced from `standards/src/repos.json`.\nPaths are relative to the `aetos/` workspace root.\n\n---\n\n## Packages (Type A)\n\nA wheel + sdist published to the private index. Version source is\n`pyproject.toml`; Drone file is `python-lib.yaml` (tag-triggered).\n\n| Repo | Path | Docs | MCP server |\n|------|------|------|------------|\n| `dagpipe` | `dagpipe` | lib, wiki | `dagpipe:8006` |\n| `doc-forge` | `doc-forge` | lib, wiki | `docforge:8001` |\n| `hexa` | `hexa` | lib, wiki | `hexa:8008` |\n| `mail-intake` | `mail-intake` | lib, wiki | `mail_intake:8002` |\n| `mongo-ops` | `mongo-ops` | lib, wiki | `mongo_ops:8007` |\n| `omniread` | `omniread` | lib, wiki | `omniread:8003` |\n| `openapi-first` | `openapi-first` | lib, wiki | `openapi_first:8004` |\n| `py-jwt` | `py-jwt` | lib, wiki | `jwtlib:8005` |\n\n---\n\n## Services (Type B)\n\nA container image pushed to the registry and run on the Docker host. Version\nsource is the `VERSION` file; Drone file is `service-docker.yaml`.\n\n| Repo | Path | Trigger | Docs |\n|------|------|---------|------|\n| `auth-server` | `auth-server` | tag | api, lib, wiki |\n\nTag-triggered and enforces `tag == VERSION`.\n\n---\n\n## Required files per repo\n\n| Type | Version source | Changelog | Drone |\n|------|----------------|-----------|-------|\n| package | `pyproject.toml` | `CHANGELOG.md` | `python-lib.yaml` |\n| service | `VERSION` | `CHANGELOG.md` | `service-docker.yaml` |\n\nEvery covered repository must be able to satisfy `tag == version`:\nthe version file (never a commit id) is bumped in the release MR, the MR is\nmerged, and the tag is created on the merged commit.\n\n---\n\n## Reading this at runtime\n\n- Resource: `registry://repos`\n- Tool: `list_repos()`\n- Humans: this page (mirror of `standards/src/repos.json`).\n\n---\n\n## Related\n\n- [10 – Drone Pipelines](10_drone_pipelines.md) · [11 – Versioning & Changelog](11_versioning_and_changelog.md) · [13 – Library Registry](13_library_registry.md)\n",
|
||||
"docstring": "# Repository Inventory\n\n## Summary\n\nThe canonical list of Aetos repositories covered by the CI and versioning\nstandards, with the artifact each one produces, its version source, and its\nDrone shape. Every entry maps to the contract in\n[91 – Versioning & Changelog](91_versioning_and_changelog.md) and the two CI\nfiles in [90 – Drone Pipelines](90_drone_pipelines.md).\n\nThe same data is published machine-readably as the `registry://repos` MCP\nresource (and the `list_repos` tool), sourced from `standards/src/repos.json`.\nPaths are relative to the `aetos/` workspace root.\n\n---\n\n## Packages (Type A)\n\nA wheel + sdist published to the private index. Version source is\n`pyproject.toml`; Drone file is `python-lib.yaml` (tag-triggered).\n\n| Repo | Path | Docs | MCP server |\n|------|------|------|------------|\n| `dagpipe` | `dagpipe` | lib, wiki | `dagpipe:8006` |\n| `doc-forge` | `doc-forge` | lib, wiki | `docforge:8001` |\n| `hexa` | `hexa` | lib, wiki | `hexa:8008` |\n| `mail-intake` | `mail-intake` | lib, wiki | `mail_intake:8002` |\n| `mongo-ops` | `mongo-ops` | lib, wiki | `mongo_ops:8007` |\n| `omniread` | `omniread` | lib, wiki | `omniread:8003` |\n| `openapi-first` | `openapi-first` | lib, wiki | `openapi_first:8004` |\n| `py-jwt` | `py-jwt` | lib, wiki | `jwtlib:8005` |\n\n---\n\n## Services (Type B)\n\nA container image pushed to the registry and run on the Docker host. Version\nsource is the `VERSION` file; Drone file is `service-docker.yaml`.\n\n| Repo | Path | Trigger | Docs |\n|------|------|---------|------|\n| `auth-server` | `auth-server` | tag | api, lib, wiki |\n\nTag-triggered and enforces `tag == VERSION`.\n\n---\n\n## Required files per repo\n\n| Type | Version source | Changelog | Drone |\n|------|----------------|-----------|-------|\n| package | `pyproject.toml` | `CHANGELOG.md` | `python-lib.yaml` |\n| service | `VERSION` | `CHANGELOG.md` | `service-docker.yaml` |\n\nEvery covered repository must be able to satisfy `tag == version`:\nthe version file (never a commit id) is bumped in the release MR, the MR is\nmerged, and the tag is created on the merged commit.\n\n---\n\n## Reading this at runtime\n\n- Resource: `registry://repos`\n- Tool: `list_repos()`\n- Humans: this page (mirror of `standards/src/repos.json`).\n\n---\n\n## Related\n\n- [90 – Drone Pipelines](90_drone_pipelines.md) · [91 – Versioning & Changelog](91_versioning_and_changelog.md) · [93 – Library Registry](93_library_registry.md)\n",
|
||||
"objects": {}
|
||||
}
|
||||
}
|
||||
8
standards/mcp/modules/ui_admin.json
Normal file
8
standards/mcp/modules/ui_admin.json
Normal file
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"module": "ui_admin",
|
||||
"content": {
|
||||
"path": "ui_admin",
|
||||
"docstring": "# UI: Auto-Rendered Admin & Custom Pages\n\n## Summary\n\nThe UI axis of an Aetos app is a **published React client**, not code written\nper application. Two npm packages carry the whole surface:\n\n| Package | Role |\n|---|---|\n| `@aetoskia/react-openapi` | Renders a complete admin panel (CRUD tables, forms, filters, sorting, pagination, uploads) **from the app's `openapi.yaml`** — zero UI code. |\n| `@aetoskia/react-auth` | Auth contexts and pages (login/register/me) wired to the auth-server, plus the axios client with token handling. |\n\nBoth publish to the private registry `https://npm.aetoskia.com`. The server\nspec is the single source of truth: the same `openapi.yaml` that drives\n`openapi-first` routing drives the admin UI, through **x- extension fields**\n(see below).\n\n---\n\n## Scaffold\n\n```bash\ncp -r <docs>/standards/src/templates/client apps/<your-app>-client\ncd apps/<your-app>-client\nnpm install # deps come from npm.aetoskia.com via .npmrc\nnpm run dev\n```\n\nThe client template is a Vite + MUI app with:\n\n- `src/openapi-config.ts` — points the renderer at the app's spec and the\n auth-server's spec;\n- `.env.example` — `VITE_API_BASE_URL` (app API) and `VITE_AUTH_BASE_URL`\n (auth-server);\n- a `Home` page that auto-lists every resource the spec declares, and a\n `Header`/`Footer`/theme scaffold.\n\nCustom pages are ordinary React routes layered on top; the auto-rendered admin\nis available per resource at `#/resource/<name>`.\n\n---\n\n## x- extensions: how the spec steers the UI\n\nThe admin renderer reads a catalog of OpenAPI extension fields (`x-resource`,\n`x-list-columns`, `x-display-format`, `x-label`, `x-order`, `x-hidden`,\n`x-sortable`, `x-filterable`, `x-autocomplete`, `x-fk`, `x-ui-type`,\n`x-upload`, `x-sse`, `x-profile`, and the auth wiring `x-server-url` /\n`x-login-path` / `x-me-path` / …) declared on schemas and properties.\n\n**The catalog is canonical in the react-openapi source, not in this doc.**\nRead it from the MCP bundle:\n\n```\ndocs://modules/react-openapi # module: specExtensions — the full catalog\n```\n\nThe app's own spec carries the per-resource values; the catalog explains what\neach field does. The template's `openapi.yaml` shows the convention on the\nexample `Item` and `Job` schemas.\n\n---\n\n## Golden rules\n\n1. **The spec owns the UI.** Add a resource or rename a column in\n `openapi.yaml`; the admin follows. Never fork the renderer per app.\n2. **Custom pages for workflows, auto-render for CRUD.** Anything that is\n \"list / create / edit / delete an entity\" is a spec concern; anything that\n is a bespoke workflow is a React page.\n3. **Auth is consumed, never re-implemented.** `@aetoskia/react-auth` holds\n tokens and calls the auth-server endpoints declared by the x- wiring; pages\n read the context.\n4. **Publish, don't vendor.** UI shared across apps belongs in\n `@aetoskia/react-openapi` or `@aetoskia/react-auth` (SemVer, tag-triggered\n npm release), not copy-pasted into app trees.\n\n---\n\n## Notes\n\n- The server template ships authless by default (see\n [22 – Auth Integration](22_auth_integration.md)); the client template pairs\n with it and degrades to \"no login\" until a security scheme is declared.\n- `react/vet` is the full-stack reference implementation: spec with x-\n extensions, server, and the consuming client in one tree.\n",
|
||||
"objects": {}
|
||||
}
|
||||
}
|
||||
File diff suppressed because one or more lines are too long
@@ -2,7 +2,7 @@
|
||||
"module": "wiki_development_releasing",
|
||||
"content": {
|
||||
"path": "wiki_development_releasing",
|
||||
"docstring": "# Releasing & Versioning\n\nHow to cut a release of any Aetos repository. The rule lives in the reference\npage [Versioning & Changelog](../lib/11_versioning_and_changelog/); this is the\nrunbook you follow.\n\nEvery repository is one of two Drone shapes — a **PyPI package** or a **Docker\ndeployment** ([Drone Pipelines](../lib/10_drone_pipelines/)). Both release the\nsame way: the version bump and changelog promotion go **in the merge request**,\nand the tag is created on the merged commit.\n\n---\n\n## 🧾 Before you start\n\n- You have an open **merge request** holding the change, and `main` is green\n (the Drone quality gate passed on the last run).\n- You know whether this is a **breaking**, **feature**, or **fix** release.\n- The version file exists:\n - package → `version` in `pyproject.toml`\n - service → `VERSION` at the repo root\n\n---\n\n## 🚦 Pick the next version\n\nThe version file and the tag must be identical. For `0.y.z`, `0.y` is the major\nline (see the reference page); once at `1.0.0`, normal SemVer applies.\n\n| Change | `0.y.z` → | `1.0.0+` → |\n|--------|-----------|------------|\n| Breaking | `0.(y+1).0` | `(x+1).0.0` |\n| Feature | `0.y.(z+1)` | `x.(y+1).0` |\n| Fix | `0.y.(z+1)` | `x.y.(z+1)` |\n\n---\n\n## 🌿 Release in the MR\n\nThe version is known while the change is still a merge request, so the bump\nrides along with it. Do all edits **in the MR**:\n\n- **Reconcile the changelog first.** `[Unreleased]` is a **draft, not the source\n of truth**: diff the change against the last tag\n (`git log <last-tag>..HEAD`, `git diff --stat <last-tag>..HEAD`) and add an\n entry for every user-facing change that is missing. **Always show the proposed\n additions to the user and wait for approval** before promoting — ask rather\n than guess when an entry is ambiguous.\n\n- **Promote the changelog** in `CHANGELOG.md`: move the (now reconciled)\n `[Unreleased]` content under a new `## [x.y.z] - YYYY-MM-DD` heading, leave a\n fresh empty `[Unreleased]` on top, and add the compare links — naming the\n **version/tag**, never a commit id:\n\n ```markdown\n [Unreleased]: https://git.aetoskia.com/aetos/<repo>/compare/x.y.z...HEAD\n [x.y.z]: https://git.aetoskia.com/aetos/<repo>/compare/x.y.(z-1)...x.y.z\n ```\n\n- **Bump the version file** to the intended release version: `version = \"x.y.z\"`\n in `pyproject.toml` (packages) or the `VERSION` file (services).\n\n---\n\n## 🏷️ Tag the merged commit\n\n1. **Merge or squash** the MR into `main`.\n2. **Create the tag** on the resulting commit: `git tag x.y.z` (lightweight).\n3. **Push the tag** (`git push origin x.y.z`) — Drone builds the release.\n\n### 🤖 Agent-assisted tagging\n\nThe agent does not author or merge the MR and never tags before the merge. After\nyou confirm the MR is merged/squashed and tell it to proceed, the agent:\n\n1. Waits for that explicit go-ahead.\n2. Finds the commit that introduced the bump:\n - package:\n `git log -S 'version = \"x.y.z\"' -n 1 --format='%H %s' -- pyproject.toml`\n - service:\n `git log -S 'x.y.z' -n 1 --format='%H %s' -- VERSION`\n3. Verifies that commit's version file equals `x.y.z`, then tags **only** that\n commit: `git tag x.y.z <sha>`.\n4. Does **not** push — it asks you to run `git push origin x.y.z`.\n\n---\n\n## 🤖 What Drone does\n\n- **Type A (package):** asserts `tag == pyproject version`, then skips if that\n version already exists on the index, runs the quality gate, builds, and\n uploads the wheel + sdist.\n- **Type B (service):** asserts `tag == VERSION`, resolves the tag, skips if the\n image already exists, runs the quality gate, builds, pushes, and restarts the\n container.\n\nIf the guard fails, nothing is published — fix the version file, amend the\ncommit, and move the tag **only** if it was never pushed.\n\n---\n\n## 🛟 Backfill / recovery\n\nIf an older tag never published (a past version-file mismatch, an index\noutage):\n\n- **Package:** run the `backfill-pypi-from-tags` pipeline (custom event). It\n checks out every tag, verifies `tag == pyproject version` at that commit,\n and uploads the ones missing from the index. Already-fixed history is never\n rewritten.\n- **Service:** rebuild the image for the missing tag with a fresh commit and a\n new patch version; do not move a published tag.\n\n---\n\n## 🔁 If a release is wrong\n\n- Never reuse or force-move a pushed tag.\n- Fix forward: bump to the next patch, promote the changelog, tag again.\n\n---\n\n## Related\n\n- [Testing & Quality Gates](01_testing.md) · [Versioning & Changelog](../lib/11_versioning_and_changelog/) · [Drone Pipelines](../lib/10_drone_pipelines/)\n",
|
||||
"docstring": "# Releasing & Versioning\n\nHow to cut a release of any Aetos repository. The rule lives in the reference\npage [Versioning & Changelog](../lib/91_versioning_and_changelog/); this is the\nrunbook you follow.\n\nEvery repository is one of two Drone shapes — a **PyPI package** or a **Docker\ndeployment** ([Drone Pipelines](../lib/90_drone_pipelines/)). Both release the\nsame way: the version bump and changelog promotion go **in the merge request**,\nand the tag is created on the merged commit.\n\n---\n\n## 🧾 Before you start\n\n- You have an open **merge request** holding the change, and `main` is green\n (the Drone quality gate passed on the last run).\n- You know whether this is a **breaking**, **feature**, or **fix** release.\n- The version file exists:\n - package → `version` in `pyproject.toml`\n - service → `VERSION` at the repo root\n\n---\n\n## 🚦 Pick the next version\n\nThe version file and the tag must be identical. For `0.y.z`, `0.y` is the major\nline (see the reference page); once at `1.0.0`, normal SemVer applies.\n\n| Change | `0.y.z` → | `1.0.0+` → |\n|--------|-----------|------------|\n| Breaking | `0.(y+1).0` | `(x+1).0.0` |\n| Feature | `0.y.(z+1)` | `x.(y+1).0` |\n| Fix | `0.y.(z+1)` | `x.y.(z+1)` |\n\n---\n\n## 🌿 Release in the MR\n\nThe version is known while the change is still a merge request, so the bump\nrides along with it. Do all edits **in the MR**:\n\n- **Reconcile the changelog first.** `[Unreleased]` is a **draft, not the source\n of truth**: diff the change against the last tag\n (`git log <last-tag>..HEAD`, `git diff --stat <last-tag>..HEAD`) and add an\n entry for every user-facing change that is missing. **Always show the proposed\n additions to the user and wait for approval** before promoting — ask rather\n than guess when an entry is ambiguous.\n\n- **Promote the changelog** in `CHANGELOG.md`: move the (now reconciled)\n `[Unreleased]` content under a new `## [x.y.z] - YYYY-MM-DD` heading, leave a\n fresh empty `[Unreleased]` on top, and add the compare links — naming the\n **version/tag**, never a commit id:\n\n ```markdown\n [Unreleased]: https://git.aetoskia.com/aetos/<repo>/compare/x.y.z...HEAD\n [x.y.z]: https://git.aetoskia.com/aetos/<repo>/compare/x.y.(z-1)...x.y.z\n ```\n\n- **Bump the version file** to the intended release version: `version = \"x.y.z\"`\n in `pyproject.toml` (packages) or the `VERSION` file (services).\n\n---\n\n## 🏷️ Tag the merged commit\n\n1. **Merge or squash** the MR into `main`.\n2. **Create the tag** on the resulting commit: `git tag x.y.z` (lightweight).\n3. **Push the tag** (`git push origin x.y.z`) — Drone builds the release.\n\n### 🤖 Agent-assisted tagging\n\nThe agent does not author or merge the MR and never tags before the merge. After\nyou confirm the MR is merged/squashed and tell it to proceed, the agent:\n\n1. Waits for that explicit go-ahead.\n2. Finds the commit that introduced the bump:\n - package:\n `git log -S 'version = \"x.y.z\"' -n 1 --format='%H %s' -- pyproject.toml`\n - service:\n `git log -S 'x.y.z' -n 1 --format='%H %s' -- VERSION`\n3. Verifies that commit's version file equals `x.y.z`, then tags **only** that\n commit: `git tag x.y.z <sha>`.\n4. Does **not** push — it asks you to run `git push origin x.y.z`.\n\n---\n\n## 🤖 What Drone does\n\n- **Type A (package):** asserts `tag == pyproject version`, then skips if that\n version already exists on the index, runs the quality gate, builds, and\n uploads the wheel + sdist.\n- **Type B (service):** asserts `tag == VERSION`, resolves the tag, skips if the\n image already exists, runs the quality gate, builds, pushes, and restarts the\n container.\n\nIf the guard fails, nothing is published — fix the version file, amend the\ncommit, and move the tag **only** if it was never pushed.\n\n---\n\n## 🛟 Backfill / recovery\n\nIf an older tag never published (a past version-file mismatch, an index\noutage):\n\n- **Package:** run the `backfill-pypi-from-tags` pipeline (custom event). It\n checks out every tag, verifies `tag == pyproject version` at that commit,\n and uploads the ones missing from the index. Already-fixed history is never\n rewritten.\n- **Service:** rebuild the image for the missing tag with a fresh commit and a\n new patch version; do not move a published tag.\n\n---\n\n## 🔁 If a release is wrong\n\n- Never reuse or force-move a pushed tag.\n- Fix forward: bump to the next patch, promote the changelog, tag again.\n\n---\n\n## Related\n\n- [Testing & Quality Gates](01_testing.md) · [Versioning & Changelog](../lib/91_versioning_and_changelog/) · [Drone Pipelines](../lib/90_drone_pipelines/)\n",
|
||||
"objects": {}
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,7 @@
|
||||
"module": "wiki_index",
|
||||
"content": {
|
||||
"path": "wiki_index",
|
||||
"docstring": "# 🧩 Standards — the Aetos App Blueprint\n\nOne reusable architecture for every backend application in the Aetos ecosystem:\na spec-first HTTP edge, a framework-free domain core, a pluggable infrastructure\nlayer, and a single composition root.\n\nFill in **two axes only** and a new app is done: your **resource model**, and\n(if needed) your **pipeline family**. The blueprint itself never names a\nbusiness domain — expenses, health metrics, inventory, and analytics are all\nthe same shape underneath.\n\n> **Doc model:** this wiki is written for humans — how-to guides, the build\n> recipe, and quality gates. The enforceable rules (layering, composition root,\n> CRUD template, pipeline scaffold) and the library registry live in the\n> **reference** pages, mirrored by the machine-readable `standards` MCP bundle.\n> Query `find_library` before writing any infrastructure.\n\n---\n\n## 🚀 Key Features\n\n- 🧭 **Spec-first routing** — the OpenAPI document, not decorator routers, is\n the source of truth (operationId lookup)\n- 🏗️ **One-way layering** — `interfaces → domain → infra`, enforced\n- 🔌 **Single composition root** — every dependency is wired in exactly one place\n- 🧩 **Generic, not app-specific** — reusable rules versus two authoring axes\n- 📚 **Library-backed** — DB, DI, pipelines, ingestion, auth, and docs come from\n internal libraries, never hand-written\n- 🚦 **Explicit state machines** — durable job statuses, progress, and\n human-in-the-loop pauses\n\n---\n\n## 📁 Documentation Structure\n\n| Section | Description |\n|-----------------------------------------------------|--------------------------------------------------------|\n| [Overview](01_overview.md) | Philosophy, the one-way dependency rule, architecture |\n| [App Components](02_components.md) | The component model and how the pieces wire together |\n| [Start an App](03_start_an_app.md) | The entry point: gather the two axes, then build |\n| [Testing & Quality](04_development/01_testing.md) | Test layout and acceptance gates |\n\n**Reference** (separate site, mirrors the MCP bundle): the enforceable\nrules — [Build Recipe](../lib/01_build_recipe/), [Layering](../lib/02_layering_rules/), [Composition\nRoot](../lib/03_composition_root/), [Spec-First\nRouting](../lib/04_spec_first_routing/), [CRUD\nTemplate](../lib/05_crud_template/), [Pipeline\nScaffold](../lib/06_pipeline_scaffold/), [Worker &\nProgress](../lib/07_worker_and_progress/), [Human-in-the-Loop](../lib/08_human_in_loop/),\n[Infra Adapters](../lib/09_infra_adaptors/), [Genericity\nMatrix](../lib/12_genericity_matrix/), [Library\nRegistry](../lib/13_library_registry/).\n\n---\n\n## 🔗 Related Resources\n\n- **MCP bundle** — `standards` server on `:8009`: read `docs://index`,\n `docs://nav`, `docs://modules/{module}`; call `find_library(capability)`\n- **Library registry** — the catalog of internal libraries behind every app\n (`libraries.json`, served as `registry://libraries`)\n- **Template** — the runnable skeleton at `standards/src/templates/app/`\n- **Start a build** — invoke the `start_app` prompt on the `standards` server,\n or read the [Start an App](03_start_an_app.md) guide\n\n---\n\n© Aetoskia Internal — `standards`\n",
|
||||
"docstring": "# 🧩 Standards — the Aetos App Blueprint\n\nOne reusable architecture for every backend application in the Aetos ecosystem:\na spec-first HTTP edge, a framework-free domain core, a pluggable infrastructure\nlayer, and a single composition root.\n\nFill in **two axes only** and a new app is done: your **resource model**, and\n(if needed) your **pipeline family**. The blueprint itself never names a\nbusiness domain — expenses, health metrics, inventory, and analytics are all\nthe same shape underneath.\n\n> **Doc model:** this wiki is written for humans — how-to guides, the build\n> recipe, and quality gates. The enforceable rules (layering, composition root,\n> CRUD template, pipeline scaffold) and the library registry live in the\n> **reference** pages, mirrored by the machine-readable `standards` MCP bundle.\n> Query `find_library` before writing any infrastructure.\n\n---\n\n## 🚀 Key Features\n\n- 🧭 **Spec-first routing** — the OpenAPI document, not decorator routers, is\n the source of truth (operationId lookup)\n- 🏗️ **One-way layering** — `interfaces → domain → infra`, enforced\n- 🔌 **Single composition root** — every dependency is wired in exactly one place\n- 🧩 **Generic, not app-specific** — reusable rules versus two authoring axes\n- 📚 **Library-backed** — DB, DI, pipelines, ingestion, auth, and docs come from\n internal libraries, never hand-written\n- 🚦 **Explicit state machines** — durable job statuses, progress, and\n human-in-the-loop pauses\n\n---\n\n## 📁 Documentation Structure\n\n| Section | Description |\n|-----------------------------------------------------|--------------------------------------------------------|\n| [Overview](01_overview.md) | Philosophy, the one-way dependency rule, architecture |\n| [App Components](02_components.md) | The component model and how the pieces wire together |\n| [Start an App](03_start_an_app.md) | The entry point: gather the two axes, then build |\n| [Testing & Quality](04_development/01_testing.md) | Test layout and acceptance gates |\n\n**Reference** (separate site, mirrors the MCP bundle): the enforceable\nanatomy — start at the [Build Recipe](../lib/01_build_recipe/), then the\npillars: domains ([Layering](../lib/10_layering_rules/)), the OpenAPI\ncontract ([Composition Root](../lib/02_composition_root/),\n[Spec-First Routing](../lib/20_spec_first_routing/), [CRUD\nTemplate](../lib/21_crud_template/), [Auth\nIntegration](../lib/22_auth_integration/)), interfaces & infra ([Infra\nAdapters](../lib/30_infra_adaptors/)), UI ([Auto-Rendered\nAdmin](../lib/40_ui_admin/)), the optional pipelines layer ([Pipeline\nScaffold](../lib/50_pipeline_scaffold/), [Worker &\nProgress](../lib/51_worker_and_progress/), [Human-in-the-Loop](../lib/52_human_in_loop/)),\nand delivery/meta ([Genericity\nMatrix](../lib/92_genericity_matrix/), [Library\nRegistry](../lib/93_library_registry/)).\n\n---\n\n## 🔗 Related Resources\n\n- **MCP bundle** — `standards` server on `:8009`: read `docs://index`,\n `docs://nav`, `docs://modules/{module}`; call `find_library(capability)`\n- **Library registry** — the catalog of internal libraries behind every app\n (`libraries.json`, served as `registry://libraries`)\n- **Template** — the runnable skeleton at `standards/src/templates/app/`\n- **Start a build** — invoke the `start_app` prompt on the `standards` server,\n or read the [Start an App](03_start_an_app.md) guide\n\n---\n\n© Aetoskia Internal — `standards`\n",
|
||||
"objects": {}
|
||||
}
|
||||
}
|
||||
File diff suppressed because one or more lines are too long
@@ -2,7 +2,7 @@
|
||||
"module": "wiki_overview",
|
||||
"content": {
|
||||
"path": "wiki_overview",
|
||||
"docstring": "# Overview\n\nThe blueprint is a **hexagonal (ports & adapters) application** with a\n**spec-first** web edge and a **single composition root**. It favors explicit\nwiring over implicit magic and existing internal libraries over hand-written\ninfrastructure. Start here to build the mental model; the enforceable details\nlive in the reference pages.\n\n---\n\n## 🏗️ Architecture\n\n```mermaid\nflowchart LR\n subgraph EDGE[\"interfaces/ — HTTP edge\"]\n OAS[\"openapi.yaml<br/>operationId contract\"]\n RT[\"<resource>/routes.py<br/>thin handlers\"]\n end\n\n subgraph CORE[\"domain/ — business core\"]\n MD[\"models\"]\n PT[\"ports (adapter binding seam)\"]\n SV[\"services\"]\n end\n\n subgraph INFRA[\"infra/ — adapters\"]\n RP[\"mongo repos (mongo-ops)\"]\n AD[\"cache · stores · llm · mail\"]\n DB[(\"MongoDB\")]\n end\n\n CR[\"init.py<br/>composition root\"]\n\n OAS --> RT\n RT --> SV\n SV --> PT\n SV --> RP\n PT -. depends on .- RP\n CR --- RT\n CR --- SV\n CR --- RP\n RP --> DB\n AD --- CR\n```\n\nThe rule holds at every edge: code in an outer ring may depend on a ring closer\nto the core, never the reverse. `domain/` never imports a web framework;\nonly its `ports/` seam reaches into `infra/` to bind adapters.\n\n> **Legend** — solid arrows are compile-time calls; dotted arrows are the\n> port/adapter binding, performed by the composition root at startup.\n\n---\n\n## 🔄 The one-way dependency rule\n\n| Ring | May import | Never imports |\n|-------------|------------------------------------|----------------------------------|\n| `interfaces/` | `domain`, framework glue (glue only) | business logic, `infra` directly |\n| `domain/` | its own models + its `ports/` seam (which binds `infra`/libraries) | web frameworks, `interfaces/` |\n| `infra/` | `domain` ports, drivers, libraries | — |\n| `init.py` | everything (the wiring point) | — |\n\n---\n\n## 🧭 Core principles\n\n1. **One-way dependencies.** `interfaces -> domain -> infra` is allowed; the\n reverse is forbidden.\n2. **Ports in the domain, adapters in infra.** A service depends on a port; the\n port's factory binds the concrete adapter, and the composition root calls\n those factories.\n3. **One composition root.** Nothing constructs its own dependencies. All\n wiring lives in one module (`init.py`) exposed as a flat resource registry.\n4. **Spec-first.** The HTTP contract is declared in `openapi.yaml`; route\n handlers are looked up by `operationId`. There are no decorator routers.\n5. **Reuse the libraries.** Orchestration, DI, Mongo repositories, ingestion,\n auth, and docs come from internal libraries — see the [Library\n Registry](../lib/13_library_registry/).\n6. **Explicit state machines.** Long-running work moves through explicit,\n durable statuses and can pause for human input.\n\n---\n\n## ⚙️ Runtime processes\n\nA standard app may run as up to three processes that share the same composition\nroot:\n\n| Process | Entry point | Responsibility |\n|---------|------------------------|-------------------------------------------|\n| API | `main.py` | serve HTTP; start/stop resources via lifespan |\n| Worker | `worker.py` | poll durable jobs, run pipelines, publish progress |\n| Scripts | `python -m scripts.<name>` | one-shot operator tasks |\n\n---\n\n## ➡️ Read Next\n\n- [02 – App Components](02_components.md) · [03 – Start an App](03_start_an_app.md)\n",
|
||||
"docstring": "# Overview\n\nThe blueprint is a **hexagonal (ports & adapters) application** with a\n**spec-first** web edge and a **single composition root**. It favors explicit\nwiring over implicit magic and existing internal libraries over hand-written\ninfrastructure. Start here to build the mental model; the enforceable details\nlive in the reference pages.\n\n---\n\n## 🏗️ Architecture\n\n```mermaid\nflowchart LR\n subgraph EDGE[\"interfaces/ — HTTP edge\"]\n OAS[\"openapi.yaml<br/>operationId contract\"]\n RT[\"<resource>/routes.py<br/>thin handlers\"]\n end\n\n subgraph CORE[\"domain/ — business core\"]\n MD[\"models\"]\n PT[\"ports (adapter binding seam)\"]\n SV[\"services\"]\n end\n\n subgraph INFRA[\"infra/ — adapters\"]\n RP[\"mongo repos (mongo-ops)\"]\n AD[\"cache · stores · llm · mail\"]\n DB[(\"MongoDB\")]\n end\n\n CR[\"init.py<br/>composition root\"]\n\n OAS --> RT\n RT --> SV\n SV --> PT\n SV --> RP\n PT -. depends on .- RP\n CR --- RT\n CR --- SV\n CR --- RP\n RP --> DB\n AD --- CR\n```\n\nThe rule holds at every edge: code in an outer ring may depend on a ring closer\nto the core, never the reverse. `domain/` never imports a web framework;\nonly its `ports/` seam reaches into `infra/` to bind adapters.\n\n> **Legend** — solid arrows are compile-time calls; dotted arrows are the\n> port/adapter binding, performed by the composition root at startup.\n\n---\n\n## 🔄 The one-way dependency rule\n\n| Ring | May import | Never imports |\n|-------------|------------------------------------|----------------------------------|\n| `interfaces/` | `domain`, framework glue (glue only) | business logic, `infra` directly |\n| `domain/` | its own models + its `ports/` seam (which binds `infra`/libraries) | web frameworks, `interfaces/` |\n| `infra/` | `domain` ports, drivers, libraries | — |\n| `init.py` | everything (the wiring point) | — |\n\n---\n\n## 🧭 Core principles\n\n1. **One-way dependencies.** `interfaces -> domain -> infra` is allowed; the\n reverse is forbidden.\n2. **Ports in the domain, adapters in infra.** A service depends on a port; the\n port's factory binds the concrete adapter, and the composition root calls\n those factories.\n3. **One composition root.** Nothing constructs its own dependencies. All\n wiring lives in one module (`init.py`) exposed as a flat resource registry.\n4. **Spec-first.** The HTTP contract is declared in `openapi.yaml`; route\n handlers are looked up by `operationId`. There are no decorator routers.\n5. **Reuse the libraries.** Orchestration, DI, Mongo repositories, ingestion,\n auth, and docs come from internal libraries — see the [Library\n Registry](../lib/93_library_registry/).\n6. **Explicit state machines.** Long-running work moves through explicit,\n durable statuses and can pause for human input.\n\n---\n\n## ⚙️ Runtime processes\n\nA standard app may run as up to three processes that share the same composition\nroot:\n\n| Process | Entry point | Responsibility |\n|---------|------------------------|-------------------------------------------|\n| API | `main.py` | serve HTTP; start/stop resources via lifespan |\n| Worker | `worker.py` | poll durable jobs, run pipelines, publish progress |\n| Scripts | `python -m scripts.<name>` | one-shot operator tasks |\n\n---\n\n## ➡️ Read Next\n\n- [02 – App Components](02_components.md) · [03 – Start an App](03_start_an_app.md)\n",
|
||||
"objects": {}
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,7 @@
|
||||
"module": "wiki_start_an_app",
|
||||
"content": {
|
||||
"path": "wiki_start_an_app",
|
||||
"docstring": "# 🚀 Start an App\n\nThis is the entry point for building a new application from the blueprint. The\ngoal is one deterministic pass: you supply only the **two axes**, and the agent\ndoes the rest by reading the `standards` MCP, importing Tier A libraries, and\ncopying Tier B template components.\n\n> **Doc model:** this page is the human entry point. The deterministic,\n> machine-facing checklist lives in the reference page\n> [Build Recipe](../lib/01_build_recipe/), served as `docs://modules/build_recipe`.\n\n---\n\n## 🧾 What the agent needs from you\n\nGather these before starting — the `start_app` MCP prompt asks for them:\n\n1. **App name + one-line purpose.**\n2. **Axis 1 — resources.** Each resource, its fields, and relationships. Paste\n `openapi.yaml` if you already have it.\n3. **Axis 2 — pipelines.** Only if an input needs a multi-step transformation:\n the families and their input formats (or \"none\").\n4. **Auth needed now?** Default **no**. Auth is deferred (`py-jwt` primitives\n only), and an authless app is just a spec with no `security` keys — see\n [Spec-First Routing → Authless apps](../lib/04_spec_first_routing/#authless-apps).\n5. **Integrations.** Mongo, ingestion formats, email, LLM provider.\n\nIf you can state axes 1 and 2, the rest is mechanical.\n\n---\n\n## ▶️ How to start\n\nFrom an MCP client connected to the `standards` server:\n\n1. Invoke the **`intake`** prompt (or `start_app` with no arguments) to get the\n intake questions.\n2. Answer them, then invoke **`build`**\n (`build(app_name=..., resources=..., pipelines=..., auth=...)`), or use\n **`start_app`** to intake-and-build in one call.\n3. The prompt hands off to `docs://modules/build_recipe`; the agent scaffolds\n with `get_app_template()` and pulls exact files with\n `get_app_component(kind, resource=..., family=...)`, authoring only the\n app-specific parts.\n4. To validate the standard without touching a real app, invoke **`trial`**\n (`trial(app_name=..., build_path=...)`) to build into a scratch directory,\n prove it builds, and report findings.\n\nManual alternative — copy the skeleton and follow the reference recipe:\n\n```bash\ncp -r <docs>/standards/src/templates/app apps/<your-app>\n```\n\n---\n\n## 📚 Reference\n\n- [Build Recipe](../lib/01_build_recipe/) — the deterministic checklist\n- [Genericity Matrix](../lib/12_genericity_matrix/) — Tier A / B / C\n- [Library Registry](../lib/13_library_registry/) — the Tier A catalog\n- [App Components](02_components.md) — the component model\n\n---\n\n## Related\n\n- [01 – Overview](01_overview.md) · [02 – App Components](02_components.md) · [04 – Testing & Quality](04_development/01_testing.md)\n",
|
||||
"docstring": "# 🚀 Start an App\n\nThis is the entry point for building a new application from the blueprint. The\ngoal is one deterministic pass: you supply only the **two axes**, and the agent\ndoes the rest by reading the `standards` MCP, importing Tier A libraries, and\ncopying Tier B template components.\n\n> **Doc model:** this page is the human entry point. The deterministic,\n> machine-facing checklist lives in the reference page\n> [Build Recipe](../lib/01_build_recipe/), served as `docs://modules/build_recipe`.\n\n---\n\n## 🧾 What the agent needs from you\n\nGather these before starting — the `start_app` MCP prompt asks for them:\n\n1. **App name + one-line purpose.**\n2. **Axis 1 — resources.** Each resource, its fields, and relationships. Paste\n `openapi.yaml` if you already have it.\n3. **Axis 2 — pipelines.** Only if an input needs a multi-step transformation:\n the families and their input formats (or \"none\").\n4. **Auth needed now?** Default **no**. Auth is deferred (`py-jwt` primitives\n only), and an authless app is just a spec with no `security` keys — see\n [Spec-First Routing → Authless apps](../lib/20_spec_first_routing/#authless-apps).\n5. **Integrations.** Mongo, ingestion formats, email, LLM provider.\n\nIf you can state axes 1 and 2, the rest is mechanical.\n\n---\n\n## ▶️ How to start\n\nFrom an MCP client connected to the `standards` server:\n\n1. Invoke the **`intake`** prompt (or `start_app` with no arguments) to get the\n intake questions.\n2. Answer them, then invoke **`build`**\n (`build(app_name=..., resources=..., pipelines=..., auth=...)`), or use\n **`start_app`** to intake-and-build in one call.\n3. The prompt hands off to `docs://modules/build_recipe`; the agent scaffolds\n with `get_app_template()` and pulls exact files with\n `get_app_component(kind, resource=..., family=...)`, authoring only the\n app-specific parts.\n4. To validate the standard without touching a real app, invoke **`trial`**\n (`trial(app_name=..., build_path=...)`) to build into a scratch directory,\n prove it builds, and report findings.\n\nManual alternative — copy the skeleton and follow the reference recipe:\n\n```bash\ncp -r <docs>/standards/src/templates/app apps/<your-app>\n```\n\n---\n\n## 📚 Reference\n\n- [Build Recipe](../lib/01_build_recipe/) — the deterministic checklist\n- [Genericity Matrix](../lib/92_genericity_matrix/) — Tier A / B / C\n- [Library Registry](../lib/93_library_registry/) — the Tier A catalog\n- [App Components](02_components.md) — the component model\n\n---\n\n## Related\n\n- [01 – Overview](01_overview.md) · [02 – App Components](02_components.md) · [04 – Testing & Quality](04_development/01_testing.md)\n",
|
||||
"objects": {}
|
||||
}
|
||||
}
|
||||
@@ -4,16 +4,16 @@
|
||||
"resource": "docs://modules/build_recipe",
|
||||
"title": "Build Recipe"
|
||||
},
|
||||
{
|
||||
"module": "layering_rules",
|
||||
"resource": "docs://modules/layering_rules",
|
||||
"title": "Layering Rules"
|
||||
},
|
||||
{
|
||||
"module": "composition_root",
|
||||
"resource": "docs://modules/composition_root",
|
||||
"title": "Composition Root"
|
||||
},
|
||||
{
|
||||
"module": "layering_rules",
|
||||
"resource": "docs://modules/layering_rules",
|
||||
"title": "Layering Rules"
|
||||
},
|
||||
{
|
||||
"module": "spec_first_routing",
|
||||
"resource": "docs://modules/spec_first_routing",
|
||||
@@ -24,6 +24,21 @@
|
||||
"resource": "docs://modules/crud_template",
|
||||
"title": "CRUD Template"
|
||||
},
|
||||
{
|
||||
"module": "auth_integration",
|
||||
"resource": "docs://modules/auth_integration",
|
||||
"title": "Auth Integration"
|
||||
},
|
||||
{
|
||||
"module": "infra_adaptors",
|
||||
"resource": "docs://modules/infra_adaptors",
|
||||
"title": "Infra Adapters"
|
||||
},
|
||||
{
|
||||
"module": "ui_admin",
|
||||
"resource": "docs://modules/ui_admin",
|
||||
"title": "UI: Auto-Rendered Admin & Custom Pages"
|
||||
},
|
||||
{
|
||||
"module": "pipeline_scaffold",
|
||||
"resource": "docs://modules/pipeline_scaffold",
|
||||
@@ -39,11 +54,6 @@
|
||||
"resource": "docs://modules/human_in_loop",
|
||||
"title": "Human-in-the-Loop"
|
||||
},
|
||||
{
|
||||
"module": "infra_adaptors",
|
||||
"resource": "docs://modules/infra_adaptors",
|
||||
"title": "Infra Adapters"
|
||||
},
|
||||
{
|
||||
"module": "drone_pipelines",
|
||||
"resource": "docs://modules/drone_pipelines",
|
||||
@@ -64,11 +74,6 @@
|
||||
"resource": "docs://modules/library_registry",
|
||||
"title": "Library Registry"
|
||||
},
|
||||
{
|
||||
"module": "auth_integration",
|
||||
"resource": "docs://modules/auth_integration",
|
||||
"title": "Auth Integration"
|
||||
},
|
||||
{
|
||||
"module": "repository_inventory",
|
||||
"resource": "docs://modules/repository_inventory",
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
DEBUG=false
|
||||
REPO_BACKEND=memory
|
||||
MONGO_URI=mongodb://localhost:27017
|
||||
MONGO_DB=app_template
|
||||
PORT=8000
|
||||
WORKER_POLL_SECONDS=30
|
||||
WORKER_MAX_RETRIES=3
|
||||
AUTH_SERVER=http://localhost:8000
|
||||
JWT_SERVER=http://localhost:8000
|
||||
JWT_SERVER=http://localhost:8000
|
||||
|
||||
@@ -3,6 +3,23 @@
|
||||
App configuration loaded from environment — a Settings dataclass with defaults
|
||||
plus a singleton settings instance populated from OS environment variables at
|
||||
import time.
|
||||
|
||||
---
|
||||
|
||||
The template reads these knobs:
|
||||
|
||||
- ``repo_backend`` — ``memory`` (default, zero-dependency process-local store)
|
||||
or ``mongo`` (persistent, via the shared mongo-ops connection manager).
|
||||
- ``mongo_uri`` / ``mongo_db`` — connection targets when the Mongo backend is
|
||||
selected.
|
||||
- ``port`` — the port uvicorn binds (keep in sync with the OpenAPI
|
||||
``servers:`` entry and the client's ``VITE_API_BASE_URL``).
|
||||
- ``worker_poll_seconds`` / ``worker_max_retries`` — background worker cadence.
|
||||
|
||||
``AUTH_SERVER`` is intentionally *not* re-exported here: ``openapi_first``
|
||||
resolves ``{AUTH_SERVER}`` straight from the process environment when the
|
||||
application is built, so the env var remains the single source of truth for
|
||||
the generated bearer-JWT introspection dependency.
|
||||
"""
|
||||
import os
|
||||
from dataclasses import dataclass
|
||||
@@ -14,23 +31,30 @@ class Settings:
|
||||
|
||||
Attributes:
|
||||
debug (bool): Enable debug behavior. Defaults to False.
|
||||
repo_backend (str): Persistence flavour, ``memory`` or ``mongo``.
|
||||
Defaults to ``memory``.
|
||||
mongo_uri (str): MongoDB connection URI. Defaults to mongodb://localhost:27017.
|
||||
mongo_db (str): MongoDB database name. Defaults to app_template.
|
||||
port (int): Local HTTP port. Defaults to 8000.
|
||||
worker_poll_seconds (int): Worker poll interval in seconds. Defaults to 30.
|
||||
worker_max_retries (int): Maximum job retries before skipping. Defaults to 3.
|
||||
"""
|
||||
|
||||
debug: bool = False
|
||||
repo_backend: str = "memory"
|
||||
mongo_uri: str = "mongodb://localhost:27017"
|
||||
mongo_db: str = "app_template"
|
||||
port: int = 8000
|
||||
worker_poll_seconds: int = 30
|
||||
worker_max_retries: int = 3
|
||||
|
||||
|
||||
settings = Settings(
|
||||
debug=os.environ.get("DEBUG", "").lower() in ("1", "true", "yes"),
|
||||
repo_backend=os.environ.get("REPO_BACKEND", "memory").lower(),
|
||||
mongo_uri=os.environ.get("MONGO_URI", "mongodb://localhost:27017"),
|
||||
mongo_db=os.environ.get("MONGO_DB", "app_template"),
|
||||
port=int(os.environ.get("PORT", "8000")),
|
||||
worker_poll_seconds=int(os.environ.get("WORKER_POLL_SECONDS", "30")),
|
||||
worker_max_retries=int(os.environ.get("WORKER_MAX_RETRIES", "3")),
|
||||
)
|
||||
)
|
||||
|
||||
@@ -9,11 +9,13 @@ class Item(BaseModel):
|
||||
"""A single countable resource.
|
||||
|
||||
Attributes:
|
||||
id (int | None): Server-assigned identifier. Defaults to None.
|
||||
name (str): Item name.
|
||||
quantity (int): Item quantity. Defaults to 1.
|
||||
"""
|
||||
|
||||
id: int | None = None
|
||||
name: str
|
||||
quantity: int = Field(default=1)
|
||||
|
||||
model_config = {"extra": "ignore"}
|
||||
model_config = {"extra": "ignore"}
|
||||
|
||||
@@ -1,21 +1,25 @@
|
||||
"""# Summary
|
||||
|
||||
Mongo persistence for items: document schema and repository factory.
|
||||
Items persistence ports — integer-id document and repository factory.
|
||||
"""
|
||||
from mongo_ops import BaseDocument, BaseRepository
|
||||
from mongo_ops import BaseDocument
|
||||
from pydantic import Field
|
||||
|
||||
from domain.item.models import Item
|
||||
from infra.db.repos.mongo import _repo_factory as mongo_repo_factory
|
||||
from infra.db.repos import create_repo
|
||||
|
||||
|
||||
class ItemDocument(Item, BaseDocument):
|
||||
"""Mongo document form of :class:`Item`."""
|
||||
"""Persisted item document. The integer ``id`` shadows the ObjectId."""
|
||||
|
||||
id: int | None = Field(default=None, validation_alias="_id")
|
||||
|
||||
|
||||
def create_item_repo() -> BaseRepository:
|
||||
"""Create the Mongo-backed item repository.
|
||||
def create_item_repo():
|
||||
"""Create the item repository selected by ``settings.repo_backend``.
|
||||
|
||||
Returns:
|
||||
BaseRepository: Repository wired to the ``items`` collection.
|
||||
IntIdMemoryRepository | IntIdMongoRepository: Repository wired to the
|
||||
``items`` collection/store.
|
||||
"""
|
||||
return mongo_repo_factory("items", ItemDocument)
|
||||
return create_repo("items", ItemDocument)
|
||||
|
||||
@@ -11,6 +11,7 @@ class Job(BaseModel):
|
||||
"""A unit of background work.
|
||||
|
||||
Attributes:
|
||||
id (int | None): Server-assigned identifier. Defaults to None.
|
||||
name (str): Job name.
|
||||
status (str): Lifecycle status. Defaults to "pending".
|
||||
retry_count (int): Times the job failed. Defaults to 0.
|
||||
@@ -18,10 +19,11 @@ class Job(BaseModel):
|
||||
payload (dict | None): Arbitrary job payload. Defaults to None.
|
||||
"""
|
||||
|
||||
id: int | None = None
|
||||
name: str
|
||||
status: Literal["pending", "processing", "done", "failed"] = "pending"
|
||||
retry_count: int = Field(default=0)
|
||||
error_message: str | None = None
|
||||
payload: dict | None = None
|
||||
|
||||
model_config = {"extra": "ignore"}
|
||||
model_config = {"extra": "ignore"}
|
||||
|
||||
@@ -1,21 +1,25 @@
|
||||
"""# Summary
|
||||
|
||||
Mongo persistence for jobs: document schema and repository factory.
|
||||
Jobs persistence ports — integer-id document and repository factory.
|
||||
"""
|
||||
from mongo_ops import BaseDocument, BaseRepository
|
||||
from mongo_ops import BaseDocument
|
||||
from pydantic import Field
|
||||
|
||||
from domain.job.models import Job
|
||||
from infra.db.repos.mongo import _repo_factory as mongo_repo_factory
|
||||
from infra.db.repos import create_repo
|
||||
|
||||
|
||||
class JobDocument(Job, BaseDocument):
|
||||
"""Mongo document form of :class:`Job`."""
|
||||
"""Persisted job document. The integer ``id`` shadows the ObjectId."""
|
||||
|
||||
id: int | None = Field(default=None, validation_alias="_id")
|
||||
|
||||
|
||||
def create_job_repo() -> BaseRepository:
|
||||
"""Create the Mongo-backed job repository.
|
||||
def create_job_repo():
|
||||
"""Create the job repository selected by ``settings.repo_backend``.
|
||||
|
||||
Returns:
|
||||
BaseRepository: Repository wired to the ``jobs`` collection.
|
||||
IntIdMemoryRepository | IntIdMongoRepository: Repository wired to the
|
||||
``jobs`` collection/store.
|
||||
"""
|
||||
return mongo_repo_factory("jobs", JobDocument)
|
||||
return create_repo("jobs", JobDocument)
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
"""# Summary
|
||||
|
||||
Repository factory — picks the in-memory or Mongo integer-id adapter based
|
||||
on ``settings.repo_backend``.
|
||||
|
||||
---
|
||||
|
||||
Every domain slice calls :func:`create_repo` so the backend choice lives in
|
||||
one place: ``REPO_BACKEND=memory`` (default) yields the zero-dependency
|
||||
process-local store; ``REPO_BACKEND=mongo`` yields the persistent adapter.
|
||||
"""
|
||||
from typing import Any
|
||||
|
||||
from config import settings
|
||||
from infra.db.repos.memory import IntIdMemoryRepository
|
||||
from infra.db.repos.mongo_int import IntIdMongoRepository
|
||||
|
||||
|
||||
def create_repo(collection: str, document_cls: type[Any]):
|
||||
"""Create the integer-id repository selected by ``settings.repo_backend``.
|
||||
|
||||
Args:
|
||||
collection (str): Collection / store name for the resource.
|
||||
document_cls (type[Any]): Document model bound to the repository.
|
||||
|
||||
Returns:
|
||||
IntIdMemoryRepository | IntIdMongoRepository: The configured repository.
|
||||
"""
|
||||
if settings.repo_backend == "mongo":
|
||||
return IntIdMongoRepository(collection, document_cls)
|
||||
return IntIdMemoryRepository(document_cls)
|
||||
|
||||
161
standards/mcp/templates/app/infra/db/repos/memory.py
Normal file
161
standards/mcp/templates/app/infra/db/repos/memory.py
Normal file
@@ -0,0 +1,161 @@
|
||||
"""# Summary
|
||||
|
||||
In-memory integer-id repository — the zero-dependency persistence adapter.
|
||||
|
||||
---
|
||||
|
||||
One process-local dictionary per resource, keyed by auto-incrementing integer
|
||||
``id``. The wire contract (``openapi.yaml``) declares integer primary keys,
|
||||
so this adapter speaks integers end-to-end and is the default backend
|
||||
(``REPO_BACKEND=memory``).
|
||||
|
||||
The method surface mirrors the mongo-ops repository duck-type consumed by
|
||||
``infra.adapters.service.CrudsServiceAdaptor``: ``create``, ``get_by_id``,
|
||||
``get_many``, ``update``, ``patch``, ``delete``.
|
||||
|
||||
Notes:
|
||||
Not thread-safe and not durable — deliberately. Swap to the Mongo
|
||||
adapter via ``REPO_BACKEND=mongo`` without touching domain code.
|
||||
"""
|
||||
from typing import Any
|
||||
|
||||
from pydantic import BaseModel
|
||||
|
||||
|
||||
class IntIdMemoryRepository:
|
||||
"""Dictionary-backed repository with auto-increment integer ids.
|
||||
|
||||
Attributes:
|
||||
document_cls (type[BaseModel]): Document model instantiated for
|
||||
every stored record.
|
||||
"""
|
||||
|
||||
def __init__(self, document_cls: type[BaseModel]):
|
||||
"""Initialize an empty store for ``document_cls``.
|
||||
|
||||
Args:
|
||||
document_cls (type[BaseModel]): Document model bound to this repo.
|
||||
"""
|
||||
self.document_cls = document_cls
|
||||
self._docs: dict[int, BaseModel] = {}
|
||||
self._seq = 0
|
||||
|
||||
def _to_doc(self, data: Any) -> BaseModel:
|
||||
"""Coerce ``data`` into a document instance.
|
||||
|
||||
Args:
|
||||
data (Any): Document instance or field mapping.
|
||||
|
||||
Returns:
|
||||
BaseModel: Document built from ``data``.
|
||||
"""
|
||||
if isinstance(data, self.document_cls):
|
||||
return data
|
||||
return self.document_cls(**dict(data))
|
||||
|
||||
async def create(self, data: Any) -> BaseModel:
|
||||
"""Persist a new document with a freshly allocated integer id.
|
||||
|
||||
Args:
|
||||
data (Any): Document instance or field mapping (id ignored).
|
||||
|
||||
Returns:
|
||||
BaseModel: The stored document with ``id`` assigned.
|
||||
"""
|
||||
doc = self._to_doc(data)
|
||||
self._seq += 1
|
||||
doc.id = self._seq
|
||||
self._docs[doc.id] = doc
|
||||
return doc
|
||||
|
||||
async def get_by_id(self, id: int) -> BaseModel | None:
|
||||
"""Fetch one document by integer id.
|
||||
|
||||
Args:
|
||||
id (int): Document identifier.
|
||||
|
||||
Returns:
|
||||
BaseModel | None: The stored document, or ``None`` when absent.
|
||||
"""
|
||||
return self._docs.get(int(id))
|
||||
|
||||
async def get_many(self, filter: dict | None = None, **_: Any) -> list[BaseModel]:
|
||||
"""List documents, optionally filtered by top-level equality.
|
||||
|
||||
Args:
|
||||
filter (dict | None): Equality filter on document fields.
|
||||
|
||||
Returns:
|
||||
list[BaseModel]: Matching documents in insertion order.
|
||||
"""
|
||||
docs = list(self._docs.values())
|
||||
if filter:
|
||||
docs = [d for d in docs if all(getattr(d, k, None) == v for k, v in filter.items())]
|
||||
return docs
|
||||
|
||||
async def update(self, id: int, data: Any) -> BaseModel | None:
|
||||
"""Replace a document by integer id.
|
||||
|
||||
Args:
|
||||
id (int): Document identifier.
|
||||
data (Any): Replacement document or field mapping.
|
||||
|
||||
Returns:
|
||||
BaseModel | None: The stored document, or ``None`` when absent.
|
||||
"""
|
||||
if int(id) not in self._docs:
|
||||
return None
|
||||
doc = self._to_doc(data)
|
||||
doc.id = int(id)
|
||||
self._docs[doc.id] = doc
|
||||
return doc
|
||||
|
||||
async def patch(self, id: int, data: dict) -> BaseModel | None:
|
||||
"""Partially update a document by integer id.
|
||||
|
||||
Args:
|
||||
id (int): Document identifier.
|
||||
data (dict): Fields to merge into the stored document.
|
||||
|
||||
Returns:
|
||||
BaseModel | None: The stored document, or ``None`` when absent.
|
||||
"""
|
||||
current = self._docs.get(int(id))
|
||||
if current is None:
|
||||
return None
|
||||
merged = current.model_dump()
|
||||
merged.update(data)
|
||||
doc = self.document_cls(**merged)
|
||||
doc.id = int(id)
|
||||
self._docs[doc.id] = doc
|
||||
return doc
|
||||
|
||||
async def delete(self, id: int) -> bool:
|
||||
"""Delete a document by integer id.
|
||||
|
||||
Args:
|
||||
id (int): Document identifier.
|
||||
|
||||
Returns:
|
||||
bool: ``True`` when a document was removed.
|
||||
"""
|
||||
return self._docs.pop(int(id), None) is not None
|
||||
|
||||
async def delete_many(self, filter: dict | None = None) -> int:
|
||||
"""Delete every document (optionally filtered by equality).
|
||||
|
||||
Args:
|
||||
filter (dict | None): Equality filter on document fields.
|
||||
|
||||
Returns:
|
||||
int: Number of documents removed.
|
||||
"""
|
||||
victims = await self.get_many(filter)
|
||||
for doc in victims:
|
||||
self._docs.pop(doc.id, None)
|
||||
return len(victims)
|
||||
|
||||
def clear(self) -> None:
|
||||
"""Remove every document and reset the id counter."""
|
||||
self._docs.clear()
|
||||
self._seq = 0
|
||||
184
standards/mcp/templates/app/infra/db/repos/mongo_int.py
Normal file
184
standards/mcp/templates/app/infra/db/repos/mongo_int.py
Normal file
@@ -0,0 +1,184 @@
|
||||
"""# Summary
|
||||
|
||||
MongoDB integer-id repository — the persistent persistence adapter.
|
||||
|
||||
---
|
||||
|
||||
The wire contract declares integer primary keys, while mongo-ops'
|
||||
``BaseRepository`` allocates ``ObjectId`` keys. This adapter therefore talks
|
||||
to the shared ``MongoConnectionManager`` database directly (the Tier A
|
||||
connection lifecycle is reused; only the id strategy differs) and stores
|
||||
records with auto-incrementing integer ``_id`` values allocated from a
|
||||
``_counters`` collection.
|
||||
|
||||
The method surface mirrors the in-memory adapter exactly, so
|
||||
``CrudsServiceAdaptor`` and the domain services are backend-agnostic.
|
||||
"""
|
||||
from typing import Any
|
||||
|
||||
from mongo_ops import MongoConnectionManager
|
||||
from pydantic import BaseModel
|
||||
|
||||
|
||||
class IntIdMongoRepository:
|
||||
"""Motor-backed repository with auto-increment integer ids.
|
||||
|
||||
Attributes:
|
||||
collection (str): MongoDB collection name.
|
||||
document_cls (type[BaseModel]): Document model bound to this repo.
|
||||
"""
|
||||
|
||||
def __init__(self, collection: str, document_cls: type[BaseModel]):
|
||||
"""Bind the repository to a collection and document model.
|
||||
|
||||
Args:
|
||||
collection (str): Collection name to operate on.
|
||||
document_cls (type[BaseModel]): Document model persisted here.
|
||||
"""
|
||||
self.collection = collection
|
||||
self.document_cls = document_cls
|
||||
|
||||
@property
|
||||
def _col(self):
|
||||
"""AsyncIOMotorCollection: The live collection handle."""
|
||||
return MongoConnectionManager._database[self.collection]
|
||||
|
||||
async def _next_id(self) -> int:
|
||||
"""Allocate the next integer id from the shared counters collection.
|
||||
|
||||
Returns:
|
||||
int: A monotonically increasing identifier.
|
||||
"""
|
||||
counters = MongoConnectionManager._database["_counters"]
|
||||
doc = await counters.find_one_and_update(
|
||||
{"_id": self.collection},
|
||||
{"$inc": {"seq": 1}},
|
||||
upsert=True,
|
||||
return_document=True,
|
||||
)
|
||||
return int(doc["seq"])
|
||||
|
||||
def _to_doc(self, data: Any) -> BaseModel:
|
||||
"""Coerce ``data`` into a document instance.
|
||||
|
||||
Args:
|
||||
data (Any): Document instance or field mapping.
|
||||
|
||||
Returns:
|
||||
BaseModel: Document built from ``data``.
|
||||
"""
|
||||
if isinstance(data, self.document_cls):
|
||||
return data
|
||||
return self.document_cls(**dict(data))
|
||||
|
||||
def _to_payload(self, doc: BaseModel, id: int | None = None) -> dict:
|
||||
"""Serialize a document into a Mongo-ready payload.
|
||||
|
||||
Args:
|
||||
doc (BaseModel): Document to serialize.
|
||||
id (int | None): Explicit ``_id``; taken from the doc when omitted.
|
||||
|
||||
Returns:
|
||||
dict: Mapping with an integer ``_id`` key.
|
||||
"""
|
||||
payload = doc.model_dump()
|
||||
payload.pop("id", None)
|
||||
payload["_id"] = id if id is not None else doc.id
|
||||
return payload
|
||||
|
||||
async def create(self, data: Any) -> BaseModel:
|
||||
"""Persist a new document with a freshly allocated integer id.
|
||||
|
||||
Args:
|
||||
data (Any): Document instance or field mapping (id ignored).
|
||||
|
||||
Returns:
|
||||
BaseModel: The stored document with ``id`` assigned.
|
||||
"""
|
||||
doc = self._to_doc(data)
|
||||
new_id = await self._next_id()
|
||||
await self._col.insert_one(self._to_payload(doc, new_id))
|
||||
doc.id = new_id
|
||||
return doc
|
||||
|
||||
async def get_by_id(self, id: int) -> BaseModel | None:
|
||||
"""Fetch one document by integer id.
|
||||
|
||||
Args:
|
||||
id (int): Document identifier.
|
||||
|
||||
Returns:
|
||||
BaseModel | None: The stored document, or ``None`` when absent.
|
||||
"""
|
||||
raw = await self._col.find_one({"_id": int(id)})
|
||||
return self.document_cls.model_validate(raw) if raw else None
|
||||
|
||||
async def get_many(self, filter: dict | None = None, **_: Any) -> list[BaseModel]:
|
||||
"""List documents, optionally filtered by top-level equality.
|
||||
|
||||
Args:
|
||||
filter (dict | None): Equality filter on document fields.
|
||||
|
||||
Returns:
|
||||
list[BaseModel]: Matching documents in insertion order.
|
||||
"""
|
||||
cursor = self._col.find(filter or {})
|
||||
return [self.document_cls.model_validate(raw) async for raw in cursor]
|
||||
|
||||
async def update(self, id: int, data: Any) -> BaseModel | None:
|
||||
"""Replace a document by integer id.
|
||||
|
||||
Args:
|
||||
id (int): Document identifier.
|
||||
data (Any): Replacement document or field mapping.
|
||||
|
||||
Returns:
|
||||
BaseModel | None: The stored document, or ``None`` when absent.
|
||||
"""
|
||||
doc = self._to_doc(data)
|
||||
payload = self._to_payload(doc, int(id))
|
||||
result = await self._col.replace_one({"_id": int(id)}, payload)
|
||||
if result.matched_count == 0:
|
||||
return None
|
||||
doc.id = int(id)
|
||||
return doc
|
||||
|
||||
async def patch(self, id: int, data: dict) -> BaseModel | None:
|
||||
"""Partially update a document by integer id.
|
||||
|
||||
Args:
|
||||
id (int): Document identifier.
|
||||
data (dict): Fields to merge into the stored document.
|
||||
|
||||
Returns:
|
||||
BaseModel | None: The stored document, or ``None`` when absent.
|
||||
"""
|
||||
updates = {k: v for k, v in data.items() if k != "id"}
|
||||
result = await self._col.update_one({"_id": int(id)}, {"$set": updates})
|
||||
if result.matched_count == 0:
|
||||
return None
|
||||
return await self.get_by_id(id)
|
||||
|
||||
async def delete(self, id: int) -> bool:
|
||||
"""Delete a document by integer id.
|
||||
|
||||
Args:
|
||||
id (int): Document identifier.
|
||||
|
||||
Returns:
|
||||
bool: ``True`` when a document was removed.
|
||||
"""
|
||||
result = await self._col.delete_one({"_id": int(id)})
|
||||
return result.deleted_count > 0
|
||||
|
||||
async def delete_many(self, filter: dict | None = None) -> int:
|
||||
"""Delete every document (optionally filtered by equality).
|
||||
|
||||
Args:
|
||||
filter (dict | None): Equality filter on document fields.
|
||||
|
||||
Returns:
|
||||
int: Number of documents removed.
|
||||
"""
|
||||
result = await self._col.delete_many(filter or {})
|
||||
return result.deleted_count
|
||||
@@ -1,8 +1,15 @@
|
||||
"""# Summary
|
||||
|
||||
Infrastructure initialization — connects MongoDB and wires all repos and services.
|
||||
Shared bootstrap for both the FastAPI app and the worker, guarded against
|
||||
repeated initialization via a module-level flag.
|
||||
Composition root — connects MongoDB (when selected), wires all repos and
|
||||
services, and returns the resources dict. Shared bootstrap for the FastAPI
|
||||
app, the worker and the seed/drop scripts, guarded against repeated
|
||||
initialization via a module-level flag.
|
||||
|
||||
---
|
||||
|
||||
The ``memory`` backend skips the Mongo connection entirely — repos are
|
||||
process-local dictionaries, so a plain ``uvicorn main:app`` runs with zero
|
||||
external services.
|
||||
"""
|
||||
from typing import Any
|
||||
|
||||
@@ -18,18 +25,21 @@ _initialized: bool = False
|
||||
|
||||
|
||||
async def init() -> dict[str, Any]:
|
||||
"""Connect MongoDB, wire all repos and services, and return the resources dict.
|
||||
"""Wire all repos and services, and return the resources dict.
|
||||
|
||||
Idempotent: repeated calls short-circuit and return the cached resources.
|
||||
Only the ``mongo`` backend performs a network connection here.
|
||||
|
||||
Returns:
|
||||
Dict[str, Any]: Named services keyed by resource name.
|
||||
Dict[str, Any]: Named services keyed by resource name
|
||||
(``<resource>_svc`` and ``<resource>_repo``).
|
||||
"""
|
||||
global _resources, _initialized
|
||||
if _initialized:
|
||||
return _resources
|
||||
|
||||
await setup_database(uri=settings.mongo_uri, db_name=settings.mongo_db)
|
||||
if settings.repo_backend == "mongo":
|
||||
await setup_database(uri=settings.mongo_uri, db_name=settings.mongo_db)
|
||||
|
||||
item_repo = create_item_repo()
|
||||
job_repo = create_job_repo()
|
||||
@@ -44,8 +54,9 @@ async def init() -> dict[str, Any]:
|
||||
|
||||
|
||||
async def shutdown() -> None:
|
||||
"""Disconnect MongoDB and reset the resources cache."""
|
||||
"""Disconnect MongoDB (if connected) and reset the resources cache."""
|
||||
global _initialized
|
||||
await shutdown_database()
|
||||
if settings.repo_backend == "mongo":
|
||||
await shutdown_database()
|
||||
_resources.clear()
|
||||
_initialized = False
|
||||
_initialized = False
|
||||
|
||||
146
standards/mcp/templates/app/interfaces/_common.py
Normal file
146
standards/mcp/templates/app/interfaces/_common.py
Normal file
@@ -0,0 +1,146 @@
|
||||
"""# Summary
|
||||
|
||||
Shared interface helpers — service resolution, serialization, pagination and
|
||||
foreign-key expansion used by every route module.
|
||||
|
||||
---
|
||||
|
||||
FK fields on the wire may arrive either as a bare integer id (from an
|
||||
``x-fk`` picker) or as an already-expanded object. The wire contract always
|
||||
*returns* fully expanded objects, so create/update handlers normalize the
|
||||
input through :func:`expand_ref` before persisting.
|
||||
"""
|
||||
from fastapi import HTTPException, Request
|
||||
|
||||
|
||||
def svc(request: Request, name: str):
|
||||
"""Resolve a CRUD service from app state by resource name.
|
||||
|
||||
Args:
|
||||
request (Request): Incoming request whose app.state carries resources.
|
||||
name (str): Resource key suffix, e.g. ``"parent"`` → ``parent_svc``.
|
||||
|
||||
Returns:
|
||||
Any: The named CRUD service.
|
||||
"""
|
||||
return request.app.state.db_resources[f"{name}_svc"]
|
||||
|
||||
|
||||
def dump(doc) -> dict:
|
||||
"""Serialize a document to a JSON-ready mapping with an integer id.
|
||||
|
||||
Args:
|
||||
doc (Any): Pydantic document to serialize.
|
||||
|
||||
Returns:
|
||||
dict: JSON-mode mapping (``by_alias`` so ``_id`` maps back to ``id``).
|
||||
"""
|
||||
return doc.model_dump(mode="json", by_alias=True)
|
||||
|
||||
|
||||
def paginate(items: list, limit: int, offset: int) -> dict:
|
||||
"""Slice ``items`` into the ``{total, items}`` pagination envelope.
|
||||
|
||||
A ``limit`` of 0 means "all remaining items" (used by react-openapi for
|
||||
FK option lists and counts).
|
||||
|
||||
Args:
|
||||
items (list): Full result list.
|
||||
limit (int): Page size; ``0`` returns everything after ``offset``.
|
||||
offset (int): Number of items to skip.
|
||||
|
||||
Returns:
|
||||
dict: ``{"total": int, "items": list}``.
|
||||
"""
|
||||
offset = max(offset, 0)
|
||||
page = items[offset:] if limit == 0 else items[offset : offset + limit]
|
||||
return {"total": len(items), "items": page}
|
||||
|
||||
|
||||
async def expand_ref(svc_obj, value, label: str) -> dict | None:
|
||||
"""Normalize a foreign-key reference into a fully expanded object.
|
||||
|
||||
Args:
|
||||
svc_obj (Any): Target resource CRUD service used for lookups.
|
||||
value (dict | int | None): Bare id, ``{"id": N}`` stub, or full object.
|
||||
label (str): Human label used in 422 error messages.
|
||||
|
||||
Returns:
|
||||
dict | None: Expanded object, or ``None`` when ``value`` is ``None``.
|
||||
|
||||
Raises:
|
||||
HTTPException: 422 when the reference cannot be resolved to a document.
|
||||
"""
|
||||
if value is None:
|
||||
return None
|
||||
if isinstance(value, dict):
|
||||
if set(value.keys()) == {"id"}:
|
||||
value = value["id"]
|
||||
else:
|
||||
return value
|
||||
if isinstance(value, int):
|
||||
doc = await svc_obj.read(value)
|
||||
if doc is None:
|
||||
raise HTTPException(status_code=422, detail=f"{label} {value} not found")
|
||||
return dump(doc)
|
||||
raise HTTPException(status_code=422, detail=f"invalid {label} reference")
|
||||
|
||||
|
||||
async def expand_ref_list(svc_obj, value, label: str) -> list[dict]:
|
||||
"""Normalize a list foreign-key reference into expanded objects.
|
||||
|
||||
Args:
|
||||
svc_obj (Any): Target resource CRUD service used for lookups.
|
||||
value (list | None): List of bare ids, stubs, or full objects.
|
||||
label (str): Human label used in 422 error messages.
|
||||
|
||||
Returns:
|
||||
list[dict]: Expanded objects.
|
||||
|
||||
Raises:
|
||||
HTTPException: 422 when any reference cannot be resolved.
|
||||
"""
|
||||
if value is None:
|
||||
return []
|
||||
if not isinstance(value, list):
|
||||
raise HTTPException(status_code=422, detail=f"invalid {label} list")
|
||||
results = []
|
||||
for entry in value:
|
||||
results.append(await expand_ref(svc_obj, entry, label))
|
||||
return results
|
||||
|
||||
|
||||
async def read_or_404(svc_obj, id: int, label: str):
|
||||
"""Read a document by id or raise a 404 HTTPException.
|
||||
|
||||
Args:
|
||||
svc_obj (Any): CRUD service to read from.
|
||||
id (int): Document identifier.
|
||||
label (str): Human label used in the 404 detail message.
|
||||
|
||||
Returns:
|
||||
Any: The found document.
|
||||
|
||||
Raises:
|
||||
HTTPException: 404 when no document matches ``id``.
|
||||
"""
|
||||
doc = await svc_obj.read(id)
|
||||
if doc is None:
|
||||
raise HTTPException(status_code=404, detail=f"{label} not found")
|
||||
return doc
|
||||
|
||||
|
||||
async def delete_or_404(svc_obj, id: int, label: str) -> None:
|
||||
"""Delete a document by id or raise a 404 HTTPException.
|
||||
|
||||
Args:
|
||||
svc_obj (Any): CRUD service to delete from.
|
||||
id (int): Document identifier.
|
||||
label (str): Human label used in the 404 detail message.
|
||||
|
||||
Raises:
|
||||
HTTPException: 404 when no document matches ``id``.
|
||||
"""
|
||||
ok = await svc_obj.delete(id)
|
||||
if not ok:
|
||||
raise HTTPException(status_code=404, detail=f"{label} not found")
|
||||
@@ -2,41 +2,89 @@
|
||||
|
||||
Item route handlers — names must match openapi.yaml operationIds.
|
||||
"""
|
||||
from fastapi import Request
|
||||
from fastapi.responses import JSONResponse
|
||||
from fastapi import Request, Response
|
||||
|
||||
from domain.item.models import Item
|
||||
from interfaces._common import delete_or_404, dump, paginate, read_or_404, svc
|
||||
|
||||
|
||||
def svc(request: Request):
|
||||
"""Resolve the item CRUD service from app state."""
|
||||
return request.app.state.db_resources["item_svc"]
|
||||
async def list_items(request: Request, limit: int = 20, offset: int = 0) -> dict:
|
||||
"""List items (paginated). ``limit=0`` returns all remaining items.
|
||||
|
||||
Args:
|
||||
request (Request): Incoming request.
|
||||
limit (int): Page size. Defaults to 20.
|
||||
offset (int): Items to skip. Defaults to 0.
|
||||
|
||||
Returns:
|
||||
dict: ``{"total": int, "items": list[Item]}``.
|
||||
"""
|
||||
docs = await svc(request, "item").search({})
|
||||
return paginate([dump(d) for d in docs], limit, offset)
|
||||
|
||||
|
||||
async def create_item(request: Request, body: dict):
|
||||
"""Create an item from the request body."""
|
||||
data = body.model_dump() if hasattr(body, "model_dump") else dict(body)
|
||||
doc = await svc(request).create(Item(**data))
|
||||
return JSONResponse(status_code=201, content=doc.model_dump(mode="json", by_alias=True))
|
||||
async def create_item(request: Request, body: dict, response: Response) -> dict:
|
||||
"""Create an item.
|
||||
|
||||
Args:
|
||||
request (Request): Incoming request.
|
||||
body (dict): Item fields (``id`` ignored).
|
||||
response (Response): Response object; set to 201 on success.
|
||||
|
||||
Returns:
|
||||
dict: The created item.
|
||||
"""
|
||||
response.status_code = 201
|
||||
body.pop("id", None)
|
||||
doc = await svc(request, "item").create(body)
|
||||
return dump(doc)
|
||||
|
||||
|
||||
async def get_item(request: Request, id: str):
|
||||
"""Fetch one item by id."""
|
||||
doc = await svc(request).read(id)
|
||||
if doc is None:
|
||||
return JSONResponse(status_code=404, content={"detail": "item not found"})
|
||||
return doc.model_dump(mode="json", by_alias=True)
|
||||
async def get_item(request: Request, id: int) -> dict:
|
||||
"""Fetch one item by id.
|
||||
|
||||
Args:
|
||||
request (Request): Incoming request.
|
||||
id (int): Item identifier.
|
||||
|
||||
Returns:
|
||||
dict: The item document.
|
||||
|
||||
Raises:
|
||||
HTTPException: 404 when the item does not exist.
|
||||
"""
|
||||
return dump(await read_or_404(svc(request, "item"), id, "item"))
|
||||
|
||||
|
||||
async def list_items(request: Request):
|
||||
"""List all items."""
|
||||
docs = await svc(request).search({})
|
||||
return [d.model_dump(mode="json", by_alias=True) for d in docs]
|
||||
async def update_item(request: Request, id: int, body: dict) -> dict:
|
||||
"""Replace an item by id.
|
||||
|
||||
Args:
|
||||
request (Request): Incoming request.
|
||||
id (int): Item identifier.
|
||||
body (dict): Full replacement payload.
|
||||
|
||||
Returns:
|
||||
dict: The updated item.
|
||||
|
||||
Raises:
|
||||
HTTPException: 404 when the item does not exist.
|
||||
"""
|
||||
await read_or_404(svc(request, "item"), id, "item")
|
||||
body.pop("id", None)
|
||||
doc = await svc(request, "item").update(id, body)
|
||||
return dump(doc)
|
||||
|
||||
|
||||
async def delete_item(request: Request, id: str):
|
||||
"""Delete one item by id."""
|
||||
ok = await svc(request).delete(id)
|
||||
if not ok:
|
||||
return JSONResponse(status_code=404, content={"detail": "item not found"})
|
||||
return {"deleted": True}
|
||||
async def delete_item(request: Request, id: int, response: Response) -> None:
|
||||
"""Delete an item by id.
|
||||
|
||||
Args:
|
||||
request (Request): Incoming request.
|
||||
id (int): Item identifier.
|
||||
response (Response): Response object; set to 204 on success.
|
||||
|
||||
Raises:
|
||||
HTTPException: 404 when the item does not exist.
|
||||
"""
|
||||
await delete_or_404(svc(request, "item"), id, "item")
|
||||
response.status_code = 204
|
||||
|
||||
@@ -2,33 +2,89 @@
|
||||
|
||||
Job route handlers — names must match openapi.yaml operationIds.
|
||||
"""
|
||||
from fastapi import Request
|
||||
from fastapi.responses import JSONResponse
|
||||
from fastapi import Request, Response
|
||||
|
||||
from domain.job.models import Job
|
||||
from interfaces._common import delete_or_404, dump, paginate, read_or_404, svc
|
||||
|
||||
|
||||
def svc(request: Request):
|
||||
"""Resolve the job CRUD service from app state."""
|
||||
return request.app.state.db_resources["job_svc"]
|
||||
async def list_jobs(request: Request, limit: int = 20, offset: int = 0) -> dict:
|
||||
"""List jobs (paginated). ``limit=0`` returns all remaining items.
|
||||
|
||||
Args:
|
||||
request (Request): Incoming request.
|
||||
limit (int): Page size. Defaults to 20.
|
||||
offset (int): Items to skip. Defaults to 0.
|
||||
|
||||
Returns:
|
||||
dict: ``{"total": int, "items": list[Job]}``.
|
||||
"""
|
||||
docs = await svc(request, "job").search({})
|
||||
return paginate([dump(d) for d in docs], limit, offset)
|
||||
|
||||
|
||||
async def create_job(request: Request, body: dict):
|
||||
"""Create a job from the request body."""
|
||||
data = body.model_dump() if hasattr(body, "model_dump") else dict(body)
|
||||
doc = await svc(request).create(Job(**data))
|
||||
return JSONResponse(status_code=201, content=doc.model_dump(mode="json", by_alias=True))
|
||||
async def create_job(request: Request, body: dict, response: Response) -> dict:
|
||||
"""Create a job.
|
||||
|
||||
Args:
|
||||
request (Request): Incoming request.
|
||||
body (dict): Job fields (``id`` ignored).
|
||||
response (Response): Response object; set to 201 on success.
|
||||
|
||||
Returns:
|
||||
dict: The created job.
|
||||
"""
|
||||
response.status_code = 201
|
||||
body.pop("id", None)
|
||||
doc = await svc(request, "job").create(body)
|
||||
return dump(doc)
|
||||
|
||||
|
||||
async def get_job(request: Request, id: str):
|
||||
"""Fetch one job by id."""
|
||||
doc = await svc(request).read(id)
|
||||
if doc is None:
|
||||
return JSONResponse(status_code=404, content={"detail": "job not found"})
|
||||
return doc.model_dump(mode="json", by_alias=True)
|
||||
async def get_job(request: Request, id: int) -> dict:
|
||||
"""Fetch one job by id.
|
||||
|
||||
Args:
|
||||
request (Request): Incoming request.
|
||||
id (int): Job identifier.
|
||||
|
||||
Returns:
|
||||
dict: The job document.
|
||||
|
||||
Raises:
|
||||
HTTPException: 404 when the job does not exist.
|
||||
"""
|
||||
return dump(await read_or_404(svc(request, "job"), id, "job"))
|
||||
|
||||
|
||||
async def list_jobs(request: Request):
|
||||
"""List all jobs."""
|
||||
docs = await svc(request).search({})
|
||||
return [d.model_dump(mode="json", by_alias=True) for d in docs]
|
||||
async def update_job(request: Request, id: int, body: dict) -> dict:
|
||||
"""Replace a job by id.
|
||||
|
||||
Args:
|
||||
request (Request): Incoming request.
|
||||
id (int): Job identifier.
|
||||
body (dict): Full replacement payload.
|
||||
|
||||
Returns:
|
||||
dict: The updated job.
|
||||
|
||||
Raises:
|
||||
HTTPException: 404 when the job does not exist.
|
||||
"""
|
||||
await read_or_404(svc(request, "job"), id, "job")
|
||||
body.pop("id", None)
|
||||
doc = await svc(request, "job").update(id, body)
|
||||
return dump(doc)
|
||||
|
||||
|
||||
async def delete_job(request: Request, id: int, response: Response) -> None:
|
||||
"""Delete a job by id.
|
||||
|
||||
Args:
|
||||
request (Request): Incoming request.
|
||||
id (int): Job identifier.
|
||||
response (Response): Response object; set to 204 on success.
|
||||
|
||||
Raises:
|
||||
HTTPException: 404 when the job does not exist.
|
||||
"""
|
||||
await delete_or_404(svc(request, "job"), id, "job")
|
||||
response.status_code = 204
|
||||
|
||||
@@ -6,4 +6,5 @@ re-exports every route handler from the subpackages into one flat namespace.
|
||||
"""
|
||||
# ruff: noqa: F403
|
||||
from interfaces.item.routes import *
|
||||
from interfaces.job.routes import *
|
||||
from interfaces.job.routes import *
|
||||
from interfaces.system.routes import *
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
"""# Summary
|
||||
|
||||
System interfaces."""
|
||||
13
standards/mcp/templates/app/interfaces/system/routes.py
Normal file
13
standards/mcp/templates/app/interfaces/system/routes.py
Normal file
@@ -0,0 +1,13 @@
|
||||
"""# Summary
|
||||
|
||||
System route handlers — health probe and other non-resource endpoints.
|
||||
"""
|
||||
|
||||
|
||||
async def health() -> dict:
|
||||
"""Liveness probe — public, unauthenticated.
|
||||
|
||||
Returns:
|
||||
dict: ``{"status": "ok", "service": "app-template"}``.
|
||||
"""
|
||||
return {"status": "ok", "service": "app-template"}
|
||||
@@ -3,6 +3,12 @@
|
||||
FastAPI application bootstrap — uses OpenAPIFirstApp for spec-driven routing.
|
||||
Handlers are looked up by operationId in interfaces.openapi, so no router tables
|
||||
are declared here; the lifespan initializes and shuts down app resources.
|
||||
|
||||
---
|
||||
|
||||
``load_dotenv()`` runs before the app is constructed so ``{AUTH_SERVER}`` in
|
||||
``openapi.yaml``'s bearer-JWT security scheme resolves from ``.env`` at build
|
||||
time (openapi_first resolves env placeholders when the spec is loaded).
|
||||
"""
|
||||
# ruff: noqa: E402
|
||||
import logging
|
||||
@@ -12,8 +18,6 @@ from dotenv import load_dotenv
|
||||
from openapi_first.app import OpenAPIFirstApp
|
||||
from starlette.middleware.cors import CORSMiddleware
|
||||
|
||||
from init import init, shutdown
|
||||
|
||||
load_dotenv()
|
||||
|
||||
logging.basicConfig(
|
||||
@@ -22,6 +26,7 @@ logging.basicConfig(
|
||||
)
|
||||
|
||||
import interfaces.openapi as openapi_routes
|
||||
from init import init, shutdown
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -47,9 +52,9 @@ async def lifespan(app: OpenAPIFirstApp):
|
||||
app = OpenAPIFirstApp(
|
||||
openapi_path="openapi.yaml",
|
||||
routes_module=openapi_routes,
|
||||
title="Item API",
|
||||
title="App Template API",
|
||||
version="0.1.0",
|
||||
lifespan=lifespan,
|
||||
)
|
||||
|
||||
app.add_middleware(CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"])
|
||||
app.add_middleware(CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"])
|
||||
|
||||
@@ -1,161 +1,451 @@
|
||||
openapi: 3.0.3
|
||||
openapi: 3.1.0
|
||||
|
||||
info:
|
||||
title: Item API
|
||||
title: App Template API
|
||||
version: 0.1.0
|
||||
paths:
|
||||
/items:
|
||||
get:
|
||||
operationId: list_items
|
||||
summary: List items
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: array
|
||||
items:
|
||||
$ref: "#/components/schemas/Item"
|
||||
post:
|
||||
operationId: create_item
|
||||
summary: Create an item
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/ItemInput"
|
||||
responses:
|
||||
"201":
|
||||
description: Created
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/Item"
|
||||
/items/{id}:
|
||||
get:
|
||||
operationId: get_item
|
||||
summary: Get an item
|
||||
parameters:
|
||||
- name: id
|
||||
in: path
|
||||
required: true
|
||||
schema:
|
||||
type: string
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/Item"
|
||||
"404":
|
||||
description: Not found
|
||||
delete:
|
||||
operationId: delete_item
|
||||
summary: Delete an item
|
||||
parameters:
|
||||
- name: id
|
||||
in: path
|
||||
required: true
|
||||
schema:
|
||||
type: string
|
||||
responses:
|
||||
"200":
|
||||
description: Deleted
|
||||
"404":
|
||||
description: Not found
|
||||
/jobs:
|
||||
get:
|
||||
operationId: list_jobs
|
||||
summary: List jobs
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: array
|
||||
items:
|
||||
$ref: "#/components/schemas/Job"
|
||||
post:
|
||||
operationId: create_job
|
||||
summary: Create a job
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/JobInput"
|
||||
responses:
|
||||
"201":
|
||||
description: Created
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/Job"
|
||||
/jobs/{id}:
|
||||
get:
|
||||
operationId: get_job
|
||||
summary: Get a job
|
||||
parameters:
|
||||
- name: id
|
||||
in: path
|
||||
required: true
|
||||
schema:
|
||||
type: string
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/Job"
|
||||
"404":
|
||||
description: Not found
|
||||
description: |
|
||||
App template API — OpenAPI-first backend pairing with the client template
|
||||
and the @aetoskia/react-openapi admin panel renderer. Resources are driven
|
||||
by OpenAPI x- extension fields; auth is bearer JWT introspected against
|
||||
the auth-server. Item and Job are example domains — replace them with
|
||||
your own, keeping the x- conventions documented in the react-openapi MCP
|
||||
bundle (module react-openapi, object specExtensions).
|
||||
|
||||
servers:
|
||||
- url: http://localhost:8000
|
||||
|
||||
security:
|
||||
- bearerAuth: []
|
||||
|
||||
components:
|
||||
securitySchemes:
|
||||
bearerAuth:
|
||||
type: http
|
||||
scheme: bearer
|
||||
bearerFormat: JWT
|
||||
x-server-url: "{AUTH_SERVER}"
|
||||
x-introspect-path: "/introspect"
|
||||
x-login-path: "/login"
|
||||
x-register-path: "/register"
|
||||
x-logout-path: "/logout"
|
||||
x-me-path: "/me"
|
||||
|
||||
schemas:
|
||||
Item:
|
||||
type: object
|
||||
required: [name, quantity]
|
||||
x-resource: items
|
||||
x-primary-key: id
|
||||
x-display-format: "{name} × {quantity}"
|
||||
x-list-columns: [name, quantity]
|
||||
properties:
|
||||
id:
|
||||
type: string
|
||||
name:
|
||||
type: string
|
||||
quantity:
|
||||
type: integer
|
||||
ItemInput:
|
||||
type: object
|
||||
required: [name]
|
||||
properties:
|
||||
readOnly: true
|
||||
x-order: 0
|
||||
x-hidden: { form: true, list: true }
|
||||
x-label: "ID"
|
||||
name:
|
||||
type: string
|
||||
x-order: 1
|
||||
x-label: "Name"
|
||||
x-description: "Item name"
|
||||
x-filterable: true
|
||||
x-sortable: true
|
||||
x-autocomplete: token
|
||||
quantity:
|
||||
type: integer
|
||||
default: 1
|
||||
x-order: 2
|
||||
x-label: "Quantity"
|
||||
x-description: "How many units"
|
||||
x-sortable: true
|
||||
required: [id, name]
|
||||
|
||||
Job:
|
||||
type: object
|
||||
required: [name, status]
|
||||
x-resource: jobs
|
||||
x-primary-key: id
|
||||
x-display-format: "{name} [{status}]"
|
||||
x-list-columns: [name, status, retry_count]
|
||||
properties:
|
||||
id:
|
||||
type: string
|
||||
type: integer
|
||||
readOnly: true
|
||||
x-order: 0
|
||||
x-hidden: { form: true, list: true }
|
||||
x-label: "ID"
|
||||
name:
|
||||
type: string
|
||||
x-order: 1
|
||||
x-label: "Name"
|
||||
x-description: "Job name"
|
||||
x-filterable: true
|
||||
x-autocomplete: token
|
||||
status:
|
||||
type: string
|
||||
enum: [pending, processing, done, failed]
|
||||
x-order: 2
|
||||
x-label: "Status"
|
||||
x-description: "Lifecycle status"
|
||||
x-filterable: true
|
||||
retry_count:
|
||||
type: integer
|
||||
readOnly: true
|
||||
x-order: 3
|
||||
x-label: "Retries"
|
||||
error_message:
|
||||
type: string
|
||||
readOnly: true
|
||||
x-order: 4
|
||||
x-label: "Last Error"
|
||||
payload:
|
||||
type: object
|
||||
JobInput:
|
||||
x-order: 5
|
||||
x-label: "Payload"
|
||||
x-description: "Arbitrary job payload"
|
||||
required: [id, name, status]
|
||||
|
||||
ErrorBody:
|
||||
type: object
|
||||
required: [name]
|
||||
properties:
|
||||
name:
|
||||
detail:
|
||||
type: string
|
||||
payload:
|
||||
type: object
|
||||
required: [detail]
|
||||
|
||||
HTTPValidationError:
|
||||
type: object
|
||||
properties:
|
||||
detail:
|
||||
type: array
|
||||
items:
|
||||
$ref: '#/components/schemas/ValidationError'
|
||||
|
||||
ValidationError:
|
||||
type: object
|
||||
properties:
|
||||
loc:
|
||||
type: array
|
||||
items:
|
||||
type: string
|
||||
msg:
|
||||
type: string
|
||||
type:
|
||||
type: string
|
||||
required: [loc, msg, type]
|
||||
|
||||
responses:
|
||||
Unauthorized:
|
||||
description: Not authenticated
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/ErrorBody'
|
||||
Forbidden:
|
||||
description: Insufficient permissions
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/ErrorBody'
|
||||
NotFound:
|
||||
description: Resource not found
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/ErrorBody'
|
||||
ValidationError:
|
||||
description: Validation Error
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/HTTPValidationError'
|
||||
InternalServerError:
|
||||
description: Internal server error
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/ErrorBody'
|
||||
|
||||
paths:
|
||||
/health:
|
||||
get:
|
||||
summary: Liveness probe (public, unauthenticated)
|
||||
operationId: health
|
||||
security: []
|
||||
responses:
|
||||
'200':
|
||||
description: Service is alive
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
status:
|
||||
type: string
|
||||
service:
|
||||
type: string
|
||||
|
||||
/items:
|
||||
get:
|
||||
summary: List items (paginated)
|
||||
operationId: list_items
|
||||
parameters:
|
||||
- in: query
|
||||
name: limit
|
||||
schema: {type: integer, default: 20}
|
||||
- in: query
|
||||
name: offset
|
||||
schema: {type: integer, default: 0}
|
||||
responses:
|
||||
'200':
|
||||
description: Paginated list of items
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
total:
|
||||
type: integer
|
||||
items:
|
||||
type: array
|
||||
items:
|
||||
$ref: '#/components/schemas/Item'
|
||||
'401':
|
||||
$ref: '#/components/responses/Unauthorized'
|
||||
'403':
|
||||
$ref: '#/components/responses/Forbidden'
|
||||
'422':
|
||||
$ref: '#/components/responses/ValidationError'
|
||||
'500':
|
||||
$ref: '#/components/responses/InternalServerError'
|
||||
post:
|
||||
summary: Create an item
|
||||
operationId: create_item
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/Item'
|
||||
responses:
|
||||
'201':
|
||||
description: Item created
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/Item'
|
||||
'401':
|
||||
$ref: '#/components/responses/Unauthorized'
|
||||
'403':
|
||||
$ref: '#/components/responses/Forbidden'
|
||||
'422':
|
||||
$ref: '#/components/responses/ValidationError'
|
||||
'500':
|
||||
$ref: '#/components/responses/InternalServerError'
|
||||
/items/{id}:
|
||||
get:
|
||||
operationId: get_item
|
||||
parameters:
|
||||
- name: id
|
||||
in: path
|
||||
required: true
|
||||
schema: {type: integer}
|
||||
responses:
|
||||
'200':
|
||||
description: Single item
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/Item'
|
||||
'401':
|
||||
$ref: '#/components/responses/Unauthorized'
|
||||
'403':
|
||||
$ref: '#/components/responses/Forbidden'
|
||||
'404':
|
||||
$ref: '#/components/responses/NotFound'
|
||||
'422':
|
||||
$ref: '#/components/responses/ValidationError'
|
||||
'500':
|
||||
$ref: '#/components/responses/InternalServerError'
|
||||
put:
|
||||
operationId: update_item
|
||||
parameters:
|
||||
- name: id
|
||||
in: path
|
||||
required: true
|
||||
schema: {type: integer}
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/Item'
|
||||
responses:
|
||||
'200':
|
||||
description: Item updated
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/Item'
|
||||
'401':
|
||||
$ref: '#/components/responses/Unauthorized'
|
||||
'403':
|
||||
$ref: '#/components/responses/Forbidden'
|
||||
'404':
|
||||
$ref: '#/components/responses/NotFound'
|
||||
'422':
|
||||
$ref: '#/components/responses/ValidationError'
|
||||
'500':
|
||||
$ref: '#/components/responses/InternalServerError'
|
||||
delete:
|
||||
operationId: delete_item
|
||||
parameters:
|
||||
- name: id
|
||||
in: path
|
||||
required: true
|
||||
schema: {type: integer}
|
||||
responses:
|
||||
'204':
|
||||
description: Item deleted
|
||||
'401':
|
||||
$ref: '#/components/responses/Unauthorized'
|
||||
'403':
|
||||
$ref: '#/components/responses/Forbidden'
|
||||
'404':
|
||||
$ref: '#/components/responses/NotFound'
|
||||
'422':
|
||||
$ref: '#/components/responses/ValidationError'
|
||||
'500':
|
||||
$ref: '#/components/responses/InternalServerError'
|
||||
|
||||
/jobs:
|
||||
get:
|
||||
summary: List jobs (paginated)
|
||||
operationId: list_jobs
|
||||
parameters:
|
||||
- in: query
|
||||
name: limit
|
||||
schema: {type: integer, default: 20}
|
||||
- in: query
|
||||
name: offset
|
||||
schema: {type: integer, default: 0}
|
||||
responses:
|
||||
'200':
|
||||
description: Paginated list of jobs
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
total:
|
||||
type: integer
|
||||
items:
|
||||
type: array
|
||||
items:
|
||||
$ref: '#/components/schemas/Job'
|
||||
'401':
|
||||
$ref: '#/components/responses/Unauthorized'
|
||||
'403':
|
||||
$ref: '#/components/responses/Forbidden'
|
||||
'422':
|
||||
$ref: '#/components/responses/ValidationError'
|
||||
'500':
|
||||
$ref: '#/components/responses/InternalServerError'
|
||||
post:
|
||||
summary: Create a job
|
||||
operationId: create_job
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/Job'
|
||||
responses:
|
||||
'201':
|
||||
description: Job created
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/Job'
|
||||
'401':
|
||||
$ref: '#/components/responses/Unauthorized'
|
||||
'403':
|
||||
$ref: '#/components/responses/Forbidden'
|
||||
'422':
|
||||
$ref: '#/components/responses/ValidationError'
|
||||
'500':
|
||||
$ref: '#/components/responses/InternalServerError'
|
||||
/jobs/{id}:
|
||||
get:
|
||||
operationId: get_job
|
||||
parameters:
|
||||
- name: id
|
||||
in: path
|
||||
required: true
|
||||
schema: {type: integer}
|
||||
responses:
|
||||
'200':
|
||||
description: Single job
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/Job'
|
||||
'401':
|
||||
$ref: '#/components/responses/Unauthorized'
|
||||
'403':
|
||||
$ref: '#/components/responses/Forbidden'
|
||||
'404':
|
||||
$ref: '#/components/responses/NotFound'
|
||||
'422':
|
||||
$ref: '#/components/responses/ValidationError'
|
||||
'500':
|
||||
$ref: '#/components/responses/InternalServerError'
|
||||
put:
|
||||
operationId: update_job
|
||||
parameters:
|
||||
- name: id
|
||||
in: path
|
||||
required: true
|
||||
schema: {type: integer}
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/Job'
|
||||
responses:
|
||||
'200':
|
||||
description: Job updated
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/Job'
|
||||
'401':
|
||||
$ref: '#/components/responses/Unauthorized'
|
||||
'403':
|
||||
$ref: '#/components/responses/Forbidden'
|
||||
'404':
|
||||
$ref: '#/components/responses/NotFound'
|
||||
'422':
|
||||
$ref: '#/components/responses/ValidationError'
|
||||
'500':
|
||||
$ref: '#/components/responses/InternalServerError'
|
||||
delete:
|
||||
operationId: delete_job
|
||||
parameters:
|
||||
- name: id
|
||||
in: path
|
||||
required: true
|
||||
schema: {type: integer}
|
||||
responses:
|
||||
'204':
|
||||
description: Job deleted
|
||||
'401':
|
||||
$ref: '#/components/responses/Unauthorized'
|
||||
'403':
|
||||
$ref: '#/components/responses/Forbidden'
|
||||
'404':
|
||||
$ref: '#/components/responses/NotFound'
|
||||
'422':
|
||||
$ref: '#/components/responses/ValidationError'
|
||||
'500':
|
||||
$ref: '#/components/responses/InternalServerError'
|
||||
|
||||
@@ -5,7 +5,7 @@ Item-sync pipeline — the demo pipeline axis of the blueprint.
|
||||
Runs on the worker, consumes a pending job, and materializes its payload as an
|
||||
item. Steps are plain async functions here; once the chain branches or needs
|
||||
deterministic replay, wrap the steps in a dagpipe DAG (see standards
|
||||
"06_pipeline_scaffold").
|
||||
"50_pipeline_scaffold").
|
||||
"""
|
||||
import logging
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
"""# Summary
|
||||
|
||||
Shared pipeline scaffolding — ports, loader, and registry reused by every
|
||||
pipeline family. See standards "06_pipeline_scaffold".
|
||||
pipeline family. See standards "50_pipeline_scaffold".
|
||||
"""
|
||||
|
||||
@@ -8,14 +8,25 @@ import interfaces.openapi as routes_module
|
||||
def test_openapi_app_builds():
|
||||
"""The spec-first app must build and plant each route handler."""
|
||||
module = importlib.import_module(routes_module.__name__)
|
||||
for operation in ("create_item", "get_item", "list_items", "delete_item",
|
||||
"create_job", "get_job", "list_jobs"):
|
||||
for operation in (
|
||||
"health",
|
||||
"list_items",
|
||||
"create_item",
|
||||
"get_item",
|
||||
"update_item",
|
||||
"delete_item",
|
||||
"list_jobs",
|
||||
"create_job",
|
||||
"get_job",
|
||||
"update_job",
|
||||
"delete_job",
|
||||
):
|
||||
assert hasattr(module, operation)
|
||||
|
||||
app = OpenAPIFirstApp(
|
||||
openapi_path="openapi.yaml",
|
||||
routes_module=module,
|
||||
title="Item API",
|
||||
title="App Template API",
|
||||
version="0.1.0",
|
||||
)
|
||||
assert app is not None
|
||||
assert app is not None
|
||||
|
||||
@@ -7,7 +7,7 @@ the API axis, workers consume them on a fixed cadence.
|
||||
Notes:
|
||||
- This process is separate from the API process. Any in-memory event bus is per
|
||||
process — if the pipeline must surface live progress to the API, swap the bus
|
||||
adaptor for a broker-backed one (see standards 07_worker_and_progress).
|
||||
adaptor for a broker-backed one (see standards 51_worker_and_progress).
|
||||
"""
|
||||
import asyncio
|
||||
import logging
|
||||
|
||||
89
standards/mcp/templates/drone/npm-lib.yaml
Normal file
89
standards/mcp/templates/drone/npm-lib.yaml
Normal file
@@ -0,0 +1,89 @@
|
||||
---
|
||||
kind: pipeline
|
||||
type: docker
|
||||
name: build-and-publish-npm
|
||||
|
||||
platform:
|
||||
os: linux
|
||||
arch: arm64
|
||||
|
||||
workspace:
|
||||
path: /drone/src
|
||||
|
||||
steps:
|
||||
- name: check-version
|
||||
image: node:22-alpine
|
||||
environment:
|
||||
NPM_REPO_URL:
|
||||
from_secret: NPM_REPO_URL
|
||||
NPM_USERNAME:
|
||||
from_secret: NPM_USERNAME
|
||||
NPM_PASSWORD:
|
||||
from_secret: NPM_PASSWORD
|
||||
commands:
|
||||
- apk add --no-cache curl
|
||||
- PACKAGE_NAME=$(node -p "require('./package.json').name")
|
||||
- VERSION=$(node -p "require('./package.json').version")
|
||||
- |
|
||||
if [ "$DRONE_TAG" != "$VERSION" ]; then
|
||||
echo "Tag '$DRONE_TAG' does not match package.json version '$VERSION'; refusing to publish."
|
||||
exit 1
|
||||
fi
|
||||
- echo "registry=$NPM_REPO_URL" > /tmp/.npmrc
|
||||
- echo "_auth=$(echo -n "$NPM_USERNAME:$NPM_PASSWORD" | base64 | tr -d '\n')" >> /tmp/.npmrc
|
||||
- echo "Checking if $PACKAGE_NAME@$VERSION exists on $NPM_REPO_URL ..."
|
||||
- |
|
||||
if npm view "$PACKAGE_NAME@$VERSION" version --userconfig /tmp/.npmrc >/dev/null 2>&1; then
|
||||
echo "$PACKAGE_NAME@$VERSION already exists; skipping build."
|
||||
exit 78
|
||||
else
|
||||
echo "New version detected: $PACKAGE_NAME@$VERSION"
|
||||
fi
|
||||
|
||||
- name: quality-gate
|
||||
image: node:22-alpine
|
||||
environment:
|
||||
NPM_REPO_URL:
|
||||
from_secret: NPM_REPO_URL
|
||||
NPM_USERNAME:
|
||||
from_secret: NPM_USERNAME
|
||||
NPM_PASSWORD:
|
||||
from_secret: NPM_PASSWORD
|
||||
commands:
|
||||
- |
|
||||
if [ -z "$NPM_REPO_URL" ] || [ -z "$NPM_USERNAME" ] || [ -z "$NPM_PASSWORD" ]; then
|
||||
echo "NPM_REPO_URL / NPM_USERNAME / NPM_PASSWORD are not set" >&2
|
||||
exit 1
|
||||
fi
|
||||
- echo "registry=$NPM_REPO_URL" > .npmrc
|
||||
- echo "_auth=$(echo -n "$NPM_USERNAME:$NPM_PASSWORD" | base64 | tr -d '\n')" >> .npmrc
|
||||
- npm install
|
||||
- echo "Running quality gate..."
|
||||
- npm run quality-gate
|
||||
|
||||
- name: build-package
|
||||
image: node:22-alpine
|
||||
commands:
|
||||
- npm install
|
||||
- echo "Building npm package..."
|
||||
- npm run build
|
||||
- ls -l dist
|
||||
|
||||
- name: publish-to-private-npm
|
||||
image: node:22-alpine
|
||||
environment:
|
||||
NPM_REPO_URL:
|
||||
from_secret: NPM_REPO_URL
|
||||
NPM_USERNAME:
|
||||
from_secret: NPM_USERNAME
|
||||
NPM_PASSWORD:
|
||||
from_secret: NPM_PASSWORD
|
||||
commands:
|
||||
- echo "registry=$NPM_REPO_URL" > .npmrc
|
||||
- echo "_auth=$(echo -n "$NPM_USERNAME:$NPM_PASSWORD" | base64 | tr -d '\n')" >> .npmrc
|
||||
- echo "Publishing to private npm at $NPM_REPO_URL ..."
|
||||
- npm publish --access restricted
|
||||
|
||||
trigger:
|
||||
event:
|
||||
- tag
|
||||
Reference in New Issue
Block a user