Skip to content

feat: use a configuration without an app - #742

Merged
uniqueg merged 5 commits into
devfrom
feat/741-use-config
Nov 7, 2026
Merged

uniqueg merged 5 commits into
devfrom
feat/741-use-config

Conversation

@uniqueg

@uniqueg uniqueg commented Nov 7, 2026 •

Copy link
Copy Markdown
Member

Summary

Scripts and tools that use a FOCA configuration and its collections without creating the app had no replacement for the deprecated set_app_config(): they attached the configuration to a bare Flask app and ran in its app context. Foca.use_config() replaces that, without Flask or an app context:

foca = Foca(config_file="config.yaml")
foca.use_config()
run()  # get_config() and get_collection() work here
  • get_config() returns the configuration outside app contexts; the most recent of use_config() and creating an app (of any Foca instance) wins, and in an app context the app's own configuration is used, as before.
  • The databases, and the collection of the stored policy rules if access control is enabled, are registered without creating indexes, and nothing else of the startup of apps runs (no app, specifications or policy sync), so nothing is written to the database. There is no app context: what only apps register (e.g., the Casbin adapter) isn't available, as documented.
  • The API is one method, returning None. Internals shared with app creation: _use_config(), and _register_policy_collection(), moved out of register_access_control() unchanged. get_config()'s error without any configuration and the deprecation warning of set_app_config() now point to Foca.use_config().

Docs: Preparing for the ASGI release (Configuration: before/after example instead of "no Flask-free replacement in 0.22"), the migration guide (table row for set_app_config() and the rule of get_config()), the database configuration (scripts), the API reference (from the docstrings of Foca.use_config(), get_config() and get_collection()), and the 0.22.0 release notes (Features).

Closes #741

How cloud-registry would switch (not changed here)

cloud_registry/namespace_subjects.py, _read_only_app() for --dry-run:

  • Keep create_foca() and refuse_old_format().
  • Drop the bare Flask(__name__), set_app_config(), adding the collection of the stored rules, clearing the indexes of the collections and register_mongodb(): call foca.use_config() instead, which registers all configured collections and that of the stored rules without creating indexes.
  • In main(), run the dry run without an app context (e.g., contextlib.nullcontext()), and keep create_app().app.app_context() for real runs, which need the Casbin adapter (mark_changed()) that only apps register.

Verification

  • ruff format, ruff check, mypy foca tests: clean.
  • coverage run -m pytest with MongoDB 7.0: 4895 passed, 2 skipped; coverage report: 100% (before the last, test- and docs-only commit; its new tests and the release-notes and docs tests pass).
  • mkdocs build --strict: OK.
  • CI: all checks passed (CI passed, tests on Python 3.11 to 3.15, Codecov, Read the Docs).
  • New tests in tests/test_foca.py: use without an app or app context and without indexes; without databases; twice; with access control (policy collection registered, with and without app databases, then create_app()); a clashing policy collection; the most recent of use_config() and create_app() wins, and the app context keeps its own; an app created afterwards shares the registered collections and creates its indexes.

Declined review findings

  • A spy test that _register_policy_collection() passes create_indexes=False on to _register_database() from use_config(): on that path the app databases are already registered (so the merge branch only sets the collection's client), and a new policy database has no indexes, so the flag can't change what use_config() writes; the refactor keeps the default (db.create_indexes_on_startup) for apps, and the existing access-control tests pass.
  • Deduplicating the description of use_config() across the docs: each page keeps a short version for its readers and links to Preparing for the ASGI release.
  • Sourcery: preserving app collections added to the policy-only database between two registrations: this bookkeeping is moved unchanged from register_access_control() (repeated create_app() behaves the same), and changing the configured collections between registrations isn't a supported flow.

Open questions

None.

🤖 Generated with Claude Code

uniqueg and others added 4 commits November 7, 2026 18:00
Foca.use_config() makes the configuration the one that get_config()
returns outside app contexts and registers its databases without
creating indexes, so that scripts need neither Flask, an app context
nor set_app_config(), and write nothing to the database (#741).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Scripts of apps with access control read the stored policy rules;
use_config() registers their collection too, via the part of
register_access_control() that registers it, now shared. use_config()
returns None, and the docs say that it gives no app context
(review of #741).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@sourcery-ai

sourcery-ai Bot commented Nov 7, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

API

Add the public Foca.use_config() method and document its behavior, including how it selects the configuration outside app contexts and registers collections without startup writes.

  • foca/foca.py L14, L24, L301-338

Update the configuration-access API documentation and deprecation guidance to point callers to Foca.use_config() and describe the changed get_config() behavior.

  • foca/config/access.py L223-228 (+4 small edits)

Implementation

Extract configuration selection and access-control policy-collection registration so direct configuration use and app startup can share the registration logic.

  • foca/config/access.py L134-146
  • foca/security/access_control/register_access_control.py L42, L118-124, L502-612

Documentation

Explain how scripts use configured collections without an app and update the migration guidance for set_app_config() and configuration precedence.

  • docs/configuration/db.md L44-48
  • docs/migration-0.22.md L74, L80-90

Replace the note that no Flask-free replacement exists with a before-and-after example for Foca.use_config() and clarify what remains app-only.

  • docs/preparing-for-asgi.md L121-152

Add Foca.use_config() to the 0.22.0 feature notes and mention it in the deprecation guidance.

  • docs/releases/0.22.0.md L5, L10

Tests

Cover configuration use without an app, collection and policy registration, index behavior, configuration precedence, and later app creation.

  • tests/test_foca.py L9-12, L22-23, L613-743

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 7, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (1c155af) to head (9a7fe60).

Additional details and impacted files
@@            Coverage Diff            @@
##               dev      #742   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           74        74           
  Lines         9385      9400   +15     
=========================================
+ Hits          9385      9400   +15     
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 7, 2026 17:42

@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 2 issues

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

## Individual Comments

### Comment 1
<location path="foca/security/access_control/register_access_control.py" line_range="553" />
<code_context>
-        registered_db, registered_collection, added_db = registered
-        registered_db_conf = mongo_config.dbs.get(registered_db)
-        if added_db:
-            mongo_config.dbs.pop(registered_db, None)
-        elif (
-            registered_db_conf is not None
</code_context>
<issue_to_address>
**Repeated registration drops configured collections**

When access control is enabled, `use_config()` creates the policy-only database, and the caller adds an app collection to that database before calling `use_config()` again, `added_db` remains true even if the caller later adds app collections to that database, so `_register_policy_collection()` removes the entire database on the next `use_config()` call and those collections disappear from `get_collection()`.

Before removing the database, preserve it if it now contains app collections, removing only the previously registered policy collection.
</issue_to_address>

### Comment 2
<location path="tests/test_foca.py" line_range="705" />
<code_context>
+    assert collection.name == access_control.collection_name
+    assert not list(collection.find())
+    foca.create_app()
+    assert get_collection(*names).full_name == collection.full_name
+
+
</code_context>
<issue_to_address>
**Separate policy database passes**

When app creation registers the policy collection against a different MongoDB client, when app creation registers the policy collection against a different MongoDB client, `test_use_config_access_control` line 705 still passes because it compares only `full_name`; both clients can expose the same database and collection name while the app cannot see the previously registered collection’s data.

Verify shared backing data across app creation, for example by inserting a document before it and reading that document afterward.
</issue_to_address>

Linked issues

#741 feat: use a configuration without creating an app · 5 of 5 met

# Requirement Status Notes
1 Provide a public, framework-neutral way to use a configuration without creating an app. ✅ Met Foca.use_config() makes its configuration available through get_config() outside app contexts.
2 Make configured collections usable without creating indexes. ✅ Met use_config() registers configured databases and collections with index creation disabled; it also registers the stored policy-rules collection when access control is enabled.
3 Work without a Flask app context and define which configuration is used when apps and use_config() calls are mixed. ✅ Met The docstrings define the most-recent-call rule outside app contexts and app-specific configuration inside an app context; tests cover both.
4 Cover the API and behavior with tests, and update the Preparing for the ASGI release guide, migration guide, and API reference. ✅ Met Tests cover use without an app, collection registration, precedence, and app reuse; the guides are updated, and the API reference is generated from the updated docstrings.
5 Ship the feature in 0.22.0. ✅ Met The 0.22.0 release notes list Foca.use_config() as a feature.

Sourcery assessment

Needs a human reviewer. 2 findings to address first, and use_config() registers configured collections, including the access-control policy collection, so a registration bug could send a script’s database operations to the wrong collection; any records already written would remain after reverting and need repair. The method itself creates no indexes or other database writes.

Blocking findings: foca/security/access_control/register_access_control.py:553, tests/test_foca.py:705


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

Comment thread tests/test_foca.py Resolved
@uniqueg
uniqueg merged commit 98bdf2d into dev Nov 7, 2026
83 checks passed
@uniqueg
uniqueg deleted the feat/741-use-config branch November 7, 2026 18:02
@uniqueg uniqueg added this to the v0.22.0 milestone Nov 9, 2026
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: use a configuration without creating an app

1 participant