Skip to content

refactor(config): deprecate config.foca accessors - #721

Merged
uniqueg merged 5 commits into
devfrom
refactor/716-deprecate-config-foca
Nov 5, 2026
Merged

uniqueg merged 5 commits into
devfrom
refactor/716-deprecate-config-foca

Conversation

@uniqueg

@uniqueg uniqueg commented Nov 5, 2026 •

Copy link
Copy Markdown
Member

Summary

As decided in #634, get_config() and get_custom_config() are the only supported ways to read the configuration in apps. This deprecates the other two, which keep working until the first release candidate on ASGI:

  • app.config.foca / current_app.config.foca: reading, setting and deleting it emits a DeprecationWarning. The configuration stays where it was (the Flask config's instance attribute); set_app_config() swaps Flask configurations of Flask's own class, as Connexion creates them, to a static subclass whose foca property warns. A config class can't do this, as Connexion creates app.config before FOCA attaches its configuration. Apps with a configuration class of their own keep it, without the warning ("where FOCA can emit one").
  • foca.config.access.get_app_config(app) emits a DeprecationWarning.

FOCA's own reads use get_config(), or, where the app is known but not current (while it is created, in the Celery factory, require_no_service_clients(app), API registration), the private _get_app_config()/_find_app_config() without the warning. FOCA's tests, the gateway example, "Accessing the configuration" (docs/configuration/index.md) and docs/migration-0.22.md (new section "Configuration access", with a before/after example for apps that aren't the current one) follow.

Closes #716

Verification

  • coverage run -m pytest with MongoDB 7.0, with these deprecations turned into errors (-W "error:'app.config.foca' is deprecated:DeprecationWarning", likewise for setting, deleting and get_app_config()): 4622 passed, 2 skipped, 100% coverage, so FOCA itself no longer uses them
  • ruff check, ruff format --check, mypy, ast-grep scan, semgrep scan --config .semgrep --error, mkdocs build --strict: pass
  • Downstream, with this branch (371e627) installed over their locked environments (helm dependency build deployment with Helm 3.22.1, as CI). Both use the deprecated accessors only in their tests, with Flask's own config class, so they warn the same with the final design (c86e81a only changes how the warning is installed); their CI runs pytest -W ignore::DeprecationWarning, so nothing fails, and their app code uses neither:
    • cloud-registry dev (4e707a9): mongomock with coverage (deprecation warnings not ignored): 2337 passed, 11 skipped, 100% coverage; against MongoDB 7.0: 2348 passed. get_app_config() warns at 7 places in its tests: tests/conftest.py:440, tests/test_app.py:159, :638, :1108, :2444, tests/test_exceptions.py:35, tests/ga4gh/registry/test_service_info.py:114.
    • proTES dev (e47cac2): mongomock with coverage (deprecation warnings not ignored): 1613 passed, 11 skipped, 100% coverage; against MongoDB 7.0: 1623 passed. app.config.foca warns at tests/test_gateway.py:44.
  • CI: all checks passed on c86e81a

Declined review findings

  • Private _get_app_config()/_find_app_config() imported across modules and in tests: the codebase's convention for internal helpers (e.g., _match_rule, _normalize_resolver, _redact), and they mustn't become public API next to the deprecated one.
  • The deprecated setter doesn't update the configuration that get_config() falls back to outside app contexts: unchanged from before, when app.config.foca was a plain attribute.
  • ownership_server reads server.public_url with get_config() (falls back to the latest app if the current one has no FOCA configuration) instead of raising: as the issue asks; within requests to a FOCA app, the current app always has its configuration.
  • The swap changes type(app.config) for apps with Flask's own config class: noted in the migration guide; isinstance(app.config, flask.Config) still holds.

Sourcery's findings on the earlier design (per-class subclasses created at runtime: custom metaclasses, __init_subclass__ hooks, custom reductions, inherited markers, memory) are fixed by the static subclass.

Open questions

None.

🤖 Generated with Claude Code

Summary by Sourcery

Migrate application configuration access to get_config() and get_custom_config() while warning on legacy accessors ahead of their removal.

Enhancements:

  • Deprecate Flask configuration access through app.config.foca and get_app_config() in favor of the supported typed configuration accessors.
  • Update FOCA internals and examples to use non-deprecated configuration access, including safe access for known non-current applications.
  • Preserve deprecated accessor compatibility with warnings while supporting Flask’s native and custom configuration classes.

Documentation:

  • Document the supported configuration access patterns, deprecations, migration examples, and removal timeline.

Tests:

  • Add coverage for deprecation warnings, configuration mutation and deletion, custom configuration classes, pickling, and internal warning-free access.

uniqueg and others added 3 commits November 5, 2026 21:55
get_config() and get_custom_config() are the only supported ways to
read the configuration in apps. Reading or setting app.config.foca and
calling get_app_config() now emit a DeprecationWarning and keep
working: the configuration stays where it was, and the class of the
app's Flask configuration gets a property that warns. FOCA's own reads
use get_config() or, where the app is known but not current (while it
is created), a private helper without the warning. Tests, the gateway
example, the configuration docs and the migration guide follow.

Closes #716

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Read the configuration without the warning also where FOCA registers
APIs (error media type, rejection of invalid tokens), which looked it
up with getattr(). Let deleting app.config.foca work, deprecated, and
pickle Flask configurations as their original class. Attach the
configurations of test apps with set_app_config(), and show how to read
that of an app that isn't the current one in the migration guide.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Rewrite only the reductions of copyreg (and those naming the subclass
itself) when pickling a Flask configuration as its original class, so
that configuration classes with their own __reduce__() keep working,
also with keyword arguments of __new__() and globals. Note in the
migration guide that the class of app.config is a subclass while the
attribute is deprecated.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@uniqueg uniqueg added this to the v0.22.0 milestone Nov 5, 2026
@sourcery-ai

sourcery-ai Bot commented Nov 5, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

The PR deprecates direct app.config.foca and get_app_config() access with runtime warnings, implements compatibility via dynamic Flask config subclasses and internal warning-free lookups, migrates FOCA code and tests to supported access patterns, and documents the migration path and edge cases.

Sequence diagram for deprecated configuration access

sequenceDiagram
    participant App as FlaskApp
    participant Config as AppConfig
    participant Access as foca.config.access
    participant Caller

    App->>Access: set_app_config(app, config)
    Access->>Config: vars(config)[foca] = config
    Access->>Config: _deprecate_attribute(app)
    Access-->>App: Dynamic config subclass installed
    Caller->>Config: app.config.foca
    Config->>Access: _get_foca_attribute(config)
    Access-->>Caller: DeprecationWarning + configuration
    Caller->>Access: get_app_config(app)
    Access-->>Caller: DeprecationWarning + _get_app_config(app)
Loading

Flow diagram for supported configuration access

flowchart LR
    AppContext[App context] --> GetConfig["get_config()"]
    GetConfig --> CurrentConfig[Current app configuration]
    NoAppContext[No app context] --> GetConfig
    GetConfig --> LatestConfig[Most recently created FOCA app]
    KnownApp[Known non-current app] --> PrivateLookup["_get_app_config(app)"]
    CurrentConfig --> Custom["get_custom_config()"]
Loading

File-Level Changes

Change Details Files
Deprecated direct Flask configuration access while preserving compatibility through warning-emitting accessors.
  • Wrapped each app’s existing Flask config class in a cached dynamic subclass with a deprecated foca property for reads, writes, and deletes.
  • Stored FOCA configuration directly in the Flask config instance and added warning-free private lookup helpers for internal app-specific access.
  • Added pickle/copy compatibility handling so serialized configurations retain their original class.
  • Retained get_app_config() as a warning-emitting compatibility API.
foca/config/access.py
tests/config/test_access.py
Migrated FOCA runtime code and examples away from deprecated configuration APIs.
  • Changed current-app reads to get_config() and known-app reads to _get_app_config().
  • Updated app creation, database, access-control, authentication, Celery, OpenAPI, ownership, and gateway code paths.
  • Reworked tests and fixtures to use supported or internal access methods and set_app_config().
foca/api/register_openapi.py
foca/factories/celery_app.py
foca/foca.py
foca/security/access_control/ownership_server.py
foca/security/access_control/register_access_control.py
foca/security/auth.py
examples/gateway/controllers.py
tests/api/test_service_info.py
tests/factories/test_connexion_app.py
tests/plugins/test_plugin_adapter.py
tests/security/access_control/callers.py
tests/security/access_control/test_access_control_server.py
tests/security/access_control/test_checks_and_model_options.py
tests/security/access_control/test_current_roles.py
tests/security/access_control/test_enforcement.py
tests/security/access_control/test_enforcer_cache.py
tests/security/access_control/test_ownership.py
tests/security/access_control/test_ownership_server.py
tests/security/access_control/test_register_access_control.py
tests/security/access_control/test_service_clients.py
tests/security/test_auth.py
tests/test_foca.py
Documented the supported configuration access pattern and migration implications.
  • Identified get_config() and get_custom_config() as the supported application accessors.
  • Documented deprecations, replacement patterns, warning-based migration checks, dynamic config subclasses, and pickle/copy behavior.
  • Updated configuration usage guidance and migration notes.
docs/configuration/index.md
docs/migration-0.22.md

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

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (e5a25e1) to head (0c803b9).

Additional details and impacted files
@@            Coverage Diff            @@
##               dev      #721   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           71        71           
  Lines         9066      9099   +33     
=========================================
+ Hits          9066      9099   +33     
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 5, 2026 22:09

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

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

## Individual Comments

### Comment 1
<location path="foca/config/access.py" line_range="180" />
<code_context>
+        return
+    with _deprecating_classes_lock:
+        if cls not in _deprecating_classes:
+            _deprecating_classes[cls] = type(
+                cls.__name__,
+                (cls,),
</code_context>
<issue_to_address>
**Custom config metaclass breaks app creation**

When an app uses a Flask config class with a custom metaclass, `type(...)` constructs the wrapper with the built-in metaclass instead of the config class’s metaclass. For a config class whose metaclass is not compatible with `type`, class creation raises `TypeError`, so attaching the FOCA config fails.

Create the wrapper using the config class’s metaclass, or use another approach that preserves custom metaclasses.
</issue_to_address>

### Comment 2
<location path="foca/config/access.py" line_range="180-194" />
<code_context>
+        return
+    with _deprecating_classes_lock:
+        if cls not in _deprecating_classes:
+            _deprecating_classes[cls] = type(
+                cls.__name__,
+                (cls,),
+                {
+                    "__module__": cls.__module__,
+                    "__qualname__": cls.__qualname__,
+                    "__reduce_ex__": _reduce_ex,
+                    _DEPRECATING_MARKER: True,
+                    _ATTRIBUTE: property(
+                        _get_foca_attribute,
+                        _set_foca_attribute,
+                        _delete_foca_attribute,
+                    ),
+                },
+            )
+    app.config.__class__ = _deprecating_classes[cls]
+
</code_context>
<issue_to_address>
**Custom config apps fail at setup**

When an app uses a custom Flask config class with a required-keyword `__init_subclass__` hook, `type()` creates the warning subclass without forwarding any class keywords, so a custom Flask config class whose `__init_subclass__` requires a keyword raises `TypeError` and `set_app_config()` aborts app creation.

Provide a way to create the warning subclass for custom config classes whose subclass hooks require arguments, or avoid making app creation depend on subclassing them.
</issue_to_address>

### Comment 3
<location path="foca/config/access.py" line_range="177" />
<code_context>
+    """
+    cls = type(app.config)
+    if getattr(cls, _DEPRECATING_MARKER, False):
+        return
+    with _deprecating_classes_lock:
+        if cls not in _deprecating_classes:
</code_context>
<issue_to_address>
**Inherited config classes fail pickling**

When an app uses a Flask config class derived from the runtime class of a previously wrapped app config, `_deprecate_attribute` sees the inherited marker through `getattr` and skips wrapping the child; its inherited `_reduce_ex` then treats the generated class as the original or recurses through `super(Child, instance)`, so pickling raises `PicklingError` or `RecursionError`.

Skip wrapping only when the marker is defined directly on the config class, not inherited.

Also at `foca/config/access.py:113`.
</issue_to_address>

### Comment 4
<location path="foca/config/access.py" line_range="130" />
<code_context>
+    original = cls.__mro__[1]
+    reduced = super(cls, flask_config).__reduce_ex__(protocol)
+    if isinstance(reduced, str):
+        return reduced
+    function, args, *rest = cast("tuple[Any, ...]", reduced)
+    # E.g., `__reduce__()` returning `type(self)` and its arguments
</code_context>
<issue_to_address>
**Custom config reducers fail pickling**

When a custom Flask config class returns a reduction whose arguments include `type(self)` and whose callable is not the class itself or one of the handled `copyreg` functions, `_reduce_ex` returns the reduction unchanged, leaving the generated wrapper class in the factory arguments; pickle cannot resolve that synthetic class through its original module and qualified name, so serializing the config raises `PicklingError`.

Replace the generated wrapper class with the original config class in the custom reduction’s arguments.
</issue_to_address>

### Comment 5
<location path="foca/config/access.py" line_range="35" />
<code_context>
+
+# Subclasses of Flask configuration classes with the deprecated attribute, by
+# class
+_deprecating_classes: dict[type[FlaskConfig], type[FlaskConfig]] = {}
+_deprecating_classes_lock = threading.Lock()
+
</code_context>
<issue_to_address>
**Discarded config classes remain in memory**

When apps are repeatedly created and discarded with distinct dynamically generated config classes, `_deprecating_classes` strongly retains each original config class and its generated subclass, so their classes and associated definitions remain alive and process memory grows.

Avoid retaining original and generated config classes in a module-level strong-reference cache.

Also at `foca/config/access.py:179`.
</issue_to_address>

Linked issues

#716 refactor(config): deprecate config.foca accessors · 3 of 3 met

# Requirement Status Notes
1 Deprecate current_app.config.foca and get_app_config(flask_app) with a DeprecationWarning. ✅ Met Reads and writes of the Flask config attribute warn, and the public get_app_config() warns; both continue to work.
2 Switch FOCA's internal uses to get_config(). ✅ Met FOCA uses get_config() for current-app access and the private _get_app_config() where it must retrieve a known, possibly non-current app's config; internal code no longer uses the deprecated public accessor or reads config.foca.
3 Note the deprecation in docs/migration-0.22.md. ✅ Met The new “Configuration access” section lists the deprecated forms, replacements, and migration guidance.

Sourcery assessment

Approval pending. 5 findings to address first.

Blocking findings: foca/config/access.py:180, foca/config/access.py:194, foca/config/access.py:177, foca/config/access.py:130, foca/config/access.py:35


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

Comment thread foca/config/access.py Resolved
Comment thread foca/config/access.py Resolved
Comment thread foca/config/access.py Resolved
Comment thread foca/config/access.py Resolved
Comment thread foca/config/access.py Resolved
Give only Flask configurations of Flask's own class, as Connexion
creates them, a static subclass whose attribute foca warns, instead of
creating a subclass of any configuration class at runtime: those broke
custom metaclasses, __init_subclass__ hooks, reductions and inheritance
in corner cases, and were kept in memory. Apps with configuration
classes of their own keep them, without the warning.

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

@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.

Sourcery assessment

Approved.

…-config-foca

# Conflicts:
#	docs/migration-0.22.md
@uniqueg
uniqueg merged commit 438c8a1 into dev Nov 5, 2026
58 checks passed
@uniqueg
uniqueg deleted the refactor/716-deprecate-config-foca branch November 5, 2026 22:57
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.

refactor(config): deprecate config.foca accessors

1 participant