Repository navigation
feat: merge equivalent checks in BatchCheck #334
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Siddhant-K-code
wants to merge
17
commits into
main
Choose a base branch
from
siddhant-k-code-optimize-relation-aliases
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
17 commits
Select commit
Hold shift + click to select a range
f490b44
feat: merge equivalent checks in BatchCheck (beta)
Siddhant-K-code 3f707aa
fix: tighten merge_equivalent_checks validation
Siddhant-K-code e07c07f
test: cover an empty model response and the checks_sent setter
Siddhant-K-code fae9939
docs: note that merge_equivalent_checks may change while in beta
Siddhant-K-code 4805d23
fix: count merged checks even when a request fails
Siddhant-K-code 45d733c
fix: don't keep a model read that finished before it was registered
Siddhant-K-code d579913
test: check the sent context and contextual tuples in shared cases
Siddhant-K-code ccf64fb
test: update shared cases to declare contextual tuple condition params
Siddhant-K-code 23b945e
fix: send checks with deeply nested context as is when merging
Siddhant-K-code 1d4d01a
test: check that merged batch checks send the consistency option
Siddhant-K-code 882d25e
fix: fail early when the model doesn't exist and retry transient mode…
Siddhant-K-code ce0957a
fix: fail the call when the credentials can't read the model
Siddhant-K-code 16a29a2
docs: drop beta wording from merge_equivalent_checks
Siddhant-K-code f74eac1
test: update shared equivalent-checks cases to openfga/language@153c7a9
Siddhant-K-code c1f6de3
refactor: address review on merge_equivalent_checks
Siddhant-K-code 8d27822
Merge remote-tracking branch 'origin/main' into siddhant-k-code-optim…
Siddhant-K-code 56574bc
fix: don't retry the model read for merge_equivalent_checks
Siddhant-K-code File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,112 @@ | ||
| """ | ||
| Steps of a BatchCheck call with `merge_equivalent_checks` on that are the same in the | ||
| async and sync clients. The clients only read the model and send the checks. Not part | ||
| of the public API. | ||
| """ | ||
|
|
||
| import logging | ||
|
|
||
| from openfga_sdk.client._model_cache_base import ModelLookup, model_read_fails_call | ||
| from openfga_sdk.client.equivalent_checks import ( | ||
| EquivalentCheckGroup, | ||
| resolve, | ||
| unmerged, | ||
| ) | ||
| from openfga_sdk.client.models.batch_check_item import ClientBatchCheckItem | ||
| from openfga_sdk.telemetry.attributes import TelemetryAttributes | ||
|
|
||
|
|
||
| logger = logging.getLogger(__name__) | ||
|
|
||
|
|
||
| def log_model_read_failure( | ||
| error: Exception, store_id: str, authorization_model_id: str | ||
| ) -> None: | ||
| """ | ||
| Warn that the checks go out unmerged, unless the error fails the call. | ||
| """ | ||
| if model_read_fails_call(error): | ||
| return | ||
| logger.warning( | ||
| "merge_equivalent_checks: couldn't read authorization model %s in store %s (status: %s). " | ||
| "Sending checks unmerged.", | ||
| authorization_model_id, | ||
| store_id, | ||
| getattr(error, "status", None), | ||
| ) | ||
|
|
||
|
|
||
| def checks_to_send( | ||
| api_client, | ||
| store_id: str, | ||
| authorization_model_id: str, | ||
| lookup: ModelLookup, | ||
| checks: list[ClientBatchCheckItem], | ||
| ) -> list[EquivalentCheckGroup]: | ||
| """ | ||
| Group the checks using the model from the cache, or send them unmerged if the model | ||
| couldn't be read or grouping failed. Raise if the model read error fails the call. | ||
| """ | ||
| metrics = _MergeMetrics(api_client, store_id, authorization_model_id) | ||
| metrics.model_cache_lookup(lookup.hit) | ||
|
|
||
| if lookup.aliases is None: | ||
| if model_read_fails_call(lookup.error): | ||
| # BatchCheck would fail too if the model is missing or no token can be | ||
| # fetched, and falling back on a 401 or 403 would hide wrong credentials. | ||
| # Fail before sending anything. | ||
| raise lookup.error | ||
| groups = unmerged(checks) | ||
| metrics.fallback(getattr(lookup.error, "status", None)) | ||
| else: | ||
| try: | ||
| groups = resolve(lookup.aliases, checks) | ||
| except Exception: | ||
| logger.warning( | ||
| "merge_equivalent_checks: couldn't group the checks. Sending checks unmerged.", | ||
| exc_info=True, | ||
| ) | ||
| groups = unmerged(checks) | ||
| metrics.fallback(None) | ||
|
|
||
| # Every chunk is sent even if another one fails, so count them up front. | ||
| metrics.checks(requested=len(checks), sent=len(groups)) | ||
| return groups | ||
|
|
||
|
|
||
| class _MergeMetrics: | ||
| def __init__(self, api_client, store_id: str, authorization_model_id: str) -> None: | ||
| self._metrics = api_client._telemetry.metrics | ||
| self._configuration = api_client.configuration.telemetry | ||
| self._attributes = { | ||
| TelemetryAttributes.fga_client_request_store_id: store_id, | ||
| TelemetryAttributes.fga_client_request_model_id: authorization_model_id, | ||
| } | ||
|
|
||
| def model_cache_lookup(self, hit: bool) -> None: | ||
| self._metrics.modelCacheLookup( | ||
| attributes={ | ||
| **self._attributes, | ||
| TelemetryAttributes.fga_client_model_cache_result: ( | ||
| "hit" if hit else "miss" | ||
| ), | ||
| }, | ||
| configuration=self._configuration, | ||
| ) | ||
|
|
||
| def fallback(self, status: int | None) -> None: | ||
| self._metrics.batchCheckMergeFallback( | ||
| attributes={ | ||
| **self._attributes, | ||
| TelemetryAttributes.http_response_status_code: status, | ||
| }, | ||
| configuration=self._configuration, | ||
| ) | ||
|
|
||
| def checks(self, requested: int, sent: int) -> None: | ||
| self._metrics.batchCheckChecksRequested( | ||
| requested, attributes=self._attributes, configuration=self._configuration | ||
| ) | ||
| self._metrics.batchCheckChecksSent( | ||
| sent, attributes=self._attributes, configuration=self._configuration | ||
| ) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,104 @@ | ||
| """ | ||
| The parts of the BatchCheck model cache that the async and sync clients share. Not | ||
| part of the public API. | ||
|
|
||
| A model never changes once it's written, so a cached model never goes stale. Only | ||
| successful reads are cached. A 429 is remembered for a short time, so rate limiting | ||
| doesn't add a read to every call. Other failures aren't, so the next call reads again. | ||
| """ | ||
|
|
||
| import time | ||
|
|
||
| from collections import OrderedDict | ||
| from collections.abc import Callable | ||
| from dataclasses import dataclass | ||
|
|
||
| from openfga_sdk.client.equivalent_checks import ModelAliases | ||
| from openfga_sdk.exceptions import ApiException, AuthenticationError | ||
|
|
||
|
|
||
| MAX_MODELS = 32 | ||
| FAILURE_TTL_SECONDS = 60.0 | ||
| REMEMBERED_FAILURE_STATUSES = frozenset({429}) | ||
| CREDENTIAL_FAILURE_STATUSES = frozenset({401, 403}) | ||
| NOT_FOUND_CODES = frozenset({"authorization_model_not_found", "store_id_not_found"}) | ||
|
|
||
| ModelCacheKey = tuple[str, str] | ||
|
|
||
|
|
||
| def model_read_fails_call(error: Exception | None) -> bool: | ||
| """ | ||
| Whether a model read error fails the BatchCheck call instead of sending the checks | ||
| unmerged: the model or store doesn't exist, or the credentials can't read the model | ||
| (a 401 or 403, or the token request failed) | ||
| """ | ||
| if isinstance(error, AuthenticationError): | ||
| return True | ||
| return isinstance(error, ApiException) and ( | ||
| error.code in NOT_FOUND_CODES or error.status in CREDENTIAL_FAILURE_STATUSES | ||
| ) | ||
|
|
||
|
|
||
| @dataclass | ||
| class ModelLookup: | ||
| """ | ||
| The result of a cache lookup: the model's aliases, or the error from reading it. | ||
| `hit` is True only when they were already in the cache. | ||
| """ | ||
|
|
||
| aliases: ModelAliases | None = None | ||
| hit: bool = False | ||
| error: Exception | None = None | ||
|
|
||
|
|
||
| class ModelCacheBase: | ||
| """ | ||
| The cached models and remembered failures. The async and sync caches add the reads. | ||
| """ | ||
|
|
||
| def __init__( | ||
| self, | ||
| max_models: int = MAX_MODELS, | ||
| failure_ttl: float = FAILURE_TTL_SECONDS, | ||
| clock: Callable[[], float] = time.monotonic, | ||
| ) -> None: | ||
| self._max_models = max_models | ||
| self._failure_ttl = failure_ttl | ||
| self._clock = clock | ||
| self._models: OrderedDict[ModelCacheKey, ModelAliases] = OrderedDict() | ||
| self._failures: OrderedDict[ModelCacheKey, tuple[float, Exception]] = ( | ||
| OrderedDict() | ||
| ) | ||
|
|
||
| def _cached(self, key: ModelCacheKey) -> ModelLookup | None: | ||
| aliases = self._models.get(key) | ||
| if aliases is not None: | ||
| self._models.move_to_end(key) | ||
| return ModelLookup(aliases=aliases, hit=True) | ||
|
|
||
| failure = self._failures.get(key) | ||
| if failure is not None: | ||
| expires_at, error = failure | ||
| if self._clock() < expires_at: | ||
| return ModelLookup(error=error) | ||
| del self._failures[key] | ||
|
|
||
| return None | ||
|
|
||
| def _store(self, key: ModelCacheKey, aliases: ModelAliases) -> None: | ||
| self._failures.pop(key, None) | ||
| self._models[key] = aliases | ||
| self._models.move_to_end(key) | ||
| while len(self._models) > self._max_models: | ||
| self._models.popitem(last=False) | ||
|
|
||
| def _remember_failure(self, key: ModelCacheKey, error: Exception) -> None: | ||
| if not ( | ||
| isinstance(error, ApiException) | ||
| and error.status in REMEMBERED_FAILURE_STATUSES | ||
| ): | ||
| return | ||
| self._failures[key] = (self._clock() + self._failure_ttl, error) | ||
| self._failures.move_to_end(key) | ||
| while len(self._failures) > self._max_models: | ||
| self._failures.popitem(last=False) |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.