App Builder · Ep 3: cron, config and custom tables, once your code leaves Adobe Commerce

Step 1 of 7

An Adobe Commerce (Magento 2) module is more than its business logic. It ships with a crontab.xml, a system.xml for settings, maybe a db_schema.xml with its own tables, observers, plugins and a log file in var/log/. When the logic moves to App Builder, every one of those needs a new home. If you skip that mapping, you end up with an action that works on demo day and has no schedule, no settings and no memory.

This episode does the mapping first. Then it builds the most common case: a job that runs every 15 minutes, finds orders stuck in pending_payment, and alerts the team once per order, not once per run. About an hour. In short: crontab.xml becomes an alarm trigger plus a rule in app.config.yaml, system.xml settings become action inputs read from .env, and custom tables become State, Files or Database Storage, depending on whether the data expires, is a blob, or needs queries.

Where each part of a module goes

In an Adobe Commerce moduleIn App BuilderWhere in this series
crontab.xml and cron groupsAn alarm trigger plus a rule that runs an actionthis one
system.xml and core_config_dataAction inputs from .env, or a settings page through the Admin UI SDKhere; Admin UI SDK pages in episode 9
Custom tables in db_schema.xmlState for key-value data with a time to live, Files for blobs and exports, Database Storage for records you queryhere; Database Storage in episode 4
Observers in events.xmlAdobe I/O Events registrationsepisode 6
Plugins on core methodsWebhooksepisode 7
Message queue consumersEvents, with retries and idempotent handlersthe pattern is in episode 6
var/log/*.logaio app logs, or log forwarding to your log platformhere; forwarding in episode 5

Two points here matter more than they look. First, nothing in App Builder shares a database with Adobe Commerce, so anything you used to JOIN now comes from an API call. Second, State, the key-value store scoped to your workspace, has a time to live by design: it remembers what you did, then forgets. It is not a system of record.

You’ll need

  • The project from episode 2, deployed to Stage
  • A Commerce integration access token with read access to Sales > Operations > Orders
  • On PaaS, Commerce configured to accept integration tokens as bearer tokens: Stores > Configuration > Services > OAuth > Consumer Settings > Allow OAuth Access Tokens to be used as standalone Bearer tokens
  • A webhook URL to alert, such as a Slack or Teams incoming webhook

Schedule the action with an alarm

Scheduling is two entries in app.config.yaml. A trigger fires on a cron expression using the built-in alarms feed. A rule connects that trigger to an action. The action itself is not web: 'yes', because nothing outside should call it.

application:
  runtimeManifest:
    packages:
      ops:
        actions:
          stuck-orders:
            function: actions/stuck-orders/index.js
            runtime: nodejs:20
            inputs:
              LOG_LEVEL: info
              COMMERCE_BASE_URL: $COMMERCE_BASE_URL
              COMMERCE_TOKEN: $COMMERCE_TOKEN
              ALERT_WEBHOOK_URL: $ALERT_WEBHOOK_URL
              STUCK_AFTER_MINUTES: 30
            annotations:
              final: true
        triggers:
          every15Minutes:
            feed: /whisk.system/alarms/alarm
            inputs:
              cron: '*/15 * * * *'
        rules:
          stuckOrdersSchedule:
            trigger: every15Minutes
            action: stuck-orders

Tip: The feed also offers /whisk.system/alarms/interval for "every N minutes" and /whisk.system/alarms/once for a single run at a date. The cron expression is in UTC, so a "9 a.m. India time" job is 30 3 * * *.

Ask Commerce for stuck orders

The action reads its settings from params, which come from the inputs above. It asks the Commerce REST API for orders still in pending_payment that were created before the cut-off, oldest first.

const stateLib = require('@adobe/aio-lib-state')
const { Core } = require('@adobe/aio-sdk')

async function findStuckOrders (params) {
  const cutoff = new Date(Date.now() - Number(params.STUCK_AFTER_MINUTES) * 60000)
    .toISOString().slice(0, 19).replace('T', ' ')
  const q = new URLSearchParams({
    'searchCriteria[filter_groups][0][filters][0][field]': 'status',
    'searchCriteria[filter_groups][0][filters][0][value]': 'pending_payment',
    'searchCriteria[filter_groups][1][filters][0][field]': 'created_at',
    'searchCriteria[filter_groups][1][filters][0][value]': cutoff,
    'searchCriteria[filter_groups][1][filters][0][condition_type]': 'lt',
    'searchCriteria[sortOrders][0][field]': 'created_at',
    'searchCriteria[sortOrders][0][direction]': 'ASC',
    'searchCriteria[pageSize]': '50',
    fields: 'items[increment_id,grand_total,created_at]'
  })
  const base = String(params.COMMERCE_BASE_URL).replace(/\/+$/, '')
  const res = await fetch(`${base}/rest/V1/orders?${q}`, {
    headers: { Authorization: `Bearer ${params.COMMERCE_TOKEN}` }
  })
  if (!res.ok) throw new Error(`Commerce returned ${res.status}`)
  return (await res.json()).items || []
}

Separate filter groups combine with AND, which is what this job needs: status and age. The sort matters more than it looks. Without it, a gateway outage that leaves 80 orders stuck returns the same first 50 on every run, and the other 30 are never reported. Oldest first, the alerted ones drop out and the rest come through on the next run.

Remember what you already alerted with State

Without memory, the job alerts on the same order every 15 minutes until someone fixes it, and the channel gets muted by lunchtime. State is a key-value store scoped to your workspace. Keep one key per alerted order, with a time to live longer than the order can stay stuck. Read and write in two separate steps, because the order matters: remember an order only after the alert went out. Mark it first, and a webhook that fails once means that order is never alerted at all.

const safe = v => String(v).replace(/[^a-zA-Z0-9-_.]/g, '_')

async function notAlertedYet (state, orders) {
  const fresh = []
  for (const o of orders) {
    if (!(await state.get(`stuck-${safe(o.increment_id)}`))) fresh.push(o)
  }
  return fresh
}

async function markAlerted (state, orders) {
  for (const o of orders) {
    await state.put(`stuck-${safe(o.increment_id)}`, '1', { ttl: 7 * 24 * 3600 })
  }
}

Tip: Keys allow letters, numbers, dashes, underscores and dots, and order numbers don't always stick to that, so safe() replaces anything else. Prefix every key with the job name, so two jobs in the same workspace never collide.

Stop overlapping runs with a lock

Adobe Commerce's cron runner locks each job, so a job never overlaps itself. An alarm has no such lock: if one run takes longer than 15 minutes, the next starts anyway. A short-lived key in State works as a lock, as long as taking it is one call. put with ifNotExists writes the key only if it isn't there yet and returns null if it is, so two runs can't both think they got it.

async function withLock (state, name, seconds, fn) {
  const key = `lock-${name}`
  const got = await state.put(key, String(Date.now()), { ttl: seconds, ifNotExists: true })
  if (got === null) return { skipped: true }
  try { return await fn() } finally { await state.delete(key) }
}

The time to live frees a lock left behind by a run that crashed. ifNotExists needs @adobe/aio-lib-state 5.4 or later. If you take State from @adobe/aio-sdk, check the version. The SDK accepts any 5.x, so an older lock file can keep a release that ignores the option without an error. npm ls @adobe/aio-lib-state shows which one you have.

Put it together and alert

The job takes the lock, asks Commerce for stuck orders, drops the ones it has already alerted, sends one alert for the rest, and only then marks them in State.

async function sendAlert (webhookUrl, orders) {
  const lines = orders.map(o => `#${o.increment_id} (${o.grand_total}) since ${o.created_at}`)
  const res = await fetch(webhookUrl, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ text: `Orders stuck in pending_payment:\n${lines.join('\n')}` })
  })
  if (!res.ok) throw new Error(`alert webhook returned ${res.status}`)
}

async function main (params) {
  const logger = Core.Logger('stuck-orders', { level: params.LOG_LEVEL || 'info' })
  try {
    const state = await stateLib.init()
    return await withLock(state, 'stuck-orders', 600, async () => {
      const fresh = await notAlertedYet(state, await findStuckOrders(params))
      if (fresh.length) {
        await sendAlert(params.ALERT_WEBHOOK_URL, fresh)
        await markAlerted(state, fresh)
      }
      logger.info(`stuck orders alerted: ${fresh.length}`)
      return { statusCode: 200, body: { alerted: fresh.length } }
    })
  } catch (e) {
    logger.error(e)
    return { statusCode: 500, body: { error: e.message } }
  }
}
exports.main = main

fetch doesn't throw on a 500, so sendAlert checks res.ok itself. A rate-limited or rotated webhook then fails the run loudly, nothing is marked, and the next run tries again. Deploy with aio app deploy. Then run it once by hand rather than waiting for the clock: aio rt action invoke ops/stuck-orders --result.

Use Files for anything bigger than a value

If the job should also keep a CSV of what it found, for finance or for an audit trail, that's not State's job. Use Files, App Builder's blob storage.

const filesLib = require('@adobe/aio-lib-files')
const files = await filesLib.init()
await files.write(`reports/stuck-orders/${new Date().toISOString().slice(0, 10)}.csv`, csv)

For data you'd have kept in a real table, with queries by field, that's App Builder's Database Storage, the subject of episode 4. Otherwise keep that data in the system that owns it, and reach it through its API.

Watch it run

Every alarm-triggered run is a normal activation, so the usual tools work:

aio rt trigger list
aio rt rule list
aio rt activation list
aio app logs

If the rule shows as inactive, nothing runs and nothing errors. aio rt rule enable stuckOrdersSchedule fixes it. It works the other way too: aio app deploy switched my disabled rules back on, twice, so run aio rt rule disable stuckOrdersSchedule again after a deploy if the job shouldn't be running yet. Episode 9 will give these alerts a page in the Commerce admin.

Tested on: unit tests of the job against a mocked Commerce and State, and a real Stage workspace. There I've seen State store a string value with a 7-day time to live, a deploy create the trigger and rule, and aio rt rule disable stop them. The lock call is checked from a local script, not from two alarm runs: of three concurrent put calls with ifNotExists, one won and two got null. The alarm has fired too: enabling the rule made it fire on the quarter hour and start the action.

Not tested: the job and its alert for real (with no Commerce credentials deployed, the alarm's run returned an error), and the Files write on a real workspace. The current list is in the repo README.

Done!

Your module now has a schedule, settings and memory outside Adobe Commerce. Episode 4 gives it a real database for the data State can't hold.

> the job, its config and unit tests against a mocked Commerce and StateGitHub · ep3-cron-state-files →Agent hand-off →

Written by Vishwas Bhatnagar

Technical Architect. Adobe Commerce, marketplaces and AI-assisted engineering.

More about me →

More