Skip to content

feat(cli): add foca CLI and startup switches - #690

Merged
uniqueg merged 10 commits into
devfrom
feat/621-foca-cli
Nov 4, 2026
Merged

uniqueg merged 10 commits into
devfrom
feat/621-foca-cli

Conversation

@uniqueg

@uniqueg uniqueg commented Nov 4, 2026 •

Copy link
Copy Markdown
Member

Summary

Adds the console script foca with check-config, create-indexes, sync-policies and export-spec, and the switches db.create_indexes_on_startup and security.access_control.sync_policies_on_startup, both on by default, so that deployments can run these steps on their own.

  • --app module:attribute or FOCA_APP names a Foca instance or a function returning one. The Connexion app isn't accepted, as commands need the configuration.
  • check-config calls create_app() with both switches off. The issue says "without creating the web app", but most startup checks only run there, and it needs no database. Say if you'd prefer it the other way.
  • export-spec writes what the app serves, base path and all, and --spec takes a name from api.specs or a base path.
  • With sync_policies_on_startup: false, configured rules are still checked on startup; sync-policies fails if stored rules of a newer revision stay.
  • create-indexes also sets up the store of gateway plugins, and fails on its errors, unlike startup, which logs them.
  • Foca instances created while the command runs, also in modules that controllers import, don't write on startup.
  • Only the output of a command goes to the standard output, so what apps print or log there can't corrupt an exported specification.

Docs: new docs/cli.md, notes in the guides for access control, plugins, database, and in the migration guide.

Closes #621

How it was verified

  • Local checks after merging dev: ruff, mypy, docs build; pytest: 4171 passed, 1 skipped, 100% coverage, with own MongoDB.
  • Tests run the commands in-process and as a subprocess, against MongoDB, and compare the exported specification, whole, with what the app serves (Swagger 2 and OpenAPI 3).
  • CI: see the checks of this PR.

Not verified: a real Helm hook or init container running these commands.

Declined review findings

  • setup_store(strict=True) still only warns in the branch reached when its 10-second deadline runs out between namespaces: this only happens on a very slow database, and the writes then come with the next run.

Open questions

None.

🤖 Generated with Claude Code

Summary by Sourcery

Provide deployment-oriented administration commands and configurable startup behavior for FOCA applications.

New Features:

  • Add the foca console tool with commands for configuration checks, index creation, policy synchronization, and API specification export.

Enhancements:

  • Add startup controls that allow database indexes, gateway plugin stores, and access-control policies to be prepared separately during deployment while preserving existing defaults.
  • Support loading Foca instances or factories from --app or FOCA_APP, clean command output, deployment-friendly error handling, and specification selection/export matching the served API.

Build:

  • Register the foca console script as a project entry point.

Documentation:

  • Document the CLI, startup controls, and deployment guidance across the CLI, configuration, plugin, and migration documentation.

Tests:

  • Add comprehensive in-process, subprocess, and MongoDB-backed coverage for CLI behavior, startup controls, policy synchronization, index setup, specification export, output isolation, and exit codes.

uniqueg and others added 8 commits November 4, 2026 09:38
- jobs.periodic sets the schedule of Celery beat.
- Workers run the checks of the configuration that apps run.
- IndexConflictError tells conflicts of indexes from other failures,
  which stay errors of PyMongo.
- Keys of the configuration that FOCA removed fail with a hint.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
From review: stored documents violating a unique index stay ValueErrors,
as proTES relies on, now IndexConflictError. Workers don't compute the
service info, which can need what apps register. Crons that never occur
or fail to parse stop the worker naming the job, and every is bounded.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…keys

# Conflicts:
#	foca/security/access_control/register_access_control.py
Resolve the migration guide, keeping both sections. Treat the code
IndexAlreadyExists as an index conflict, and give the removed key
`api.specs[].path_out` a hint too, as a list and as named specs.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Add the console script `foca`, with the commands `check-config`,
`create-indexes`, `sync-policies` and `export-spec`, finding the app via
`--app` or `FOCA_APP`. Add the switches `db.create_indexes_on_startup`
and `security.access_control.sync_policies_on_startup`, which default
to what startup did so far. The commands share the code of startup.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
check-config checks configured rules, also on startup without syncing.
sync-policies fails if stored rules of a newer revision stay. Apps
created while loading don't write. create-indexes fails on errors of
the plugin store. export-spec writes what's served. Store warnings stay
without its setup. Only routines count as factories, and only the
output of commands goes to the standard output.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Instances created while a command runs, e.g., in a worker module that a
controller imports, had startup writes on. Restores the guard of
export-spec options, and clears up the docs on factories.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
# Conflicts:
#	docs/configuration/db.md
#	docs/migration-0.21.md
#	foca/foca.py
@uniqueg uniqueg added this to the v0.21.0 milestone Nov 4, 2026
@sourcery-ai

sourcery-ai Bot commented Nov 4, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

Introduces a deployable foca administration CLI for configuration checks, database/plugin initialization, policy synchronization, and served API-spec export, while adding opt-out startup switches, strict explicit setup behavior, output isolation, and comprehensive documentation and tests.

Sequence diagram for deferred startup initialization

sequenceDiagram
    participant Deploy
    participant CLI as foca
    participant Foca
    participant DB as Database
    participant Policy as PolicyStore

    Deploy->>CLI: create-indexes
    CLI->>Foca: create_indexes()
    Foca->>DB: register_mongodb(create_indexes=True)
    Foca->>DB: setup_store(strict=True)
    DB-->>CLI: success or error
    Deploy->>CLI: sync-policies
    CLI->>Foca: create_app()
    Foca->>Foca: check_policies()
    CLI->>Policy: sync_policies()
    Policy-->>CLI: applied or newer revision
    CLI-->>Deploy: exit code
Loading

Sequence diagram for isolated API specification export

sequenceDiagram
    participant Operator
    participant CLI as foca
    participant Foca
    participant APIs
    participant Stdout

    Operator->>CLI: export-spec --format yaml --spec name
    CLI->>Foca: _create_app_without_writes()
    Foca-->>CLI: Connexion app
    CLI->>APIs: _get_apis()
    APIs-->>CLI: served specification with base path
    CLI->>Stdout: serialized specification
    CLI-->>Operator: clean command output
Loading

State diagram for startup write switches

stateDiagram-v2
    [*] --> StartupWritesEnabled
    StartupWritesEnabled --> StartupWritesDisabled: db.create_indexes_on_startup=false
    StartupWritesEnabled --> StartupWritesDisabled: sync_policies_on_startup=false
    StartupWritesDisabled --> ExplicitAdministration: create-indexes / sync-policies
    ExplicitAdministration --> Ready: setup completed
    StartupWritesDisabled --> Ready: startup checks only
Loading

Flow diagram for the FOCA administration CLI

flowchart LR
    Input["foca --app module:attribute command"] --> Load["_load_app"]
    Load --> Dispatch["args.function"]
    Dispatch --> Check["_check_config"]
    Dispatch --> Indexes["_create_indexes"]
    Dispatch --> Policies["_sync_policies"]
    Dispatch --> Spec["_export_spec"]
    Check --> Create["Foca.create_app"]
    Indexes --> CreateIndexes["Foca.create_indexes"]
    Policies --> Sync["sync_policies"]
    Spec --> Served["_get_apis / specification"]
Loading

File-Level Changes

Change Details Files
Added the foca administration CLI with app loading, command dispatch, output isolation, validation, and exit-code handling.
  • Registered the foca console entry point and FOCA_APP/--app loading for Foca instances or factories.
  • Implemented check-config, create-indexes, sync-policies, and export-spec, including multi-spec selection and YAML/JSON output.
  • Redirected application stdout and logs to stderr so command output remains machine-readable.
  • Added extensive in-process, subprocess, MongoDB, and specification-comparison coverage.
foca/cli.py
pyproject.toml
tests/test_cli.py
Added deployment switches and explicit startup-task APIs to defer database, plugin-store, and policy initialization.
  • Added db.create_indexes_on_startup and security.access_control.sync_policies_on_startup, both enabled by default.
  • Added Foca.create_indexes() and startup-write suppression covering app instances created during imports and command execution.
  • Made explicit index/plugin-store setup strict while preserving tolerant logging during normal startup.
  • Separated policy validation from synchronization and made synchronization report newer stored revisions without overwriting them.
  • Propagated index-creation settings through MongoDB and access-control registration.
foca/foca.py
foca/models/config.py
foca/database/register_mongodb.py
foca/plugins/engine.py
foca/security/access_control/register_access_control.py
Captured and exported API specifications in the same form they are served by the application.
  • Recorded specification names and base-path-adjusted served documents during OpenAPI registration.
  • Used registered app APIs to exclude FOCA's permissions API and support selection by configured name or base path.
  • Added Swagger 2 and OpenAPI 3 export verification, including base paths and YAML type preservation.
foca/api/register_openapi.py
foca/utils/urls.py
foca/cli.py
tests/test_cli.py
Documented CLI usage, deployment sequencing, startup switches, and migration implications.
  • Added command reference and examples for configuration checks, index creation, policy synchronization, and spec export.
  • Updated database, access-control, plugin, and migration documentation with deferred-startup behavior and deployment guidance.
  • Added the CLI module to generated API reference and documentation navigation.
docs/cli.md
docs/configuration/access-control.md
docs/configuration/db.md
docs/configuration/plugins.md
docs/migration-0.21.md
docs/reference.md
mkdocs.yml

Possibly linked issues


Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@codecov

codecov Bot commented Nov 4, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (f3ecc8c) to head (46849ac).

Additional details and impacted files
@@            Coverage Diff             @@
##               dev      #690    +/-   ##
==========================================
  Coverage   100.00%   100.00%            
==========================================
  Files           64        65     +1     
  Lines         8346      8510   +164     
==========================================
+ Hits          8346      8510   +164     
Flag Coverage Δ
test_unit 100.00% <100.00%> (ø)

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@uniqueg
uniqueg marked this pull request as ready for review November 4, 2026 10:43

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey - I've found 3 issues

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="foca/cli.py" line_range="84" />
<code_context>
+        Connexion app.
+    """
+    foca.disable_startup_writes()
+    return foca.create_app()
+
+
</code_context>
<issue_to_address>
**Configuration checks write to MongoDB**

When the `check-config` command runs with access control enabled and `conf.db` omitted, `_create_app_without_writes` calls `Foca.create_app()` instead of checking configuration without creating the app. `register_access_control` then synthesizes a default `MongoConfig` with `create_indexes_on_startup=True` and writes policy indexes to MongoDB, so the check fails when MongoDB is unavailable.

Implement `check-config` without calling `Foca.create_app()`.

Also at `foca/security/access_control/register_access_control.py:158`.
</issue_to_address>

### Comment 2
<location path="foca/cli.py" line_range="83" />
<code_context>
+    Returns:
+        Connexion app.
+    """
+    foca.disable_startup_writes()
+    return foca.create_app()
+
</code_context>
<issue_to_address>
**Later startup skips initialization**

When a caller invokes `main()` in-process and reuses the loaded module-level `Foca` instance afterward, `_create_app_without_writes` calls `disable_startup_writes()`, which permanently sets both startup switches to `False` on the loaded `Foca` instance. If a caller invokes `main()` in-process and then reuses that instance to start the app, index creation and policy synchronization are skipped.

Save and restore the startup-switch values around command app creation, or apply the overrides to a separate configuration instance.
</issue_to_address>

### Comment 3
<location path="tests/test_cli.py" line_range="404" />
<code_context>
+        with patch("foca.cli._create_app_without_writes", create):
+            assert main(["--app", f"{name}:foca", "check-config"]) == 0
+        assert created[0].conf.db is not None
+        assert created[0].conf.db.create_indexes_on_startup is False
+
+    def test_app_failure_shows_debug_traceback(self, app_module: AppFactory) -> None:
</code_context>
<issue_to_address>
**Dynamic app writes go unchecked**

When `Foca.create_app()` performs startup writes despite `create_indexes_on_startup` being `False`, `test_instances_created_while_running_write_nothing` checks only that the new instance has `create_indexes_on_startup` set to `False`; it never calls `created[0].create_app()` or checks the database. Startup can therefore ignore that switch and write indexes for the dynamically created instance while this test still passes.

Start the dynamically created instance under the command context and assert that it leaves the database unchanged.
</issue_to_address>

Linked issues

#621 feat(cli): add foca CLI and startup switches · 9 of 10 met

# Requirement Status Notes
1 Provide the foca console script with check-config, create-indexes, sync-policies, and export-spec. ✅ Met The console entry point is registered in pyproject.toml and the four commands are wired in foca.cli.
2 Load the app from --app or FOCA_APP, with --app taking precedence. ✅ Met The CLI loads a Foca instance or routine returning one and gives the command-line option precedence over the environment variable.
3 Default both startup switches to today's behaviour and allow startup to skip those steps when they are false. ✅ Met Both settings default to true; database registration and policy registration consult their respective switches.
4 Have check-config report validation errors without a traceback and run startup checks. ✅ Met The command creates the app to run its startup checks, then reports task exceptions without a traceback by default.
5 Build the configuration for CLI tasks without creating the web app. ❌ Not addressed The issue proposal asks for configuration checking without creating the web app, but check-config calls Foca.create_app() to run startup checks.
6 Export the merged specification as YAML or JSON, with --spec required when the app has several specifications. ✅ Met export-spec supports both formats and selects a specification by name or base path.
7 Support command help and exit codes 0 for success, 1 for configuration or validation errors, and 2 for usage errors. ✅ Met The parser defines help for each command; task exceptions return 1 and usage errors use argparse's exit code 2.
8 Share index-creation and policy-sync code with the startup paths. ✅ Met The CLI uses register_mongodb and sync_policies, the same paths used during startup.
9 Provide 100% coverage, MongoDB-backed tests for both writing commands, mypy, ruff, and a strict docs build. ✅ Met The PR reports these checks passed and includes MongoDB-backed tests for create-indexes and sync-policies.
10 Document the CLI and startup switches. ✅ Met The new CLI guide documents the commands and switches, with related notes added to the configuration and migration guides.

Sourcery assessment

Needs a human reviewer. 3 findings to address first, and with startup syncing disabled, stored Casbin rules remain in effect until sync-policies runs; a missed sync can leave obsolete grants active, while an incorrect sync can persist an overly permissive rule set. Reverting the code does not restore the prior stored rules or undo access already granted.

Blocking findings: foca/cli.py:84, foca/cli.py:83, tests/test_cli.py:404


Sourcery is free for open source - if you like our reviews please consider sharing them ✨

Comment thread foca/cli.py Resolved
Comment thread foca/cli.py Resolved
Comment thread tests/test_cli.py Resolved
Starts the second instance under the command and checks that the
database stays empty, also for the database access control adds.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@uniqueg
uniqueg merged commit 20f46f9 into dev Nov 4, 2026
72 of 83 checks passed
@uniqueg
uniqueg deleted the feat/621-foca-cli branch November 4, 2026 11:27
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat(cli): add foca CLI and startup switches

1 participant