-
Notifications
You must be signed in to change notification settings - Fork 0
PTHMINT-119: SSE event stream support and EventManager #59
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
zulquer
wants to merge
4
commits into
master
Choose a base branch
from
PTHMINT-119
base: master
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
4 commits
Select commit
Hold shift + click to select a range
9c7b961
PTHMINT-119: SSE event stream support and EventManager
zulquer e36297e
PTHMINT-119: Add streaming support to transport and SSE
zulquer 517936d
Merge 'master' into 'PTHMINT-119' and solve merge conflict
danielcivit 810ab18
PTHMINT-119: HTTPStreamingTransport and SSE checks
zulquer 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,107 @@ | ||
| # Copyright (c) MultiSafepay, Inc. All rights reserved. | ||
|
|
||
| # This file is licensed under the Open Software License (OSL) version 3.0. | ||
| # For a copy of the license, see the LICENSE.txt file in the project root. | ||
|
|
||
| # See the DISCLAIMER.md file for disclaimer details. | ||
|
|
||
| """Create a Cloud POS order and subscribe to its event stream.""" | ||
|
|
||
| import os | ||
| import time | ||
|
|
||
| from dotenv import load_dotenv | ||
| from multisafepay import Sdk | ||
| from multisafepay.api.paths.orders.request import OrderRequest | ||
| from multisafepay.client import ScopedCredentialResolver | ||
|
|
||
| # Load environment variables from a .env file | ||
| load_dotenv() | ||
|
|
||
|
|
||
| def _get_first_env(*names: str) -> str: | ||
| for name in names: | ||
| value = os.getenv(name, "").strip() | ||
| if value: | ||
| return value | ||
|
|
||
| return "" | ||
|
|
||
|
|
||
| def _require_first_env(*names: str) -> str: | ||
| value = _get_first_env(*names) | ||
| if value: | ||
| return value | ||
|
|
||
| raise RuntimeError( | ||
| f"Missing required environment variable. Set one of: {', '.join(names)}", | ||
| ) | ||
|
|
||
|
|
||
| DEFAULT_ACCOUNT_API_KEY = _require_first_env("API_KEY", "E2E_API_KEY") | ||
| TERMINAL_GROUP_DEFAULT_API_KEY = _require_first_env( | ||
| "TERMINAL_GROUP_API_KEY_GROUP_DEFAULT", | ||
| "E2E_TERMINAL_GROUP_API_KEY_GROUP_DEFAULT", | ||
| ) | ||
| CLOUD_POS_TERMINAL_GROUP_ID = _require_first_env( | ||
| "CLOUD_POS_TERMINAL_GROUP_ID", | ||
| ) | ||
| TERMINAL_ID = _require_first_env( | ||
| "CLOUD_POS_TERMINAL_ID", | ||
| "E2E_CLOUD_POS_TERMINAL_ID", | ||
| ) | ||
|
|
||
| if __name__ == "__main__": | ||
| # This example executes Cloud POS calls with terminal-group scope. | ||
| scoped_terminal_group_id = CLOUD_POS_TERMINAL_GROUP_ID | ||
| resolver_kwargs = { | ||
| "default_api_key": DEFAULT_ACCOUNT_API_KEY, | ||
| } | ||
| if scoped_terminal_group_id: | ||
| resolver_kwargs["terminal_group_api_keys"] = { | ||
| scoped_terminal_group_id: TERMINAL_GROUP_DEFAULT_API_KEY, | ||
| } | ||
|
|
||
| credential_resolver = ScopedCredentialResolver(**resolver_kwargs) | ||
|
|
||
| multisafepay_sdk = Sdk( | ||
| is_production=False, | ||
| credential_resolver=credential_resolver, | ||
| ) | ||
| order_manager = multisafepay_sdk.get_order_manager() | ||
| event_manager = multisafepay_sdk.get_event_manager() | ||
|
|
||
| order_id = f"cloud-pos-{int(time.time())}" | ||
|
|
||
| order_request = ( | ||
| OrderRequest() | ||
| .add_type("redirect") | ||
| .add_order_id(order_id) | ||
| .add_description("Cloud POS order") | ||
| .add_amount(100) | ||
| .add_currency("EUR") | ||
| .add_gateway_info( | ||
| { | ||
| "terminal_id": TERMINAL_ID, | ||
| }, | ||
| ) | ||
| ) | ||
|
|
||
| create_response = order_manager.create( | ||
| order_request, | ||
| terminal_group_id=scoped_terminal_group_id, | ||
| ) | ||
| order = create_response.get_data() | ||
|
|
||
| if order is None: | ||
| raise RuntimeError("Order creation did not return order data") | ||
|
|
||
| print(f"Created Cloud POS order: {order.order_id}") | ||
| print("Listening for events. Press Ctrl+C to stop.") | ||
|
|
||
| try: | ||
| with event_manager.subscribe_order_events(order, timeout=45.0) as stream: | ||
| for event in stream: | ||
| print(event) | ||
| except KeyboardInterrupt: | ||
| print("Stream interrupted by user.") |
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,14 @@ | ||
| # Copyright (c) MultiSafepay, Inc. All rights reserved. | ||
|
|
||
| # This file is licensed under the Open Software License (OSL) version 3.0. | ||
| # For a copy of the license, see the LICENSE.txt file in the project root. | ||
|
|
||
| # See the DISCLAIMER.md file for disclaimer details. | ||
|
|
||
| """Events API endpoints.""" | ||
|
|
||
| from multisafepay.api.paths.events.event_manager import EventManager | ||
|
|
||
| __all__ = [ | ||
| "EventManager", | ||
| ] |
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,89 @@ | ||
| # Copyright (c) MultiSafepay, Inc. All rights reserved. | ||
|
|
||
| # This file is licensed under the Open Software License (OSL) version 3.0. | ||
| # For a copy of the license, see the LICENSE.txt file in the project root. | ||
|
|
||
| # See the DISCLAIMER.md file for disclaimer details. | ||
|
|
||
| """Event manager for event stream subscription helpers.""" | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| from multisafepay.api.base.abstract_manager import AbstractManager | ||
| from multisafepay.api.paths.events.stream import EventStream | ||
| from multisafepay.api.paths.orders.response.order_response import Order | ||
| from multisafepay.client.client import Client | ||
|
|
||
|
|
||
| class EventManager(AbstractManager): | ||
| """Manages event stream subscriptions for order events.""" | ||
|
|
||
| def __init__(self: EventManager, client: Client) -> None: | ||
| """Initialize the EventManager with a client.""" | ||
| super().__init__(client) | ||
|
|
||
| def subscribe_events( | ||
| self: EventManager, | ||
| events_token: str, | ||
| events_stream_url: str, | ||
| last_event_id: str | None = None, | ||
| timeout: float = 30.0, | ||
| ) -> EventStream: | ||
| """ | ||
| Subscribe to order events using the SSE stream endpoint. | ||
|
|
||
| Parameters | ||
| ---------- | ||
| events_token (str): Token returned by order creation for event auth. | ||
| events_stream_url (str): Full SSE stream URL. | ||
| last_event_id (str | None): Optional resume cursor. | ||
| timeout (float): Socket timeout in seconds. | ||
|
|
||
| Returns | ||
| ------- | ||
| EventStream: An iterator over incoming SSE messages. | ||
|
|
||
| """ | ||
| return EventStream.open( | ||
| events_token=events_token, | ||
| events_stream_url=events_stream_url, | ||
| transport=self.client.transport, | ||
| last_event_id=last_event_id, | ||
| timeout=timeout, | ||
| ) | ||
|
|
||
| def subscribe_order_events( | ||
| self: EventManager, | ||
| order: Order, | ||
| last_event_id: str | None = None, | ||
| timeout: float = 30.0, | ||
| ) -> EventStream: | ||
| """ | ||
| Subscribe to events for an existing order response object. | ||
|
|
||
| Parameters | ||
| ---------- | ||
| order (Order): Order response that contains event credentials. | ||
| last_event_id (str | None): Optional resume cursor. | ||
| timeout (float): Socket timeout in seconds. | ||
|
|
||
| Returns | ||
| ------- | ||
| EventStream: An iterator over incoming SSE messages. | ||
|
|
||
| """ | ||
| events_token = order.events_token or order.event_token | ||
| events_stream_url = order.events_stream_url or order.event_stream_url | ||
|
|
||
| if not events_token or not events_stream_url: | ||
| raise ValueError( | ||
| "Order does not contain events_token/event_token " | ||
| "or events_stream_url/event_stream_url.", | ||
| ) | ||
|
|
||
| return self.subscribe_events( | ||
| events_token=events_token, | ||
| events_stream_url=events_stream_url, | ||
| last_event_id=last_event_id, | ||
| timeout=timeout, | ||
| ) |
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.