diff --git a/docs/README.md b/docs/README.md index 4b0d085cb7..128c1334d7 100644 --- a/docs/README.md +++ b/docs/README.md @@ -116,7 +116,6 @@ Reference docs are generated from the source code and live under `./reference/ar - [Software Matching Helpers](./reference/architecture/data-mongo-sync/software-matching-helpers/software-matching-helpers.md), [Software Matching Service](./reference/architecture/data-mongo-sync/software-matching-service/software-matching-service.md) - [Software Repository](./reference/architecture/data-mongo-sync/software-repository/software-repository.md) - [Tenant Repository](./reference/architecture/data-mongo-sync/tenant-repository/tenant-repository.md) - - [Ticket Repository](./reference/architecture/data-mongo-sync/ticket-repository/ticket-repository.md) - [Timetracking Repository](./reference/architecture/data-mongo-sync/timetracking-repository/timetracking-repository.md) - [Tool Repository](./reference/architecture/data-mongo-sync/tool-repository/tool-repository.md) - [User Repository](./reference/architecture/data-mongo-sync/user-repository/user-repository.md), [Invitation Query Repository](./reference/architecture/data-mongo-sync/user-repository/invitation-query-repository.md), [User Publication](./reference/architecture/data-mongo-sync/user-repository/user-publication.md), [User Query Repository](./reference/architecture/data-mongo-sync/user-repository/user-query-repository.md) diff --git a/docs/reference/architecture/data-mongo-sync/ticket-repository/ticket-repository.md b/docs/reference/architecture/data-mongo-sync/ticket-repository/ticket-repository.md deleted file mode 100644 index 856c6d32ac..0000000000 --- a/docs/reference/architecture/data-mongo-sync/ticket-repository/ticket-repository.md +++ /dev/null @@ -1,222 +0,0 @@ -# Ticket Repository - -The Ticket Repository module is the tenant-aware MongoDB persistence boundary for ticket records in OpenFrame. It combines query construction, keyset pagination, ticket statistics, status transitions, denormalized-field maintenance, activity tracking, and ticket publication metadata behind a focused repository contract. - -The module is implemented in `openframe-data-mongo-sync` and is enabled only when `openframe.tenant-isolation.enabled` is set to `true`. It relies on the shared tenant-aware MongoDB infrastructure and operates on the `Ticket` document model supplied by the data layer. - -## Module Contents - -| Component | Responsibility | -| --- | --- | -| `CustomTicketRepository` | Defines the ticket query, pagination, reporting, transition, synchronization, and activity-stamping contract. | -| `CustomTicketRepositoryImpl` | Implements the contract with Spring Data MongoDB queries, aggregations, targeted updates, tenant criteria, and cursor handling. | -| `TicketAggregateSpec` | Describes the ticket aggregate for event publication and connects ticket changes to projections. | -| `TimeEntryTicketView` | Stores the ticket fields reconciled by the time-entry projection. | - -Source files: - -- [`CustomTicketRepository.java`](https://github.com/flamingo-stack/openframe-oss-lib/blob/main/openframe-data-mongo-sync/src/main/java/com/openframe/data/repository/ticket/CustomTicketRepository.java) -- [`CustomTicketRepositoryImpl.java`](https://github.com/flamingo-stack/openframe-oss-lib/blob/main/openframe-data-mongo-sync/src/main/java/com/openframe/data/repository/ticket/CustomTicketRepositoryImpl.java) -- [`TicketAggregateSpec.java`](https://github.com/flamingo-stack/openframe-oss-lib/blob/main/openframe-data-mongo-sync/src/main/java/com/openframe/data/repository/ticket/publishing/TicketAggregateSpec.java) -- [`TimeEntryTicketView.java`](https://github.com/flamingo-stack/openframe-oss-lib/blob/main/openframe-data-mongo-sync/src/main/java/com/openframe/data/repository/ticket/publishing/TimeEntryTicketView.java) - -## Architecture Overview - -The repository separates read composition, persistence operations, and publication metadata while sharing tenant-aware MongoDB access. Query callers provide filters and optional scope constraints; the implementation translates them into MongoDB criteria. Writes use either targeted updates or aggregate publication, depending on whether the change is a user-visible aggregate mutation or an operational field stamp. - -```mermaid -flowchart LR - Caller["Ticket Service or API Caller"] --> Contract["Custom Ticket Repository"] - Contract --> Impl["Custom Ticket Repository Implementation"] - Impl --> TenantSupport["Tenant-Aware Repository Support"] - TenantSupport --> Mongo["Tenant-Aware Mongo Template"] - Mongo --> Tickets[("Ticket Documents")] - Impl --> Stats["Mongo Aggregations"] - Stats --> Tickets - Impl --> Publisher["Outbox Publisher"] - Publisher --> Aggregate["Ticket Aggregate Specification"] - Aggregate --> Projection["Time-Entry Projection"] - Projection --> View[("Time-Entry Ticket View")] -``` - -## Runtime Conditions and Tenant Isolation - -`CustomTicketRepositoryImpl` extends `TenantAwareRepositorySupport`, so tenant criteria are applied through the shared repository infrastructure for tenant-bound operations. The implementation is conditionally registered only when tenant isolation is enabled. This prevents the custom repository from being active in an application configuration that has not opted into the tenant-aware data path. - -Owner-scoped reads add a second layer of visibility control for agent principals: - -- The ticket owner machine must match the requested machine. -- If an owner organization is supplied, the ticket organization may match it or remain `null` for tickets created before the organization snapshot was backfilled. -- The effective creation-time lower bound is the later of the requested filter lower bound and the organization assignment timestamp. -- An unrestricted owner scope, represented by `null`, is intended for administrative queries. - -```mermaid -flowchart TD - Request["Ticket Query Request"] --> Tenant["Apply Tenant Criteria"] - Tenant --> Owner{{"Owner Scope Present?"}} - Owner -->|"No"| Filters["Apply Query Filters"] - Owner -->|"Yes"| Machine["Match Owner Machine"] - Machine --> Organization["Match Organization or Null Snapshot"] - Organization --> Cutoff["Use Latest Creation-Time Cutoff"] - Cutoff --> Filters - Filters --> Search{{"Search Text Present?"}} - Search -->|"No"| Results["Execute Query"] - Search -->|"Yes"| Alternatives["Match Ticket Fields or Number"] - Alternatives --> Results -``` - -## Query Construction - -`buildTicketQuery` creates a Spring Data MongoDB `Query` from four inputs: a `TicketQueryFilter`, free-text search, an optional allow-list of ticket IDs, and an optional `ClientOwnerScope`. - -### Structured Filters - -When present, filter lists are translated into `in` criteria for ticket number, status ID, status kind, organization ID, assignee ID, device ID, and creation source. Boolean flags are handled explicitly: - -- `escalatedByUser = true` requires the field to be `true`. -- `escalatedByUser = false` matches false values and documents where the field is absent. -- `hasPendingApproval` follows the same compatibility behavior for older documents. - -Creation-time ranges use an inclusive lower bound and an exclusive upper bound. This makes adjacent time windows composable without overlapping boundary records. - -### Activity Filters - -Activity criteria support stale tickets, active tickets, and tickets awaiting an external response. Status-specific stale cutoffs are grouped by timestamp so the generated query can combine statuses sharing the same cutoff. Tickets without `lastActivityAt` fall back to `createdAt` when comparing activity thresholds. - -- Stale: `lastActivityAt` is before the cutoff, or activity is missing and `createdAt` is before it. -- Active: `lastActivityAt` is at or after the cutoff, or activity is missing and `createdAt` is at or after it. -- Awaiting external: `awaitingClientSince` is present. - -### Text Search - -Free-text search is trimmed and escaped with `Pattern.quote`, then compared case-insensitively against: - -- Ticket title -- Device hostname -- Organization name -- Assigned user name - -A search consisting only of digits is also parsed as an integer ticket number when possible. Invalid or overflowing numeric input remains a text search and does not fail query construction. - -## Cursor Pagination and Sorting - -The repository uses keyset pagination rather than offset pagination. `findTicketsWithCursor` accepts a base query, a cursor position, direction, page size, sort field, and sort direction. Every sort is stabilized with `_id` as a tie-breaker, which keeps pages deterministic when multiple tickets share the same primary sort value. - -Supported sortable fields are: - -- `_id` -- `ticketNumber` -- `statusKind` -- `organizationName` -- `assignedName` -- `deviceHostname` -- `createdAt` -- `updatedAt` -- `resolvedAt` -- `lastActivityAt` -- `order` - -The default sort field is `_id`. Sort direction defaults to ascending unless the caller requests `DESC`. - -The cursor implementation handles several edge cases: - -- A keyset cursor must use the same sort field and direction as the request. -- A row-ID cursor is converted into a keyset anchor by loading the row when the sort field is not `_id`. -- A missing anchor row can fall back to an ID anchor for `createdAt`; other unsupported cases raise `InvalidCursorException`. -- Null sort values are treated as a distinct group, with `_id` resolving ties inside that group. -- Invalid MongoDB object IDs and unrecognized cursor types raise `InvalidCursorException`. -- Cursor criteria are merged under `$and` instead of adding duplicate top-level criteria keys. This is important when the base query already contains `_id` or `$or` conditions. - -## Statistics and Reporting - -The implementation exposes both direct counts and aggregation-based metrics: - -- `countTickets` counts records matching a caller-provided query. -- `countTicketsByStatusKind` groups tenant-visible records by `statusKind` and ignores unknown enum values with a warning. -- `countTicketsByStatusId` groups tenant-visible records by status ID. -- `getTotalCount` counts all tenant-visible tickets. -- `getAverageResolutionTimeMs` averages the difference between `resolvedAt` and `createdAt` for records where both timestamps exist. It returns an empty optional when no qualifying ticket exists. -- `findAuditFieldsByStatusId` reads a minimal field projection using the primary read preference, which favors current data for audit-related operations. - -## Status Transitions - -Two operations support status movement: - -- `reassignTicketsToStatus` updates every ticket with a source status ID. -- `moveFromStatus` updates one ticket only when both its ID and current status match the expected source status. - -Both operations set the destination status ID, destination status kind, and a new `updatedAt` timestamp. The single-ticket operation returns a projected ticket when the compare-and-move succeeds and an empty optional when the expected source state no longer matches. - -## Denormalized Field Maintenance - -Ticket documents retain display-name snapshots for related entities so ticket lists can be rendered without repeatedly joining related collections. The repository provides bulk synchronization methods for: - -- Assigned user names -- Resolver names -- Organization names -- Device hostnames - -Each method updates only records whose source ID matches and whose copied value differs. The update is issued against `Ticket.class`, allowing Spring Data's version-aware behavior to detect conflicts with stale ticket copies. The method returns the number of modified records. - -Title updates use a targeted `$set` and refresh `updatedAt`. When both an `OutboxPublisher` and `TicketAggregateSpec` are available, the write is published as an aggregate change. If optimistic locking reports a concurrent save, the title write is retried because the operation is a plain idempotent `$set`. - -## Activity and Approval Stamps - -Operational activity updates intentionally avoid full document saves: - -- `updatePendingApproval` changes only the pending-approval flag and increments the version by zero. -- `updateLastActivityAt` stamps the last activity timestamp. -- `updateActivityAndAwaiting` stamps activity and either sets or removes `awaitingClientSince`. - -The activity methods return the newly written ticket when available. Their version increment of zero prevents a chat or activity message from conflicting with a concurrent user edit. They also leave `updatedAt` untouched because consumers interpret `updatedAt` as a meaningful ticket-state change, not merely as message activity. - -## Event Publication and Projection Support - -`TicketAggregateSpec` identifies the aggregate type as `tickets`. It converts a `Ticket` into a compact `TicketEvent` containing the ticket ID and title, then exposes the `TicketOnTimeEntriesProjection` as its projection. - -This means a ticket change can update the ticket-related fields used by time-entry processing without requiring the projection to consume the entire ticket document. `CustomTicketRepositoryImpl.updateTitle` explicitly uses the same specification for title writes that occur outside the normal repository save path, preserving publication behavior for that special mutation. - -`TimeEntryTicketView` is the projection's persisted read model. It contains: - -- The view ID -- Tenant ID -- Ticket ID -- Ticket title - -The view is deliberately small: the projection job reads only the ticket identity and title fields needed to reconcile time entries. - -```mermaid -sequenceDiagram - participant Caller as "Ticket Write Caller" - participant Repo as "Ticket Repository" - participant Mongo as "MongoDB" - participant Outbox as "Outbox Publisher" - participant Projection as "Time-Entry Projection" - participant View as "Time-Entry Ticket View" - - Caller->>Repo: Update ticket title - Repo->>Mongo: Find and modify title and updatedAt - Mongo-->>Repo: Return changed ticket - Repo->>Outbox: Publish tickets aggregate event - Outbox->>Projection: Deliver ticket ID and title event - Projection->>View: Reconcile ticket fields -``` - -## Consistency and Concurrency Rules - -The module uses targeted writes where a full aggregate save would create unnecessary conflicts or alter semantic timestamps: - -- Status changes update the state fields and `updatedAt` together. -- Approval and activity stamps use `$inc` by zero to avoid version conflicts. -- Copied-name synchronization targets only stale snapshots. -- Title publication retries a safe plain `$set` after an optimistic-locking conflict. -- Cursor queries always include a deterministic ID tie-breaker. -- Audit reads use the primary MongoDB read preference. - -These rules allow high-frequency activity and denormalization maintenance to coexist with user edits while retaining tenant visibility and stable pagination behavior. - -## Operational Guidance - -When adding a query filter, update the filter-to-criteria mapping and consider whether the field needs an index or a sortable-field entry. When adding a sortable field, update all three related behaviors together: the allow-list, sort construction, and cursor value extraction. When adding a published ticket field, update the aggregate event and the projection view only if the downstream projection requires that field. - -Callers should treat cursor values as opaque, preserve the requested sort field and direction between pages, and use the repository's default sort when no explicit ordering is required. Administrative callers should omit owner scope only when their authorization layer has already established unrestricted tenant access. diff --git a/openframe-api-lib/src/test/java/com/openframe/api/service/TicketQueryServiceTest.java b/openframe-api-lib/src/test/java/com/openframe/api/service/TicketQueryServiceTest.java index 8f136099de..b9a09b2452 100644 --- a/openframe-api-lib/src/test/java/com/openframe/api/service/TicketQueryServiceTest.java +++ b/openframe-api-lib/src/test/java/com/openframe/api/service/TicketQueryServiceTest.java @@ -5,8 +5,8 @@ import com.openframe.data.document.ticket.filter.TicketQueryFilter; import com.openframe.data.mongo.TenantAwareMongoTemplate; import com.openframe.data.repository.cursor.CursorPosition; -import com.openframe.data.repository.ticket.CustomTicketRepository; -import com.openframe.data.repository.ticket.CustomTicketRepositoryImpl; +import com.openframe.data.repository.ticket.TicketRepositoryOperations; +import com.openframe.data.repository.ticket.TicketRepositoryOperationsImpl; import com.openframe.data.repository.ticket.TicketRepository; import com.openframe.data.repository.ticket.publishing.TicketAggregateSpec; import com.openframe.publishing.api.OutboxPublisher; @@ -113,7 +113,7 @@ void searchTickets_afterARawTicketId_newestFirstPastThatRow() { @Test void searchTickets_afterATicketThatWasRemoved_newestFirstPastThatId() { // setup - CustomTicketRepository storedTickets = new CustomTicketRepositoryImpl(mongoTemplate, outboxPublisher, ticketSpec); + TicketRepositoryOperations storedTickets = new TicketRepositoryOperationsImpl(mongoTemplate, outboxPublisher, ticketSpec); CursorPosition afterRow = new CursorPosition.RowId(AFTER_TICKET_ID); Document pastTheRemovedTicket = new Document("_id", new Document("$lt", new ObjectId(AFTER_TICKET_ID))); Document newestFirst = new Document(CREATED_AT, -1).append("_id", -1); diff --git a/openframe-api-lib/src/test/java/com/openframe/api/service/ticket/TicketServicePaginationTest.java b/openframe-api-lib/src/test/java/com/openframe/api/service/ticket/TicketServicePaginationTest.java index 39e5462aad..90c34b328d 100644 --- a/openframe-api-lib/src/test/java/com/openframe/api/service/ticket/TicketServicePaginationTest.java +++ b/openframe-api-lib/src/test/java/com/openframe/api/service/ticket/TicketServicePaginationTest.java @@ -17,8 +17,8 @@ import com.openframe.data.repository.cursor.KeysetCursor; import com.openframe.data.repository.device.MachineRepository; import com.openframe.data.repository.organization.OrganizationRepository; -import com.openframe.data.repository.ticket.CustomTicketRepository; -import com.openframe.data.repository.ticket.CustomTicketRepositoryImpl; +import com.openframe.data.repository.ticket.TicketRepositoryOperations; +import com.openframe.data.repository.ticket.TicketRepositoryOperationsImpl; import com.openframe.data.repository.ticket.TicketRepository; import com.openframe.data.repository.user.UserRepository; import com.openframe.security.authentication.ActorType; @@ -107,7 +107,7 @@ class TicketServicePaginationTest { .build(); @SuppressWarnings("unchecked") - private final CustomTicketRepository cursorIssuer = new CustomTicketRepositoryImpl( + private final TicketRepositoryOperations cursorIssuer = new TicketRepositoryOperationsImpl( mock(TenantAwareMongoTemplate.class), mock(ObjectProvider.class), mock(ObjectProvider.class)); @Test diff --git a/openframe-data-mongo-common/src/main/java/com/openframe/data/document/audit/AuditAction.java b/openframe-data-mongo-common/src/main/java/com/openframe/data/document/audit/AuditAction.java index ce4f9d8ff2..4b72994e05 100644 --- a/openframe-data-mongo-common/src/main/java/com/openframe/data/document/audit/AuditAction.java +++ b/openframe-data-mongo-common/src/main/java/com/openframe/data/document/audit/AuditAction.java @@ -433,6 +433,10 @@ public enum AuditAction { AI_DIALOG_RENAME("ai.dialog.rename", "AI chat renamed", CHANGE, DIALOG), AI_DIALOG_RATING_SET("ai.dialog_rating.set", "AI chat rated", CHANGE, DIALOG), AI_DIALOG_CONTEXT_UPDATE("ai.dialog_context.update", "AI chat context summarized", CHANGE, DIALOG), + CHAT_ATTACHMENT_UPLOAD("ai.chat_attachment.upload", "Chat attachment uploaded", CHANGE, CHAT_ATTACHMENT), + CHAT_ATTACHMENT_DOWNLOAD_LINK_ISSUE("ai.chat_attachment.download_link.issue", + "Chat attachment link issued", SENSITIVE_READ, CHAT_ATTACHMENT), + CHAT_ATTACHMENT_DELETE("ai.chat_attachment.delete", "Chat attachment deleted", CHANGE, CHAT_ATTACHMENT), AUDIT_LOG_VIEW("audit_log.view", "Audit log viewed", SENSITIVE_READ, AUDIT_LOG), AUDIT_LOG_EVENT_VIEW("audit_log.event.view", "Audit event viewed", SENSITIVE_READ, AUDIT_LOG), LOG_VIEW("log.view", "Logs viewed", SENSITIVE_READ, LOG), diff --git a/openframe-data-mongo-common/src/main/java/com/openframe/data/document/audit/AuditTargetType.java b/openframe-data-mongo-common/src/main/java/com/openframe/data/document/audit/AuditTargetType.java index f58e1b1ba8..8c819b103c 100644 --- a/openframe-data-mongo-common/src/main/java/com/openframe/data/document/audit/AuditTargetType.java +++ b/openframe-data-mongo-common/src/main/java/com/openframe/data/document/audit/AuditTargetType.java @@ -21,6 +21,7 @@ public enum AuditTargetType { BILLING_PLAN("Billing plan"), BLOCKED_EMAIL("Blocked email"), BLOCKED_EMAIL_DOMAIN("Blocked email domain"), + CHAT_ATTACHMENT("Chat attachment"), CUSTOMER_USER("End user"), DEVICE("Device"), DIALOG("AI chat"), diff --git a/openframe-data-mongo-common/src/main/java/com/openframe/data/document/ticket/TicketAttachment.java b/openframe-data-mongo-common/src/main/java/com/openframe/data/document/ticket/TicketAttachment.java index 76c21c00ce..6f8e538be8 100644 --- a/openframe-data-mongo-common/src/main/java/com/openframe/data/document/ticket/TicketAttachment.java +++ b/openframe-data-mongo-common/src/main/java/com/openframe/data/document/ticket/TicketAttachment.java @@ -4,6 +4,7 @@ import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; +import lombok.experimental.FieldNameConstants; import lombok.NoArgsConstructor; import org.springframework.data.annotation.CreatedDate; import org.springframework.data.annotation.Id; @@ -17,7 +18,8 @@ * Files are stored externally (S3/MinIO), this stores metadata. */ @Data -@Builder +@FieldNameConstants +@Builder(toBuilder = true) @NoArgsConstructor @AllArgsConstructor @Document(collection = "ticket_attachments") diff --git a/openframe-data-mongo-sync/src/main/java/com/openframe/data/repository/ticket/TicketAttachmentInsertionResult.java b/openframe-data-mongo-sync/src/main/java/com/openframe/data/repository/ticket/TicketAttachmentInsertionResult.java new file mode 100644 index 0000000000..dacf038c59 --- /dev/null +++ b/openframe-data-mongo-sync/src/main/java/com/openframe/data/repository/ticket/TicketAttachmentInsertionResult.java @@ -0,0 +1,7 @@ +package com.openframe.data.repository.ticket; + +import com.openframe.data.document.ticket.TicketAttachment; + +/** Carries the stored attachment and whether this attempt created its ticket link. */ +public record TicketAttachmentInsertionResult(TicketAttachment attachment, boolean inserted) { +} diff --git a/openframe-data-mongo-sync/src/main/java/com/openframe/data/repository/ticket/TicketAttachmentRepository.java b/openframe-data-mongo-sync/src/main/java/com/openframe/data/repository/ticket/TicketAttachmentRepository.java index 740e051dfa..495440bfcd 100644 --- a/openframe-data-mongo-sync/src/main/java/com/openframe/data/repository/ticket/TicketAttachmentRepository.java +++ b/openframe-data-mongo-sync/src/main/java/com/openframe/data/repository/ticket/TicketAttachmentRepository.java @@ -9,8 +9,10 @@ import java.util.List; import java.util.Optional; +/** Reads and writes metadata for files linked to tickets. */ @Repository -public interface TicketAttachmentRepository extends MongoRepository { +public interface TicketAttachmentRepository extends MongoRepository, + TicketAttachmentUpsertOperations { List findByTicketId(String ticketId); diff --git a/openframe-data-mongo-sync/src/main/java/com/openframe/data/repository/ticket/TicketAttachmentUpsertOperations.java b/openframe-data-mongo-sync/src/main/java/com/openframe/data/repository/ticket/TicketAttachmentUpsertOperations.java new file mode 100644 index 0000000000..4362569610 --- /dev/null +++ b/openframe-data-mongo-sync/src/main/java/com/openframe/data/repository/ticket/TicketAttachmentUpsertOperations.java @@ -0,0 +1,15 @@ +package com.openframe.data.repository.ticket; + +import com.openframe.data.document.ticket.TicketAttachment; + +/** Stores each ticket attachment once using a storage path owned by that ticket and unique within its tenant. */ +public interface TicketAttachmentUpsertOperations { + + TicketAttachment insertIfAbsent(TicketAttachment attachment); + + TicketAttachmentInsertionResult insertIfAbsentWithResult(TicketAttachment attachment); + + /** Keeps one link for the logical path while storing the actual path of the committed copy. */ + TicketAttachmentInsertionResult insertIfAbsentWithResult(TicketAttachment attachment, + String logicalStoragePath); +} diff --git a/openframe-data-mongo-sync/src/main/java/com/openframe/data/repository/ticket/TicketAttachmentUpsertOperationsImpl.java b/openframe-data-mongo-sync/src/main/java/com/openframe/data/repository/ticket/TicketAttachmentUpsertOperationsImpl.java new file mode 100644 index 0000000000..9b6682ac32 --- /dev/null +++ b/openframe-data-mongo-sync/src/main/java/com/openframe/data/repository/ticket/TicketAttachmentUpsertOperationsImpl.java @@ -0,0 +1,96 @@ +package com.openframe.data.repository.ticket; + +import com.mongodb.ReadPreference; +import com.openframe.data.document.ticket.TicketAttachment; +import com.openframe.data.document.ticket.TicketAttachment.Fields; +import lombok.RequiredArgsConstructor; +import org.springframework.dao.DuplicateKeyException; +import org.springframework.data.mongodb.core.FindAndModifyOptions; +import org.springframework.data.mongodb.core.MongoTemplate; +import org.springframework.data.mongodb.core.query.Criteria; +import org.springframework.data.mongodb.core.query.Query; +import org.springframework.data.mongodb.core.query.Update; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +import java.time.Instant; +import java.util.Optional; +import java.util.UUID; + +import static java.nio.charset.StandardCharsets.UTF_8; +import static java.time.temporal.ChronoUnit.MILLIS; + +/** Atomically inserts ticket attachment metadata while preserving an existing copy on retry. */ +@RequiredArgsConstructor +public class TicketAttachmentUpsertOperationsImpl implements TicketAttachmentUpsertOperations { + private static final String DOCUMENT_ID = "_id"; + + private final MongoTemplate mongoTemplate; + + @Override + public TicketAttachment insertIfAbsent(TicketAttachment attachment) { + return insertIfAbsentWithResult(attachment).attachment(); + } + + @Override + public TicketAttachmentInsertionResult insertIfAbsentWithResult(TicketAttachment attachment) { + String storagePath = attachment.getStoragePath(); + Query query = Query.query(ticketScope(attachment).and(Fields.storagePath).is(storagePath)); + String id = attachmentId(attachment.getTenantId(), storagePath); + return insertTicketAttachment(attachment, query, id); + } + + @Override + public TicketAttachmentInsertionResult insertIfAbsentWithResult(TicketAttachment attachment, + String logicalStoragePath) { + String id = attachmentId(attachment.getTenantId(), logicalStoragePath); + Query query = Query.query(ticketScope(attachment).and(DOCUMENT_ID).is(id)); + return insertTicketAttachment(attachment, query, id); + } + + private Criteria ticketScope(TicketAttachment attachment) { + return Criteria.where(Fields.tenantId).is(attachment.getTenantId()) + .and(Fields.ticketId).is(attachment.getTicketId()); + } + + private String attachmentId(String tenantId, String storagePath) { + String identity = tenantId + "/" + storagePath; + return UUID.nameUUIDFromBytes(identity.getBytes(UTF_8)).toString(); + } + + private TicketAttachmentInsertionResult insertTicketAttachment(TicketAttachment attachment, Query query, String id) { + Instant uploadedAt = Instant.now().truncatedTo(MILLIS); + Update update = new Update() + .setOnInsert(DOCUMENT_ID, id) + .setOnInsert(Fields.storagePath, attachment.getStoragePath()) + .setOnInsert(Fields.fileName, attachment.getFileName()) + .setOnInsert(Fields.contentType, attachment.getContentType()) + .setOnInsert(Fields.fileSize, attachment.getFileSize()) + .setOnInsert(Fields.uploadedBy, attachment.getUploadedBy()) + .setOnInsert(Fields.uploadedAt, uploadedAt); + + TicketAttachment existing = findOrInsert(query, update); + if (existing != null) { + return new TicketAttachmentInsertionResult(existing, false); + } + TicketAttachment inserted = attachment.toBuilder().id(id).uploadedAt(uploadedAt).build(); + return new TicketAttachmentInsertionResult(inserted, true); + } + + private TicketAttachment findOrInsert(Query query, Update update) { + FindAndModifyOptions options = FindAndModifyOptions.options().upsert(true); + try { + return mongoTemplate.findAndModify(query, update, options, TicketAttachment.class); + } catch (DuplicateKeyException exception) { + return findConcurrentCopy(query, exception); + } + } + + private TicketAttachment findConcurrentCopy(Query query, DuplicateKeyException exception) { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw exception; + } + return Optional.ofNullable(mongoTemplate.findOne(query.withReadPreference(ReadPreference.primary()), + TicketAttachment.class)) + .orElseThrow(() -> exception); + } +} diff --git a/openframe-data-mongo-sync/src/main/java/com/openframe/data/repository/ticket/TicketRepository.java b/openframe-data-mongo-sync/src/main/java/com/openframe/data/repository/ticket/TicketRepository.java index d2787f5a5f..8899ec0475 100644 --- a/openframe-data-mongo-sync/src/main/java/com/openframe/data/repository/ticket/TicketRepository.java +++ b/openframe-data-mongo-sync/src/main/java/com/openframe/data/repository/ticket/TicketRepository.java @@ -13,7 +13,7 @@ @Repository @TenantAwareRepository -public interface TicketRepository extends MongoRepository, CustomTicketRepository { +public interface TicketRepository extends MongoRepository, TicketRepositoryOperations { Optional findByTicketNumber(Integer ticketNumber); diff --git a/openframe-data-mongo-sync/src/main/java/com/openframe/data/repository/ticket/CustomTicketRepository.java b/openframe-data-mongo-sync/src/main/java/com/openframe/data/repository/ticket/TicketRepositoryOperations.java similarity index 98% rename from openframe-data-mongo-sync/src/main/java/com/openframe/data/repository/ticket/CustomTicketRepository.java rename to openframe-data-mongo-sync/src/main/java/com/openframe/data/repository/ticket/TicketRepositoryOperations.java index a7d60283ba..643fb1d273 100644 --- a/openframe-data-mongo-sync/src/main/java/com/openframe/data/repository/ticket/CustomTicketRepository.java +++ b/openframe-data-mongo-sync/src/main/java/com/openframe/data/repository/ticket/TicketRepositoryOperations.java @@ -13,7 +13,7 @@ import java.util.Map; import java.util.Optional; -public interface CustomTicketRepository { +public interface TicketRepositoryOperations { default Query buildTicketQuery(TicketQueryFilter filter) { return buildTicketQuery(filter, null, null, null); diff --git a/openframe-data-mongo-sync/src/main/java/com/openframe/data/repository/ticket/CustomTicketRepositoryImpl.java b/openframe-data-mongo-sync/src/main/java/com/openframe/data/repository/ticket/TicketRepositoryOperationsImpl.java similarity index 98% rename from openframe-data-mongo-sync/src/main/java/com/openframe/data/repository/ticket/CustomTicketRepositoryImpl.java rename to openframe-data-mongo-sync/src/main/java/com/openframe/data/repository/ticket/TicketRepositoryOperationsImpl.java index ba30103b5c..a1fedd6d5d 100644 --- a/openframe-data-mongo-sync/src/main/java/com/openframe/data/repository/ticket/CustomTicketRepositoryImpl.java +++ b/openframe-data-mongo-sync/src/main/java/com/openframe/data/repository/ticket/TicketRepositoryOperationsImpl.java @@ -47,7 +47,7 @@ @Slf4j @ConditionalOnProperty(name = "openframe.tenant-isolation.enabled", havingValue = "true") -public class CustomTicketRepositoryImpl extends TenantAwareRepositorySupport implements CustomTicketRepository { +public class TicketRepositoryOperationsImpl extends TenantAwareRepositorySupport implements TicketRepositoryOperations { private static final String SORT_DESC = "DESC"; private static final String ID_FIELD = "_id"; @@ -104,8 +104,9 @@ public class CustomTicketRepositoryImpl extends TenantAwareRepositorySupport imp private final ObjectProvider outboxPublisher; private final ObjectProvider ticketSpec; - public CustomTicketRepositoryImpl(TenantAwareMongoTemplate mongoTemplate, ObjectProvider outboxPublisher, - ObjectProvider ticketSpec) { + public TicketRepositoryOperationsImpl(TenantAwareMongoTemplate mongoTemplate, + ObjectProvider outboxPublisher, + ObjectProvider ticketSpec) { super(mongoTemplate); this.outboxPublisher = outboxPublisher; this.ticketSpec = ticketSpec; diff --git a/openframe-data-mongo-sync/src/main/java/com/openframe/data/repository/ticket/publishing/TicketAggregateSpec.java b/openframe-data-mongo-sync/src/main/java/com/openframe/data/repository/ticket/publishing/TicketAggregateSpec.java index cd4a8c7e57..720c587f47 100644 --- a/openframe-data-mongo-sync/src/main/java/com/openframe/data/repository/ticket/publishing/TicketAggregateSpec.java +++ b/openframe-data-mongo-sync/src/main/java/com/openframe/data/repository/ticket/publishing/TicketAggregateSpec.java @@ -8,7 +8,7 @@ import java.util.List; -// TicketRepository publishes with this spec, and so does CustomTicketRepositoryImpl.updateTitle, which writes outside it. +// TicketRepository publishes with this spec, and so does TicketRepositoryOperationsImpl.updateTitle, which writes outside it. @Component @RequiredArgsConstructor public class TicketAggregateSpec implements AggregateSpec { diff --git a/openframe-data-mongo-sync/src/main/java/com/openframe/data/service/GcsCopySourceNotFoundException.java b/openframe-data-mongo-sync/src/main/java/com/openframe/data/service/GcsCopySourceNotFoundException.java new file mode 100644 index 0000000000..4a2de68569 --- /dev/null +++ b/openframe-data-mongo-sync/src/main/java/com/openframe/data/service/GcsCopySourceNotFoundException.java @@ -0,0 +1,15 @@ +package com.openframe.data.service; + +/** Identifies a missing source object when copying a stored attachment. */ +public class GcsCopySourceNotFoundException extends IllegalStateException { + + private static final String MESSAGE = "Immutable copy source is unavailable"; + + public GcsCopySourceNotFoundException() { + super(MESSAGE); + } + + public GcsCopySourceNotFoundException(Throwable cause) { + super(MESSAGE, cause); + } +} diff --git a/openframe-data-mongo-sync/src/main/java/com/openframe/data/service/GcsPresignedUrlService.java b/openframe-data-mongo-sync/src/main/java/com/openframe/data/service/GcsPresignedUrlService.java index bd53a9431c..083be47b62 100644 --- a/openframe-data-mongo-sync/src/main/java/com/openframe/data/service/GcsPresignedUrlService.java +++ b/openframe-data-mongo-sync/src/main/java/com/openframe/data/service/GcsPresignedUrlService.java @@ -1,24 +1,33 @@ package com.openframe.data.service; +import com.google.cloud.ReadChannel; +import com.google.cloud.storage.Blob; import com.google.cloud.storage.BlobId; import com.google.cloud.storage.BlobInfo; import com.google.cloud.storage.HttpMethod; import com.google.cloud.storage.Storage; +import com.google.cloud.storage.StorageException; import com.google.cloud.storage.StorageOptions; import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.stereotype.Service; +import java.io.IOException; +import java.net.URLEncoder; +import java.nio.channels.Channels; import java.time.Duration; +import java.util.Arrays; import java.util.Map; +import java.util.Objects; +import java.util.OptionalLong; import java.util.concurrent.TimeUnit; +import static java.nio.charset.StandardCharsets.UTF_8; + /** - * Service for generating presigned URLs using GCS SDK with ADC. - * Uses Application Default Credentials (same as Images). - * - * Requires IAM role: roles/iam.serviceAccountTokenCreator + * Signs GCS file URLs and protects attachment contents with bounded reads and immutable copies. */ @Service @Slf4j @@ -26,20 +35,36 @@ public class GcsPresignedUrlService { public static final String CONTENT_LENGTH_RANGE_HEADER = "x-goog-content-length-range"; + private static final String INLINE_DISPOSITION = "inline"; + private static final String ATTACHMENT_DISPOSITION = "attachment"; + private static final String ENCODED_FILE_NAME_PARAMETER = "; filename*=UTF-8''"; + private static final String RESPONSE_CONTENT_DISPOSITION = "response-content-disposition"; + private static final String RESPONSE_CONTENT_TYPE = "response-content-type"; + private static final String COPY_ORIGIN_PATH = "immutable-copy-origin-path"; + private static final String COPY_ORIGIN_GENERATION = "immutable-copy-origin-generation"; + private static final String FILE_EXCEEDS_SIZE_LIMIT = "File exceeds the allowed size"; + private static final String IMMUTABLE_FILE_CONFLICT = "Immutable file already contains different bytes"; + private static final int NOT_FOUND = 404; + private static final int PRECONDITION_FAILED = 412; private final Storage storage; private final String bucketName; private final String prefix; private final boolean prefixEnabled; + @Autowired public GcsPresignedUrlService( @Value("${storage.s3.bucket}") String bucketName, @Value("${storage.s3.prefix:}") String prefix, @Value("${storage.s3.prefix-enabled:false}") boolean prefixEnabled) { + this(bucketName, prefix, prefixEnabled, StorageOptions.getDefaultInstance().getService()); + } + + GcsPresignedUrlService(String bucketName, String prefix, boolean prefixEnabled, Storage storage) { this.bucketName = bucketName; this.prefix = prefix; this.prefixEnabled = prefixEnabled; - this.storage = StorageOptions.getDefaultInstance().getService(); + this.storage = storage; log.info("GcsPresignedUrlService initialized for bucket: {}, prefix: '{}', prefixEnabled: {}", bucketName, prefix, prefixEnabled); } @@ -87,6 +112,14 @@ public static String contentLengthRange(long maxSizeBytes) { return "0," + maxSizeBytes; } + public String generateUploadUrl(String path, Duration expiration, Map signedHeaders) { + BlobInfo blob = BlobInfo.newBuilder(bucketName, withPrefix(path)).build(); + return storage.signUrl(blob, expiration.toMinutes(), TimeUnit.MINUTES, + Storage.SignUrlOption.httpMethod(HttpMethod.PUT), + Storage.SignUrlOption.withExtHeaders(signedHeaders), + Storage.SignUrlOption.withV4Signature()).toString(); + } + public String generateDownloadUrl(String path, Duration expiration) { String fullPath = withPrefix(path); BlobInfo blobInfo = BlobInfo.newBuilder(bucketName, fullPath).build(); @@ -103,6 +136,27 @@ public String generateDownloadUrl(String path, Duration expiration) { return url; } + public String generateDownloadUrl(String path, Duration expiration, String fileName, String contentType) { + return generateReadUrl(path, expiration, fileName, contentType, ATTACHMENT_DISPOSITION); + } + + public String generatePreviewUrl(String path, Duration expiration, String fileName, String contentType) { + return generateReadUrl(path, expiration, fileName, contentType, INLINE_DISPOSITION); + } + + private String generateReadUrl(String path, Duration expiration, String fileName, String contentType, + String disposition) { + String encodedName = URLEncoder.encode(fileName, UTF_8).replace("+", "%20").replace("*", "%2A"); + Map responseHeaders = Map.of( + RESPONSE_CONTENT_DISPOSITION, disposition + ENCODED_FILE_NAME_PARAMETER + encodedName, + RESPONSE_CONTENT_TYPE, contentType); + return storage.signUrl(BlobInfo.newBuilder(bucketName, withPrefix(path)).build(), + expiration.toMinutes(), TimeUnit.MINUTES, + Storage.SignUrlOption.httpMethod(HttpMethod.GET), + Storage.SignUrlOption.withQueryParams(responseHeaders), + Storage.SignUrlOption.withV4Signature()).toString(); + } + public void deleteFile(String path) { String fullPath = withPrefix(path); boolean deleted = storage.delete(BlobId.of(bucketName, fullPath)); @@ -113,6 +167,184 @@ public void deleteFile(String path) { } } + /** Removes only the immutable object produced by a particular copy attempt. */ + public void deleteFileGeneration(String path, long generation) { + BlobId objectId = BlobId.of(bucketName, withPrefix(path), generation); + storage.delete(objectId, Storage.BlobSourceOption.generationMatch(generation)); + } + + public byte[] readFile(String path, long maxSizeBytes) { + Blob blob = storage.get(BlobId.of(bucketName, withPrefix(path))); + if (blob == null) { + throw new IllegalArgumentException("Uploaded file not found"); + } + long sizeLimit = Math.min(maxSizeBytes, Integer.MAX_VALUE - 1L); + if (blob.getSize() > sizeLimit) { + throw new IllegalArgumentException(FILE_EXCEEDS_SIZE_LIMIT); + } + byte[] content = readWithOverflowCheck(blob, Math.toIntExact(sizeLimit)); + if (content.length > sizeLimit) { + throw new IllegalArgumentException(FILE_EXCEEDS_SIZE_LIMIT); + } + return content; + } + + private byte[] readWithOverflowCheck(Blob blob, int sizeLimit) { + // The extra byte distinguishes an oversized response from a file of exactly the allowed size. + int readLimit = sizeLimit + 1; + try (ReadChannel reader = blob.reader()) { + reader.limit(readLimit); + return Channels.newInputStream(reader).readNBytes(readLimit); + } catch (IOException failure) { + throw readFailure(failure); + } + } + + private StorageException readFailure(IOException failure) { + return failure.getCause() instanceof StorageException storageFailure + ? storageFailure : new StorageException(failure); + } + + public boolean fileExists(String path) { + return storage.get(BlobId.of(bucketName, withPrefix(path))) != null; + } + + public void writeFileIfAbsent(String path, String contentType, byte[] content) { + BlobInfo blobInfo = BlobInfo.newBuilder(bucketName, withPrefix(path)).setContentType(contentType).build(); + try { + storage.create(blobInfo, content, Storage.BlobTargetOption.doesNotExist()); + } catch (StorageException exception) { + requireMatchingExistingFile(path, content, exception); + } + } + + public void copyImmutableFile(String sourcePath, String targetPath, String contentType) { + Blob source = requireCopySource(sourcePath); + Map origin = sourceVersionMetadata(source); + BlobInfo target = BlobInfo.newBuilder(bucketName, withPrefix(targetPath)) + .setContentType(contentType) + .setMetadata(origin) + .build(); + copyIfAbsent(source, target); + } + + public void copyImmutableDownload(String sourcePath, String targetPath, String contentType) { + copyImmutableDownloadGeneration(sourcePath, targetPath, contentType); + } + + /** Returns the generation this call created, or empty when it reused a verified existing object. */ + public OptionalLong copyImmutableDownloadGeneration(String sourcePath, String targetPath, String contentType) { + Blob source = requireCopySource(sourcePath); + Map origin = copyOrigin(source); + BlobInfo target = BlobInfo.newBuilder(bucketName, withPrefix(targetPath)) + .setContentType(contentType) + .setContentDisposition(ATTACHMENT_DISPOSITION) + .setMetadata(origin) + .build(); + try { + Blob copied = copyIfAbsent(source, target); + return OptionalLong.of(requireCopiedGeneration(copied)); + } catch (StorageException exception) { + verifyExistingCopy(source, target, exception); + return OptionalLong.empty(); + } + } + + private long requireCopiedGeneration(Blob copied) { + Long generation = copied.getGeneration(); + if (generation == null) { + throw new IllegalStateException("Immutable copy generation is unavailable"); + } + return generation; + } + + private void verifyExistingCopy(Blob source, BlobInfo target, StorageException exception) { + if (exception.getCode() != PRECONDITION_FAILED) { + throw exception; + } + requireMatchingCopy(source, target); + } + + private Blob requireCopySource(String path) { + BlobId id = BlobId.of(bucketName, withPrefix(path)); + Blob source = storage.get(id); + if (source == null) { + throw new GcsCopySourceNotFoundException(); + } + if (source.getGeneration() == null) { + throw new IllegalStateException("Immutable copy source is unavailable"); + } + return source; + } + + private Map sourceVersionMetadata(Blob source) { + String generation = source.getGeneration().toString(); + return Map.of(COPY_ORIGIN_PATH, source.getName(), COPY_ORIGIN_GENERATION, generation); + } + + private Map copyOrigin(Blob source) { + Map metadata = source.getMetadata(); + if (metadata == null) { + return sourceVersionMetadata(source); + } + String path = metadata.get(COPY_ORIGIN_PATH); + String generation = metadata.get(COPY_ORIGIN_GENERATION); + if (path == null || generation == null) { + return sourceVersionMetadata(source); + } + return Map.of(COPY_ORIGIN_PATH, path, COPY_ORIGIN_GENERATION, generation); + } + + private Blob copyIfAbsent(Blob source, BlobInfo target) { + BlobId sourceId = source.getBlobId(); + long generation = source.getGeneration(); + Storage.CopyRequest request = Storage.CopyRequest.newBuilder() + .setSource(sourceId) + .setSourceOptions(Storage.BlobSourceOption.generationMatch(generation)) + .setTarget(target, Storage.BlobTargetOption.doesNotExist()) + .build(); + try { + return storage.copy(request).getResult(); + } catch (StorageException failure) { + throw copyFailure(failure); + } + } + + private RuntimeException copyFailure(StorageException failure) { + return failure.getCode() == NOT_FOUND ? new GcsCopySourceNotFoundException(failure) : failure; + } + + private void requireMatchingCopy(Blob source, BlobInfo target) { + Blob existing = storage.get(target.getBlobId()); + String checksum = source.getCrc32c(); + boolean matches = existing != null && checksum != null && checksum.equals(existing.getCrc32c()) + && Objects.equals(source.getSize(), existing.getSize()) + && Objects.equals(target.getMetadata(), existing.getMetadata()) + && Objects.equals(target.getContentType(), existing.getContentType()) + && Objects.equals(target.getContentDisposition(), existing.getContentDisposition()); + if (!matches) { + throw new IllegalStateException("Immutable copy target does not match the verified source"); + } + } + + private void requireMatchingExistingFile(String path, byte[] content, StorageException exception) { + if (exception.getCode() != PRECONDITION_FAILED) { + throw exception; + } + Blob existing = storage.get(BlobId.of(bucketName, withPrefix(path))); + if (existing == null) { + throw exception; + } + if (!matchesExistingContent(existing, content)) { + throw new IllegalStateException(IMMUTABLE_FILE_CONFLICT); + } + } + + private boolean matchesExistingContent(Blob existing, byte[] content) { + return existing.getSize() == content.length + && Arrays.equals(readWithOverflowCheck(existing, content.length), content); + } + public void moveFile(String sourcePath, String destPath) { BlobId sourceId = BlobId.of(bucketName, withPrefix(sourcePath)); BlobId targetId = BlobId.of(bucketName, withPrefix(destPath)); diff --git a/openframe-data-mongo-sync/src/test/java/com/openframe/data/repository/ticket/TicketAttachmentRepositoryIT.java b/openframe-data-mongo-sync/src/test/java/com/openframe/data/repository/ticket/TicketAttachmentRepositoryIT.java index a7477a491f..0b00ca7667 100644 --- a/openframe-data-mongo-sync/src/test/java/com/openframe/data/repository/ticket/TicketAttachmentRepositoryIT.java +++ b/openframe-data-mongo-sync/src/test/java/com/openframe/data/repository/ticket/TicketAttachmentRepositoryIT.java @@ -2,10 +2,10 @@ import com.openframe.data.document.ticket.TicketAttachment; import com.openframe.data.integration.BaseMongoIntegrationTest; -import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.condition.EnabledIfSystemProperty; +import org.junit.jupiter.api.parallel.Execution; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringBootConfiguration; import org.springframework.boot.autoconfigure.ImportAutoConfiguration; @@ -14,47 +14,114 @@ import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.FilterType; +import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mongodb.repository.config.EnableMongoRepositories; +import org.springframework.test.context.DynamicPropertyRegistry; +import org.springframework.test.context.DynamicPropertySource; import java.util.Optional; +import java.util.UUID; import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.parallel.ExecutionMode.CONCURRENT; @SpringBootTest(classes = TicketAttachmentRepositoryIT.TestApplication.class) @Tag("integration") -@EnabledIfSystemProperty(named = "integration.tests", matches = "true") +@Execution(CONCURRENT) class TicketAttachmentRepositoryIT extends BaseMongoIntegrationTest { - private static final String TENANT_ID = "tenant-1"; - private static final String TICKET_ID = "ticket-1"; - private static final String OTHER_TICKET_ID = "ticket-2"; - private static final String PATH = "attachments/ticket-1/email-receipt-1/1-invoice.pdf"; - private static final String OTHER_PATH = "attachments/ticket-1/email-receipt-1/2-photo.png"; + private static final String DATABASE = "ticket_attachments_" + UUID.randomUUID().toString().replace("-", ""); @Autowired private TicketAttachmentRepository repository; - @BeforeEach - void setUp() { - repository.deleteAll(); + @DynamicPropertySource + static void isolateDatabase(DynamicPropertyRegistry registry) { + registry.add("spring.mongodb.database", () -> DATABASE); + } + + @AfterAll + static void dropIsolatedDatabase(@Autowired MongoTemplate mongoTemplate) { + assertThat(mongoTemplate.getDb().getName()).isEqualTo(DATABASE); + mongoTemplate.getDb().drop(); } @Test void findByTicketIdAndStoragePathFromPrimary_matchesOnlyThatTicketAndPath() { // setup - TicketAttachment target = repository.save(attachment(TICKET_ID, PATH)); - repository.save(attachment(TICKET_ID, OTHER_PATH)); - repository.save(attachment(OTHER_TICKET_ID, PATH)); + String ticketId = UUID.randomUUID().toString(); + String path = "attachments/" + ticketId + "/email-receipt-1/1-invoice.pdf"; + TicketAttachment target = repository.save(attachment(ticketId, path)); + repository.save(attachment(ticketId, "attachments/" + ticketId + "/email-receipt-1/2-photo.png")); + repository.save(attachment(UUID.randomUUID().toString(), path)); // execution - Optional found = repository.findByTicketIdAndStoragePathFromPrimary(TICKET_ID, PATH); + Optional found = repository.findByTicketIdAndStoragePathFromPrimary(ticketId, path); // verifications assertThat(found).map(TicketAttachment::getId).contains(target.getId()); } + @Test + void insertIfAbsentWithResult_existingPath_returnsOriginalWithoutCountingAnInsertion() { + // setup + String ticketId = UUID.randomUUID().toString(); + String path = "attachments/" + ticketId + "/email-receipt-1/1-invoice.pdf"; + TicketAttachment original = attachment(ticketId, path); + TicketAttachment retry = original.toBuilder().fileName("different-name").build(); + + // execution + TicketAttachmentInsertionResult first = repository.insertIfAbsentWithResult(original); + TicketAttachmentInsertionResult second = repository.insertIfAbsentWithResult(retry); + + // verifications + assertThat(first.inserted()).isTrue(); + assertThat(second.inserted()).isFalse(); + assertThat(second.attachment()).isEqualTo(first.attachment()); + assertThat(repository.findByTicketIdAndStoragePathFromPrimary(ticketId, path)) + .contains(first.attachment()); + } + + @Test + void insertNewAttempt_committedCopyAlreadyExists_returnsOriginalActualPath() { + // setup + String ticketId = UUID.randomUUID().toString(); + String logicalPath = "attachments/" + ticketId + "/chat/file"; + String firstPath = logicalPath + "/first-attempt"; + TicketAttachment original = attachment(ticketId, firstPath); + TicketAttachment retry = attachment(ticketId, logicalPath + "/next-attempt"); + + // execution + TicketAttachmentInsertionResult first = repository.insertIfAbsentWithResult(original, logicalPath); + TicketAttachmentInsertionResult second = repository.insertIfAbsentWithResult(retry, logicalPath); + + // verifications + assertThat(first.inserted()).isTrue(); + assertThat(second.inserted()).isFalse(); + assertThat(second.attachment()).isEqualTo(first.attachment()); + assertThat(repository.findByTicketId(ticketId)).containsExactly(first.attachment()); + assertThat(first.attachment().getStoragePath()).isEqualTo(firstPath); + } + + @Test + void insertNewAttempt_previouslyLinkedLogicalPath_reusesExistingAttachmentId() { + // setup + String ticketId = UUID.randomUUID().toString(); + String logicalPath = "attachments/" + ticketId + "/chat/file"; + TicketAttachment existing = repository.insertIfAbsent(attachment(ticketId, logicalPath)); + + // execution + TicketAttachmentInsertionResult attempt = repository.insertIfAbsentWithResult( + attachment(ticketId, logicalPath + "/new-attempt"), logicalPath); + + // verifications + assertThat(attempt.inserted()).isFalse(); + assertThat(attempt.attachment()).isEqualTo(existing); + assertThat(repository.findById(existing.getId())).contains(existing); + } + private static TicketAttachment attachment(String ticketId, String storagePath) { return TicketAttachment.builder() - .tenantId(TENANT_ID) + .tenantId("tenant-1") .ticketId(ticketId) .fileName("file") .contentType("application/octet-stream") diff --git a/openframe-data-mongo-sync/src/test/java/com/openframe/data/repository/ticket/CustomTicketRepositoryActivitySearchTest.java b/openframe-data-mongo-sync/src/test/java/com/openframe/data/repository/ticket/TicketRepositoryOperationsActivitySearchTest.java similarity index 96% rename from openframe-data-mongo-sync/src/test/java/com/openframe/data/repository/ticket/CustomTicketRepositoryActivitySearchTest.java rename to openframe-data-mongo-sync/src/test/java/com/openframe/data/repository/ticket/TicketRepositoryOperationsActivitySearchTest.java index 3928b3c2a6..cd1bd86619 100644 --- a/openframe-data-mongo-sync/src/test/java/com/openframe/data/repository/ticket/CustomTicketRepositoryActivitySearchTest.java +++ b/openframe-data-mongo-sync/src/test/java/com/openframe/data/repository/ticket/TicketRepositoryOperationsActivitySearchTest.java @@ -37,7 +37,7 @@ import static org.mockito.Mockito.when; @ExtendWith(MockitoExtension.class) -class CustomTicketRepositoryActivitySearchTest { +class TicketRepositoryOperationsActivitySearchTest { private static final Instant CUT_OFF = Instant.parse("2026-10-20T10:00:00Z"); private static final String AND_OPERATOR = "$and"; @@ -57,11 +57,11 @@ class CustomTicketRepositoryActivitySearchTest { @Mock private ObjectProvider ticketSpec; @Captor private ArgumentCaptor queryCaptor; - private CustomTicketRepositoryImpl repository; + private TicketRepositoryOperationsImpl repository; @BeforeEach void setUp() { - repository = new CustomTicketRepositoryImpl(mongoTemplate, outboxPublisher, ticketSpec); + repository = new TicketRepositoryOperationsImpl(mongoTemplate, outboxPublisher, ticketSpec); } @ParameterizedTest @@ -123,7 +123,7 @@ void buildTicketQuery_numericSearchWithActivity_ticketNumberAlternativeKept() { // verifications assertThat(alternativeCountsOf(query)).containsExactly(1, TEXT_ALTERNATIVES + 1); assertThat(conjunctsOf(query)).last() - .extracting(CustomTicketRepositoryActivitySearchTest::alternativesOf, list(Document.class)) + .extracting(TicketRepositoryOperationsActivitySearchTest::alternativesOf, list(Document.class)) .last() .isEqualTo(new Document("ticketNumber", 4217)); } @@ -257,7 +257,7 @@ private static List conjunctsOf(Document query) { private static List alternativeCountsOf(Document query) { return conjunctsOf(query).stream() - .map(CustomTicketRepositoryActivitySearchTest::alternativesOf) + .map(TicketRepositoryOperationsActivitySearchTest::alternativesOf) .map(List::size) .toList(); } diff --git a/openframe-data-mongo-sync/src/test/java/com/openframe/data/repository/ticket/CustomTicketRepositoryCursorTest.java b/openframe-data-mongo-sync/src/test/java/com/openframe/data/repository/ticket/TicketRepositoryOperationsCursorTest.java similarity index 99% rename from openframe-data-mongo-sync/src/test/java/com/openframe/data/repository/ticket/CustomTicketRepositoryCursorTest.java rename to openframe-data-mongo-sync/src/test/java/com/openframe/data/repository/ticket/TicketRepositoryOperationsCursorTest.java index 73231c8bd9..a11218f2ad 100644 --- a/openframe-data-mongo-sync/src/test/java/com/openframe/data/repository/ticket/CustomTicketRepositoryCursorTest.java +++ b/openframe-data-mongo-sync/src/test/java/com/openframe/data/repository/ticket/TicketRepositoryOperationsCursorTest.java @@ -43,7 +43,7 @@ import static org.mockito.Mockito.when; @ExtendWith(MockitoExtension.class) -class CustomTicketRepositoryCursorTest { +class TicketRepositoryOperationsCursorTest { private static final String ID_FIELD = "_id"; private static final String TICKET_NUMBER = "ticketNumber"; @@ -87,11 +87,11 @@ class CustomTicketRepositoryCursorTest { @Captor private ArgumentCaptor queryCaptor; - private CustomTicketRepositoryImpl repository; + private TicketRepositoryOperationsImpl repository; @BeforeEach void setUp() { - repository = new CustomTicketRepositoryImpl(mongoTemplate, outboxPublisher, ticketSpec); + repository = new TicketRepositoryOperationsImpl(mongoTemplate, outboxPublisher, ticketSpec); } @Test diff --git a/openframe-data-mongo-sync/src/test/java/com/openframe/data/repository/ticket/CustomTicketRepositoryFilterTest.java b/openframe-data-mongo-sync/src/test/java/com/openframe/data/repository/ticket/TicketRepositoryOperationsFilterTest.java similarity index 98% rename from openframe-data-mongo-sync/src/test/java/com/openframe/data/repository/ticket/CustomTicketRepositoryFilterTest.java rename to openframe-data-mongo-sync/src/test/java/com/openframe/data/repository/ticket/TicketRepositoryOperationsFilterTest.java index 4c0bfa88f7..df36792de3 100644 --- a/openframe-data-mongo-sync/src/test/java/com/openframe/data/repository/ticket/CustomTicketRepositoryFilterTest.java +++ b/openframe-data-mongo-sync/src/test/java/com/openframe/data/repository/ticket/TicketRepositoryOperationsFilterTest.java @@ -32,7 +32,7 @@ import static org.assertj.core.api.Assertions.assertThat; @ExtendWith(MockitoExtension.class) -class CustomTicketRepositoryFilterTest { +class TicketRepositoryOperationsFilterTest { private static final Instant CUT_OFF = Instant.parse("2026-10-20T10:00:00Z"); @@ -46,11 +46,11 @@ class CustomTicketRepositoryFilterTest { @Captor private ArgumentCaptor queryCaptor; @Captor private ArgumentCaptor updateCaptor; - private CustomTicketRepositoryImpl repository; + private TicketRepositoryOperationsImpl repository; @BeforeEach void setUp() { - repository = new CustomTicketRepositoryImpl(mongoTemplate, outboxPublisher, ticketSpec); + repository = new TicketRepositoryOperationsImpl(mongoTemplate, outboxPublisher, ticketSpec); } @Test diff --git a/openframe-data-mongo-sync/src/test/java/com/openframe/data/repository/ticket/CustomTicketRepositoryStampTest.java b/openframe-data-mongo-sync/src/test/java/com/openframe/data/repository/ticket/TicketRepositoryOperationsStampTest.java similarity index 93% rename from openframe-data-mongo-sync/src/test/java/com/openframe/data/repository/ticket/CustomTicketRepositoryStampTest.java rename to openframe-data-mongo-sync/src/test/java/com/openframe/data/repository/ticket/TicketRepositoryOperationsStampTest.java index 72f419ead4..0551492f13 100644 --- a/openframe-data-mongo-sync/src/test/java/com/openframe/data/repository/ticket/CustomTicketRepositoryStampTest.java +++ b/openframe-data-mongo-sync/src/test/java/com/openframe/data/repository/ticket/TicketRepositoryOperationsStampTest.java @@ -21,7 +21,7 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; -class CustomTicketRepositoryStampTest { +class TicketRepositoryOperationsStampTest { private static final Instant ACTIVITY = Instant.parse("2026-01-01T00:05:00Z"); private static final Document KEEP_VERSION = new Document("version", 0); @@ -31,7 +31,7 @@ class CustomTicketRepositoryStampTest { private final ObjectProvider outboxPublisher = mock(ObjectProvider.class); @SuppressWarnings("unchecked") private final ObjectProvider ticketSpec = mock(ObjectProvider.class); - private final CustomTicketRepositoryImpl repository = new CustomTicketRepositoryImpl(mongoTemplate, outboxPublisher, + private final TicketRepositoryOperationsImpl repository = new TicketRepositoryOperationsImpl(mongoTemplate, outboxPublisher, ticketSpec); @Test diff --git a/openframe-data-mongo-sync/src/test/java/com/openframe/data/repository/ticket/CustomTicketRepositoryStatusMoveTest.java b/openframe-data-mongo-sync/src/test/java/com/openframe/data/repository/ticket/TicketRepositoryOperationsStatusMoveTest.java similarity index 90% rename from openframe-data-mongo-sync/src/test/java/com/openframe/data/repository/ticket/CustomTicketRepositoryStatusMoveTest.java rename to openframe-data-mongo-sync/src/test/java/com/openframe/data/repository/ticket/TicketRepositoryOperationsStatusMoveTest.java index 3614027762..6685f699eb 100644 --- a/openframe-data-mongo-sync/src/test/java/com/openframe/data/repository/ticket/CustomTicketRepositoryStatusMoveTest.java +++ b/openframe-data-mongo-sync/src/test/java/com/openframe/data/repository/ticket/TicketRepositoryOperationsStatusMoveTest.java @@ -17,14 +17,14 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; -class CustomTicketRepositoryStatusMoveTest { +class TicketRepositoryOperationsStatusMoveTest { private final TenantAwareMongoTemplate mongoTemplate = mock(TenantAwareMongoTemplate.class); @SuppressWarnings("unchecked") private final ObjectProvider outboxPublisher = mock(ObjectProvider.class); @SuppressWarnings("unchecked") private final ObjectProvider ticketSpec = mock(ObjectProvider.class); - private final CustomTicketRepositoryImpl repository = new CustomTicketRepositoryImpl(mongoTemplate, outboxPublisher, + private final TicketRepositoryOperationsImpl repository = new TicketRepositoryOperationsImpl(mongoTemplate, outboxPublisher, ticketSpec); @Test diff --git a/openframe-data-mongo-sync/src/test/java/com/openframe/data/repository/ticket/CustomTicketRepositoryTitleTest.java b/openframe-data-mongo-sync/src/test/java/com/openframe/data/repository/ticket/TicketRepositoryOperationsTitleTest.java similarity index 88% rename from openframe-data-mongo-sync/src/test/java/com/openframe/data/repository/ticket/CustomTicketRepositoryTitleTest.java rename to openframe-data-mongo-sync/src/test/java/com/openframe/data/repository/ticket/TicketRepositoryOperationsTitleTest.java index 13271bb7ce..9239aec7ff 100644 --- a/openframe-data-mongo-sync/src/test/java/com/openframe/data/repository/ticket/CustomTicketRepositoryTitleTest.java +++ b/openframe-data-mongo-sync/src/test/java/com/openframe/data/repository/ticket/TicketRepositoryOperationsTitleTest.java @@ -15,12 +15,12 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -class CustomTicketRepositoryTitleTest { +class TicketRepositoryOperationsTitleTest { private final TenantAwareMongoTemplate mongoTemplate = mock(TenantAwareMongoTemplate.class); private final OutboxPublisher publisher = mock(OutboxPublisher.class); private final TicketAggregateSpec spec = mock(TicketAggregateSpec.class); - private final CustomTicketRepositoryImpl repository = buildRepository(); + private final TicketRepositoryOperationsImpl repository = buildRepository(); // The generated title arrives while the user may save the same ticket; a lost title would stay null for good. @Test @@ -43,11 +43,11 @@ void aSecondConflict_reachesTheCaller() { } @SuppressWarnings("unchecked") - private CustomTicketRepositoryImpl buildRepository() { + private TicketRepositoryOperationsImpl buildRepository() { ObjectProvider outboxPublisher = mock(ObjectProvider.class); when(outboxPublisher.getIfAvailable()).thenReturn(publisher); ObjectProvider ticketSpec = mock(ObjectProvider.class); when(ticketSpec.getIfAvailable()).thenReturn(spec); - return new CustomTicketRepositoryImpl(mongoTemplate, outboxPublisher, ticketSpec); + return new TicketRepositoryOperationsImpl(mongoTemplate, outboxPublisher, ticketSpec); } } diff --git a/openframe-data-mongo-sync/src/test/java/com/openframe/data/service/GcsAttachmentStorageContractTest.java b/openframe-data-mongo-sync/src/test/java/com/openframe/data/service/GcsAttachmentStorageContractTest.java new file mode 100644 index 0000000000..13d7da99d8 --- /dev/null +++ b/openframe-data-mongo-sync/src/test/java/com/openframe/data/service/GcsAttachmentStorageContractTest.java @@ -0,0 +1,210 @@ +package com.openframe.data.service; + +import com.google.cloud.NoCredentials; +import com.google.cloud.storage.Storage; +import com.google.cloud.storage.StorageOptions; +import com.sun.net.httpserver.HttpExchange; +import com.sun.net.httpserver.HttpServer; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.parallel.Execution; + +import java.io.IOException; +import java.net.InetSocketAddress; +import java.util.Arrays; +import java.util.OptionalLong; +import java.util.concurrent.atomic.AtomicReference; + +import static java.nio.charset.StandardCharsets.UTF_8; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.junit.jupiter.api.parallel.ExecutionMode.CONCURRENT; + +@Execution(CONCURRENT) +class GcsAttachmentStorageContractTest { + + private static final String FILE_PATH = "upload/file"; + private static final byte[] CONTENT = "sample".getBytes(UTF_8); + private static final String JSON = "application/json"; + private static final String NOT_FOUND = """ + {"error":{"code":404,"message":"Object not found"}} + """; + private static final String PRECONDITION_FAILED = """ + {"error":{"code":412,"message":"Object already exists"}} + """; + private static final String SUCCESSFUL_COPY = """ + {"done":true,"totalBytesRewritten":"6","objectSize":"6", + "resource":{"bucket":"bucket","name":"tenant/ticket/file","generation":"12","size":"6"}} + """; + + private final AtomicReference mediaRead = new AtomicReference<>(); + private final AtomicReference deletedGeneration = new AtomicReference<>(); + private volatile long objectSize = CONTENT.length; + private volatile byte[] media = CONTENT; + private volatile boolean sourceMissing; + private volatile boolean sourceMissingAtCopy; + private HttpServer server; + private GcsPresignedUrlService service; + + @BeforeEach + void startStorageProvider() throws IOException { + server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); + server.createContext("/", this::handleStorageRequest); + server.start(); + Storage storage = StorageOptions.newBuilder() + .setHost("http://127.0.0.1:" + server.getAddress().getPort()) + .setProjectId("attachment-contract-test") + .setCredentials(NoCredentials.getInstance()) + .build() + .getService(); + service = new GcsPresignedUrlService("bucket", "tenant", true, storage); + } + + @AfterEach + void stopStorageProvider() { + if (server != null) { + server.stop(0); + } + } + + @Test + void requestsOnlyTheBoundedRangeFromTheVerifiedGeneration() { + // execution + byte[] file = service.readFile(FILE_PATH, 10L); + + // verifications + assertThat(file).isEqualTo(CONTENT); + assertThat(mediaRead.get().query()).contains("generation=7"); + assertThat(mediaRead.get().range()).isEqualTo("bytes=0-10"); + } + + @Test + void rejectsMediaLargerThanTheDeclaredMetadataWithoutReadingPastTheOverflowByte() { + // setup + media = "longer than ten bytes".getBytes(UTF_8); + + // execution and verifications + assertThatThrownBy(() -> service.readFile(FILE_PATH, 10L)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("File exceeds the allowed size"); + assertThat(mediaRead.get().range()).isEqualTo("bytes=0-10"); + } + + @Test + void identifiesMissingCopySource() { + // setup + sourceMissing = true; + + // execution and verifications + assertThatThrownBy(() -> service.copyImmutableDownload(FILE_PATH, "ticket/file", "text/plain")) + .isInstanceOf(GcsCopySourceNotFoundException.class) + .hasMessage("Immutable copy source is unavailable"); + } + + @Test + void deletesOnlyTheCreatedCopyGeneration() { + // execution + OptionalLong copiedGeneration = service.copyImmutableDownloadGeneration(FILE_PATH, "ticket/file", "text/plain"); + service.deleteFileGeneration("ticket/file", copiedGeneration.orElseThrow()); + + // verifications + assertThat(copiedGeneration).hasValue(12); + assertThat(deletedGeneration.get()).contains("generation=12", "ifGenerationMatch=12"); + } + + @Test + void identifiesSourceThatDisappearsAfterMetadataLookup() { + sourceMissingAtCopy = true; + + assertThatThrownBy(() -> service.copyImmutableDownload(FILE_PATH, "ticket/file", "text/plain")) + .isInstanceOf(GcsCopySourceNotFoundException.class) + .hasMessage("Immutable copy source is unavailable"); + } + + @Test + void identifiesLargerExistingObjectAsAnImmutableConflictWithoutReadingIt() { + // setup + objectSize = CONTENT.length + 1; + + // execution and verifications + assertThatThrownBy(() -> service.writeFileIfAbsent(FILE_PATH, "text/plain", CONTENT)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Immutable file already contains different bytes"); + assertThat(mediaRead.get()).isNull(); + } + + private void handleStorageRequest(HttpExchange request) throws IOException { + if ("DELETE".equals(request.getRequestMethod())) { + respondWithDelete(request); + return; + } + if ("POST".equals(request.getRequestMethod())) { + respondToWrite(request); + return; + } + String query = request.getRequestURI().getQuery(); + if (query != null && query.contains("alt=media")) { + respondWithMedia(request, query); + return; + } + respondWithMetadata(request); + } + + private void respondWithDelete(HttpExchange request) throws IOException { + deletedGeneration.set(request.getRequestURI().getQuery()); + try (request) { + request.sendResponseHeaders(204, -1); + } + } + + private void respondToWrite(HttpExchange request) throws IOException { + if (request.getRequestURI().getPath().contains("/rewriteTo/")) { + respondToRewrite(request); + return; + } + respond(request, 412, JSON, PRECONDITION_FAILED.getBytes(UTF_8)); + } + + private void respondToRewrite(HttpExchange request) throws IOException { + if (sourceMissingAtCopy) { + respond(request, 404, JSON, NOT_FOUND.getBytes(UTF_8)); + return; + } + respond(request, 200, JSON, SUCCESSFUL_COPY.getBytes(UTF_8)); + } + + private void respondWithMetadata(HttpExchange request) throws IOException { + if (sourceMissing) { + respond(request, 404, JSON, NOT_FOUND.getBytes(UTF_8)); + return; + } + String metadata = """ + {"bucket":"bucket","name":"tenant/upload/file","generation":"7","size":"%d"} + """.formatted(objectSize); + respond(request, 200, JSON, metadata.getBytes(UTF_8)); + } + + private void respondWithMedia(HttpExchange request, String query) throws IOException { + String range = request.getRequestHeaders().getFirst("Range"); + mediaRead.set(new MediaRead(query, range)); + if (range == null) { + respond(request, 200, "text/plain", media); + return; + } + int lastByte = Math.min(Integer.parseInt(range.substring("bytes=0-".length())), media.length - 1); + request.getResponseHeaders().set("Content-Range", "bytes 0-" + lastByte + "/" + media.length); + respond(request, 206, "text/plain", Arrays.copyOf(media, lastByte + 1)); + } + + private static void respond(HttpExchange request, int status, String contentType, byte[] body) throws IOException { + request.getResponseHeaders().set("Content-Type", contentType); + request.sendResponseHeaders(status, body.length); + try (request) { + request.getResponseBody().write(body); + } + } + + private record MediaRead(String query, String range) { + } +} diff --git a/openframe-data-mongo-sync/src/test/java/com/openframe/data/service/GcsPresignedUrlServiceReadTest.java b/openframe-data-mongo-sync/src/test/java/com/openframe/data/service/GcsPresignedUrlServiceReadTest.java new file mode 100644 index 0000000000..ae7b0e326d --- /dev/null +++ b/openframe-data-mongo-sync/src/test/java/com/openframe/data/service/GcsPresignedUrlServiceReadTest.java @@ -0,0 +1,301 @@ +package com.openframe.data.service; + +import com.google.cloud.ReadChannel; +import com.google.cloud.storage.Blob; +import com.google.cloud.storage.BlobId; +import com.google.cloud.storage.BlobInfo; +import com.google.cloud.storage.Storage; +import com.google.cloud.storage.StorageException; +import com.google.cloud.storage.CopyWriter; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.Captor; +import org.mockito.ArgumentCaptor; +import org.mockito.junit.jupiter.MockitoExtension; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.net.URI; +import java.nio.ByteBuffer; +import java.nio.channels.Channels; +import java.nio.channels.ReadableByteChannel; +import java.time.Duration; +import java.util.Map; +import java.util.OptionalLong; +import java.util.concurrent.TimeUnit; + +import static java.nio.charset.StandardCharsets.UTF_8; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; + +@ExtendWith(MockitoExtension.class) +class GcsPresignedUrlServiceReadTest { + + private static final BlobId SENT_ID = BlobId.of("bucket", "tenant/ready/file", 9L); + private static final BlobId TICKET_ID = BlobId.of("bucket", "tenant/ticket/file"); + private static final Map DRAFT_ORIGIN = Map.of( + "immutable-copy-origin-path", "tenant/draft/file", "immutable-copy-origin-generation", "7"); + + @Mock + private Storage storage; + @Mock + private Blob blob; + @Mock + private Blob ticketBlob; + @Mock + private ReadChannel reader; + @Mock + private CopyWriter copyWriter; + @Captor + private ArgumentCaptor copyRequestCaptor; + @Captor + private ArgumentCaptor blobInfoCaptor; + @Captor + private ArgumentCaptor signOptionsCaptor; + + private GcsPresignedUrlService service; + + @BeforeEach + void setUp() { + service = new GcsPresignedUrlService("bucket", "tenant", true, storage); + } + + @Test + void rejectsOversizedObjectBeforeDownloading() { + // setup + when(storage.get(BlobId.of("bucket", "tenant/upload/file"))).thenReturn(blob); + when(blob.getSize()).thenReturn(11L); + + // execution + assertThatThrownBy(() -> service.readFile("upload/file", 10L)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("File exceeds the allowed size"); + + // verifications + verify(blob, never()).reader(); + } + + @Test + void rejectsMissingObject() { + // setup + when(storage.get(BlobId.of("bucket", "tenant/upload/file"))).thenReturn(null); + + // execution + assertThatThrownBy(() -> service.readFile("upload/file", 10L)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Uploaded file not found"); + + // verifications + verify(storage).get(BlobId.of("bucket", "tenant/upload/file")); + } + + @Test + void writesPrivateOriginalWithoutReplacingExistingFile() { + // setup + byte[] content = "sample".getBytes(UTF_8); + + // execution + service.writeFileIfAbsent("ready/file", "text/plain", content); + + // verifications + verify(storage).create(blobInfoCaptor.capture(), org.mockito.ArgumentMatchers.eq(content), + org.mockito.ArgumentMatchers.eq(Storage.BlobTargetOption.doesNotExist())); + assertThat(blobInfoCaptor.getValue().getBlobId()).isEqualTo(BlobId.of("bucket", "tenant/ready/file")); + assertThat(blobInfoCaptor.getValue().getContentType()).isEqualTo("text/plain"); + } + + @Test + void generateUploadUrl_signsContentTypeAndSizeRange() throws Exception { + // setup + Map headers = Map.of("Content-Type", "text/plain", "x-goog-content-length-range", "0,10"); + when(storage.signUrl(any(BlobInfo.class), eq(15L), eq(TimeUnit.MINUTES), + any(Storage.SignUrlOption[].class))).thenReturn(URI.create("https://storage.example/file").toURL()); + + // execution + service.generateUploadUrl("upload/file", Duration.ofMinutes(15), headers); + + // verifications + verify(storage).signUrl(blobInfoCaptor.capture(), eq(15L), eq(TimeUnit.MINUTES), signOptionsCaptor.capture()); + assertThat(signOptionsCaptor.getValue()).usingRecursiveFieldByFieldElementComparator() + .contains(Storage.SignUrlOption.withExtHeaders(headers)); + } + + @Test + void copyImmutableFile_sentFile_copiesWithoutOverwriting() { + // setup + BlobId draftId = BlobId.of("bucket", "tenant/draft/file", 7L); + when(storage.get(BlobId.of("bucket", "tenant/draft/file"))).thenReturn(blob); + when(blob.getBlobId()).thenReturn(draftId); + when(blob.getGeneration()).thenReturn(7L); + when(blob.getName()).thenReturn(draftId.getName()); + when(storage.copy(any(Storage.CopyRequest.class))).thenReturn(copyWriter); + + // execution + service.copyImmutableFile("draft/file", "ready/file", "text/plain"); + + // verifications + verify(storage).copy(copyRequestCaptor.capture()); + Storage.CopyRequest request = copyRequestCaptor.getValue(); + assertThat(request.getSource()).isEqualTo(draftId); + assertThat(request.getSourceOptions()).containsExactly(Storage.BlobSourceOption.generationMatch(7L)); + assertThat(request.getTarget().getName()).isEqualTo("tenant/ready/file"); + assertThat(request.getTarget().getMetadata()).isEqualTo(DRAFT_ORIGIN); + assertThat(request.overrideInfo()).isTrue(); + assertThat(request.getTargetOptions()).containsExactly(Storage.BlobTargetOption.doesNotExist()); + verify(copyWriter).getResult(); + } + + @Test + void copyImmutableDownload_matchingExistingCopy_reusesAcrossDifferentSentGenerations() { + // setup + stubTicketCopyConflict(); + when(blob.getSize()).thenReturn(7L); + when(ticketBlob.getCrc32c()).thenReturn("checksum"); + when(ticketBlob.getSize()).thenReturn(7L); + when(ticketBlob.getMetadata()).thenReturn(DRAFT_ORIGIN); + when(ticketBlob.getContentType()).thenReturn("text/plain"); + when(ticketBlob.getContentDisposition()).thenReturn("attachment"); + + // execution + OptionalLong generation = service.copyImmutableDownloadGeneration("ready/file", "ticket/file", "text/plain"); + + // verifications + assertThat(generation).isEmpty(); + verify(storage).copy(copyRequestCaptor.capture()); + Storage.CopyRequest copy = copyRequestCaptor.getValue(); + assertThat(copy.getSource()).isEqualTo(SENT_ID); + assertThat(copy.getTarget().getBlobId()).isEqualTo(TICKET_ID); + assertThat(copy.getTarget().getMetadata()).isEqualTo(DRAFT_ORIGIN); + assertThat(copy.getTarget().getContentDisposition()).isEqualTo("attachment"); + verify(blob, never()).reader(); + verify(ticketBlob, never()).reader(); + } + + @Test + void copyImmutableDownload_unrelatedTarget_failsWithoutDownloading() { + // setup + stubTicketCopyConflict(); + when(ticketBlob.getCrc32c()).thenReturn("different-checksum"); + + // execution + var error = assertThatThrownBy(() -> service.copyImmutableDownload("ready/file", "ticket/file", "text/plain")); + + // verifications + error.isInstanceOf(IllegalStateException.class).hasMessage("Immutable copy target does not match the verified source"); + verify(blob, never()).reader(); + verify(ticketBlob, never()).reader(); + } + + @Test + void signsDownloadsWithSafeOriginalFileNameAndContentType() throws Exception { + // setup + when(storage.signUrl(any(BlobInfo.class), eq(15L), eq(java.util.concurrent.TimeUnit.MINUTES), + any(Storage.SignUrlOption[].class))).thenReturn(java.net.URI.create("https://storage.example/file").toURL()); + + // execution + String result = service.generateDownloadUrl("ready/file", java.time.Duration.ofMinutes(15), + "résumé report.txt", "text/plain"); + + // verifications + assertThat(result).isEqualTo("https://storage.example/file"); + verify(storage).signUrl(blobInfoCaptor.capture(), eq(15L), eq(java.util.concurrent.TimeUnit.MINUTES), signOptionsCaptor.capture()); + assertThat(blobInfoCaptor.getValue().getName()).isEqualTo("tenant/ready/file"); + assertThat(signOptionsCaptor.getValue()).usingRecursiveFieldByFieldElementComparator().contains( + Storage.SignUrlOption.withQueryParams(java.util.Map.of( + "response-content-disposition", "attachment; filename*=UTF-8''r%C3%A9sum%C3%A9%20report.txt", + "response-content-type", "text/plain"))); + } + + @Test + void signsPreviewsWithInlineDispositionAndExplicitContentType() throws Exception { + // setup + var previewUrl = URI.create("https://storage.example/preview").toURL(); + when(storage.signUrl(any(BlobInfo.class), eq(15L), eq(TimeUnit.MINUTES), + any(Storage.SignUrlOption[].class))).thenReturn(previewUrl); + + // execution + String result = service.generatePreviewUrl("ready/file", Duration.ofMinutes(15), + "agent log*.csv", "text/plain; charset=utf-8"); + + // verifications + assertThat(result).isEqualTo(previewUrl.toString()); + verify(storage).signUrl(blobInfoCaptor.capture(), eq(15L), eq(TimeUnit.MINUTES), + signOptionsCaptor.capture()); + assertThat(blobInfoCaptor.getValue().getName()).isEqualTo("tenant/ready/file"); + assertThat(signOptionsCaptor.getValue()).usingRecursiveFieldByFieldElementComparator().contains( + Storage.SignUrlOption.withQueryParams(Map.of( + "response-content-disposition", "inline; filename*=UTF-8''agent%20log%2A.csv", + "response-content-type", "text/plain; charset=utf-8"))); + } + + @Test + void acceptsRetryOnlyWhenImmutableBytesMatch() throws IOException { + // setup + byte[] content = "sample".getBytes(UTF_8); + when(storage.create(any(BlobInfo.class), eq(content), any(Storage.BlobTargetOption[].class))) + .thenThrow(new com.google.cloud.storage.StorageException(412, "already exists")); + when(storage.get(BlobId.of("bucket", "tenant/ready/file"))).thenReturn(blob); + when(blob.getSize()).thenReturn(6L); + stubReadContent(content); + + // execution + service.writeFileIfAbsent("ready/file", "text/plain", content); + + // verifications + verify(reader).close(); + } + + @Test + void rejectsReplacingExistingImmutableBytes() throws IOException { + // setup + byte[] content = "sample".getBytes(UTF_8); + when(storage.create(any(BlobInfo.class), eq(content), any(Storage.BlobTargetOption[].class))) + .thenThrow(new com.google.cloud.storage.StorageException(412, "already exists")); + when(storage.get(BlobId.of("bucket", "tenant/ready/file"))).thenReturn(blob); + when(blob.getSize()).thenReturn(6L); + stubReadContent("edited".getBytes(UTF_8)); + + // execution + assertThatThrownBy(() -> service.writeFileIfAbsent("ready/file", "text/plain", content)) + .isInstanceOf(IllegalStateException.class).hasMessage("Immutable file already contains different bytes"); + + // verifications + verify(reader).close(); + } + + @Test + void reportsMissingRecoveryObject() { + // setup + when(storage.get(BlobId.of("bucket", "tenant/ready/file"))).thenReturn(null); + + // execution + boolean result = service.fileExists("ready/file"); + + // verifications + assertThat(result).isFalse(); + } + + private void stubReadContent(byte[] content) throws IOException { + ReadableByteChannel contents = Channels.newChannel(new ByteArrayInputStream(content)); + when(blob.reader()).thenReturn(reader); + when(reader.read(any(ByteBuffer.class))).thenAnswer(call -> contents.read(call.getArgument(0))); + } + + private void stubTicketCopyConflict() { + BlobId unversionedSentId = BlobId.of("bucket", "tenant/ready/file"); + when(storage.get(unversionedSentId)).thenReturn(blob); + when(blob.getGeneration()).thenReturn(9L); + when(blob.getBlobId()).thenReturn(SENT_ID); + when(blob.getMetadata()).thenReturn(DRAFT_ORIGIN); + when(blob.getCrc32c()).thenReturn("checksum"); + when(storage.copy(any(Storage.CopyRequest.class))).thenThrow(new StorageException(412, "Target exists")); + when(storage.get(TICKET_ID)).thenReturn(ticketBlob); + } +} diff --git a/openframe-data-mongo-sync/src/test/resources/junit-platform.properties b/openframe-data-mongo-sync/src/test/resources/junit-platform.properties new file mode 100644 index 0000000000..1d27b78fbb --- /dev/null +++ b/openframe-data-mongo-sync/src/test/resources/junit-platform.properties @@ -0,0 +1 @@ +junit.jupiter.execution.parallel.enabled=true diff --git a/openframe-data-nats/src/main/java/com/openframe/data/nats/publisher/NatsMessagePublisher.java b/openframe-data-nats/src/main/java/com/openframe/data/nats/publisher/NatsMessagePublisher.java index e59988f3b1..7e9353712a 100644 --- a/openframe-data-nats/src/main/java/com/openframe/data/nats/publisher/NatsMessagePublisher.java +++ b/openframe-data-nats/src/main/java/com/openframe/data/nats/publisher/NatsMessagePublisher.java @@ -4,12 +4,14 @@ import com.openframe.core.exception.NatsException; import io.nats.client.Connection; import io.nats.client.JetStream; +import io.nats.client.PublishOptions; import io.nats.client.api.PublishAck; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.stereotype.Service; +/** Publishes application messages and supports stable identities for JetStream delivery. */ @Service @RequiredArgsConstructor @Slf4j @@ -37,4 +39,13 @@ public PublishAck publishPersistent(String subject, T payload) { throw new NatsException("Error publishing persistent message to subject: " + subject, e); } } -} \ No newline at end of file + + public PublishAck publishPersistentWithId(String subject, T payload, String messageId) { + PublishOptions options = PublishOptions.builder().messageId(messageId).build(); + try { + return natsConnection.jetStream().publish(subject, objectMapper.writeValueAsBytes(payload), options); + } catch (Exception e) { + throw new NatsException("Error publishing persistent message to subject: " + subject, e); + } + } +}