Repository navigation
feat(cli): add foca CLI and startup switches - #690
Conversation
- 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
Reviewer's GuideIntroduces a deployable Sequence diagram for deferred startup initializationsequenceDiagram
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
Sequence diagram for isolated API specification exportsequenceDiagram
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
State diagram for startup write switchesstateDiagram-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
Flow diagram for the FOCA administration CLIflowchart 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"]
File-Level Changes
Possibly linked issues
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
# Conflicts: # docs/migration-0.21.md
Codecov Report✅ All modified and coverable lines are covered by tests. 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
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
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
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]>
Summary
Adds the console script
focawithcheck-config,create-indexes,sync-policiesandexport-spec, and the switchesdb.create_indexes_on_startupandsecurity.access_control.sync_policies_on_startup, both on by default, so that deployments can run these steps on their own.--app module:attributeorFOCA_APPnames aFocainstance or a function returning one. The Connexion app isn't accepted, as commands need the configuration.check-configcallscreate_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-specwrites what the app serves, base path and all, and--spectakes a name fromapi.specsor a base path.sync_policies_on_startup: false, configured rules are still checked on startup;sync-policiesfails if stored rules of a newer revision stay.create-indexesalso sets up the store of gateway plugins, and fails on its errors, unlike startup, which logs them.Focainstances created while the command runs, also in modules that controllers import, don't write on startup.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
dev: ruff, mypy, docs build; pytest: 4171 passed, 1 skipped, 100% coverage, with own MongoDB.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:
focaconsole tool with commands for configuration checks, index creation, policy synchronization, and API specification export.Enhancements:
--apporFOCA_APP, clean command output, deployment-friendly error handling, and specification selection/export matching the served API.Build:
focaconsole script as a project entry point.Documentation:
Tests: