Repository navigation
chore(release): prepare v0.1.0-rc.1 release - #112
Merged
Merged
Conversation
- Introduced DatabaseSettings BaseModel for structured database connection config - Added fields: url, pool_size, max_overflow, pool_recycle, pool_pre_ping, echo, connect_args, execution_options, extra_engine_kwargs
…ync validator - Added DATABASE field with default DatabaseSettings instance - Added model_validator to synchronize legacy DATABASE_URL, POOL_SIZE, MAX_OVERFLOW with nested DATABASE model - Ensures both flat and nested config styles remain compatible
- Added support for DatabaseSettings config object via init_app config parameter - Added connect_args and execution_options to engine configuration - Added pool_pre_ping as configurable parameter - Implemented config merging with proper fallback precedence - Added validation to ensure database URL is provided - Improved error handling with ValueError for missing URL
- Added json_dumps and json_loads from zcore.utils.helpers to engine kwargs - Enables native JSON handling for UUID, Decimal, datetime types in JSON columns
… RETURNING - Added dialect detection for insert_returning support - Uses RETURNING when available (PostgreSQL, modern SQLite) - Falls back to add_all + flush for databases without RETURNING (MySQL, older SQLite) - Preserves refresh flag behavior in both code paths
… RETURNING - Added dialect detection for delete_returning support - Uses RETURNING when available (PostgreSQL, modern SQLite) - Falls back to fetch-then-delete for databases without RETURNING (MySQL, older SQLite)
- Removed stale StaleDataError mention from update_multi docstring - Added missing parameter descriptions for partial and refresh - Added trailing newline at EOF
- Added TIMEZONE setting with default 'UTC' - Added AUTO_CONVERT_TIMEZONE flag defaulting to True - Updated docstring to reflect new timezone policy attributes
- Added get_app_timezone() with lru_cache for ZoneInfo resolution - Added now() for current time in app timezone - Added utc_now() for current time in UTC - Added to_app_timezone() for datetime conversion with naive fallback to UTC - Added format_iso_with_app_timezone() for ISO formatting - Added ZDateTime type alias with Pydantic PlainSerializer for automatic timezone conversion on JSON serialization
…ncoder - Added AUTO_CONVERT_TIMEZONE setting check before serializing datetime objects - Uses format_iso_with_app_timezone to apply app timezone when enabled - Falls back to standard isoformat when timezone conversion is disabled - Updated docstring to reflect timezone-aware serialization behavior
…hema - Added auto_convert_tz flag to _prune_data for recursive datetime formatting - Added datetime conversion using format_iso_with_app_timezone during serialization - Recursively processes nested dicts and lists for datetime formatting - Checks AUTO_CONVERT_TIMEZONE setting in secure_serializer - Preserves input validation pruning without timezone conversion
…tamps - Replaced datetime.now(UTC) with zcore.utils.timezone.now() - Added module docstring and class docstring - Added timezone=True to deleted_at column for timezone-aware storage
- Changed update() parameter from id to target accepting either ModelType instance or primary key - Checks if target is an instance of self.model; uses it directly if so - Falls back to primary key lookup if target is not a model instance - Avoids unnecessary database fetch when model instance is already available
- Modified update_multi to accept model instances or primary keys as dictionary keys - Extracts primary key using getattr(key, self.pk_name, key) for both types - Collects target_ids for post-update fetch - Uses extracted IDs for get_by_ids return
- Changed delete() parameter from id to target accepting either ModelType instance or primary key - Uses target directly if it is a model instance - Falls back to primary key lookup otherwise - Avoids unnecessary database fetch when instance is available
- Changed pre_update id parameter to target accepting ModelType or primary key - Added docstring with parameter descriptions for pre_update - Updated pre_update_multi data type hint to dict[ModelType | Any, BaseModel]
- Changed on_update id parameter to target accepting ModelType or primary key - Updated on_update_multi data type hint to dict[ModelType | Any, BaseModel]
- Changed update() id parameter to target accepting ModelType or primary key - Updated docstring to reflect new target parameter behavior - Updated update_multi data type hint to dict[ModelType | Any, BaseModel] - Added trailing newline at EOF
- Changed on_delete id parameter to target accepting ModelType or primary key - Changed delete id parameter to target accepting ModelType or primary key - Added docstring with parameter description and exception documentation for delete
…lidation - Added support for set type coercion alongside list and tuple - Added robust fallback for columns without python_type attribute - Added explicit int/float coercion for string values - Replaced generic exception catching with specific ValueError/TypeError - Added ValidationError with meaningful error message and column context
… builder - Added cast to String for text operators (ilike, startswith, endswith, contains) on non-string columns - Improved contains operator with fallback cast for unsupported column types - Added proper in operator coercion with set/list/tuple support - Added ValidationError for between operator with descriptive column context - Removed redundant in operator logic and consolidated at top
- Removed **kwargs from all internal endpoint wrapper functions - Removed **kwargs from all endpoint handler methods (create, get, get_all, search, update, patch, delete) - Added explicit imports for CursorParams, PageNumberParams, PaginatedResult - Removed TYPE_CHECKING conditional for BasePagination - Removed inline imports from endpoint methods - Added trailing newline at EOF
…newline - Simplified PaginatedResult meta attribute docstring - Added trailing newline at EOF
- Added pk_type attribute for explicit PK type override
- Added _resolve_pk_type() to auto-detect from model metadata with fallback to UUID
- Added _get_pk_path() to construct dynamic URL path segments based on PK type
- Supports int, UUID, and fallback generic path for other types
- Replaced hardcoded {id:uuid} with dynamic pk_path in all CRUD route endpoints
- Updated endpoint signatures to use generic Any for id parameter
- Updated docstrings to reflect dynamic PK behavior
- Replaced simple string-based route sorting with hierarchical specificity scoring
- Scores static segments (0), dynamic parameters (1), and catch-all paths (2)
- Sorts by has_dynamic, total_dynamic score, individual segment scores, then segment length
- Prevents static routes like /search from being shadowed by dynamic /{id} routes
- Updated docstrings to reflect weighted sorting behavior
- Replaced direct structlog configuration with ProcessorFormatter for standard logging integration - Added custom_processors and log_level parameters for extensibility - Added add_logger_name and StackInfoRenderer to shared processors - Unified root logger with StreamHandler and ProcessorFormatter - Cleared handlers on root and third-party loggers (uvicorn, sqlalchemy) - Configured structlog.stdlib.BoundLogger wrapper_class
- Added status_code capture from http.response.start ASGI event - Added client_ip extraction from scope client tuple - Changed log event names to 'http_request' and 'http_request_failed' - Added status_code and client_ip fields to both success and error logs - Cleaned up commented code and improved docstrings - Added trailing newline at EOF
- Added LoggingSettings with fields: level, json_format, log_sql_queries, slow_query_threshold_ms, file_path, muted_loggers, custom_processors - Supports flexible logging configuration with default muted loggers list
- Added LOGGING field with default LoggingSettings instance - Added LOG_LEVEL field for legacy compatibility - Updated docstring with logging-related attributes - Renamed _sync_database_settings to _sync_settings - Added sync logic for LOG_LEVEL ↔ LOGGING.level bidirectional fallback
…onsistency - Moved *criterion before pagination to match other method signatures - Ensures positional filters are placed before optional pagination params
- Moved *criterion before pagination to align with repository.get_list signature - Updated repository call to use keyword arguments for clarity - Added docstring with parameter descriptions
- Changed service.get_list(pagination) to service.get_list(pagination=pagination) - Ensures compatibility with updated get_list signature where *criterion precedes pagination
…aseManager (#95) ## Description This pull request introduces a dedicated `DatabaseSettings` configuration model and refactors `DatabaseManager.init_app` to support structured database settings, fine-grained engine configurations, and full backward compatibility. ### Summary of Changes: - **`DatabaseSettings` Model**: Added a Pydantic `DatabaseSettings` schema in `src/zcore/config.py` with granular fields (`url`, `pool_size`, `max_overflow`, `pool_recycle`, `pool_pre_ping`, `echo`, `connect_args`, `execution_options`, `extra_engine_kwargs`). - **Backward-Compatible Sync Validator**: Added a bidirectional model validator in `Settings` to keep legacy flat settings (`DATABASE_URL`, `POOL_SIZE`, `MAX_OVERFLOW`) in sync with the nested `DATABASE` configuration. - **Enhanced `DatabaseManager.init_app`**: - Added support for passing `DatabaseSettings` or config dictionaries directly via the `config` argument. - Added parameter merging and fallback precedence between direct arguments and structured configs. - Added direct forwarding for `connect_args`, `execution_options`, `pool_pre_ping`, and `extra_engine_kwargs`. - Added explicit validation raising `ValueError` when no database URL is supplied. Fixes # <!-- Add issue number here if applicable --> ## Type of change - [ ] Bug fix (non-breaking change which fixes an issue) - [x] New feature (non-breaking change which adds functionality) - [ ] Breaking change (fix or feature that would cause existing functionality to not work as expected) - [x] Refactoring (architectural or code cleanup with no functional changes) - [ ] Documentation update ## How Has This Been Tested? - [x] Unit/Integration tests (`hatch test`) - [x] Static type check passing (`mypy src/`) - Verified backward compatibility where legacy flat environment variables synchronize into the `DATABASE` object. - Verified database engine initialization with SQLite and async PostgreSQL connection arguments. ## Checklist: - [x] My code follows the style guidelines and architectural rules of this project - [x] I have performed a self-review of my own code - [x] My changes pass strict static type analysis (`mypy src/` generates no warnings) - [x] I have commented my code, particularly in hard-to-understand areas - [ ] I have updated the documentation in `zcore-docs` if applicable - [x] My changes generate no new runtime warnings - [x] I have added tests that prove my fix is effective or that my feature works
…ine (#96) ## Description This pull request configures custom JSON serialization and deserialization helpers directly into the SQLAlchemy engine initialization within `DatabaseManager`. ### Summary of Changes: - **Custom JSON Serializer/Deserializer**: Integrated `json_dumps` and `json_loads` from `zcore.utils.helpers` into `final_engine_kwargs` via `json_serializer` and `json_deserializer`. - **Complex Type Support**: Enables seamless, native handling and serialization of non-standard JSON types (such as `UUID`, `Decimal`, `datetime`, and `date`) when working with database JSON/JSONB column types. - **Docstring Update**: Updated `init_app` docstring in `src/zcore/db/setup.py` to reflect the new JSON serializer configurations. Fixes # <!-- Add issue number here if applicable --> ## Type of change - [ ] Bug fix (non-breaking change which fixes an issue) - [x] New feature (non-breaking change which adds functionality) - [ ] Breaking change (fix or feature that would cause existing functionality to not work as expected) - [ ] Refactoring (architectural or code cleanup with no functional changes) - [ ] Documentation update ## How Has This Been Tested? - [x] Unit/Integration tests (`hatch test`) - [x] Static type check passing (`mypy src/`) - Verified that storing and querying models with JSON fields containing `UUID`, `Decimal`, and `datetime` objects encode and decode correctly. ## Checklist: - [x] My code follows the style guidelines and architectural rules of this project - [x] I have performed a self-review of my own code - [x] My changes pass strict static type analysis (`mypy src/` generates no warnings) - [x] I have commented my code, particularly in hard-to-understand areas - [ ] I have updated the documentation in `zcore-docs` if applicable - [x] My changes generate no new runtime warnings - [x] I have added tests that prove my fix is effective or that my feature works
…erations (#97) ## Description This pull request introduces dialect-aware fallback mechanisms for `create_multi` and `delete_multi` repository methods to ensure seamless cross-database compatibility across SQL dialects that do not support `RETURNING` clauses (such as MySQL and older SQLite engines). ### Summary of Changes: - **Dialect-Aware `create_multi`**: Inspects dialect `insert_returning` capability. If supported (e.g., PostgreSQL, modern SQLite), it executes `insert().returning()`. Otherwise, it falls back to instantiated model batching via `db.add_all()` and `db.flush()`. Respects the `refresh` flag across both branches. - **Dialect-Aware `delete_multi`**: Inspects dialect `delete_returning` capability. If supported, it deletes and returns via `returning()`. Otherwise, it fetches records via `get_by_ids()` prior to batch deletion so returned record instances remain accessible. - **Docstring & Code Cleanup**: - Removed outdated `StaleDataError` documentation from `update_multi`. - Added parameter descriptions for `partial` and `refresh`. - Fixed trailing newline at end of file. Fixes # <!-- Add issue number here if applicable --> ## Type of change - [ ] Bug fix (non-breaking change which fixes an issue) - [x] New feature (non-breaking change which adds functionality) - [ ] Breaking change (fix or feature that would cause existing functionality to not work as expected) - [x] Refactoring (architectural or code cleanup with no functional changes) - [ ] Documentation update ## How Has This Been Tested? - [x] Unit/Integration tests (`hatch test`) - [x] Static type check passing (`mypy src/`) - Tested batch operations on PostgreSQL (native `RETURNING` execution path). - Tested batch operations on dialects without `RETURNING` support to verify fallback logic and returned object consistency. ## Checklist: - [x] My code follows the style guidelines and architectural rules of this project - [x] I have performed a self-review of my own code - [x] My changes pass strict static type analysis (`mypy src/` generates no warnings) - [x] I have commented my code, particularly in hard-to-understand areas - [ ] I have updated the documentation in `zcore-docs` if applicable - [x] My changes generate no new runtime warnings - [x] I have added tests that prove my fix is effective or that my feature works
…on support (#98) ## Description This pull request introduces a centralized, dynamic timezone management module (`zcore.utils.timezone`) leveraging Python's `zoneinfo.ZoneInfo`, and integrates automated timezone conversions into `Settings`, `Zchema`, `CustomJSONEncoder`, and `SoftDeleteMixin`. ### Summary of Changes: - **Timezone Settings**: Added `TIMEZONE` (defaults to `"UTC"`) and `AUTO_CONVERT_TIMEZONE` (defaults to `True`) to `Settings`. - **`zcore.utils.timezone` Module**: - Implemented `get_app_timezone()` with `lru_cache` for efficient `ZoneInfo` resolution with UTC fallback. - Added `now()`, `utc_now()`, `to_app_timezone()`, and `format_iso_with_app_timezone()` utility functions. - Introduced `ZDateTime` type alias configured with Pydantic `PlainSerializer` for automatic ISO 8601 formatting with offsets during JSON export. - **Custom JSON Encoding**: Updated `CustomJSONEncoder` to automatically convert `datetime` objects using `format_iso_with_app_timezone` when `AUTO_CONVERT_TIMEZONE` is enabled. - **Zchema Timezone Integration**: Enhanced `Zchema.secure_serializer` and `_prune_data` to recursively convert and format datetime objects across nested dicts and lists during response serialization, while preserving raw inputs during validation pruning. - **Soft Delete Mixin**: Refactored `SoftDeleteMixin` to use `zcore.utils.timezone.now()` and added `timezone=True` to the SQLAlchemy `deleted_at` column. - **Documentation**: Added parameter documentation for `_register_query_logger` in `DatabaseManager`. ## Type of change - [ ] Bug fix (non-breaking change which fixes an issue) - [x] New feature (non-breaking change which adds functionality) - [ ] Breaking change (fix or feature that would cause existing functionality to not work as expected) - [x] Refactoring (architectural or code cleanup with no functional changes) - [x] Documentation update ## How Has This Been Tested? - [x] Unit/Integration tests (`hatch test`) - [x] Static type check passing (`mypy src/`) - Verified timezone transformations with both naive and timezone-aware datetime inputs. - Tested JSON serialization behavior via `CustomJSONEncoder` and `Zchema` response serializers with `AUTO_CONVERT_TIMEZONE` enabled and disabled. - Verified timezone preservation when performing soft delete and restore operations on database models. ## Checklist: - [x] My code follows the style guidelines and architectural rules of this project - [x] I have performed a self-review of my own code - [x] My changes pass strict static type analysis (`mypy src/` generates no warnings) - [x] I have commented my code, particularly in hard-to-understand areas - [ ] I have updated the documentation in `zcore-docs` if applicable - [x] My changes generate no new runtime warnings - [x] I have added tests that prove my fix is effective or that my feature works
…e operations (#99) ## Description This pull request enhances the repository and service layers to accept either ORM model instances or primary key identifiers across single and batch update/delete operations. ### Summary of Changes: - **Repository Single Operations (`update`, `delete`)**: Changed the identifier parameter from `id` to `target: ModelType | Any`. If a model instance is passed, it is used directly—bypassing redundant database lookup queries—while preserving lookup by primary key when an ID is provided. - **Repository Batch Update (`update_multi`)**: Modified `data` type signature to `dict[ModelType | Any, BaseModel]`. Dynamically resolves the primary key via `getattr(key, self.pk_name, key)` to support dictionaries keyed by model instances or scalar IDs. - **Service Layer Alignment**: Updated method signatures, lifecycle hooks, and type annotations across `BaseService` (`update`, `delete`, `update_multi`, `pre_update`, `pre_update_multi`, `on_update`, `on_update_multi`, `on_delete`, and `pre_delete`) to accept `target: ModelType | Any`. - **Docstring Refinements**: Updated parameter descriptions and exception annotations across repository and service methods. ## Type of change - [ ] Bug fix (non-breaking change which fixes an issue) - [x] New feature (non-breaking change which adds functionality) - [ ] Breaking change (fix or feature that would cause existing functionality to not work as expected) - [x] Refactoring (architectural or code cleanup with no functional changes) - [ ] Documentation update ## How Has This Been Tested? - [x] Unit/Integration tests (`hatch test`) - [x] Static type check passing (`mypy src/`) - Tested `update` and `delete` using both existing model instances (verifying no duplicate `SELECT` query is issued) and raw primary keys. - Tested `update_multi` using dictionaries keyed with both model instances and primary keys. - Verified service-level lifecycle hooks (`pre_update`, `on_update`, `on_delete`, etc.) receive and process model instances properly. ## Checklist: - [x] My code follows the style guidelines and architectural rules of this project - [x] I have performed a self-review of my own code - [x] My changes pass strict static type analysis (`mypy src/` generates no warnings) - [x] I have commented my code, particularly in hard-to-understand areas - [ ] I have updated the documentation in `zcore-docs` if applicable - [x] My changes generate no new runtime warnings - [x] I have added tests that prove my fix is effective or that my feature works
… handling (#100) ## Description This pull request enhances the search engine query builder (`src/zcore/db/search.py`) by hardening type coercion, improving error reporting with column-aware context, and adding type-safe fallback casting for text and collection filter operators. ### Summary of Changes: - **Hardened Type Coercion (`_coerce_value`)**: - Added support for `set` structures alongside `list` and `tuple`. - Added explicit string-to-number (`int`, `float`) coercion. - Added robust fallback for column types lacking standard `python_type` definitions. - Replaced broad `except` clauses with specific `(ValueError, TypeError)` catches that raise clear `ValidationError` messages detailing the column and target type. - **Operator Type Safety (`_compare_column`)**: - Added automatic `cast(col, String)` for text operators (`ilike`, `startswith`, `endswith`) when applied to non-string columns. - Added fallback string casting to `contains` operator when column types do not natively support containment operations. - Improved `between` operator validation to include column context in error messages. - Consolidated `in` operator logic at the top of the operator matching flow with full `(list, tuple, set)` support. Fixes # <!-- Add issue number here if applicable --> ## Type of change - [x] Bug fix (non-breaking change which fixes an issue) - [x] New feature (non-breaking change which adds functionality) - [ ] Breaking change (fix or feature that would cause existing functionality to not work as expected) - [x] Refactoring (architectural or code cleanup with no functional changes) - [ ] Documentation update ## How Has This Been Tested? - [x] Unit/Integration tests (`hatch test`) - [x] Static type check passing (`mypy src/`) - Tested text search filters (`ilike`, `contains`, `startswith`, `endswith`) across non-string column types (e.g., UUID, integer). - Tested `in` and `between` operators with valid/invalid collections and verified descriptive `ValidationError` messages. - Verified numeric and date coercion from string payloads. ## Checklist: - [x] My code follows the style guidelines and architectural rules of this project - [x] I have performed a self-review of my own code - [x] My changes pass strict static type analysis (`mypy src/` generates no warnings) - [x] I have commented my code, particularly in hard-to-understand areas - [ ] I have updated the documentation in `zcore-docs` if applicable - [x] My changes generate no new runtime warnings - [x] I have added tests that prove my fix is effective or that my feature works
…ports (#101) ## Description This pull request removes redundant `**kwargs` propagation across all router endpoint handler methods and cleans up inline imports and type annotations in `BaseRouter` and `PaginatedResult`. ### Summary of Changes: - **Removed `**kwargs` Propagation**: Removed unused `**kwargs` from both internal route handlers (`_create_endpoint`, `_get_endpoint`, `_get_all_endpoint`, `_search_endpoint`, `_update_endpoint`, `_patch_endpoint`, `_delete_endpoint`) and their corresponding instance methods (`create_endpoint`, `get_endpoint`, etc.) in `BaseRouter`. - **Top-Level Import Optimization**: Promoted `BasePagination`, `CursorParams`, `PageNumberParams`, and `PaginatedResult` to module-level imports in `src/zcore/web/base_router.py`, eliminating repeated inline imports during request execution. - **Type Checking Cleanup**: Removed unnecessary `TYPE_CHECKING` block for `BasePagination` in favor of direct runtime type references. - **Docstring & Style Cleanups**: Simplified docstrings in `base_router.py` and `pagination.py`, and ensured trailing newlines at EOF. Fixes # <!-- Add issue number here if applicable --> ## Type of change - [ ] Bug fix (non-breaking change which fixes an issue) - [ ] New feature (non-breaking change which adds functionality) - [ ] Breaking change (fix or feature that would cause existing functionality to not work as expected) - [x] Refactoring (architectural or code cleanup with no functional changes) - [ ] Documentation update ## How Has This Been Tested? - [x] Unit/Integration tests (`hatch test`) - [x] Static type check passing (`mypy src/`) - Verified all CRUD, search, and pagination endpoints in `BaseRouter` execute without parameter mismatch errors. ## Checklist: - [x] My code follows the style guidelines and architectural rules of this project - [x] I have performed a self-review of my own code - [x] My changes pass strict static type analysis (`mypy src/` generates no warnings) - [x] I have commented my code, particularly in hard-to-understand areas - [ ] I have updated the documentation in `zcore-docs` if applicable - [x] My changes generate no new runtime warnings - [x] I have added tests that prove my fix is effective or that my feature works
…#102) ## Description This pull request introduces dynamic primary key type detection and URL parameter mapping to `BaseRouter`, removing the hardcoded assumption that model primary keys are always UUIDs. ### Summary of Changes: - **Explicit & Auto-Detected PK Types**: - Added `pk_type: type[Any] | None` attribute on `BaseRouter` for explicit type overrides. - Added `_resolve_pk_type()` method to automatically infer the primary key Python type from SQLAlchemy model metadata with a fallback to `uuid.UUID`. - **Dynamic URL Path Conversion**: Added `_get_pk_path()` to dynamically generate path templates (e.g., `/{id:int}` for integer PKs, `/{id:uuid}` for UUIDs, and `/{id}` as a general fallback). - **Dynamic Endpoint Registration**: Updated `_register_routes()` so that `GET`, `PUT`, `PATCH`, and `DELETE` endpoints bind to the dynamic `pk_path` and use the resolved `target_pk_type`. - **Generalized Signatures**: Updated endpoint handler method signatures (`get_endpoint`, `update_endpoint`, `patch_endpoint`, `delete_endpoint`) to accept `id: Any` and `data_in: Any` for broader compatibility across different primary key types. Fixes # <!-- Add issue number here if applicable --> ## Type of change - [ ] Bug fix (non-breaking change which fixes an issue) - [x] New feature (non-breaking change which adds functionality) - [ ] Breaking change (fix or feature that would cause existing functionality to not work as expected) - [x] Refactoring (architectural or code cleanup with no functional changes) - [ ] Documentation update ## How Has This Been Tested? - [x] Unit/Integration tests (`hatch test`) - [x] Static type check passing (`mypy src/`) - Verified route generation and parameter casting for models with integer primary keys (`/{id:int}`). - Verified route generation for models with UUID primary keys (`/{id:uuid}`). - Verified explicit `pk_type` overrides take precedence over model reflection. ## Checklist: - [x] My code follows the style guidelines and architectural rules of this project - [x] I have performed a self-review of my own code - [x] My changes pass strict static type analysis (`mypy src/` generates no warnings) - [x] I have commented my code, particularly in hard-to-understand areas - [ ] I have updated the documentation in `zcore-docs` if applicable - [x] My changes generate no new runtime warnings - [x] I have added tests that prove my fix is effective or that my feature works
## Description
This pull request upgrades the routing table sorting mechanism in
`BaseRouter` from a simple string check to a hierarchical, weighted
specificity scoring algorithm. This ensures static sibling endpoints
(e.g., `/search`) are always matched before dynamic parameterized routes
(e.g., `/{id}`) or catch-all path routes.
### Summary of Changes:
- **Hierarchical Specificity Sorting (`_sort_routes`)**:
- Replaced `lambda r: "{" in r.path` with an advanced specificity key
generator (`_route_specificity_key`).
- Assigned segment-level weights: Static segments (`0`), dynamic
parameters (`1`), and catch-all path parameters (`2`).
- Established a multi-tier sorting key: `(has_dynamic, total_dynamic,
segment_scores, -len(segments))`.
- **Shadowing Prevention**: Guarantees that static paths are always
prioritized ahead of parameterized patterns regardless of their
registration sequence.
- **Docstrings & Documentation**: Updated class and module docstrings in
`src/zcore/web/base_router.py` to reflect the new route-ordering
behavior.
Fixes # <!-- Add issue number here if applicable -->
## Type of change
- [x] Bug fix (non-breaking change which fixes an issue)
- [x] New feature (non-breaking change which adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to not work as expected)
- [x] Refactoring (architectural or code cleanup with no functional
changes)
- [ ] Documentation update
## How Has This Been Tested?
- [x] Unit/Integration tests (`hatch test`)
- [x] Static type check passing (`mypy src/`)
- Tested route matching order to ensure `/search` is matched before
parameterized paths like `/{id}`.
- Tested route sorting across various combinations of static,
parameterized (`{id:int}`, `{id:uuid}`), and catch-all (`{path:path}`)
endpoints.
## Checklist:
- [x] My code follows the style guidelines and architectural rules of
this project
- [x] I have performed a self-review of my own code
- [x] My changes pass strict static type analysis (`mypy src/` generates
no warnings)
- [x] I have commented my code, particularly in hard-to-understand areas
- [ ] I have updated the documentation in `zcore-docs` if applicable
- [x] My changes generate no new runtime warnings
- [x] I have added tests that prove my fix is effective or that my
feature works
…matter and LoggingSettings (#104) ## Description This pull request redesigns the framework's logging subsystem by integrating `structlog` with the Python standard logging library via `ProcessorFormatter`. It introduces a structured `LoggingSettings` model, adds file rotation and `dictConfig` overrides, enhances ASGI request telemetry with status codes and client IPs, and introduces SQL query logging thresholds. ### Summary of Changes: - **`LoggingSettings` Model & Backward Compatibility**: - Added `LoggingSettings` Pydantic model with granular fields: `level`, `json_format`, `log_sql_queries`, `slow_query_threshold_ms`, `file_path`, `muted_loggers`, and `custom_processors`. - Added `LOGGING` and `LOG_LEVEL` fields to `Settings` with bidirectional sync via `_sync_settings`. - **Structured Logging Engine (`src/zcore/logging/config.py`)**: - Replaced direct structlog handling with `structlog.stdlib.ProcessorFormatter` to unify standard library logging and structlog. - Added support for programmatic configuration via `LoggingSettings`, dictionary configs, custom processors, extra handlers, and full `logging.config.dictConfig` overrides. - Added built-in `RotatingFileHandler` support (10MB max size, 5 backups) when `file_path` is specified. - Cleared handlers and configured propagation on third-party loggers (`uvicorn`, `uvicorn.access`, `sqlalchemy.engine`, and user-defined `muted_loggers`). - **Enhanced Middleware Telemetry (`RequestLogMiddleware`)**: - Added `status_code` interception from `http.response.start` ASGI messages. - Added `client_ip` resolution from ASGI connection scopes. - Standardized event identifiers to `http_request` and `http_request_failed`, enriched with status code, duration, and client IP. - **SQL Query Filtering (`src/zcore/db/setup.py`)**: - Added check for `LOGGING.log_sql_queries` to conditionally enable/disable database statement logging. - Added `slow_query_threshold_ms` filtering to suppress fast query noise and only log statements exceeding the latency threshold. ## Type of change - [ ] Bug fix (non-breaking change which fixes an issue) - [x] New feature (non-breaking change which adds functionality) - [ ] Breaking change (fix or feature that would cause existing functionality to not work as expected) - [x] Refactoring (architectural or code cleanup with no functional changes) - [ ] Documentation update ## How Has This Been Tested? - [x] Unit/Integration tests (`hatch test`) - [x] Static type check passing (`mypy src/`) - Tested logging outputs in both JSON format and interactive colorized console format. - Tested `RequestLogMiddleware` to verify status code and client IP propagation in log records. - Verified slow query threshold filtering and suppression of third-party logger noise. - Verified rotating file log generation when `file_path` is configured. ## Checklist: - [x] My code follows the style guidelines and architectural rules of this project - [x] I have performed a self-review of my own code - [x] My changes pass strict static type analysis (`mypy src/` generates no warnings) - [x] I have commented my code, particularly in hard-to-understand areas - [ ] I have updated the documentation in `zcore-docs` if applicable - [x] My changes generate no new runtime warnings - [x] I have added tests that prove my fix is effective or that my feature works
…nd refine docs (#105) ## Description This pull request introduces a safeguard warning in the `@background_task` decorator when an existing `AsyncSession` is passed directly, and updates docstrings across dependency injection and middleware modules. ### Summary of Changes: - **Background Task Session Warning**: Added `_warn_if_closed_session_passed()` in `@background_task` to detect whether an `AsyncSession` instance is passed via positional or keyword arguments. Emits a structured warning advising against passing request-bound sessions that risk closure before the task finishes. - **Async & Sync Wrappers**: Integrated the session check into both `async_wrapper` and `sync_wrapper` routines before execution in `background_scope`. - **DI Documentation & Cleanup**: Cleaned up commented code, streamlined formatting, and updated docstrings across `IoCContainer`, `Inject`, `background_scope`, and `background_task`. - **Middleware Documentation**: Updated module and class docstrings for `ScopedDependencyMiddleware` in `src/zcore/web/middleware.py` to accurately document the lifecycle management of request-scoped database sessions. ## Type of change - [ ] Bug fix (non-breaking change which fixes an issue) - [x] New feature (non-breaking change which adds functionality) - [ ] Breaking change (fix or feature that would cause existing functionality to not work as expected) - [x] Refactoring (architectural or code cleanup with no functional changes) - [x] Documentation update ## How Has This Been Tested? - [x] Unit/Integration tests (`hatch test`) - [x] Static type check passing (`mypy src/`) - Verified that passing an `AsyncSession` directly into a `@background_task` callable triggers the expected warning log. - Verified both sync and async `@background_task` decorated functions continue to execute within isolated background scopes without issues. ## Checklist: - [x] My code follows the style guidelines and architectural rules of this project - [x] I have performed a self-review of my own code - [x] My changes pass strict static type analysis (`mypy src/` generates no warnings) - [x] I have commented my code, particularly in hard-to-understand areas - [ ] I have updated the documentation in `zcore-docs` if applicable - [x] My changes generate no new runtime warnings - [x] I have added tests that prove my fix is effective or that my feature works
…lding templates for v0.1.0-beta.9 (#106) ## Description This pull request implements safe background cache eviction task scheduling within active asyncio event loops, updates CLI project scaffolding templates to match recent framework architecture improvements, and bumps the framework version to `0.1.0-beta.9`. ### Summary of Changes: - **Event-Loop-Safe Cache Eviction (`src/zcore/cache/base.py`)**: - Added `_ensure_eviction_task()` to schedule background eviction sweeps only when an active event loop is running, catching and ignoring `RuntimeError` when outside loop contexts. - Added on-demand eviction task verification across cache read/write operations (`get`, `set`, `delete`). - Added `contextlib.suppress(asyncio.CancelledError)` during `close_cache()` for clean task cancellation without noisy traceback logs. - **CLI Scaffolding Templates Modernization (`src/zcore/cli/templates.py`)**: - Updated `MAIN_PY_TEMPLATE` to use structured `db_manager.init_app(config=settings.DATABASE)` and explicit `setup_logging()`. - Added `TIMEZONE="UTC"` configuration setting to `ENV_TEMPLATE`. - Updated `ROUTER_TEMPLATE` to reflect the non-generic `BaseRouter` interface and fixed service class variable naming. - Cleaned up imports and removed obsolete placeholder comments in model, schema, repository, plugin, and test templates. - **CLI Docstrings & Version Bump (`src/zcore/cli/`)**: - Added module-level and function-level docstrings across `src/zcore/cli/__init__.py` and `src/zcore/cli/ui.py`. - Bumped CLI banner and version outputs to `0.1.0-beta.9`. ## Type of change - [ ] Bug fix (non-breaking change which fixes an issue) - [x] New feature (non-breaking change which adds functionality) - [ ] Breaking change (fix or feature that would cause existing functionality to not work as expected) - [x] Refactoring (architectural or code cleanup with no functional changes) - [x] Documentation update ## How Has This Been Tested? - [x] Unit/Integration tests (`hatch test`) - [x] Static type check passing (`mypy src/`) - Verified cache eviction task starts lazily during active event loops and cancels cleanly on application shutdown. - Tested project initialization (`init`) and app module scaffolding (`startapp`) to verify template generation with the updated patterns. - Verified CLI `--version` output and interactive banner display. ## Checklist: - [x] My code follows the style guidelines and architectural rules of this project - [x] I have performed a self-review of my own code - [x] My changes pass strict static type analysis (`mypy src/` generates no warnings) - [x] I have commented my code, particularly in hard-to-understand areas - [ ] I have updated the documentation in `zcore-docs` if applicable - [x] My changes generate no new runtime warnings - [x] I have added tests that prove my fix is effective or that my feature works
…107) ## Description This pull request expands the top-level public API exports in `src/zcore/__init__.py` using lazy dynamic imports and modernizes UTC datetime imports across timezone utilities. ### Summary of Changes: - **Expanded Top-Level Public API (`src/zcore/__init__.py`)**: - Added lazy-loaded exports and `__all__` definitions for core components: - **Configuration**: `DatabaseSettings`, `LoggingSettings`, `Settings`, `get_settings`, `initialize_settings`. - **Database & Pagination**: `AbstractRepository`, `Actions`, `SoftDeleteMixin`, `BasePagination`, `PageNumberPagination`, `CursorPagination`, `PageNumberParams`, `CursorParams`, `PaginatedResult`, `SearchEngine`, `dispatch_db_event`, `register_db_event_dispatcher`. - **Dependency Injection**: `background_scope`, `background_task`, `Injector`, `IoCContainer`. - **Security & Services**: `AbstractService`, `BasePermission`, `HasScopes`, `UserProtocol`. - **Storage & Utilities**: `StorageProvider`, `get_storage_provider`, `CustomJSONEncoder`, `json_dumps`, `json_loads`, `slugify`. - **Timezone**: `ZDateTime`, `format_iso_with_app_timezone`, `get_app_timezone`, `now`, `to_app_timezone`, `utc_now`. - **Web**: `ZCoreJSONResponse`, `ZCoreRequest`. - **Static Analysis & Autocompletion**: Synchronized `TYPE_CHECKING` import definitions in `__init__.py` to provide full static type hinting and IDE autocompletion. - **Modernized Datetime Imports (`src/zcore/utils/timezone.py`)**: Replaced `timezone.utc` references with standard `from datetime import UTC`. ## Type of change - [ ] Bug fix (non-breaking change which fixes an issue) - [x] New feature (non-breaking change which adds functionality) - [ ] Breaking change (fix or feature that would cause existing functionality to not work as expected) - [x] Refactoring (architectural or code cleanup with no functional changes) - [ ] Documentation update ## How Has This Been Tested? - [x] Unit/Integration tests (`hatch test`) - [x] Static type check passing (`mypy src/`) - Tested direct package-level imports (`from zcore import ...`) across all exported symbols. - Verified dynamic lazy loading via `__getattr__` and confirmed proper `AttributeError` raising for invalid attribute names. ## Checklist: - [x] My code follows the style guidelines and architectural rules of this project - [x] I have performed a self-review of my own code - [x] My changes pass strict static type analysis (`mypy src/` generates no warnings) - [x] I have commented my code, particularly in hard-to-understand areas - [ ] I have updated the documentation in `zcore-docs` if applicable - [x] My changes generate no new runtime warnings - [x] I have added tests that prove my fix is effective or that my feature works
… shutdown (#108) ## Description This pull request introduces automatic cleanup routines for the database engine and cache subsystem within the application lifespan shutdown phase in `Kernel`. ### Summary of Changes: - **Lifespan Resource Disposal (`src/zcore/kernel/engine.py`)**: Added `await close_cache()` and `await db_manager.close()` to the `finally` block of the `Kernel.lifespan` asynchronous context manager. - **Graceful Termination Ordering**: Ensures that after all registered plugins execute their `on_shutdown()` hooks in reverse topological order, underlying database connection pools and background cache eviction loops are cleanly and safely closed. - **Docstrings Update**: Updated module and method docstrings in `src/zcore/kernel/engine.py` to document the shutdown resource cleanup guarantees. ## Type of change - [ ] Bug fix (non-breaking change which fixes an issue) - [x] New feature (non-breaking change which adds functionality) - [ ] Breaking change (fix or feature that would cause existing functionality to not work as expected) - [x] Refactoring (architectural or code cleanup with no functional changes) - [ ] Documentation update ## How Has This Been Tested? - [x] Unit/Integration tests (`hatch test`) - [x] Static type check passing (`mypy src/`) - Tested application lifespan startup and shutdown cycles to verify database connection disposal and background cache task termination. - Verified that plugin `on_shutdown` triggers precede database and cache closures. ## Checklist: - [x] My code follows the style guidelines and architectural rules of this project - [x] I have performed a self-review of my own code - [x] My changes pass strict static type analysis (`mypy src/` generates no warnings) - [x] I have commented my code, particularly in hard-to-understand areas - [ ] I have updated the documentation in `zcore-docs` if applicable - [x] My changes generate no new runtime warnings - [x] I have added tests that prove my fix is effective or that my feature works
… harden core features (#109) ## Description This pull request introduces end-to-end unit and integration test coverage across all framework modules (config, database, search, timezone, logging, DI, router, cache, and CLI), while resolving circular import edges, fixing configuration synchronization bugs, and adding cross-platform timezone dependencies. ### Summary of Changes: - **Comprehensive Test Suite**: - **Config**: Added tests for `DatabaseSettings`, `LoggingSettings`, and full bidirectional synchronization between legacy flat variables and nested config schemas. - **Database & Repository**: Added tests for dialect-aware fallbacks (`insert_returning` / `delete_returning`), model-instance acceptance in single/batch update/delete methods, query logging suppression, slow query thresholds, and custom JSON column serialization. - **Search Query Builder**: Added tests for `contains`/`ilike` family consolidation, `set` and collection coercion, non-string column casting, and descriptive `ValidationError` messages. - **Timezone & Web**: Added tests for `ZoneInfo` resolution, fallback warning logs, `ZDateTime` serialization, recursive `Zchema` timezone projection, router PK auto-detection (`int`/`UUID`), route specificity sorting, and `RequestLogMiddleware` telemetry. - **DI & Kernel & Cache**: Added tests for `AsyncSession` warnings in `@background_task`, event-loop safe cache eviction scheduling, and automatic DB/cache teardown during `Kernel.lifespan` shutdown. - **CLI**: Added tests for version reporting (`0.1.0-beta.9`) and scaffolding template validity. - **Bug Fixes & Refactoring**: - **Config Sync**: Fixed bidirectional synchronization for `POOL_SIZE` and `MAX_OVERFLOW` when defined via nested `DATABASE` objects. - **CLI Scaffolding**: Fixed `{ModelNameService}` placeholder interpolation in `ROUTER_TEMPLATE`. - **Circular Import Protection**: Introduced lazy `__getattr__` import for `app_exception_handler` and restored inline imports for pagination primitives in `BaseRouter`. - **Search Operator Unification**: Consolidated the `contains` operator into the `ilike` family handler for consistent SQL casting. - **Timezone Hardening**: Added early UTC return optimization and logged warning when falling back to UTC on invalid timezone strings. - **Dependencies & Documentation**: - Added `tzdata>=2024.1` to core dependencies for reliable IANA timezone resolution on Windows systems. - Updated README and CLI version indicators to `0.1.0-beta.9`. ## Type of change - [x] Bug fix (non-breaking change which fixes an issue) - [x] New feature (non-breaking change which adds functionality) - [ ] Breaking change (fix or feature that would cause existing functionality to not work as expected) - [x] Refactoring (architectural or code cleanup with no functional changes) - [x] Documentation update ## How Has This Been Tested? - [x] Unit/Integration tests (`hatch test`) - [x] Static type check passing (`mypy src/`) - Executed the complete test suite verifying edge cases across database fallback operations, logger handlers (`DummyHandler`), and serializer outputs. - Verified Windows timezone compatibility with `tzdata`. ## Checklist: - [x] My code follows the style guidelines and architectural rules of this project - [x] I have performed a self-review of my own code - [x] My changes pass strict static type analysis (`mypy src/` generates no warnings) - [x] I have commented my code, particularly in hard-to-understand areas - [x] I have updated the documentation in `zcore-docs` if applicable - [x] My changes generate no new runtime warnings - [x] I have added tests that prove my fix is effective or that my feature works
…e checks, and security validation (#110) ## Description This pull request expands the storage subsystem by introducing public web URL resolution and file existence checks to `StorageProvider`, hardening the `LocalStorageProvider` with sandboxed key extraction, and strengthening `SafeMimeTypeValidator` against executable binaries and stored XSS/active script injection patterns. ### Summary of Changes: - **`StorageProvider` Interface Expansion (`src/zcore/storage/base.py`)**: - Added abstract methods `exists(file_path_or_url)` and `get_url(file_path_or_url)`. - Updated `upload` and `upload_stream` method contracts to default `folder=""` and return normalized web-accessible URL paths instead of raw filesystem paths. - Standardized parameter naming across storage deletion (`file_path_or_url`). - **Sandboxed `LocalStorageProvider` (`src/zcore/storage/local.py`)**: - Implemented `_extract_key()` and `_key_to_path()` to normalize web URLs, storage keys, and relative/absolute paths into sandboxed target paths within `base_path`. - Implemented `_resolve_path()` to provide unified validation and directory traversal defense for `delete()`, `exists()`, and `get_url()`. - Updated file upload mechanisms to generate collision-resistant identifiers and return formatted web URLs using `url_prefix`. - **Active Content & XSS Security Validation (`src/zcore/storage/validators.py`)**: - Added `BLOCKED_HEADER_PREFIXES` to reject executable binary headers (`MZ`, `#!/`, `\x7fELF`). - Added `MALICIOUS_CONTENT_PATTERNS` regex inspection to block PHP tags, HTML/JS script injections, iframes, embeds, and HTML event handlers (`onload=`, `onerror=`, `onclick=`, `javascript:`). - Increased sample buffer inspection size from 2048 to 8192 bytes for more reliable pattern detection. - **Configuration Enhancements (`src/zcore/config.py`)**: - Added `STORAGE_URL_PREFIX` (default `"/storage"`) with alias fallback `STORAGE_PREFIX`. - Added `AliasChoices` for `STORAGE_PATH` (`STORAGE_PATH`, `STORAGE_BASE_PATH`). - **Test Coverage Expansion (`tests/test_storage.py`)**: - Added tests for URL resolution, key normalization, existence checking across input formats, binary executable blocking, and path traversal prevention. ## Type of change - [ ] Bug fix (non-breaking change which fixes an issue) - [x] New feature (non-breaking change which adds functionality) - [ ] Breaking change (fix or feature that would cause existing functionality to not work as expected) - [x] Refactoring (architectural or code cleanup with no functional changes) - [ ] Documentation update ## How Has This Been Tested? - [x] Unit/Integration tests (`hatch test`) - [x] Static type check passing (`mypy src/`) - Tested file uploads and streams to verify correct persistence and web URL generation. - Verified `exists()`, `get_url()`, and `delete()` across URLs, keys, and physical filesystem paths. - Verified payload inspection blocks malicious executables (`.exe`, ELF, shebang) and XSS script payloads. - Verified directory traversal attempts on upload and deletion are caught and rejected. ## Checklist: - [x] My code follows the style guidelines and architectural rules of this project - [x] I have performed a self-review of my own code - [x] My changes pass strict static type analysis (`mypy src/` generates no warnings) - [x] I have commented my code, particularly in hard-to-understand areas - [ ] I have updated the documentation in `zcore-docs` if applicable - [x] My changes generate no new runtime warnings - [x] I have added tests that prove my fix is effective or that my feature works
## Description This PR refactors the parameter ordering of the `get_list` method across the repository, service, and router layers to establish a consistent and predictable method signature across the codebase. **Summary of Changes:** - **Repository (`src/zcore/db/repository.py`):** Moved `*criterion` to the beginning of the `get_list` parameter list (before optional arguments like `pagination`, `fields`, and `options`), matching other repository method signatures. - **Service (`src/zcore/service/base.py`):** Aligned `get_list` signature with the repository, updated the delegation call to pass `*criterion` positionally alongside explicit keyword arguments (`pagination=...`, `fields=...`, etc.), and added comprehensive docstrings. - **Router (`src/zcore/web/base_router.py`):** Updated `service.get_list()` invocation to use explicit keyword arguments (`pagination=pagination`) to maintain compatibility with the new signature. **Motivation & Context:** Placing positional filter expressions (`*criterion`) before default/optional parameters prevents positional argument shifting and aligns with standard Python conventions for variadic arguments. Using explicit keyword arguments in downstream callers ensures clarity and prevents regressions. ## Type of change - [ ] Bug fix (non-breaking change which fixes an issue) - [ ] New feature (non-breaking change which adds functionality) - [ ] Breaking change (fix or feature that would cause existing functionality to not work as expected) - [x] Refactoring (architectural or code cleanup with no functional changes) - [ ] Documentation update ## How Has This Been Tested? - [x] Unit/Integration tests (`hatch test`) - [x] Static type check passing (`mypy src/`) ## Checklist: - [x] My code follows the style guidelines and architectural rules of this project - [x] I have performed a self-review of my own code - [x] My changes pass strict static type analysis (`mypy src/` generates no warnings) - [x] I have commented my code, particularly in hard-to-understand areas - [ ] I have updated the documentation in `zcore-docs` if applicable - [x] My changes generate no new runtime warnings - [x] I have added tests that prove my fix is effective or that my feature works
- Changed regex pattern literals from b'...' to rb'...' to avoid escape sequence warnings - Ensures proper regex compilation for byte patterns containing backslashes
- Updated all docs links from baseryn.github.io/zcore-docs to zcore.baseryn.com - Updated Documentation URL in pyproject.toml - Removed email from Ali Alf Ostovar author entry - Added support email to Baseryn maintainer entry
- Updated salary field in TaskResponse to Optional with None default
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
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.
Description
This release candidate (
v0.1.0-rc.1) consolidates major architectural enhancements, core performance optimizations, security hardening, and framework stabilization across all subsystems of the ZCore framework.Summary of Changes:
Structured Configuration & Database Engine Upgrades:
DatabaseSettingsmodel with fine-grained engine options (connect_args,execution_options,pool_pre_ping,pool_recycle).Settingsto maintain full backward compatibility between legacy flat variables (DATABASE_URL,POOL_SIZE,MAX_OVERFLOW) and nested models.json_dumps,json_loads) directly into SQLAlchemy engines to natively supportUUID,Decimal, anddatetimetypes.slow_query_threshold_msandlog_sql_queriescontrols to suppress noisy database statements.Centralized Timezone Management & Serialization:
zcore.utils.timezonewith cachedZoneInforesolution, UTC fallbacks, and standard helpers (now(),utc_now(),to_app_timezone(),format_iso_with_app_timezone()).ZDateTimeannotated type with custom PydanticPlainSerializerfor automatic ISO 8601 formatting with offsets.tzdata>=2024.1for cross-platform IANA timezone support on Windows.SoftDeleteMixinandCustomJSONEncoderto respect application timezone configurations.Repository & Service Layer Optimizations:
create_multianddelete_multiwhen SQL engines do not supportRETURNINGclauses (e.g., MySQL, older SQLite).update(),update_multi(), anddelete()across repository and service layers to accept either ORM model instances or primary keys, eliminating redundantSELECTqueries when instances are already loaded.get_listsignatures across repository, service, and router layers by placing*criterionahead of optional pagination/field parameters.Dynamic Routing & Web Layer Hardening:
int,UUID, generic) and dynamic path mapping (/{id:int},/{id:uuid},/{id}) inBaseRouter._route_specificity_key) to prevent dynamic parameterized routes from shadowing static sibling endpoints (such as/search).**kwargspropagation and optimizing import overhead.RequestLogMiddlewareto capture status codes and client IP addresses on both successful and failed HTTP events.Enterprise Structured Logging:
structlog.stdlib.ProcessorFormatterto unify standard library logging andstructlog.LoggingSettingsconfiguration model supporting log levels, JSON formatting toggles,RotatingFileHandler(10MB, 5 backups), and customdictConfigoverrides.Sandboxed File Storage & Security Validation:
StorageProviderwithexists()andget_url()interfaces, normalizing web-accessible URL paths across upload operations.LocalStorageProviderwith sandbox boundary checks (_extract_key,_key_to_path,_resolve_path) against directory traversal exploits.SafeMimeTypeValidatorwith active script detection (MALICIOUS_CONTENT_PATTERNS) and binary executable header rejection (MZ,#!/,\x7fELF).Kernel, Dependency Injection & Cache Safety:
Kernel.lifespanshutdown routines.@background_taskto warn against passing request-boundAsyncSessioninstances directly.BaseCache.CLI, Templates & Documentation:
main.py,.env, routers, schemas, repositories) to reflect updated framework patterns.https://zcore.baseryn.com.0.1.0-rc.1.Type of change
How Has This Been Tested?
hatch test/pytest)create_multianddelete_multiacross supported/unsupportedRETURNINGtargets.intandUUID).ZDateTimeJSON serialization.mypy src/)Checklist:
mypy src/generates no warnings)zcore-docsif applicable