diff --git a/.github/workflows/sdk-reference.yml b/.github/workflows/sdk-reference.yml index 0778499..6c8a477 100644 --- a/.github/workflows/sdk-reference.yml +++ b/.github/workflows/sdk-reference.yml @@ -8,7 +8,8 @@ on: jobs: docs: - runs-on: ubuntu-latest + # Python 3.8 has no actions/python-versions build for ubuntu-26.04, which ubuntu-latest now resolves to. + runs-on: ubuntu-24.04 environment: name: sdk-reference url: ${{ steps.deploy.outputs.deployment-url }} diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index f7763d5..9224cd1 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -11,7 +11,8 @@ on: jobs: pytest: - runs-on: ubuntu-latest + # Python 3.8 has no actions/python-versions build for ubuntu-26.04, which ubuntu-latest now resolves to. + runs-on: ubuntu-24.04 strategy: matrix: python-version: ["3.8", "3.x"] @@ -34,7 +35,8 @@ jobs: uses: codecov/codecov-action@v3 black: - runs-on: ubuntu-latest + # Python 3.8 has no actions/python-versions build for ubuntu-26.04, which ubuntu-latest now resolves to. + runs-on: ubuntu-24.04 name: Pylint and Black steps: - uses: actions/checkout@v2 diff --git a/.pylintrc b/.pylintrc index afe4b0f..559b3d3 100644 --- a/.pylintrc +++ b/.pylintrc @@ -35,3 +35,4 @@ generated-members= FreeBusyError.from_dict, FreeBusy.from_dict, ScheduledMessage.from_dict, + BatchEventResult.from_dict, diff --git a/CHANGELOG.md b/CHANGELOG.md index 28e25fe..dced9d7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,9 @@ nylas-python Changelog ====================== +Unreleased +---------- +* Added Events batch endpoint (Google and Microsoft): `events.batch()` runs create, update, and delete operations in one `POST /v3/grants/{grant_id}/events/batch` request, with the `BatchEventsRequest`, `BatchEventsQueryParams`, and `BatchEventResult` models. A partial failure (HTTP 207) returns the per-operation results instead of raising an error + v6.18.0 ---------- * Added optional `tracking_options.domain_name` support for custom link and open tracking hostnames in message sends, scheduled sends, drafts, and Transactional Send diff --git a/README.md b/README.md index 2de22aa..a538662 100644 --- a/README.md +++ b/README.md @@ -135,7 +135,7 @@ logging.getLogger("urllib3").setLevel(logging.DEBUG) ## 💡 Examples -Runnable examples live in [`examples/`](examples/) — including [send email](examples/send_email_demo/), [inline attachments](examples/inline_attachment_demo/), [folders](examples/folders_demo/), [import events](examples/import_events_demo/), [Notetaker API](examples/notetaker_api_demo/), [Notetaker calendar](examples/notetaker_calendar_demo/), [message fields](examples/message_fields_demo/), [metadata fields](examples/metadata_field_demo/), [provider errors](examples/provider_error_demo/), [response headers](examples/response_headers_demo/), [`select` parameter](examples/select_param_demo/), [special characters](examples/special_characters_demo/), [hidden folders](examples/include_hidden_folders_demo/), and [plain text](examples/is_plaintext_demo/). +Runnable examples live in [`examples/`](examples/) — including [send email](examples/send_email_demo/), [inline attachments](examples/inline_attachment_demo/), [folders](examples/folders_demo/), [import events](examples/import_events_demo/), [events batch](examples/events_batch_demo/), [Notetaker API](examples/notetaker_api_demo/), [Notetaker calendar](examples/notetaker_calendar_demo/), [message fields](examples/message_fields_demo/), [metadata fields](examples/metadata_field_demo/), [provider errors](examples/provider_error_demo/), [response headers](examples/response_headers_demo/), [`select` parameter](examples/select_param_demo/), [special characters](examples/special_characters_demo/), [hidden folders](examples/include_hidden_folders_demo/), and [plain text](examples/is_plaintext_demo/). For full sample apps and product quickstarts, browse [**nylas-samples** on GitHub](https://github.com/orgs/nylas-samples/repositories?q=python) — every official SDK has Email, Calendar, Contacts, Scheduler, and Webhooks quickstarts. diff --git a/examples/events_batch_demo/README.md b/examples/events_batch_demo/README.md new file mode 100644 index 0000000..2b7715f --- /dev/null +++ b/examples/events_batch_demo/README.md @@ -0,0 +1,135 @@ +# Events Batch Demo + +This example demonstrates how to create, update, and delete events in a single request with `events.batch()`, and how to retry the operations that failed. + +Batch operations are available for Google and Microsoft grants. For other providers, the API returns a 400 error. + +## Usage + +```python +from nylas import Client + +nylas = Client(api_key="NYLAS_API_KEY") + +operations = [ + { + "method": "create", + "body": { + "title": "Standup", + "when": {"start_time": 1798794000, "end_time": 1798795800}, + }, + }, + {"method": "update", "event_id": "EVENT_ID_1", "body": {"title": "Renamed"}}, + {"method": "delete", "event_id": "EVENT_ID_2"}, +] + +response = nylas.events.batch( + identifier="NYLAS_GRANT_ID", + query_params={"calendar_id": "primary"}, + request_body={"operations": operations}, +) + +# response.data[i] is the result of operations[i]. +for operation, result in zip(operations, response.data): + if result.error is None: + print(operation["method"], "succeeded with status", result.status) + else: + print(operation["method"], "failed:", result.status, result.error.type, result.error.message) +``` + +Each operation has a `method` of `create`, `update`, or `delete`: + +- `create` needs a `body`. The body has the same fields as the request body of `events.create()`. +- `update` needs an `event_id` and a `body`. The body has the same fields as the request body of `events.update()`. +- `delete` needs an `event_id`. + +The query parameters (`calendar_id`, `notify_participants`, `grant_email`, `tentative_as_busy`, and `select`) apply to every operation in the batch. `calendar_id` is required. An event can appear in only one operation per batch. + +## Results + +`response.data` has one result for each operation, in the same order as the operations. Each result has these fields: + +| Field | Description | +| --- | --- | +| `status` | The HTTP status code of the operation. | +| `data` | The created or updated `Event`. `None` for delete operations and for failed operations. | +| `error` | The `type`, `message`, and `provider_error` of the error. `None` if the operation succeeded. | +| `retry_after` | The number of seconds to wait before a retry. Only set if the provider throttled the request. Can be `0`. | +| `provider_event_created` | `True` if the provider created the event before a later step failed. | + +If some or all of the operations fail, the API returns HTTP 207. `events.batch()` doesn't raise an error for a 207 response. It returns the results, so check the `status` or `error` of each result. + +If the request itself is invalid, the API returns HTTP 400 and runs none of the operations. For example, the request is invalid if `calendar_id` is missing, if the batch has too many operations, or if two operations use the same `event_id`. `events.batch()` then raises a `NylasApiError`, as for any other API error. + +## Retrying Failed Operations + +The SDK doesn't retry failed operations. Use these rules to retry them yourself: + +- Retry an operation if its `status` is `429` or `503`. If `retry_after` is set, wait that number of seconds first. A `retry_after` of `0` means that you can retry now, so compare it with `None` instead of checking whether it is truthy. +- **Never** retry an operation if `provider_event_created` is `True`. The provider already created the event, so a retry creates a duplicate event. +- Send only the failed operations again. Don't send the operations that succeeded. + +```python +import time + +RETRYABLE_STATUSES = {429, 503} + + +def run_batch(nylas, grant_id, calendar_id, operations, max_attempts=3): + """Run a batch, and retry the failed operations that are safe to retry.""" + results = [None] * len(operations) + pending = list(range(len(operations))) + + for attempt in range(1, max_attempts + 1): + response = nylas.events.batch( + identifier=grant_id, + query_params={"calendar_id": calendar_id}, + request_body={"operations": [operations[index] for index in pending]}, + ) + + retry = [] + wait_seconds = 0 + for index, result in zip(pending, response.data): + results[index] = result + if result.error is None or result.provider_event_created: + continue + if result.status in RETRYABLE_STATUSES: + retry.append(index) + delay = 1 if result.retry_after is None else result.retry_after + wait_seconds = max(wait_seconds, delay) + + if not retry or attempt == max_attempts: + break + time.sleep(wait_seconds) + pending = retry + + return results +``` + +## Setup + +1. Install the SDK in development mode from the repository root: +```bash +cd /path/to/nylas-python +pip install -e . +``` + +2. Set your environment variables: +```bash +export NYLAS_API_KEY="your_api_key" +export NYLAS_GRANT_ID="your_grant_id" # A Google or Microsoft grant +export NYLAS_CALENDAR_ID="primary" # Optional, defaults to primary +export NYLAS_API_URI="https://api.us.nylas.com" # Optional, defaults to US +``` + +## Running the Example + +```bash +python examples/events_batch_demo/events_batch_example.py +``` + +The example changes the calendar of the grant: + +1. It creates two events one day from now, in one batch. +2. It renames one of the events. In the same batch, it deletes an event ID that doesn't exist, so the API returns HTTP 207 with one failed result. +3. It deletes both events in one batch. diff --git a/examples/events_batch_demo/events_batch_example.py b/examples/events_batch_demo/events_batch_example.py new file mode 100644 index 0000000..5dce3ee --- /dev/null +++ b/examples/events_batch_demo/events_batch_example.py @@ -0,0 +1,185 @@ +#!/usr/bin/env python3 +""" +Nylas SDK Example: Creating, Updating, and Deleting Events in a Batch + +This example demonstrates how to use events.batch() to run several event operations +in a single request, and how to retry only the failed operations that are safe to retry. + +The example changes the calendar. It creates two events one day from now, renames one +of them, and then deletes both. The second batch also deletes an event ID that doesn't +exist, to show how the results of a partial failure (HTTP 207) are returned. + +Batch operations are only available for Google and Microsoft grants. + +Required Environment Variables: + NYLAS_API_KEY: Your Nylas API key + NYLAS_GRANT_ID: Your Nylas grant ID for a Google or Microsoft account + +Optional Environment Variables: + NYLAS_API_URI: The Nylas API URI (defaults to https://api.us.nylas.com) + NYLAS_CALENDAR_ID: The calendar to use (defaults to "primary") + +Usage: + First, install the SDK in development mode: + cd /path/to/nylas-python + pip install -e . + + Then set environment variables and run: + export NYLAS_API_KEY="your_api_key" + export NYLAS_GRANT_ID="your_grant_id" + python examples/events_batch_demo/events_batch_example.py +""" + +import os +import sys +import time + +from nylas import Client +from nylas.models.errors import NylasApiError + +RETRYABLE_STATUSES = {429, 503} +DEFAULT_RETRY_SECONDS = 1 +MAX_ATTEMPTS = 3 + + +def get_env_or_exit(var_name: str) -> str: + """Get an environment variable or exit if not found.""" + value = os.getenv(var_name) + if not value: + print(f"Error: {var_name} environment variable is required") + sys.exit(1) + return value + + +def run_batch(client, grant_id, calendar_id, operations): + """ + Run a batch of event operations, and retry the failed operations that are safe to retry. + + Returns one result for each operation, in the same order as the operations. + """ + results = [None] * len(operations) + pending = list(range(len(operations))) + + for attempt in range(1, MAX_ATTEMPTS + 1): + response = client.events.batch( + identifier=grant_id, + query_params={"calendar_id": calendar_id}, + request_body={"operations": [operations[index] for index in pending]}, + ) + + retry = [] + wait_seconds = 0 + # response.data[i] is the result of the i-th operation in this request. + for index, result in zip(pending, response.data): + results[index] = result + if result.error is None: + continue + if result.provider_event_created: + # The provider created the event before a later step failed. + # Retrying this operation would create a duplicate event. + continue + if result.status in RETRYABLE_STATUSES: + retry.append(index) + # retry_after can be 0, which means the operation can be retried now. + if result.retry_after is None: + delay = DEFAULT_RETRY_SECONDS + else: + delay = result.retry_after + wait_seconds = max(wait_seconds, delay) + + if not retry or attempt == MAX_ATTEMPTS: + break + print(f" Retrying {len(retry)} operation(s) in {wait_seconds} second(s)...") + time.sleep(wait_seconds) + pending = retry + + return results + + +def print_results(operations, results): + """Print the outcome of each operation.""" + for operation, result in zip(operations, results): + target = operation.get("event_id") or operation["body"]["title"] + if result.error is None: + print(f" ✓ {operation['method']} {target}: HTTP {result.status}") + continue + print( + f" ✗ {operation['method']} {target}: HTTP {result.status} " + f"{result.error.type}: {result.error.message}" + ) + if result.provider_event_created: + print(" The provider created this event anyway. Don't retry it.") + + +def run_demo(client, grant_id, calendar_id): + """Create two events, rename one of them, and then delete both.""" + start = int(time.time()) + 24 * 60 * 60 + create_operations = [ + { + "method": "create", + "body": { + "title": "Batch demo: standup", + "when": {"start_time": start, "end_time": start + 30 * 60}, + }, + }, + { + "method": "create", + "body": { + "title": "Batch demo: retro", + "when": {"start_time": start + 60 * 60, "end_time": start + 90 * 60}, + }, + }, + ] + + print("Creating two events in one batch...") + results = run_batch(client, grant_id, calendar_id, create_operations) + print_results(create_operations, results) + event_ids = [result.data.id for result in results if result.data is not None] + if not event_ids: + return + + try: + change_operations = [ + { + "method": "update", + "event_id": event_ids[0], + "body": {"title": "Batch demo: renamed standup"}, + }, + {"method": "delete", "event_id": "batch-demo-missing-event"}, + ] + print("\nRenaming an event and deleting an event that doesn't exist...") + results = run_batch(client, grant_id, calendar_id, change_operations) + print_results(change_operations, results) + finally: + delete_operations = [ + {"method": "delete", "event_id": event_id} for event_id in event_ids + ] + print("\nDeleting the created events in one batch...") + results = run_batch(client, grant_id, calendar_id, delete_operations) + print_results(delete_operations, results) + + +def main() -> None: + """Run the batch example.""" + api_key = get_env_or_exit("NYLAS_API_KEY") + grant_id = get_env_or_exit("NYLAS_GRANT_ID") + calendar_id = os.getenv("NYLAS_CALENDAR_ID", "primary") + + client = Client( + api_key=api_key, + api_uri=os.getenv("NYLAS_API_URI", "https://api.us.nylas.com"), + ) + + try: + run_demo(client, grant_id, calendar_id) + except NylasApiError as error: + # events.batch() raises only when the API rejects the whole request, + # for example with HTTP 400 for an invalid batch or an unsupported provider. + print( + f"Error: {error} (HTTP {error.status_code}, request ID {error.request_id})" + ) + sys.exit(1) + + +if __name__ == "__main__": + main() diff --git a/nylas/models/events_batch.py b/nylas/models/events_batch.py new file mode 100644 index 0000000..68cd51e --- /dev/null +++ b/nylas/models/events_batch.py @@ -0,0 +1,113 @@ +from dataclasses import dataclass +from typing import List, Literal, Optional, Union + +from dataclasses_json import dataclass_json +from typing_extensions import TypedDict, NotRequired + +from nylas.models.errors import NylasApiErrorResponseData +from nylas.models.events import ( + CreateEventQueryParams, + CreateEventRequest, + Event, + UpdateEventRequest, +) + + +class BatchCreateEventOperation(TypedDict): + """ + Interface representing a batch operation that creates an event. + + Attributes: + method: The operation to run. Always "create". + body: The values to create the event with. + """ + + method: Literal["create"] + body: CreateEventRequest + + +class BatchUpdateEventOperation(TypedDict): + """ + Interface representing a batch operation that updates an event. + + Attributes: + method: The operation to run. Always "update". + event_id: The ID of the event to update. + body: The values to update the event with. + """ + + method: Literal["update"] + event_id: str + body: UpdateEventRequest + + +class BatchDeleteEventOperation(TypedDict): + """ + Interface representing a batch operation that deletes an event. + + Attributes: + method: The operation to run. Always "delete". + event_id: The ID of the event to delete. + """ + + method: Literal["delete"] + event_id: str + + +BatchEventOperation = Union[ + BatchCreateEventOperation, BatchUpdateEventOperation, BatchDeleteEventOperation +] +""" Union type representing the operations that a batch request can run. """ + + +class BatchEventsRequest(TypedDict): + """ + Interface representing a request to run a batch of event operations. + + Attributes: + operations: The operations to run. + """ + + operations: List[BatchEventOperation] + + +class BatchEventsQueryParams(CreateEventQueryParams): + """ + Interface representing the query parameters for a batch of event operations. + The query parameters apply to every operation in the batch. + + Attributes: + calendar_id: The ID of the calendar that every operation in the batch acts on. + notify_participants: Whether to send email notifications containing the calendar event to all + event participants. Defaults to true. Microsoft does not support setting this to false. + tentative_as_busy: When set to false, treats tentative calendar events as busy:false. + Only applicable for Microsoft calendars. Defaults to true. + grant_email: The email address of the grant. Create operations default to the grant's email address. + select: Comma-separated list of fields to return in the event data of each result. + """ + + grant_email: NotRequired[str] + select: NotRequired[str] + + +@dataclass_json +@dataclass +class BatchEventResult: + """ + Class representation of the result of one operation in a batch. + + Attributes: + status: The HTTP status code of the operation. + data: The created or updated event. Not set for delete operations or for failed operations. + error: The error details. Only set if the operation failed. + retry_after: The number of seconds to wait before retrying the operation. Can be 0. + Only set on failed operations, when the provider throttled the request. + provider_event_created: True if the provider created the event before a later step failed. + Retrying the operation would create a duplicate event. + """ + + status: int + data: Optional[Event] = None + error: Optional[NylasApiErrorResponseData] = None + retry_after: Optional[int] = None + provider_event_created: Optional[bool] = None diff --git a/nylas/resources/events.py b/nylas/resources/events.py index 3b9223a..e9eb2dd 100644 --- a/nylas/resources/events.py +++ b/nylas/resources/events.py @@ -1,3 +1,5 @@ +from typing import List + from nylas.config import RequestOverrides from nylas.handler.api_resources import ( ListableApiResource, @@ -19,6 +21,11 @@ SendRsvpQueryParams, SendRsvpRequest, ) +from nylas.models.events_batch import ( + BatchEventsRequest, + BatchEventsQueryParams, + BatchEventResult, +) from nylas.models.response import ( Response, ListResponse, @@ -234,3 +241,45 @@ def send_rsvp( ) return RequestIdOnlyResponse.from_dict(json_response, headers) + + def batch( + self, + identifier: str, + request_body: BatchEventsRequest, + query_params: BatchEventsQueryParams, + overrides: RequestOverrides = None, + ) -> Response[List[BatchEventResult]]: + """ + Create, update, and delete Events in a single request. + Only Google and Microsoft grants support batch operations. + + The response has one result for each operation, in the same order as the operations. + If some or all of the operations fail, the API returns HTTP 207 and this method still + returns the results, so check the status and error of each result. + If the request itself is invalid, the API returns HTTP 400, runs none of the operations, + and this method raises a NylasApiError. + + Args: + identifier: The identifier of the Grant to act upon. + request_body: The operations to run. + query_params: The query parameters to include in the request. They apply to every operation. + overrides: The request overrides to use for the request. + + Returns: + The result of each operation. + """ + json_response, headers = self._http_client._execute( + "POST", + f"/v3/grants/{identifier}/events/batch", + None, + query_params, + request_body, + overrides=overrides, + ) + + results = [ + BatchEventResult.from_dict(item, infer_missing=True) + for item in json_response["data"] + ] + + return Response(results, json_response["request_id"], headers) diff --git a/tests/handler/test_http_client.py b/tests/handler/test_http_client.py index 7564e23..6836e7a 100644 --- a/tests/handler/test_http_client.py +++ b/tests/handler/test_http_client.py @@ -236,6 +236,25 @@ def test_validate_response(self): assert response_json == {"foo": "bar"} assert response_headers == {"X-Test-Header": "test"} + def test_validate_response_207_multi_status(self): + response = Mock() + response.status_code = 207 + response.json.return_value = { + "request_id": "123", + "data": [ + { + "status": 404, + "error": {"type": "not_found_error", "message": "Not found."}, + } + ], + } + response.url = "https://test.nylas.com/v3/grants/abc-123/events/batch" + response.headers = {"X-Test-Header": "test"} + + response_json, response_headers = _validate_response(response) + assert response_json == response.json.return_value + assert response_headers == {"X-Test-Header": "test"} + def test_validate_response_400_error(self): response = Mock() response.status_code = 400 diff --git a/tests/resources/test_events.py b/tests/resources/test_events.py index fdcee6d..f885b50 100644 --- a/tests/resources/test_events.py +++ b/tests/resources/test_events.py @@ -1,5 +1,16 @@ +import json +from unittest.mock import Mock, patch + +import pytest + from nylas.resources.events import Events +from nylas.models.errors import NylasApiError from nylas.models.events import Event +from nylas.models.events_batch import ( + BatchCreateEventOperation, + BatchUpdateEventOperation, + BatchDeleteEventOperation, +) class TestEvent: @@ -879,3 +890,336 @@ def test_update_event_with_partial_resource(self, http_client_response): request_body, overrides=None, ) + + +BATCH_OPERATIONS = [ + { + "method": "create", + "body": { + "title": "Standup", + "when": {"start_time": 1798794000, "end_time": 1798795800}, + }, + }, + {"method": "update", "event_id": "event-1", "body": {"title": "Renamed"}}, + {"method": "delete", "event_id": "event-2"}, +] + + +def _event_json(event_id, title): + return { + "id": event_id, + "grant_id": "abc-123", + "calendar_id": "primary", + "busy": True, + "participants": [], + "when": { + "start_time": 1798794000, + "end_time": 1798795800, + "object": "timespan", + }, + "title": title, + "object": "event", + } + + +def _http_response(status_code, body): + response = Mock() + response.status_code = status_code + response.json.return_value = body + response.headers = {"X-Test-Header": "test"} + response.url = "https://test.nylas.com/v3/grants/abc-123/events/batch" + return response + + +class TestEventBatch: + def _batch(self, http_client, status_code, body, operations=None): + events = Events(http_client) + with patch("requests.request", return_value=_http_response(status_code, body)): + return events.batch( + identifier="abc-123", + request_body={"operations": operations or BATCH_OPERATIONS}, + query_params={"calendar_id": "primary"}, + ) + + def test_batch_events_request(self, http_client): + events = Events(http_client) + body = {"request_id": "req-123", "data": [{"status": 200}] * 3} + + with patch( + "requests.request", return_value=_http_response(200, body) + ) as mock_request: + events.batch( + identifier="abc-123", + request_body={"operations": BATCH_OPERATIONS}, + query_params={ + "calendar_id": "primary", + "notify_participants": False, + "select": "id,title", + }, + overrides={"timeout": 60}, + ) + + mock_request.assert_called_once() + method, url = mock_request.call_args.args + assert method == "POST" + assert url == ( + "https://test.nylas.com/v3/grants/abc-123/events/batch" + "?calendar_id=primary¬ify_participants=False&select=id%2Ctitle" + ) + assert ( + mock_request.call_args.kwargs["headers"]["Content-type"] + == "application/json" + ) + assert mock_request.call_args.kwargs["timeout"] == 60 + assert json.loads(mock_request.call_args.kwargs["data"]) == { + "operations": [ + { + "method": "create", + "body": { + "title": "Standup", + "when": {"start_time": 1798794000, "end_time": 1798795800}, + }, + }, + { + "method": "update", + "event_id": "event-1", + "body": {"title": "Renamed"}, + }, + {"method": "delete", "event_id": "event-2"}, + ] + } + + def test_batch_events_all_succeeded(self, http_client): + response = self._batch( + http_client, + 200, + { + "request_id": "req-123", + "data": [ + {"status": 200, "data": _event_json("new-event", "Standup")}, + {"status": 200, "data": _event_json("event-1", "Renamed")}, + {"status": 200}, + ], + }, + ) + + assert response.request_id == "req-123" + assert response.headers == {"X-Test-Header": "test"} + created, updated, deleted = response.data + assert created.status == 200 + assert isinstance(created.data, Event) + assert created.data.id == "new-event" + assert created.data.title == "Standup" + assert created.data.when.start_time == 1798794000 + assert created.error is None + assert updated.status == 200 + assert isinstance(updated.data, Event) + assert updated.data.id == "event-1" + assert updated.data.title == "Renamed" + assert updated.error is None + assert deleted.status == 200 + assert deleted.data is None + assert deleted.error is None + + def test_batch_events_multi_status_returns_results(self, http_client): + response = self._batch( + http_client, + 207, + { + "request_id": "req-123", + "data": [ + { + "status": 500, + "error": { + "type": "api_error", + "message": "Failed to save the event metadata.", + }, + "provider_event_created": True, + }, + { + "status": 429, + "error": { + "type": "rate_limit_error", + "message": "Too many requests.", + "provider_error": {"error": {"code": 429}}, + }, + "retry_after": 30, + }, + {"status": 200}, + ], + }, + ) + + assert response.request_id == "req-123" + created, updated, deleted = response.data + assert created.status == 500 + assert created.data is None + assert created.error.type == "api_error" + assert created.error.message == "Failed to save the event metadata." + assert created.provider_event_created is True + assert created.retry_after is None + assert updated.status == 429 + assert updated.data is None + assert updated.error.type == "rate_limit_error" + assert updated.error.message == "Too many requests." + assert updated.error.provider_error == {"error": {"code": 429}} + assert updated.retry_after == 30 + assert updated.provider_event_created is None + assert deleted.status == 200 + assert deleted.error is None + + def test_batch_events_multi_status_all_failed_returns_results(self, http_client): + response = self._batch( + http_client, + 207, + { + "request_id": "req-123", + "data": [ + { + "status": 503, + "error": { + "type": "internal_error", + "message": "Not attempted. It is safe to retry.", + }, + }, + { + "status": 404, + "error": { + "type": "not_found_error", + "message": "Event not found.", + }, + }, + { + "status": 404, + "error": { + "type": "not_found_error", + "message": "Event not found.", + }, + }, + ], + }, + ) + + assert [result.status for result in response.data] == [503, 404, 404] + assert all(result.data is None for result in response.data) + assert response.data[0].error.type == "internal_error" + assert response.data[1].error.type == "not_found_error" + assert response.data[2].error.type == "not_found_error" + + def test_batch_events_retry_after_zero(self, http_client): + response = self._batch( + http_client, + 207, + { + "request_id": "req-123", + "data": [ + { + "status": 429, + "error": { + "type": "rate_limit_error", + "message": "Too many requests.", + }, + "retry_after": 0, + } + ], + }, + operations=[{"method": "delete", "event_id": "event-2"}], + ) + + assert response.data[0].retry_after is not None + assert response.data[0].retry_after == 0 + + def test_batch_events_invalid_request_raises_api_error(self, http_client): + events = Events(http_client) + operations = [ + {"method": "delete", "event_id": f"event-{index}"} for index in range(51) + ] + body = { + "request_id": "req-123", + "error": { + "type": "invalid_request_error", + "message": "operations cannot exceed 50", + }, + } + + with patch( + "requests.request", return_value=_http_response(400, body) + ) as mock_request: + with pytest.raises(NylasApiError) as error: + events.batch( + identifier="abc-123", + request_body={"operations": operations}, + query_params={"calendar_id": "primary"}, + ) + + mock_request.assert_called_once() + assert error.value.status_code == 400 + assert error.value.request_id == "req-123" + assert error.value.type == "invalid_request_error" + assert str(error.value) == "operations cannot exceed 50" + + def test_batch_events_results_match_operation_order(self, http_client): + operations = [ + {"method": "delete", "event_id": "event-2"}, + {"method": "update", "event_id": "event-1", "body": {"title": "Renamed"}}, + {"method": "delete", "event_id": "event-3"}, + {"method": "create", "body": BATCH_OPERATIONS[0]["body"]}, + ] + + response = self._batch( + http_client, + 207, + { + "request_id": "req-123", + "data": [ + {"status": 200}, + {"status": 200, "data": _event_json("event-1", "Renamed")}, + { + "status": 404, + "error": { + "type": "not_found_error", + "message": "Event event-3 not found.", + }, + }, + {"status": 200, "data": _event_json("new-event", "Standup")}, + ], + }, + operations=operations, + ) + + assert len(response.data) == len(operations) + assert response.data[0].status == 200 + assert response.data[0].data is None + assert response.data[1].data.id == "event-1" + assert response.data[2].error.message == "Event event-3 not found." + assert response.data[3].data.id == "new-event" + + @pytest.mark.filterwarnings("ignore:Missing value of non-optional type") + def test_batch_events_with_select_returns_partial_events(self, http_client): + response = self._batch( + http_client, + 200, + { + "request_id": "req-123", + "data": [ + {"status": 200, "data": {"id": "new-event", "title": "Standup"}} + ], + }, + operations=[BATCH_OPERATIONS[0]], + ) + + assert isinstance(response.data[0].data, Event) + assert response.data[0].data.id == "new-event" + assert response.data[0].data.title == "Standup" + assert response.data[0].data.when is None + + def test_batch_operation_types_require_event_id_and_body(self): + assert BatchCreateEventOperation.__required_keys__ == frozenset( + {"method", "body"} + ) + assert BatchUpdateEventOperation.__required_keys__ == frozenset( + {"method", "event_id", "body"} + ) + assert BatchDeleteEventOperation.__required_keys__ == frozenset( + {"method", "event_id"} + )