From 165b093b2f12e6e001f285fd7ad0f90c40a1aa69 Mon Sep 17 00:00:00 2001 From: Gordan Ovcaric Date: Wed, 4 Nov 2026 17:09:23 +0100 Subject: [PATCH] TT-5543: JAVA SDK support for Events batch operations --- CHANGELOG.md | 1 + examples/.env.example | 3 + examples/README.md | 20 ++ .../nylas/examples/BatchEventsExample.java | 128 ++++++++++ .../com/nylas/models/BatchEventOperation.kt | 70 ++++++ .../nylas/models/BatchEventsQueryParams.kt | 90 +++++++ .../com/nylas/models/BatchEventsRequest.kt | 14 ++ .../com/nylas/models/BatchEventsResponse.kt | 54 ++++ src/main/kotlin/com/nylas/resources/Events.kt | 21 ++ .../kotlin/com/nylas/resources/EventsTests.kt | 238 ++++++++++++++++++ 10 files changed, 639 insertions(+) create mode 100644 examples/src/main/java/com/nylas/examples/BatchEventsExample.java create mode 100644 src/main/kotlin/com/nylas/models/BatchEventOperation.kt create mode 100644 src/main/kotlin/com/nylas/models/BatchEventsQueryParams.kt create mode 100644 src/main/kotlin/com/nylas/models/BatchEventsRequest.kt create mode 100644 src/main/kotlin/com/nylas/models/BatchEventsResponse.kt diff --git a/CHANGELOG.md b/CHANGELOG.md index b948cce3..405d3888 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,7 @@ ### Added * Contact metadata request/response models and `metadata_pair` filtering. * `contact.updated` and `contact.deleted` webhook trigger constants with iCloud and Yahoo compatibility documentation. +* Added Events batch endpoint (Google and Microsoft): `Events.batch()` runs multiple event create, update and delete operations in one `POST /v3/grants/{grant_id}/events/batch` request. A 207 Multi-Status response is returned, not thrown; check each result's `status` and `error`. ## [v2.18.1] - Release 2026-08-18 diff --git a/examples/.env.example b/examples/.env.example index fc2533cd..ffd17e67 100644 --- a/examples/.env.example +++ b/examples/.env.example @@ -14,6 +14,9 @@ NYLAS_API_URI=https://api.us.nylas.com # You can get this from your Nylas Dashboard after connecting an account NYLAS_GRANT_ID=your_grant_id_here +# An existing event ID to update (batch events example) +NYLAS_EVENT_ID=your_event_id_here + # Test email NYLAS_TEST_EMAIL=your@email.com diff --git a/examples/README.md b/examples/README.md index 09090c21..c82aff40 100644 --- a/examples/README.md +++ b/examples/README.md @@ -22,6 +22,16 @@ The `EventsExample` demonstrates how to use the Nylas Java/Kotlin SDK to interac - Filter events by date range - Show event details +### Batch Events Example + +The `BatchEventsExample` demonstrates the Events batch endpoint (Google and Microsoft only): + +- Create, update and delete events in one request +- Loop over per-operation results (a 207 response is returned, not thrown) +- Retry throttled items (`429`/`503`) after `retry_after`, and never retry items with `provider_event_created: true` + +Requires `NYLAS_API_KEY`, `NYLAS_GRANT_ID` and `NYLAS_EVENT_ID` (an existing event to update). `NYLAS_CALENDAR_ID` is optional and defaults to `primary`. + ### Notetaker Example The `NotetakerExample` demonstrates how to use the Nylas Java/Kotlin SDK to interact with the Notetakers API: @@ -82,6 +92,9 @@ NYLAS_API_KEY=your_api_key_here # Your grant ID (required for message examples) NYLAS_GRANT_ID=your_grant_id_here +# An existing event ID to update (batch events example) +NYLAS_EVENT_ID=your_event_id_here + # Test email address (required for large attachments example) NYLAS_TEST_EMAIL=test@example.com @@ -112,6 +125,11 @@ Run Java Events example: ./gradlew :examples:run -PmainClass=com.nylas.examples.EventsExample ``` +Run Java Batch Events example: +```bash +./gradlew :examples:run -PmainClass=com.nylas.examples.BatchEventsExample +``` + Run Java Notetaker example: ```bash ./gradlew :examples:run -PmainClass=com.nylas.examples.NotetakerExample @@ -170,6 +188,7 @@ make kotlin-way - `MessagesExample.java` (Java - demonstrates new message features) - `KotlinMessagesExample.kt` (Kotlin - demonstrates new message features) - `EventsExample.java` (Java - demonstrates events) + - `BatchEventsExample.java` (Java - demonstrates the Events batch endpoint) - `FoldersExample.java` (Java - demonstrates folders and single_level parameter) - `LargeAttachmentsExample.java` (Java - demonstrates large file attachments) - `CustomTrackingDomainExample.java` (Java - demonstrates custom link and open tracking hostnames) @@ -191,6 +210,7 @@ examples/ │ └── com/nylas/examples/ │ ├── MessagesExample.java # NEW: Message features demo │ ├── EventsExample.java # Events API demo + │ ├── BatchEventsExample.java # Events batch endpoint demo │ ├── FoldersExample.java # NEW: Folders API demo with single_level parameter │ ├── LargeAttachmentsExample.java # NEW: Large file attachments demo │ └── NotetakerExample.java # Notetaker API demo diff --git a/examples/src/main/java/com/nylas/examples/BatchEventsExample.java b/examples/src/main/java/com/nylas/examples/BatchEventsExample.java new file mode 100644 index 00000000..3092a6bc --- /dev/null +++ b/examples/src/main/java/com/nylas/examples/BatchEventsExample.java @@ -0,0 +1,128 @@ +package com.nylas.examples; + +import com.nylas.NylasClient; +import com.nylas.models.BatchEventOperation; +import com.nylas.models.BatchEventResult; +import com.nylas.models.BatchEventsQueryParams; +import com.nylas.models.BatchEventsRequest; +import com.nylas.models.BatchEventsResponse; +import com.nylas.models.CreateEventRequest; +import com.nylas.models.NylasApiError; +import com.nylas.models.UpdateEventRequest; +import okhttp3.OkHttpClient; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * Runs several event operations in one request with the Events batch endpoint (Google and Microsoft only). + * + * Reads configuration from environment variables, then from examples/.env or .env. + * Required: NYLAS_API_KEY, NYLAS_GRANT_ID, NYLAS_EVENT_ID (an existing event to update). + * Optional: NYLAS_CALENDAR_ID (defaults to "primary"), NYLAS_API_URI. + */ +public class BatchEventsExample { + private static final int MAX_ATTEMPTS = 3; + private static final double DEFAULT_RETRY_SECONDS = 1.0; + + public static void main(String[] args) throws Exception { + Map config = loadConfig(); + NylasClient nylas = new NylasClient( + require(config, "NYLAS_API_KEY"), + new OkHttpClient.Builder(), + config.getOrDefault("NYLAS_API_URI", "https://api.us.nylas.com") + ); + String grantId = require(config, "NYLAS_GRANT_ID"); + String eventId = require(config, "NYLAS_EVENT_ID"); + BatchEventsQueryParams queryParams = + new BatchEventsQueryParams.Builder(config.getOrDefault("NYLAS_CALENDAR_ID", "primary")).build(); + + long start = System.currentTimeMillis() / 1000L + 60 * 60 * 24; + List operations = Arrays.asList( + BatchEventOperation.create(new CreateEventRequest.Builder( + new CreateEventRequest.When.Timespan.Builder((int) start, (int) start + 1800).build() + ).title("Batch standup").build()), + BatchEventOperation.update(eventId, new UpdateEventRequest.Builder().title("Renamed by batch").build()), + BatchEventOperation.delete("event-id-that-does-not-exist") + ); + + try { + for (int attempt = 1; attempt <= MAX_ATTEMPTS && !operations.isEmpty(); attempt++) { + // A 207 (some or all operations failed) is returned, not thrown. + // Any other non-2xx status for the whole call (e.g. 400 for an invalid batch) throws NylasApiError. + BatchEventsResponse response = nylas.events().batch(grantId, new BatchEventsRequest(operations), queryParams); + System.out.println("Attempt " + attempt + " (request_id " + response.getRequestId() + "):"); + + List retry = new ArrayList<>(); + double waitSeconds = 0; + + // data.get(i) is the result of operations.get(i). + for (int i = 0; i < response.getData().size(); i++) { + BatchEventResult result = response.getData().get(i); + if (result.getError() == null) { + System.out.println(" " + i + ": OK " + result.getStatus() + + (result.getData() != null ? " event " + result.getData().getId() : "")); + continue; + } + System.out.println(" " + i + ": FAILED " + result.getStatus() + " " + result.getError().getMessage()); + + // Never retry an item the provider already created: retrying would create a duplicate event. + if (Boolean.TRUE.equals(result.getProviderEventCreated())) { + System.out.println(" not retrying: the provider already created this event"); + continue; + } + if (result.getStatus() == 429 || result.getStatus() == 503) { + retry.add(operations.get(i)); + double retryAfter = result.getRetryAfter() != null ? result.getRetryAfter() : DEFAULT_RETRY_SECONDS; + waitSeconds = Math.max(waitSeconds, retryAfter); + } + } + + if (!retry.isEmpty() && attempt < MAX_ATTEMPTS) { + System.out.println("Retrying " + retry.size() + " throttled operation(s) after " + waitSeconds + "s"); + Thread.sleep((long) (waitSeconds * 1000)); + } + operations = retry; + } + } catch (NylasApiError e) { + System.out.println("Batch request failed (HTTP " + e.getStatusCode() + "): " + e.getMessage() + + " request_id=" + e.getRequestId()); + } + } + + private static Map loadConfig() { + Map config = new HashMap<>(System.getenv()); + for (String path : Arrays.asList("examples/.env", ".env")) { + File envFile = new File(path); + if (!envFile.exists()) { + continue; + } + try { + for (String line : Files.readAllLines(envFile.toPath())) { + String[] parts = line.split("=", 2); + if (parts.length == 2 && !line.trim().startsWith("#")) { + config.putIfAbsent(parts[0].trim(), parts[1].trim()); + } + } + } catch (IOException e) { + System.out.println("Warning: failed to read " + path + ": " + e.getMessage()); + } + } + return config; + } + + private static String require(Map config, String key) { + String value = config.get(key); + if (value == null || value.isEmpty()) { + throw new IllegalArgumentException( + "Missing required configuration: " + key + ". Set it in examples/.env or as an environment variable."); + } + return value; + } +} diff --git a/src/main/kotlin/com/nylas/models/BatchEventOperation.kt b/src/main/kotlin/com/nylas/models/BatchEventOperation.kt new file mode 100644 index 00000000..2d0bf2d1 --- /dev/null +++ b/src/main/kotlin/com/nylas/models/BatchEventOperation.kt @@ -0,0 +1,70 @@ +package com.nylas.models + +import com.squareup.moshi.Json + +/** + * Class representation of a single operation in an events batch request. + * + * Use the [create], [update] and [delete] factory methods to build an operation, + * so that each operation always carries the fields its method requires. + */ +class BatchEventOperation private constructor( + /** + * The operation to run. + */ + @Json(name = "method") + val method: BatchEventMethod, + /** + * The ID of the event to update or delete. Null for create operations. + */ + @Json(name = "event_id") + val eventId: String? = null, + /** + * The request body: a [CreateEventRequest] for create operations, + * an [UpdateEventRequest] for update operations, and null for delete operations. + * Typed as Any? so one field holds either request type; the factory methods keep it type-safe. + */ + @Json(name = "body") + val body: Any? = null, +) { + companion object { + /** + * Build a create operation. + * @param requestBody The values to create the event with + * @return The create operation + */ + @JvmStatic + fun create(requestBody: CreateEventRequest) = BatchEventOperation(BatchEventMethod.CREATE, body = requestBody) + + /** + * Build an update operation. + * @param eventId The ID of the event to update + * @param requestBody The values to update the event with + * @return The update operation + */ + @JvmStatic + fun update(eventId: String, requestBody: UpdateEventRequest) = BatchEventOperation(BatchEventMethod.UPDATE, eventId, requestBody) + + /** + * Build a delete operation. + * @param eventId The ID of the event to delete + * @return The delete operation + */ + @JvmStatic + fun delete(eventId: String) = BatchEventOperation(BatchEventMethod.DELETE, eventId) + } +} + +/** + * Enum representation of the operations supported in an events batch request. + */ +enum class BatchEventMethod { + @Json(name = "create") + CREATE, + + @Json(name = "update") + UPDATE, + + @Json(name = "delete") + DELETE, +} diff --git a/src/main/kotlin/com/nylas/models/BatchEventsQueryParams.kt b/src/main/kotlin/com/nylas/models/BatchEventsQueryParams.kt new file mode 100644 index 00000000..ee47b0cd --- /dev/null +++ b/src/main/kotlin/com/nylas/models/BatchEventsQueryParams.kt @@ -0,0 +1,90 @@ +package com.nylas.models + +import com.squareup.moshi.Json + +/** + * Class representation of the query parameters for an events batch request. + * These apply to every operation in the batch. + */ +data class BatchEventsQueryParams( + /** + * The ID of the calendar the operations run against. + */ + @Json(name = "calendar_id") + val calendarId: String, + /** + * Whether to send email notifications to all event participants. + * Microsoft accounts do not support notify_participants = False. + */ + @Json(name = "notify_participants") + val notifyParticipants: Boolean? = null, + /** + * The email address of the grant. + */ + @Json(name = "grant_email") + val grantEmail: String? = null, + /** + * When true, tentative events are counted as busy. + */ + @Json(name = "tentative_as_busy") + val tentativeAsBusy: Boolean? = null, + /** + * Comma-separated list of fields to return for each event. + */ + @Json(name = "select") + val select: String? = null, +) : IQueryParams { + /** + * Builder for [BatchEventsQueryParams]. + * @property calendarId The ID of the calendar the operations run against. + */ + data class Builder( + private val calendarId: String, + ) { + private var notifyParticipants: Boolean? = null + private var grantEmail: String? = null + private var tentativeAsBusy: Boolean? = null + private var select: String? = null + + /** + * Sets whether to send email notifications to all event participants. + * Microsoft accounts do not support notify_participants = False. + * @param notifyParticipants Whether to send email notifications. + * @return The builder. + */ + fun notifyParticipants(notifyParticipants: Boolean?) = apply { this.notifyParticipants = notifyParticipants } + + /** + * Sets the email address of the grant. + * @param grantEmail The email address of the grant. + * @return The builder. + */ + fun grantEmail(grantEmail: String?) = apply { this.grantEmail = grantEmail } + + /** + * Sets whether tentative events are counted as busy. + * @param tentativeAsBusy Whether tentative events are counted as busy. + * @return The builder. + */ + fun tentativeAsBusy(tentativeAsBusy: Boolean?) = apply { this.tentativeAsBusy = tentativeAsBusy } + + /** + * Sets the comma-separated list of fields to return for each event. + * @param select The fields to return. + * @return The builder. + */ + fun select(select: String?) = apply { this.select = select } + + /** + * Builds a [BatchEventsQueryParams] instance. + * @return The [BatchEventsQueryParams] instance. + */ + fun build() = BatchEventsQueryParams( + calendarId, + notifyParticipants, + grantEmail, + tentativeAsBusy, + select, + ) + } +} diff --git a/src/main/kotlin/com/nylas/models/BatchEventsRequest.kt b/src/main/kotlin/com/nylas/models/BatchEventsRequest.kt new file mode 100644 index 00000000..216706e0 --- /dev/null +++ b/src/main/kotlin/com/nylas/models/BatchEventsRequest.kt @@ -0,0 +1,14 @@ +package com.nylas.models + +import com.squareup.moshi.Json + +/** + * Class representation of a Nylas events batch request. + */ +data class BatchEventsRequest( + /** + * The operations to run. Results are returned in the same order. + */ + @Json(name = "operations") + val operations: List, +) diff --git a/src/main/kotlin/com/nylas/models/BatchEventsResponse.kt b/src/main/kotlin/com/nylas/models/BatchEventsResponse.kt new file mode 100644 index 00000000..f641f46a --- /dev/null +++ b/src/main/kotlin/com/nylas/models/BatchEventsResponse.kt @@ -0,0 +1,54 @@ +package com.nylas.models + +import com.squareup.moshi.Json + +/** + * Class representation of a Nylas events batch response. + * Returned for both 200 (all operations succeeded) and 207 (at least one operation failed) responses. + */ +data class BatchEventsResponse( + /** + * The results, one per operation, in the same order as the request operations. + */ + @Json(name = "data") + val data: List = emptyList(), + /** + * The request ID. + */ + @Json(name = "request_id") + val requestId: String = "", +) + +/** + * Class representation of the result of a single operation in an events batch request. + */ +data class BatchEventResult( + /** + * The HTTP status of this operation. + */ + @Json(name = "status") + val status: Int, + /** + * The created or updated event. Null for delete operations and failed operations. + */ + @Json(name = "data") + val data: Event? = null, + /** + * The error, if this operation failed. + * Only [NylasApiError.type], [NylasApiError.message] and [NylasApiError.providerError] are set; + * use [status] for this operation's HTTP status and [BatchEventsResponse.requestId] for the request ID. + */ + @Json(name = "error") + val error: NylasApiError? = null, + /** + * Seconds to wait before retrying, if the provider throttled this operation. + */ + @Json(name = "retry_after") + val retryAfter: Double? = null, + /** + * True if the provider created the event before a later step failed. + * Retrying this operation would create a duplicate event. + */ + @Json(name = "provider_event_created") + val providerEventCreated: Boolean? = null, +) diff --git a/src/main/kotlin/com/nylas/resources/Events.kt b/src/main/kotlin/com/nylas/resources/Events.kt index 7a303079..facb5c52 100644 --- a/src/main/kotlin/com/nylas/resources/Events.kt +++ b/src/main/kotlin/com/nylas/resources/Events.kt @@ -109,6 +109,27 @@ class Events(client: NylasClient) : Resource(client, Event::class.java) { return destroyResourceEncoded(path, queryParams, overrides) } + /** + * Run multiple event create, update and delete operations in one request. + * Supported for Google and Microsoft grants. + * + * A 207 response (one or more operations failed) is returned, not thrown. + * Check each result's [BatchEventResult.status] and [BatchEventResult.error]. + * @param identifier The identifier of the grant to act upon + * @param requestBody The operations to run + * @param queryParams The query parameters to include in the request, applied to every operation + * @param overrides Optional request overrides to apply + * @return The results, in the same order as the operations + */ + @Throws(NylasApiError::class, NylasSdkTimeoutError::class) + @JvmOverloads + fun batch(identifier: String, requestBody: BatchEventsRequest, queryParams: BatchEventsQueryParams, overrides: RequestOverrides? = null): BatchEventsResponse { + val path = String.format("v3/grants/%s/events/batch", PathEncoder.encode(identifier)) + val adapter = JsonHelper.moshi().adapter(BatchEventsRequest::class.java) + val serializedRequestBody = adapter.toJson(requestBody) + return client.executePostEncoded(path, BatchEventsResponse::class.java, serializedRequestBody, queryParams, overrides) + } + /** * Send RSVP. Allows users to respond to events they have been added to as an attendee. * @param identifier The identifier of the grant to act upon diff --git a/src/test/kotlin/com/nylas/resources/EventsTests.kt b/src/test/kotlin/com/nylas/resources/EventsTests.kt index 76c9360a..6e784453 100644 --- a/src/test/kotlin/com/nylas/resources/EventsTests.kt +++ b/src/test/kotlin/com/nylas/resources/EventsTests.kt @@ -6,6 +6,8 @@ import com.nylas.models.Response import com.nylas.util.JsonHelper import com.squareup.moshi.Types import okhttp3.* +import okhttp3.MediaType.Companion.toMediaType +import okhttp3.ResponseBody.Companion.toResponseBody import okio.Buffer import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Nested @@ -15,6 +17,7 @@ import org.mockito.kotlin.* import java.lang.reflect.Type import kotlin.test.Test import kotlin.test.assertEquals +import kotlin.test.assertFailsWith import kotlin.test.assertFalse import kotlin.test.assertIs import kotlin.test.assertNull @@ -1653,4 +1656,239 @@ class EventsTests { assertEquals(false, params.notifyParticipants) } } + + @Nested + inner class BatchTests { + private val grantId = "abc-123-grant-id" + private val requests = mutableListOf() + + // Real NylasClient with an interceptor that returns a canned response, so status handling + // (200/207/400) runs through the real client code instead of a mocked isSuccessful. + private fun eventsReturning(code: Int, body: String): Events { + val httpClientBuilder = OkHttpClient.Builder().addInterceptor { chain -> + requests.add(chain.request()) + okhttp3.Response.Builder() + .request(chain.request()) + .protocol(Protocol.HTTP_1_1) + .code(code) + .message("") + .body(body.toResponseBody("application/json".toMediaType())) + .build() + } + return Events(NylasClient("test-api-key", httpClientBuilder)) + } + + private val createRequest = CreateEventRequest( + whenObj = CreateEventRequest.When.Timespan(startTime = 1798794000, endTime = 1798795800), + title = "Standup", + ) + + // colorId = Clear checks that an explicit null still reaches the wire through the batch body. + private val updateRequest = UpdateEventRequest(title = "Renamed", colorId = NullableField.Clear) + private val batchRequest = BatchEventsRequest( + listOf( + BatchEventOperation.create(createRequest), + BatchEventOperation.update("EVENT_ID_1", updateRequest), + BatchEventOperation.delete("EVENT_ID_2"), + ), + ) + + @Test + fun `batch sends POST to the batch path with query params and snake_case body`() { + val events = eventsReturning(200, """{"request_id":"req-1","data":[]}""") + val queryParams = BatchEventsQueryParams.Builder("primary") + .notifyParticipants(false) + .grantEmail("user@example.com") + .tentativeAsBusy(true) + .select("id,title") + .build() + + events.batch(grantId, batchRequest, queryParams) + + val request = requests.single() + assertEquals("POST", request.method) + assertEquals("/v3/grants/$grantId/events/batch", request.url.encodedPath) + assertEquals( + setOf("calendar_id", "notify_participants", "grant_email", "tentative_as_busy", "select"), + request.url.queryParameterNames, + ) + assertEquals("primary", request.url.queryParameter("calendar_id")) + assertEquals("false", request.url.queryParameter("notify_participants")) + assertEquals("user@example.com", request.url.queryParameter("grant_email")) + assertEquals("true", request.url.queryParameter("tentative_as_busy")) + assertEquals("id,title", request.url.queryParameter("select")) + + val body = Buffer().also { request.body!!.writeTo(it) }.readUtf8() + val createJson = JsonHelper.moshi().adapter(CreateEventRequest::class.java).toJson(createRequest) + val updateJson = JsonHelper.moshi().adapter(UpdateEventRequest::class.java).toJson(updateRequest) + assertEquals( + """{"operations":[{"method":"create","body":$createJson},""" + + """{"method":"update","event_id":"EVENT_ID_1","body":$updateJson},""" + + """{"method":"delete","event_id":"EVENT_ID_2"}]}""", + body, + ) + assertTrue(body.contains("\"start_time\":1798794000")) + assertTrue(body.contains("\"color_id\":null")) + } + + @Test + fun `batch only sends calendar_id when no optional params are set`() { + val events = eventsReturning(200, """{"request_id":"req-1","data":[]}""") + + events.batch(grantId, batchRequest, BatchEventsQueryParams("primary")) + + assertEquals(setOf("calendar_id"), requests.single().url.queryParameterNames) + } + + @Test + fun `batch 200 response deserializes events in operation order`() { + val events = eventsReturning( + 200, + """ + { + "request_id": "req-200", + "data": [ + { "status": 200, "data": { "id": "new-event-id", "title": "Standup", "calendar_id": "primary", "when": { "start_time": 1798794000, "end_time": 1798795800, "object": "timespan" } } }, + { "status": 200, "data": { "id": "EVENT_ID_1", "title": "Renamed", "calendar_id": "primary", "when": { "start_time": 1798794000, "end_time": 1798795800, "object": "timespan" } } }, + { "status": 200 } + ] + } + """.trimIndent(), + ) + + val response = events.batch(grantId, batchRequest, BatchEventsQueryParams("primary")) + + assertEquals("req-200", response.requestId) + assertEquals(3, response.data.size) + assertEquals(listOf(200, 200, 200), response.data.map { it.status }) + assertEquals("new-event-id", response.data[0].data?.id) + assertEquals("Standup", response.data[0].data?.title) + assertIs(response.data[0].data?.getWhen()) + assertEquals("EVENT_ID_1", response.data[1].data?.id) + assertEquals("Renamed", response.data[1].data?.title) + assertNull(response.data[2].data) + assertTrue(response.data.all { it.error == null && it.retryAfter == null && it.providerEventCreated == null }) + } + + @Test + fun `batch 207 response is returned not thrown and exposes failure details`() { + val events = eventsReturning( + 207, + """ + { + "request_id": "req-207", + "data": [ + { "status": 200, "data": { "id": "new-event-id", "title": "Standup" } }, + { "status": 429, "error": { "type": "rate_limit_error", "message": "Too many requests", "provider_error": { "code": 429 } }, "retry_after": 2.5 }, + { "status": 500, "error": { "type": "internal_error", "message": "Failed after create" }, "provider_event_created": true } + ] + } + """.trimIndent(), + ) + + val response = events.batch(grantId, batchRequest, BatchEventsQueryParams("primary")) + + assertEquals("req-207", response.requestId) + assertEquals(listOf(200, 429, 500), response.data.map { it.status }) + assertEquals("new-event-id", response.data[0].data?.id) + assertNull(response.data[0].error) + + val throttled = response.data[1] + assertNull(throttled.data) + assertEquals("rate_limit_error", throttled.error?.type) + assertEquals("Too many requests", throttled.error?.message) + assertEquals(429.0, throttled.error?.providerError?.get("code")) + assertEquals(2.5, throttled.retryAfter) + assertNull(throttled.providerEventCreated) + + val duplicateRisk = response.data[2] + assertEquals("internal_error", duplicateRisk.error?.type) + assertEquals("Failed after create", duplicateRisk.error?.message) + assertEquals(true, duplicateRisk.providerEventCreated) + assertNull(duplicateRisk.retryAfter) + } + + @Test + fun `batch 207 response where every operation failed still returns`() { + val events = eventsReturning( + 207, + """ + { + "request_id": "req-207-all", + "data": [ + { "status": 400, "error": { "type": "invalid_request_error", "message": "Bad body" } }, + { "status": 404, "error": { "type": "not_found_error", "message": "Event EVENT_ID_1 not found" } }, + { "status": 404, "error": { "type": "not_found_error", "message": "Event EVENT_ID_2 not found" } } + ] + } + """.trimIndent(), + ) + + val response = events.batch(grantId, batchRequest, BatchEventsQueryParams("primary")) + + assertEquals(listOf(400, 404, 404), response.data.map { it.status }) + assertTrue(response.data.all { it.data == null && it.error != null }) + assertEquals("Event EVENT_ID_1 not found", response.data[1].error?.message) + assertEquals("Event EVENT_ID_2 not found", response.data[2].error?.message) + } + + @Test + fun `batch retry_after of zero deserializes as zero`() { + val events = eventsReturning( + 207, + """{"request_id":"req","data":[{"status":503,"error":{"type":"provider_error","message":"Unavailable"},"retry_after":0}]}""", + ) + + val response = events.batch(grantId, batchRequest, BatchEventsQueryParams("primary")) + + assertEquals(0.0, response.data.single().retryAfter) + } + + @Test + fun `batch 400 response throws NylasApiError`() { + val events = eventsReturning( + 400, + """{"request_id":"req-400","error":{"type":"invalid_request_error","message":"calendar_id is required"}}""", + ) + + val exception = assertFailsWith { + events.batch(grantId, batchRequest, BatchEventsQueryParams("primary")) + } + + assertEquals(400, exception.statusCode) + assertEquals("req-400", exception.requestId) + assertEquals("invalid_request_error", exception.type) + assertEquals("calendar_id is required", exception.message) + } + + @Test + fun `batch operation factories set the fields each method requires`() { + val create = BatchEventOperation.create(createRequest) + assertEquals(BatchEventMethod.CREATE, create.method) + assertNull(create.eventId) + assertEquals(createRequest, create.body) + + val update = BatchEventOperation.update("EVENT_ID_1", updateRequest) + assertEquals(BatchEventMethod.UPDATE, update.method) + assertEquals("EVENT_ID_1", update.eventId) + assertEquals(updateRequest, update.body) + + val delete = BatchEventOperation.delete("EVENT_ID_2") + assertEquals(BatchEventMethod.DELETE, delete.method) + assertEquals("EVENT_ID_2", delete.eventId) + assertNull(delete.body) + + // Operations can only be built through the factories above. + assertTrue(BatchEventOperation::class.constructors.all { it.visibility == kotlin.reflect.KVisibility.PRIVATE }) + } + + @Test + fun `batch URL-encodes the grant identifier`() { + val events = eventsReturning(200, """{"request_id":"req","data":[]}""") + + events.batch("user@example.com", batchRequest, BatchEventsQueryParams("primary")) + + assertEquals("/v3/grants/user%40example.com/events/batch", requests.single().url.encodedPath) + } + } }