Skip to main content
Version: v1 (Current)

Entity Sync System - Architecture Overview

Contents​

1. Introduction​

Problem Statement​

The GxP platform synchronizes supported entities through registered Eventfinity, Cvent and Google Drive adapters. Additional third-party systems require explicit integration work. Providers can differ in:

  • Different API structures - REST, GraphQL, SOAP, etc.
  • Different authentication methods - OAuth 2.0, API keys, JWT, etc.
  • Different entity identifiers - Some use integer IDs, others use UUIDs or composite keys
  • Different field naming conventions - camelCase, snake_case, custom names
  • Different rate limiting strategies - Per-user, per-app, time-based quotas
  • Different operation semantics - Some support upsert, others require separate create/update

Managing these differences in an ad-hoc manner leads to duplicated code, inconsistent behavior, and difficult maintenance.

Solution Approach​

The Entity Sync System provides a pluggable architecture where new sync engines can be added by implementing two interfaces:

  1. SyncBuilder - Defines how to transform local entities into sync requests for a specific service
  2. RemoteServiceInterface - Handles HTTP communication with the remote service

The system uses several design patterns:

  • Registry Pattern - Central SyncRegistry maps service+entity combinations to builders
  • Builder Pattern - Builders construct complex SyncRequestPlan objects
  • Strategy Pattern - Different builders implement the same interface for different services
  • Readonly plan properties - DTO property reassignment is restricted; referenced state and remote effects still need concurrency/recovery handling
  • Adapter Pattern - Remote services adapt third-party SDKs to a common interface

Key Benefits​

  • Extensibility - Add explicit builders, registry entries and transport bindings; a new service can require changes to orchestration/configuration.
  • Testability - Mock builders and services for unit tests
  • Consistency - All syncs follow the same execution flow
  • Maintainability - Service-specific logic is isolated in builders
  • Reusability - Common patterns (discovery, persistence) are shared
  • Observability - Centralized logging and error handling

2. System Architecture​

2.1 High-Level Architecture​

Admin Workflow System
↓
SyncToServiceAction
↓
SyncEntityJob (dispatched to queue)
↓
SyncRegistry.get(service, entityType)
↓
[Service]Builder.buildRequestPlan()
↓
[Service]RemoteService.performSync()
↓
External API (Eventfinity, Google Drive, etc.)
↓
Builder.persistRemoteIdentifier()
↓
Builder.bustEntityCache()

2.2 Component Relationships​

SyncRegistry (Central Registry)

  • Maps service.entityType → SyncBuilder instance
  • Example: "eventfinity.attendee" → EventfinityAttendeeSyncBuilder
  • Registered in AppServiceProvider
  • Singleton pattern ensures one registry per application

SyncBuilder (Strategy)

  • Service-specific logic for one entity type
  • Example: EventfinityAttendeeSyncBuilder handles syncing attendees to Eventfinity
  • Implements the current 12-method SyncBuilder interface
  • Knows how to map fields, discover remote IDs, persist results

RemoteServiceInterface (Adapter)

  • HTTP communication abstraction
  • Example: EventfinityRemoteService wraps LegacyEventfinityService
  • Implements provider-specific authentication and request/error handling; the job handles retry orchestration.
  • Returns raw responses for builder to parse

Data Transfer Objects (Readonly properties)

  • SyncRequestPlan - Complete sync request specification
  • SyncContext - Workflow and entity context
  • RemoteDiscoveryPlan - Instructions for finding remote entities
  • RemotePersistencePlan - Instructions for storing remote IDs
  • Constructors expose readonly properties; referenced objects and streams remain mutable.

2.3 Registry Pattern Implementation​

The SyncRegistry is a simple but powerful central registry:

Platform source: app/Services/Sync/SyncRegistry.php

class SyncRegistry
{
/** @var array<string, SyncBuilder> */
protected array $builders = [];

/**
* Register a builder for a specific service and entity type.
*/
public function register(string $service, SyncBuilder $builder): void
{
$key = $this->buildKey($service, $builder->getEntityType());
$this->builders[$key] = $builder;
}

/**
* Get a builder for a specific service and entity type.
*/
public function get(string $service, string $entityType): ?SyncBuilder
{
$key = $this->buildKey($service, $entityType);
return $this->builders[$key] ?? null;
}

/**
* Build a unique key for a service and entity type combination.
*/
private function buildKey(string $service, string $entityType): string
{
return $service.'.'.$entityType;
}
}

Key Structure: service.entityType

  • "eventfinity.attendee" - Eventfinity attendee sync
  • "google_drive.social_stream_post" - Google Drive social-stream post sync
  • "cvent.agenda_item" - Cvent agenda-item sync

2.4 Current registrations and setup​

The application registers SyncRegistry as a singleton. Current service/entity keys are:

ServiceEntity type
eventfinityattendee
cventagenda_item, attendee, agenda_item_enrollment, agenda_item_speaker
google_drivesocial_stream_post

Google Drive and Cvent are implemented registrations, not future placeholders. This registry does not establish support for an arbitrary service or entity; for example, Salesforce in a general integration discussion is not a registered sync target here. Operation support is checked separately by each builder.

Configure the owning workflow with the intended registered service/entity, operation, integration token and service-specific context/mappings. The job requires an existing integration token and rejects a team-bound token whose team differs from the workflow team. That check alone does not certify remote credentials, provider authorization or every project-level constraint. Use the corresponding integration's supported setup and verify a controlled entity before selecting a large population.

The job selects remote services for eventfinity, cvent and google_drive and resolves the service-specific RemoteServiceInterface binding. Adding a builder registration alone does not add a new transport branch, credentials or supported workflow UI.

2.5 Data flow through the system​

A supported batch event starts a configured sync action. The action either constructs per-entity jobs eagerly or starts a manifest fan-out job inside the bus batch. Each entity job can skip, discover identity, perform a remote operation, persist an identifier and invalidate cache. Batch signals are correlated to a workflow invocation and reconciled against batch state; they are not a claim that every remote operation succeeded.

Inspect the workflow invocation, individual sync records and remote result together. Queued/dispatched, completed-with-failures, skipped and cancelled are distinct outcomes. Use workflow authoring and recovery for the supported operator surface.

3. Data Transfer Objects (DTOs)​

3.1 Overview​

The DTO constructors expose readonly properties. This prevents reassignment of those properties after construction; it does not freeze referenced Eloquent models, mutable timestamps, streams or nested objects. It does not establish a database snapshot, cross-job locking, thread safety or atomic remote/local updates. Inspect logs through the owning redaction path rather than assuming a DTO can always be dumped safely.

3.2 SyncRequestPlan​

SyncRequestPlan contains the operation, endpoint, HTTP method and payload, plus optional multipart flag/attachments, discovery/persistence plans, remote ID, local model, remote-field list and skip metadata. requiresRemoteIdentifier and shouldSkip default false; skipReason can explain an intentional skip.

discoveryRequired() is true only when a remote ID is required and remoteId is null or the empty string. Numeric zero is not considered missing by this method. The job's later persistence condition uses truthiness, which is a different boundary; do not use that distinction to assume a provider accepts zero as a usable ID. Builders create a new plan when applying discovery results.

3.3 SyncContext​

The context holds the workflow, workflow step, SyncContextDTO and configured operation. getEntity() and the magic entity property return the DTO's model reference. Other undefined magic properties throw. The readonly reference is not an immutable model snapshot.

3.4 SyncContextDTO​

This DTO holds entity, entity type, changed-field array, optional source event, source (event or schedule), optional source integration and requested-at Carbon timestamp. fromEvent reads changes, source_event, source_integration and timestamp, with empty/null/current-time defaults. fromSchedule takes explicit changes, sets scheduled source and null event/integration. The factory's existence alone does not prove every schedule UI or event source is wired to it. Builder rules determine what an empty change list means; it is not a universal full-sync command.

3.5 RemoteDiscoveryPlan​

The plan contains remote searchField, string searchValue and optional local field/path. It describes a lookup; it does not perform one or enforce unique remote matches. The builder/remote implementation must establish how zero, one and multiple matches are handled. Check the selected provider before assuming email is a safe identity key.

3.6 RemotePersistencePlan​

The plan contains a local field and optional local field path. The builder implements persistence after the remote operation. Workflow suppression, project ownership, type conversion and cache invalidation must be handled by the implementation; the DTO does not enforce them.

3.7 SyncFileAttachment​

Attachments carry field name, contents, optional filename, headers and optional multipart name. Contents is a mixed value (commonly bytes or a stream); readonly properties do not rewind, freeze or keep a stream open across queue serialization/retry. Verify the selected builder and transport's attachment lifecycle before dispatch.

3.8 SyncOperation Enum​

The enum values are create, update, upsert and delete. A value being recognized does not imply every builder supports it. The enum's supports helper returns true for CREATE/UPDATE when called on UPSERT; it does not return true for UPSERT itself in that branch. Builders' supportsOperation checks remain the actual operation gate. Discovery, changed-field filtering, remote deletion and payload behavior are implementation-specific.

4. Core Interfaces​

4.1 SyncBuilder Interface​

A builder implements 12 methods: getEntityType, getEntityClass, findEntity, supportsOperation, buildRequestPlan, resolveRemoteIdentifier, persistRemoteIdentifier, bustEntityCache, determineEndpoint, extractRemoteIdentifierFromResponse, getRemoteIdFieldName and applyDiscoveryResults.

Discovery receives model, discovery plan, remote service and context, returning an integer/string identifier or null. Persistence receives model, persistence plan and resolved identifier. Applying discovery receives the original plan, identifier and optional additional data, returning a new plan. Follow the actual PHP interface signatures when implementing an extension.

These contracts do not prescribe one universal endpoint suffix, remote-ID field, discovery match policy, transaction or workflow-suppression mechanism. Use the intended provider builder as a reference, enforce project scope during entity lookup and test unsupported operations, missing identity, ambiguous discovery, partial remote/local failure and replay before registration.

4.2 RemoteServiceInterface​

search(string $entityType, array $criteria, array $context): array returns search results. performSync(SyncRequestPlan $plan, array $context): mixed performs the request and returns provider data. The interface declares no common response schema, automatic retry policy, endpoint-ID suffix or guaranteed rate-limit detection. Each transport implements those details and can raise rate-limit or other exceptions. Preserve the job's error/recovery path rather than assuming all adapters behave identically.

5. Execution Flow​

5.1 Job orchestration (SyncEntityJob)​

  1. Check source-integration loop prevention and claim the workflow sync record. Resolve the builder by service/entity; missing registration raises a non-retryable error.
  2. Validate the operation (default upsert) and ask the builder whether it is supported. Unsupported operations are recorded as skips; they are not completed remote writes.
  3. Load the integration token, build service-specific context and construct the request plan. A no-relevant-change plan records a skip with its context.
  4. Perform discovery when required, apply the discovery result to a new plan, and call the remote service.
  5. Prefer a response identifier when provided, otherwise retain the request plan's remote ID. Persist it when a persistence plan and truthy resolved identifier are present, then bust the entity cache.

A successful external write and local identifier persistence are separate steps. Local failure after a remote response does not undo that remote operation. Reconcile remote identity and workflow records before retrying an ambiguous result; builder discovery or immutable DTOs are not universal exactly-once guarantees.

Rate-limit exceptions record a delayed retry and release the job using the supplied delay. Non-retryable exceptions caught by the execution path fail immediately; other caught exceptions record a retry and propagate to Laravel. The job uses a retry deadline and a separate genuine-exception budget, rather than promising a fixed number of dispatch attempts. Limiter/overlap releases can consume attempts without performing a remote request. Inspect the active queue/record state and provider-specific recovery contract before retrying.

5.2 Workflow integration (SyncToServiceAction)​

The action applies workflow permission scope, checks whether the workflow may run, resolves a supplied integration token through the scoped workflow helper, and checks the sync window. It requires a supported batch trigger. The legacy Eventfinity step selects eventfinity; the external-service step accepts google_drive or cvent. Other configured external service values are rejected here.

Test mode is declared DryRun, and retry-from-step is declared NotRetryable. These are workflow-engine contracts; directly calling execute() is not a standalone preview API. Do not equate queue-job retry with permission to replay the whole workflow step.

For eager batches, the action builds jobs from entities and their corresponding event data. Missing event data increments the skipped count. Empty batches return dispatched: false, null batch ID and explanatory detail; a missing or expired population is not a successful remote write.

Manifest-backed events are resolved against the workflow team and, for project-bound workflows, the workflow project. Missing/empty manifests and entity-type mismatches return an empty result. A supplied member-count mismatch is logged, while the stored manifest count remains authoritative. The bus batch initially includes a fan-out job, which streams member rows in chunks of 500 and adds entity jobs from inside that batch.

The fan-out rehydrates current entities and can skip missing entities or source-integration loops before queueing per-entity work. A durable cursor resumes after dispatched chunks, but a crash between adding a chunk and advancing the cursor can requeue work. Per-member dispatch keys and selected transport/job behavior provide separate replay mechanisms; the cursor alone is not exactly-once delivery. Manifest membership does not freeze the entity's later field values.

The action reports batch_id, total_jobs, skipped_count, service and dispatched. For a manifest path, initial total_jobs is the target member count, while settlement uses bus-batch accounting, which includes actual fan-out/job behavior. Do not assume the two values count identical units.

Batches allow individual failures and run on workflows-fanout. Their finally callback signals counts; catch can signal an error before all work has finished. The listener correlates the invocation and rechecks current batch state: a mid-flight error is recorded without immediately settling that still-running step. Terminal outcomes can include completed-with-failures, cancelled or failed. A completion-named event and the next workflow transition do not certify that every entity reached the remote service. Review the final invocation verdict and individual records before recovery.

6. Operational Patterns​

6.1 Eventfinity attendee operations​

The following behavior belongs to EventfinityAttendeeSyncBuilder; other registered builders define their own operation and endpoint rules.

OperationCurrent behavior
CREATESends mapped fields to POST attendees/upsert; skips when a remote ID is already stored.
UPDATEUses the same upsert endpoint. Without a stored remote ID, prepares email discovery before sending. Requires change data; otherwise skips.
UPSERTUses the same upsert endpoint. Limits fields to tracked changes when a remote ID exists. Requires change data; otherwise skips.
DELETEUnsupported by this builder.

An empty normalized mapping set raises a non-retryable validation error before request construction. Email is required for every outgoing attendee payload. After change filtering, the builder adds email from its mapping or, when no email mapping exists, the attendee's primary contact email. An empty mapped email does not automatically fall back to the primary contact. If email remains empty, request construction raises a non-retryable validation error before transport. event_attendee_id is retained when present. The transport wraps JSON fields in data; the endpoint is not selected by appending the remote ID.

6.2 Field Mapping System​

For an Eventfinity attendee step, map the remote identity to the reserved local Third Party ID field:

{
"field_mappings": [
{"remote_field": "event_attendee_id", "local_field": "third_party_id"},
{"remote_field": "email", "local_field": "contact_email"},
{"remote_field": "company", "local_field": "attendee_fields.company"}
]
}

The builder indexes mappings by remote field, so duplicate remote fields overwrite earlier entries. It derives a flat local slug by removing the attendee_fields. or attendee_fields-> prefix. Value lookup first checks that flat key, including an explicitly null value; otherwise it uses the original attendee array and local_field_path, or the original local_field when no explicit path is supplied. Use a dotted path for nested lookup. Normalization does not generally convert arbitrary arrow paths into dotted lookup paths.

Transformations are built into this builder by remote field name. checkin_status converts recognized boolean, numeric and boolean-string values into CHECKED_IN or NOT_CHECKED_IN; unrecognized values become null. Numeric attendee_type values resolve to a local attendee type's slug when found, otherwise retain the original value. Other fields pass through this transformation stage. There is no generic date-to-ISO or array-to-CSV mapping engine here.

Remote identifier persistence reloads the attendee, accepts only a normalized third_party_id destination, sets the Eventfinity source and saves. An invalid destination can fail after the remote write; configure the identity mapping correctly before dispatch. The workflow configuration validator also requires the Event Attendee ID mapping for a nonempty mapping set.

6.3 Discovery Mechanism​

For Eventfinity UPDATE without a stored identifier, the email mapping must provide a nonempty search value. Discovery searches remote attendees by email. Zero results, multiple results, malformed candidates or a missing identifier raise non-retryable errors. A unique valid result supplies the identifier for the new request plan; it does not certify that the ensuing remote write or local persistence will succeed.

These match rules are provider-specific. The shared discovery DTO and interface do not require every service to search by email or use the same result policy.

6.4 Change Detection & Optimization​

Eventfinity change data is an associative change set whose keys identify local fields. CREATE does not restrict its payload to changed fields. UPDATE with nonempty change data does; UPSERT does when a remote ID is present. UPDATE and UPSERT with no change data return no_change_data, while a limited payload with no mapped changes returns no_relevant_changes.

The builder compares normalized change keys with each mapping's slug, path and original field. It also considers an attachment URL field's base column. A parent key such as attendee_fields does not automatically match every nested mapping. For a company edit, provide the actual changed field key, such as attendee_fields.company, rather than assuming the whole bag will expand.

Filtering retains the remote identifier and adds the required email as described above. Consequently, the actual outgoing fields can include identity fields in addition to the mapped changes. The plan's remote-field list includes payload and attachment fields for recording what the request touched.

6.5 File Attachments​

Eventfinity reads mapped uploads from the attendee's configured storage disk when a path exists and can be opened as a stream. Successfully constructed attachments replace their scalar payload field and select multipart transport. Missing files or unreadable streams do not produce an attachment; they do not prove the remote field was cleared.

Avatar mappings (user_avatar or user_avatar_url) first try stored uploads, then a mapped valid URL. URL downloads use a 30-second timeout and buffer the response body into a temporary stream. Failed downloads return no attachment. This path is not a guarantee of bounded-memory streaming. Avatar files use the multipart name user_avatar.

LegacyEventfinityService sends ordinary fields as data[field] multipart parts and file parts using the attachment's explicit multipart name or data[field]. Non-multipart requests use JSON { "data": payload }. The request uses the integration token and a 120-second timeout. HTTP 429 supplies a rate-limit retry delay; 502/503 are treated as transient with a 30-second delay. Other failed responses raise an exception. Stream availability, remote acceptance and recovery after partial failure still need integration testing.

Source references in the platform repository: app/Services/Sync/Eventfinity/Builders/EventfinityAttendeeSyncBuilder.php, app/Services/Sync/Eventfinity/EventfinityRemoteService.php, app/Services/LegacyEventfinityService.php and app/Services/FieldMappings/Traits/NormalizesFieldMappings.php.

Further implementation guidance​

The registry chooses a service/entity builder; the builder constructs a request plan; the remote adapter performs the provider request. Discovery, field filtering, attachments and persistence must be verified for the selected provider. Readonly DTO properties do not supply transactions or exactly-once delivery.

See Building new sync engines for the extension guide.