-
Notifications
You must be signed in to change notification settings - Fork 425
feat(server): implement Resource Scoping for tasks and push notifications
#709
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
Merged
Merged
Changes from 30 commits
Commits
Show all changes
58 commits
Select commit
Hold shift + click to select a range
2d2d31e
feat(server): implement `resource scoping` for `tasks` and `push noti…
sokoliva 6093f7f
fix: add poolclass to allow.txt
sokoliva ce1a305
Merge branch '1.0-dev' of https://github.com/a2aproject/a2a-python in…
sokoliva 6600b47
fix: test_inmemory_task_store.py merge caused error
sokoliva a212da7
Merge branch '1.0-dev' into resource-scoping
sokoliva ea89bbb
fix: - add alembic to dev field in pyproject.toml
sokoliva 9301b8c
fix: update uv.lock
sokoliva 62dce31
fix:
sokoliva 86d769e
Merge branch '1.0-dev' into resource-scoping
sokoliva 99cf89f
fix: fix linter issues
sokoliva a11d6de
Merge branch 'resource-scoping' of https://github.com/sokoliva/a2a-py…
sokoliva feb5033
Fix: fix some more linter errors
sokoliva 212ad37
fix: more linter errors fixed
sokoliva f7b5c1c
fix: make parameter `ServerCallContext` non-optional in `PushNotifica…
sokoliva 179b21a
Merge branch '1.0-dev' into resource-scoping
sokoliva 38d7df6
fix: add ServerCallContext to tests/e2e/push_notifications/agent_app.py
sokoliva 5eeb89d
Merge branch 'resource-scoping' of https://github.com/sokoliva/a2a-py…
sokoliva c4b282a
fix: small fix
sokoliva 0090ecc
fix: fix unit test error
sokoliva 0f51ef3
fi: fix
sokoliva 00e5eac
fix: fix
sokoliva 5d65aa6
chore: distribute alembic migration files. Add helper _get_owner_push…
sokoliva cbadd5b
Merge branch '1.0-dev' of https://github.com/a2aproject/a2a-python in…
sokoliva 163c8c2
Merge branch '1.0-dev' into resource-scoping
sokoliva 44ad799
fix: linter issues
sokoliva 213ebb2
Merge branch 'resource-scoping' of https://github.com/sokoliva/a2a-py…
sokoliva 5bfccf9
fix: uv run ruff format
sokoliva bde88f1
refactor: add an edge case to test_database_task_store
sokoliva db3d050
fix: uv run ruff format
sokoliva a37efe1
fix: typo
sokoliva 782fcf7
chore: add migration for `push_notification_configs` table
sokoliva b77a4f6
Merge branch '1.0-dev' into resource-scoping
sokoliva 3428956
fix: rename README to README.md
sokoliva d90b360
feat: enhance migration CLI with table and verbose options; add owner…
sokoliva efc54a9
Merge branch '1.0-dev' into resource-scoping
sokoliva 28b6cfc
feat: enhance migration CLI with SQL mode and logging; update README …
sokoliva 591fa76
Merge branch 'resource-scoping' of https://github.com/sokoliva/a2a-py…
sokoliva 94f129d
fix: uv run ruff format
sokoliva 7f9e2bc
fix: remove user existence check in resolve_user_scope function
sokoliva 59f1fd4
feat: add CLI support for alembic in migration tool and update depend…
sokoliva 31fd9c1
fix: add ImportError handling for Alembic in CLI and migration files
sokoliva e98b578
Merge branch '1.0-dev' into resource-scoping
sokoliva 0c6d5f2
docs: update installation instructions for a2a-db migration tool
sokoliva f61eaf4
refactor: replace defaultdict with dict for in-memory task and notifi…
sokoliva 73995fa
feat: introduce a2a-db CLI for database migrations and update documen…
sokoliva 61e89fa
fix: format
sokoliva 9dc9d0c
docs: clarify error message for --owner-name flag in downgrade test
sokoliva 580d2ca
feat: update CLI flags for owner column in migrations and enhance err…
sokoliva 4164a08
feat: refactor migration tests to use direct function calls and mock …
sokoliva 874e72b
feat: enhance migration tests with importlib for coverage and refacto…
sokoliva 8317e6f
Merge branch '1.0-dev' into resource-scoping
ishymko bf7961d
feat: rename a2a-db-cli to db-cli in installation instructions and up…
sokoliva 34f3d76
Merge branch 'resource-scoping' of https://github.com/sokoliva/a2a-py…
sokoliva a041116
feat: update migration version table name to 'a2a_alembic_version'
sokoliva b7bbc17
feat: use VERSION_TABLE constant for alembic version table name in mi…
sokoliva 1e19e18
fix: change last_updated type from String to DateTime
sokoliva 55ee94e
feat: update column definitions for owner and last_updated in migrati…
sokoliva 798e455
Merge branch '1.0-dev' into resource-scoping
sokoliva 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -92,6 +92,7 @@ openapiv2 | |
| opensource | ||
| otherurl | ||
| pb2 | ||
| poolclass | ||
| postgres | ||
| POSTGRES | ||
| postgresql | ||
|
|
||
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,35 @@ | ||
| # A generic, single database configuration. | ||
|
|
||
| [loggers] | ||
| keys = root,sqlalchemy,alembic | ||
|
|
||
| [handlers] | ||
| keys = console | ||
|
|
||
| [formatters] | ||
| keys = generic | ||
|
|
||
| [logger_root] | ||
| level = WARNING | ||
| handlers = console | ||
| qualname = | ||
|
|
||
| [logger_sqlalchemy] | ||
| level = WARNING | ||
| handlers = | ||
| qualname = sqlalchemy.engine | ||
|
|
||
| [logger_alembic] | ||
| level = INFO | ||
| handlers = | ||
| qualname = alembic | ||
|
|
||
| [handler_console] | ||
| class = StreamHandler | ||
| args = (sys.stderr,) | ||
| level = NOTSET | ||
| formatter = generic | ||
|
|
||
| [formatter_generic] | ||
| format = %(levelname)-5.5s [%(name)s] %(message)s | ||
| datefmt = %H:%M:%S |
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,102 @@ | ||
| import argparse | ||
| import os | ||
|
|
||
| from importlib.resources import files | ||
|
|
||
| from alembic import command | ||
| from alembic.config import Config | ||
|
|
||
|
|
||
| def run_migrations() -> None: | ||
| """CLI tool to manage database migrations.""" | ||
| parser = argparse.ArgumentParser(description='A2A Database Migration Tool') | ||
|
|
||
| # Global options | ||
| parser.add_argument( | ||
| '-o', | ||
| '--owner', | ||
| help="Value for the 'owner' column (used in specific migrations). If not set defaults to 'unknown'", | ||
| ) | ||
| parser.add_argument( | ||
| '-u', | ||
| '--database-url', | ||
| help='Database URL to use for the migrations. If not set, the DATABASE_URL environment variable will be used.', | ||
| ) | ||
|
|
||
| subparsers = parser.add_subparsers(dest='cmd', help='Migration command') | ||
|
|
||
| # Upgrade command | ||
| up_parser = subparsers.add_parser( | ||
| 'upgrade', help='Upgrade to a later version' | ||
| ) | ||
| up_parser.add_argument( | ||
| 'revision', | ||
| nargs='?', | ||
| default='head', | ||
| help='Revision target (default: head)', | ||
| ) | ||
| up_parser.add_argument( | ||
| '-o', '--owner', dest='sub_owner', help='Alias for top-level --owner' | ||
| ) | ||
| up_parser.add_argument( | ||
| '-u', | ||
| '--database-url', | ||
| dest='sub_database_url', | ||
| help='Alias for top-level --database-url', | ||
| ) | ||
|
|
||
| # Downgrade command | ||
| down_parser = subparsers.add_parser( | ||
| 'downgrade', help='Revert to a previous version' | ||
| ) | ||
| down_parser.add_argument( | ||
| 'revision', | ||
| nargs='?', | ||
| default='base', | ||
| help='Revision target (e.g., -1, base or a specific ID)', | ||
| ) | ||
| down_parser.add_argument( | ||
| '-u', | ||
| '--database-url', | ||
| dest='sub_database_url', | ||
| help='Alias for top-level --database-url', | ||
| ) | ||
|
|
||
| args = parser.parse_args() | ||
|
|
||
| # Consolidate owner value | ||
| owner = args.owner or getattr(args, 'sub_owner', None) | ||
| db_url = args.database_url or getattr(args, 'sub_database_url', None) | ||
| if db_url: | ||
| os.environ['DATABASE_URL'] = db_url | ||
|
|
||
| # Default to upgrade head if no command is provided | ||
| if not args.cmd: | ||
| args.cmd = 'upgrade' | ||
| args.revision = 'head' | ||
|
|
||
| # 1. Locate the bundled alembic.ini | ||
| ini_path = files('a2a').joinpath('alembic.ini') | ||
| cfg = Config(str(ini_path)) | ||
|
|
||
| # 2. Dynamically set the script location | ||
| migrations_path = files('a2a').joinpath('migrations') | ||
| cfg.set_main_option('script_location', str(migrations_path)) | ||
|
|
||
| # 3. Pass custom arguments to the migration context | ||
| if owner: | ||
| if args.cmd == 'downgrade': | ||
| parser.error( | ||
| "The --owner option is not supported for the 'downgrade' command." | ||
| ) | ||
| cfg.set_main_option('owner', owner) | ||
|
|
||
| # 3. Execute the requested command | ||
| if args.cmd == 'upgrade': | ||
| print(f'Upgrading database to {args.revision}...') | ||
| command.upgrade(cfg, args.revision) | ||
| elif args.cmd == 'downgrade': | ||
| print(f'Downgrading database to {args.revision}...') | ||
| command.downgrade(cfg, args.revision) | ||
|
|
||
| print('Done.') |
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,84 @@ | ||
| # A2A SDK Database Migrations | ||
|
|
||
| This directory handles the database schema updates for the A2A SDK. It uses a bundled CLI tool to simplify the migration process for both users and developers of the SDK. | ||
|
|
||
| ## User Guide (For Integrators) | ||
|
|
||
| When you install the `a2a-sdk`, you get a built-in command `a2a-db` to manage your database schema. | ||
|
|
||
| ### 1. Set your Database URL | ||
| Migrations require the `DATABASE_URL` environment variable to be set with an **async-compatible** driver or you can use the `-u` flag to specify the database URL for a single command. | ||
|
|
||
| ```bash | ||
| # SQLite example | ||
| export DATABASE_URL="sqlite+aiosqlite://user:pass@host:port/your_database_name" | ||
|
|
||
| # PostgreSQL example | ||
| export DATABASE_URL="postgresql+asyncpg://user:pass@localhost/your_database_name" | ||
|
|
||
| # MySQL example | ||
| export DATABASE_URL="mysql+aiomysql://user:pass@localhost/your_database_name" | ||
| ``` | ||
|
|
||
| ### 2. Apply Migrations | ||
| Always run this command after installing or upgrading the SDK to ensure your database matches the required schema. | ||
|
|
||
| ```bash | ||
| # Bring the database to the latest version | ||
| a2a-db | ||
| ``` | ||
|
|
||
| ### 3. Customizing Defaults | ||
| Add owner to tasks migration allows you to pass custom values for the new `owner` column. For example, to set a specific default owner for existing tasks: | ||
|
|
||
| ```bash | ||
| a2a-db -o "admin_user" | ||
| ``` | ||
|
|
||
| ### 4. Rolling Back | ||
| If you need to revert a change: | ||
|
|
||
| ```bash | ||
| # Step back one version | ||
| a2a-db downgrade -1 | ||
| ``` | ||
|
|
||
| ```bash | ||
| # Downgrade to a specific revision ID | ||
| a2a-db downgrade <revision_id> | ||
| ``` | ||
|
|
||
| ```bash | ||
| # Revert all migrations | ||
| a2a-db downgrade base | ||
| ``` | ||
|
|
||
| --- | ||
|
|
||
| ## Developer Guide (For SDK Contributors) | ||
|
|
||
| If you are modifying the SDK models and need to generate new migration files, use the following workflow. | ||
|
|
||
| ### Creating a New Migration | ||
| Developers should use the raw `alembic` command locally to generate migrations. Ensure you are in the project root. | ||
|
|
||
| ```bash | ||
| # Detect changes in models.py and generate a script | ||
| uv run alembic revision --autogenerate -m "describe your changes" | ||
| ``` | ||
|
|
||
| ### Internal Layout | ||
| - `env.py`: Configures the migration engine and applies the mandatory `DATABASE_URL` check. | ||
| - `versions/`: Contains the migration history. | ||
| - `script.py.mako`: The template for all new migration files. | ||
|
|
||
| ## Troubleshooting | ||
|
|
||
| ### "Duplicate column name" | ||
| If your database already has the required tables (e.g., created via `Base.metadata.create_all()` in a legacy script), you may need to "stamp" the database to tell the SDK that it is already up to date: | ||
|
|
||
| ```bash | ||
| # Stamp the database without running SQL commands | ||
| # (Requires raw alembic command for developer use) | ||
| uv run alembic stamp head | ||
| ``` |
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 @@ | ||
| "Alembic database migration package." |
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,102 @@ | ||
| import asyncio | ||
| import os | ||
|
|
||
| from logging.config import fileConfig | ||
|
|
||
| from sqlalchemy import Connection, pool | ||
| from sqlalchemy.ext.asyncio import async_engine_from_config | ||
|
|
||
| from a2a.server.models import Base | ||
| from alembic import context | ||
|
|
||
|
|
||
| # this is the Alembic Config object, which provides | ||
| # access to the values within the .ini file in use. | ||
| config = context.config | ||
|
|
||
| # Mandatory database configuration | ||
| db_url = os.getenv('DATABASE_URL') | ||
| if not db_url: | ||
| raise RuntimeError( | ||
| 'DATABASE_URL environment variable is not set. ' | ||
| "Please set it (e.g., export DATABASE_URL='sqlite+aiosqlite:///./my-database.db') before running migrations " | ||
| 'or use the --database-url flag.' | ||
| ) | ||
| config.set_main_option('sqlalchemy.url', db_url) | ||
|
|
||
| # Interpret the config file for Python logging. | ||
| # This line sets up loggers basically. | ||
| if config.config_file_name is not None: | ||
| fileConfig(config.config_file_name) | ||
|
|
||
| # add your model's MetaData object here for 'autogenerate' support | ||
| target_metadata = Base.metadata | ||
|
|
||
|
|
||
| def run_migrations_offline() -> None: | ||
| """Run migrations in 'offline' mode. | ||
|
|
||
| This configures the context with just a URL | ||
| and not an Engine, though an Engine is acceptable | ||
| here as well. By skipping the Engine creation | ||
| we don't even need a DBAPI to be available. | ||
|
|
||
| Calls to context.execute() here emit the given string to the | ||
| script output. | ||
|
|
||
| """ | ||
| url = config.get_main_option('sqlalchemy.url') | ||
| context.configure( | ||
| url=url, | ||
| target_metadata=target_metadata, | ||
| literal_binds=True, | ||
| dialect_opts={'paramstyle': 'named'}, | ||
| ) | ||
|
|
||
| with context.begin_transaction(): | ||
| context.run_migrations() | ||
|
|
||
|
|
||
| def do_run_migrations(connection: Connection) -> None: | ||
| """Run migrations in 'online' mode. | ||
|
|
||
| This function is called within a synchronous context (via run_sync) | ||
| to configure the migration context with the provided connection | ||
| and target metadata, then execute the migrations within a transaction. | ||
|
|
||
| Args: | ||
| connection: The SQLAlchemy connection to use for the migrations. | ||
| """ | ||
| context.configure(connection=connection, target_metadata=target_metadata) | ||
|
|
||
| with context.begin_transaction(): | ||
| context.run_migrations() | ||
|
|
||
|
|
||
| async def run_async_migrations() -> None: | ||
| """Run migrations using an Engine. | ||
|
|
||
| In this scenario we need to create an Engine | ||
| and associate a connection with the context. | ||
| """ | ||
| connectable = async_engine_from_config( | ||
| config.get_section(config.config_ini_section, {}), | ||
| prefix='sqlalchemy.', | ||
| poolclass=pool.NullPool, | ||
| ) | ||
|
|
||
| async with connectable.connect() as connection: | ||
| await connection.run_sync(do_run_migrations) | ||
|
|
||
| await connectable.dispose() | ||
|
|
||
|
|
||
| def run_migrations_online() -> None: | ||
| """Run migrations in 'online' mode.""" | ||
| asyncio.run(run_async_migrations()) | ||
|
|
||
|
|
||
| if context.is_offline_mode(): | ||
|
sokoliva marked this conversation as resolved.
|
||
| run_migrations_offline() | ||
| else: | ||
| run_migrations_online() | ||
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,28 @@ | ||
| """${message} | ||
|
|
||
| Revision ID: ${up_revision} | ||
| Revises: ${down_revision | comma,n} | ||
| Create Date: ${create_date} | ||
|
|
||
| """ | ||
| from typing import Sequence, Union | ||
|
|
||
| from alembic import op | ||
| import sqlalchemy as sa | ||
| ${imports if imports else ""} | ||
|
|
||
| # revision identifiers, used by Alembic. | ||
| revision: str = ${repr(up_revision)} | ||
| down_revision: Union[str, Sequence[str], None] = ${repr(down_revision)} | ||
| branch_labels: Union[str, Sequence[str], None] = ${repr(branch_labels)} | ||
| depends_on: Union[str, Sequence[str], None] = ${repr(depends_on)} | ||
|
|
||
|
|
||
| def upgrade() -> None: | ||
| """Upgrade schema.""" | ||
| ${upgrades if upgrades else "pass"} | ||
|
|
||
|
|
||
| def downgrade() -> None: | ||
| """Downgrade schema.""" | ||
| ${downgrades if downgrades else "pass"} |
Oops, something went wrong.
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.