Open MercatoDocsSearch docsAPI reference

Framework

Integrations & Data Sync

Separate the provider connection from an individual import. The integration owns settings and credentials. The sync run owns its parameters, progress and cancellation, which lets the next run reuse the same connection.

Open Mercato now includes a shared foundation for integration metadata (integrations) and a run orchestration hub (data_sync). Use this when you want to register provider bundles, store credentials per tenant, and execute import/export runs through workers.

What each module does

Register an integration manifest

Provider modules declare their integration metadata in integration.ts:

import {
  buildIntegrationDetailWidgetSpotId,
  type IntegrationBundle,
  type IntegrationDefinition,
} from '@open-mercato/shared/modules/integrations/types'

export const bundle: IntegrationBundle = {
  id: 'my_provider',
  title: 'My Provider',
  description: 'Bidirectional sync with My Provider.',
  credentials: {
    fields: [
      { key: 'apiUrl', label: 'API URL', type: 'url', required: true },
      { key: 'apiKey', label: 'API Key', type: 'secret', required: true },
    ],
  },
}

export const integrations: IntegrationDefinition[] = [
  {
    id: 'my_provider_products',
    title: 'My Provider Products',
    category: 'data_sync',
    hub: 'data_sync',
    providerKey: 'my_provider_products',
    bundleId: 'my_provider',
    detailPage: {
      widgetSpotId: buildIntegrationDetailWidgetSpotId('my_provider_products'),
    },
    credentials: { fields: [] },
  },
]

// Compatibility aliases for generator/discovery
export const integration = integrations[0]
export const bundles: IntegrationBundle[] = [bundle]

Integration detail page extensions

Provider modules can add custom tools to their own integration detail pages.

import { buildIntegrationDetailWidgetSpotId } from '@open-mercato/shared/modules/integrations/types'

export const injectionTable = {
  [buildIntegrationDetailWidgetSpotId('my_provider_products')]: [
    {
      widgetId: 'my_provider_products.injection.tools',
      kind: 'tab',
      groupLabel: 'my_provider_products.tabs.tools',
      priority: 100,
    },
    {
      widgetId: 'my_provider_products.injection.summary',
      kind: 'group',
      groupLabel: 'my_provider_products.groups.summary',
      priority: 80,
    },
  ],
}

Rendering semantics:

Built-in tab visibility is now provider-configurable through detailPage.hiddenTabs. This lets a provider hide stock sections such as credentials, health, or logs when they are not meaningful, then replace them with provider-specific tabs backed by injected widgets.

Example:

export const integration = {
  id: 'webhook_custom',
  title: 'Custom Webhooks',
  detailPage: {
    widgetSpotId: buildIntegrationDetailWidgetSpotId('webhook_custom'),
    hiddenTabs: ['credentials', 'health', 'logs'],
  },
} satisfies IntegrationDefinition

That pattern is useful when:

Compatibility note:

Register data sync adapters

Adapters are registered from provider setup.ts:

import type { ModuleSetupConfig } from '@open-mercato/shared/modules/setup'
import { registerDataSyncAdapter } from '../data_sync/lib/adapter-registry'
import { productsAdapter, ordersAdapter } from './lib/adapters'

export const setup: ModuleSetupConfig = {
  async onTenantCreated() {
    registerDataSyncAdapter(productsAdapter)
    registerDataSyncAdapter(ordersAdapter)
  },
}

export default setup

Adapter contract (data_sync/lib/adapter.ts) requires:

Honouring cancellation inside a batch

StreamImportInput and StreamExportInput carry an optional signal: AbortSignal. The engine aborts it as soon as it observes a cancellation request – including while your generator is still working on a batch it has not yielded yet. Without it, Cancel is only observed between batches, so an adapter whose batch is a slow page of records makes the operator wait out the whole page while the run holds its advisory lock.

async function* streamImport({ cursor, signal }: StreamImportInput): AsyncIterable<ImportBatch> {
  let page = cursor ?? null
  while (page) {
    const applied = await applyPage(page)
    // The return MUST sit above the yield. The engine commits `batch.cursor` for every batch it
    // receives, so yielding a half-applied page advances the cursor past records that were never
    // applied — and no later run walks them again.
    if (signal?.aborted) return
    // Derive `hasMore` from the source — never hardcode `true`. See below.
    yield {
      items: applied.items,
      cursor: applied.nextPage,
      hasMore: applied.nextPage !== null,
      batchIndex: applied.index,
    }
    page = applied.nextPage
  }
}

Check inside the per-record loop too, not only per page – a page whose records each go through the command bus is exactly the case where a batch outlasts the operator's patience. The in-tree adapters (sync_excel, sync_akeneo) do this and are worth copying.

Your final batch must report hasMore: false. A stream that drained and a stream the adapter stopped early on the signal both end the same way – the generator returns – so the engine uses the last batch's hasMore to tell them apart. An adapter that always reports true will have a complete run misreported as cancelled whenever a cancel lands during the final read, leaving the operator told that a finished sync was partial and the run resumable with nothing left to resume.

The signal is for work that happens before a yield. If your adapter does meaningful cleanup after its last batch – a reconcile pass, a deferred flush – let that cleanup finish rather than abandoning it on an abort. Once you have yielded hasMore: false you have declared everything delivered, and the run finalizes completed and is no longer resumable, so work skipped after that point never runs again for that cursor.

Release locks and connections in the generator's own finally – it runs when the engine closes the iterator on an early exit. The signal only reaches work running in the engine's own process: an adapter that hands part of a batch to other workers must give that work its own cancellation check. Adapters that ignore the signal keep the previous between-batches behavior.

Run parameters

An adapter can declare operator-facing parameters that the Data Sync dashboard renders as inputs on the "Run once now" card, in the spirit of a GitHub Actions workflow_dispatch input:

runParameters: [
  { key: 'dryRun', label: 'Dry run', type: 'boolean', defaultValue: false },
  { key: 'startId', label: 'Start id', type: 'number', min: 0 },
  { key: 'mode', label: 'Mode', type: 'select', options: [{ value: 'fast' }, { value: 'thorough' }] },
  // Offered only for this entity's run:
  { key: 'bulk', label: 'Bulk reindex', type: 'boolean', entityType: 'sales_orders' },
]

Types are boolean, string, number and select. A parameter may be scoped with direction (import/export) and/or entityType (a supportedEntities value or an array); unscoped parameters apply to every run.

POST /api/data_sync/run validates and coerces the submitted parameters object against the declaration – undeclared keys are dropped, blanks fall back to defaultValue, a required blank returns 422, and numbers respect min/max while select values must be members. The normalized values are persisted on sync_runs.parameters, shown read-only on the run detail page, retained across retries, and handed to the adapter on StreamImportInput.parameters / StreamExportInput.parameters.

Run parameters are operator-visible and stored in clear text, so they must never carry secrets – use the integration's credentials service for those.

For a multi-locale deployment, pair each literal with an i18n key – labelKey, descriptionKey, placeholderKey – which the dashboard prefers over label / description / placeholder. Validation failures return { key, code, params, message }, where code is one of required, type, min, max, select; the UI translates it through data_sync.runParameters.errors.<code> and treats the English message only as a fallback for non-UI callers.

Retrying a run re-normalizes the stored values against the adapter's current declaration, so parameters you have since removed or re-scoped are dropped and a value that no longer satisfies its declaration fails the retry with a 422 rather than reaching the adapter.

A recurring schedule cannot yet pin an operator-chosen value, but it does apply your declared defaults: the scheduled worker normalizes an empty input against the current declaration, so a scheduled run reaches the adapter with the same set an untouched dashboard form would rather than an empty object. Write the adapter against its defaults, not against undefined. A declared default that violates its own declaration skips the scheduled run with a logged error instead of starting it half-applied.

Start controls the dashboard renders

Alongside your runParameters, the "Run once now" card renders two controls the framework owns: Run as full sync and Batch size. Whether either one means anything depends on what your adapter does with the value for that entity type, which is something core cannot see. Declare it:

const adapter: DataSyncAdapter = {
  providerKey: 'my_provider',
  direction: 'import',
  supportedEntities: ['orders.feed', 'orders.backfill'],
  supportsStartControl: (control, entityType) =>
    !(control === 'fullSync' && entityType === 'orders.backfill'),
  // ...
}

Only an explicit false removes a control, so omitting the hook keeps today's form exactly. Return false where the operator's choice reaches you and changes nothing observable:

The predicate is per entity type for the same reason persistsSharedCursor is: one adapter commonly serves both an incremental feed and a whole-table backfill, and only one of them has a beginning to restart from.

GET /api/data_sync/options evaluates the predicate across your supportedEntities and ships the result as a sparse startControls map – entity types with no restriction are omitted, so an adapter that declares nothing sends {}.

This changes what the dashboard offers, not what the API accepts. POST /api/data_sync/run still honours both fields whatever you declare, so a script or an API client posting fullSync: true gets a null start cursor as before.

Do not infer the answer from persistsSharedCursor. Where a cursor is stored and whether restarting from scratch is meaningful are independent facts – an entity type kept out of the shared row can still have a genuine beginning – and both are yours to state.

Describing the progress job a run creates

By default, every run creates a progress job (a caller can opt out with createProgressJob: false), and the top bar shows every active one to every user with progress.view – and its Cancel works for the user who started the run (progress.cancel) or anyone holding progress.manage. That is right for a run that finishes, and wrong for one that is meant to keep going: a continuously running feed never reaches 100%, so the bar reads "1 operations running (0%)" forever and its Cancel stops the feed.

Declare how the job should read, per entity type:

const adapter: DataSyncAdapter = {
  providerKey: 'my_provider',
  direction: 'import',
  supportedEntities: ['orders.feed', 'orders.backfill'],
  describeProgressJob: ({ entityType }) =>
    entityType === 'orders.feed' ? { meta: { hiddenFromTopBar: true } } : undefined,
  // ...
}

The answer may set name, description and meta. It is consulted once per run by the helper every start path goes through – the dashboard's run route, Retry, the scheduled worker and your own provider routes – so a start path that passes no progress-job details of its own still gets it.

Shared cursor vs run-scoped cursor

Every committed batch advances the cursor on the run row (sync_runs.cursor) so a redelivered job resumes exactly where it stopped. By default the engine also mirrors that cursor into the shared sync_cursors row – one row per (integration, entityType, direction, organization, tenant) – which is what the next incremental run starts from.

That mirror is right for an incremental feed, whose cursor is a durable position in a change log, and wrong for a whole-table backfill, whose cursor is one run's scan state. Two runs of the same backfill (say a full walk and a walk narrowed to the last week) overwrite each other in that single row, so the survivor's window silently redefines where the next run starts.

Adapters that serve both kinds under one provider key opt out per entity type:

const adapter: DataSyncAdapter = {
  providerKey: 'my_provider',
  direction: 'bidirectional',
  supportedEntities: ['orders.feed', 'orders.backfill'],
  persistsSharedCursor: (entityType) => !entityType.endsWith('.backfill'),
  // ...
}

Omitting the hook keeps today's behaviour. When it returns false for an entity type:

Resetting an opted-out entity type

Reset flows that wipe imported data usually clear where the next run starts by deleting the shared sync_cursors row. An opted-out entity type has no such row, and deleting nothing leaves the resume position on the last interrupted run – so a reset followed by an incremental run would re-import only the tail of the walk it just reset against, which is the same silent partial import the opt-out exists to prevent.

Reset flows MUST therefore clear the run-scoped position too:

await syncRunService.resetResumePosition(integrationId, entityType, 'import', scope)

await em.nativeDelete(SyncCursor, { integrationId, entityType, direction: 'import', ...scope })

resetResumePosition clears the cursor on every run for that entity type that never reached completed – the only runs the resume path reads – and returns how many it cleared. It is a no-op when nothing was interrupted, so it is safe to call unconditionally, including for entity types that do keep the shared row.

Provider-owned environment preconfiguration

New integration providers should not require manual admin setup after every fresh install when deployment already knows the credentials and defaults. The provider package should own that bootstrap path itself.

Recommended pattern:

  1. Read provider env vars in a provider-local helper such as lib/preset.ts.
  2. Apply them from the provider module's setup.ts so tenant bootstrap can save credentials and default mappings automatically.
  3. Expose a provider-local CLI command such as configure-from-env so operators can rerun the same logic later.
  4. Persist through the normal integration services and data-sync mapping APIs instead of adding provider-specific branches to integrations or data_sync.
import type { ModuleSetupConfig } from '@open-mercato/shared/modules/setup'
import { applyMyProviderEnvPreset } from './lib/preset'

export const setup: ModuleSetupConfig = {
  async onTenantCreated({ em, tenantId, organizationId, container }) {
    await applyMyProviderEnvPreset({
      em,
      tenantId,
      organizationId,
      credentialsService: container.resolve('integrationCredentialsService'),
      stateService: container.resolve('integrationStateService'),
    })
  },
}

export default setup

Use stable provider-prefixed env names. Prefer the OM_INTEGRATION_<PROVIDER>_* shape for primary names.

Akeneo example envs

The Akeneo sync provider supports this pattern today. Primary envs:

OM_INTEGRATION_AKENEO_API_URL=
OM_INTEGRATION_AKENEO_CLIENT_ID=
OM_INTEGRATION_AKENEO_CLIENT_SECRET=
OM_INTEGRATION_AKENEO_USERNAME=
OM_INTEGRATION_AKENEO_PASSWORD=
OM_INTEGRATION_AKENEO_FORCE_PRECONFIGURE=false
OM_INTEGRATION_AKENEO_PRODUCT_LOCALE=
OM_INTEGRATION_AKENEO_CATEGORY_LOCALE=
OM_INTEGRATION_AKENEO_PRODUCT_CHANNEL=
OM_INTEGRATION_AKENEO_IMPORT_CHANNELS=
OM_INTEGRATION_AKENEO_IMPORT_ALL_CHANNELS=true
OM_INTEGRATION_AKENEO_CREATE_MISSING_CHANNELS=true
OM_INTEGRATION_AKENEO_SYNC_ASSOCIATIONS=true
OM_INTEGRATION_AKENEO_ATTRIBUTE_FAMILY_FILTER=
OM_INTEGRATION_AKENEO_PRODUCTS_SETTINGS_JSON=
OM_INTEGRATION_AKENEO_CATEGORIES_SETTINGS_JSON=
OM_INTEGRATION_AKENEO_ATTRIBUTES_SETTINGS_JSON=

Operational notes:

Run lifecycle

data_sync run flow:

  1. POST /api/data_sync/run creates a SyncRun row and a progress job.
  2. Run is queued (data-sync-import or data-sync-export).
  3. Worker resolves integration credentials + adapter mapping.
  4. Worker streams batches, updates counters/cursor, writes integration logs.
  5. Run completes, fails, or is cancelled; progress job is finalized.

Each run stores tenant and organization scope and must stay scoped in every read/write.

Retry, resume, and run again

A finished run offers one primary action, and sometimes one more behind the ⋯ overflow. Which ones appear is a property of the run's state, never of the operator – an action that does not apply is absent rather than disabled.

Run statePrimary actionOverflow
failedRetryRetry from the beginning
cancelledResumeStart from the beginning
completedRun again… –
running / pendingCancel –

Both the retry actions re-validate the stored run parameters against the adapter's current declaration, so a parameter you have removed or re-scoped falls away and a value that no longer satisfies its declaration fails the retry with a 422 instead of reaching your adapter.

The resume-point line

The run detail page states where a retry would resume, as a line beneath the actions.

SituationDetail page
The run committed at least one batch"Resumes from batch 41 – updated_at:2026-09-12T04:15:07Z"
The run committed no batch"This run committed no batch. Retry starts from this feed's last saved position, which may be earlier than this run began."

The runs list does not repeat it, and should not be changed to. RowActions renders each RowActionItem.label as the sole child of a fixed-width (w-44), whitespace-nowrap button, so a label carrying the resume point overflows the menu box rather than wrapping inside it – visibly so in the longer locales, where "Retry (resumes from this feed's last saved position)" runs to 64 characters in German against a budget of roughly 22. The row menu therefore names the action only (Retry / Resume), and the detail page is the single surface that states a position.

The no-committed-batch wording is deliberately non-committal, and must stay that way. It does not say "starts from the beginning", because that would often be false: the endpoint resolves a resumable retry as previous.cursor ?? resolveStartCursor(...), and resolveStartCursor reads the shared sync_cursors row (or, for an adapter that opted out, this entity type's own last run). A run that died on its first batch can therefore still resume at a cursor an earlier successful run wrote, silently skipping everything before it – exactly the partial-import trap the run-scoped cursor exists to prevent. The run row alone cannot predict that position, so the copy says only what the row knows, and Retry from the beginning stays available here precisely because it is the only action whose start position is knowable in advance.

The cursor is rendered verbatim in a monospace face and is never truncated or prettified – it is an adapter-defined opaque string, and the one value an operator can paste into a support ticket. Adapters must therefore never encode a credential or personal data in a cursor.

The run detail page also shows this run's own record – Started from (initialCursor) and Committed through (cursor) – for every state, including completed runs. Those describe what happened; the resume-point line above them is the only sentence about a future run.

Hiding the from-the-beginning action

An adapter can hide Retry from the beginning per entity type by declaring supportsStartControl('fullSync', entityType) as false – the same declaration that governs the "Run as full sync" switch on the start form. Use it for an entity type where a full replay means nothing. The run detail page states the restriction in one line beneath the actions; the runs list simply omits the menu item.

As everywhere else with this declaration, this is UI gating only. POST /api/data_sync/runs/[id]/retry keeps accepting fromBeginning: true from a script or an API client whatever you declare, exactly as POST /api/data_sync/run keeps honouring fullSync. And if the options request that resolves the declaration fails, the action renders rather than disappearing – failing open matches applicableStartControls, and hiding a valid action because an unrelated request failed would be worse.

Tracing

When telemetry is enabled, the engine wraps every batch in its own root span – data_sync.import.batch or data_sync.export.batch – linked back to the run's trace. Rooting per batch is deliberate: a sync run can last hours, and a trace inherits a single sampling decision from its root, so leaving batches nested under the triggering request would put a whole run behind one decision (emitting nothing below a sampling ratio of 1.0, or one unrenderable trace at 1.0).

The span covers the adapter's read as well as the engine's per-batch bookkeeping, so a batch trace is self-contained, and it carries data_sync.run_id, data_sync.integration_id, data_sync.provider_key, data_sync.entity_type, data_sync.direction, data_sync.batch_index, per-batch counters, and om.tenant_id / om.organization_id.

A stream is only known to be finished once a read comes back empty, and that read is real adapter work (often a remote page fetch), so it is traced too – under data_sync.import.drain / data_sync.export.drain rather than the batch name. A run over N batches therefore emits exactly N *.batch spans and one *.drain span, so counting or averaging *.batch measures batches only. Drain spans carry the run-level attributes but no data_sync.batch_index and no counters.

Adapters get this for free and should not create their own batch span; any spans an adapter does create nest under the engine's batch span as usual.

Credentials resolution

Credentials are stored by integration id. If the integration belongs to a bundle and per-integration credentials are empty, the system resolves bundle credentials as fallback. This allows one credential form to drive multiple bundle integrations.

Progress behavior (current state)

Use polling semantics as the supported behavior until event definitions and client listeners are updated.

Tests to keep

For phase A/B coverage, keep:

Publishing integration modules

Once your integration module is tested and production-ready, publish it as an npm package with create-mercato-module and list it in the Integrations & Data Sync category of Open Mercato Modules. This gives your integration discoverability, a nightly install check, and one-command installation for other Open Mercato users. See Modules catalog: Publish and list your module for details.

Previous: Devices · Next: OAuth2 Grants for Integrations