Channels
On this page

Channels

This page is for the PHP developer who needs feeds to go somewhere the module does not deliver to: an FTP server, a cloud bucket, a directory another system collects from, or a platform's API. A channel is that destination. The store chooses it in the Channel field at the top of a feed's Channel section. The module registers three:

Type Label Kind
file File A file published on the store, at pub/media/arlanix/product-feeds/.
sftp SFTP ProductFeed's file adapter, using connections and transfers from Arlanix_Sftp.
google_api Google Merchant Center (API) ProductFeed's push channel, using accounts and API clients from Arlanix_GoogleMerchant.

A channel is one of two kinds:

  • A file channel writes the feed as a file at the feed's schedule, or when the store runs it from the grid, then hands the file to a delivery adapter. The module does the mapping, writing, scheduling and retries; you write the adapter. File and SFTP both use this kind.
  • A push channel sends changed rows in batches and records an outcome for each row. Use it for an API that can update and remove individual products.

The feed model stores the channel type. Callers inject Arlanix\ProductFeed\Model\Channel\ChannelPool and resolve the implementation with $channelPool->get($feed->getChannelType()); a type no installed module provides returns null.

Add a file channel

Write the delivery adapter

The following adapter copies a feed's file into a directory under var/export, where another system collects it. The feed's setting channel/export_directory names the directory:

<?php
declare(strict_types=1);

namespace Vendor\Module\Model\Delivery;

use Arlanix\ProductFeed\Model\Channel\ChannelException;
use Arlanix\ProductFeed\Model\Channel\File\DeliveryAdapterInterface;
use Arlanix\ProductFeed\Model\Channel\File\DeliveryResult;
use Arlanix\ProductFeed\Model\Channel\File\StagedFile;
use Arlanix\ProductFeed\Model\Feed;
use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Framework\Filesystem;
use Magento\Framework\Phrase;

class ExportDirectoryAdapter implements DeliveryAdapterInterface
{
    public const DIRECTORY = 'channel/export_directory';

    public function __construct(
        private readonly Filesystem $filesystem
    ) {
    }

    public function deliver(Feed $feed, StagedFile $stagedFile): DeliveryResult
    {
        $directory = trim((string)$feed->getSetting(self::DIRECTORY), '/');
        if ($directory === '' || str_contains($directory, '..')) {
            throw new ChannelException(new Phrase('Choose the export directory of this feed.'));
        }
        $path = $directory . '/' . $feed->getIdentifier() . '.' . $stagedFile->getExtension();

        $var = $this->filesystem->getDirectoryWrite(DirectoryList::VAR_DIR);
        $export = $this->filesystem->getDirectoryWrite(DirectoryList::VAR_EXPORT);
        $temporary = $path . '.' . bin2hex(random_bytes(6)) . '.tmp';
        try {
            $var->copyFile($stagedFile->getRelativePath(), $temporary, $export);
            $export->renameFile($temporary, $path);
        } catch (\Throwable $failure) {
            try {
                $export->delete($temporary);
            } catch (\Throwable) {
                // Preserve the copy or rename failure if cleanup also fails.
            }
            throw $failure;
        }

        return new DeliveryResult(destination: 'var/export/' . $path);
    }
}

After the writer finishes and the file passes the empty-feed check, the channel calls your adapter once:

  • $stagedFile is the feed's file, written whole in the module's temporary storage. $stagedFile->open() gives a Magento\Framework\Filesystem\File\ReadInterface on it; close it when you are done. getExtension() and getSize() describe it. The module deletes the file after deliver() returns, so copy or upload it within the call.
  • $feed->getSetting(self::DIRECTORY) reads the feed's settings; see Add the channel's settings.
  • To fail the delivery, throw Arlanix\ProductFeed\Model\Channel\ChannelException. The run fails with its message, and cron retries the feed while it is active. The wait increases up to one hour, and the first retry can fall earlier if the feed's schedule comes first; see When a run fails.
  • Return a File\DeliveryResult. Its url, the address the platform fetches the file from, or its destination, a path on another server, is what the run's message names: Delivered 1779 row(s) to var/export/marketplace/google-shopping.csv. Its third argument, meta, is anything else the run should record.

Register the channel

In your module's etc/di.xml, make the channel a File\Channel with your adapter and what the admin shows of it, and add it to Channel\ChannelPool under its type:

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <virtualType name="Vendor\Module\Model\Delivery\ExportDirectoryChannel"
                 type="Arlanix\ProductFeed\Model\Channel\File\Channel">
        <arguments>
            <argument name="label" xsi:type="string" translate="true">Export directory</argument>
            <argument name="deliveryAdapter"
                      xsi:type="object">Vendor\Module\Model\Delivery\ExportDirectoryAdapter\Proxy</argument>
            <argument name="onDemandLabel" xsi:type="string" translate="true">Export now</argument>
            <argument name="onDemandMessage" xsi:type="string" translate="true">Feed "%1" is queued. Its file is exported by the feed cron, usually within a minute.</argument>
            <argument name="deletedNotice" xsi:type="string" translate="true">Files already exported were left in the export directory.</argument>
        </arguments>
    </virtualType>

    <type name="Arlanix\ProductFeed\Model\Channel\ChannelPool">
        <arguments>
            <argument name="channels" xsi:type="array">
                <item name="export_directory"
                      xsi:type="object">Vendor\Module\Model\Delivery\ExportDirectoryChannel</item>
            </argument>
        </arguments>
    </type>
</config>

The item's name is the channel's type, which a feed stores. The pool builds every channel with it, so a grid or a form that only shows labels builds the channels too: give an adapter that opens connections or loads a platform's SDK as its \Proxy, as above, and it is made only when a feed is delivered. The channel's arguments:

Argument Value
label The name in the Channel field and the grid.
deliveryAdapter Your adapter.
onDemandLabel Optional. The label of the row action in the grid's Select menu that queues the feed. The form also offers Save & followed by this label. Omit it to hide the on-demand action.
onDemandMessage The message after the action queues the feed; %1 is the feed's identifier.
publishesFile Optional, true only when the file ends up at a public address of the store, as with File. The form then shows File name and the file's URL.
deletedNotice Optional. The notice shown after a feed of this type is deleted, saying what stays behind, %1 being the feed's identifier. Without it, deleting says only that the feed was deleted.

A feed on a file channel gets the Format field and the Schedule section from the module, with no form XML of yours; see Writers for the formats.

Add the channel's settings

A channel's settings go in the feed form's Channel section, are stored with the feed under channel/, and are read with $feed->getSetting('channel/export_directory') in this example. Register each setting and add its form field. You can also validate it on save.

  1. Register the setting in etc/di.xml, inside the <config> element. getSetting() throws Magento\Framework\Exception\LocalizedException for an unregistered path. For a text setting, use the string normaliser:

    <virtualType name="Arlanix\ProductFeed\Model\Feed\SettingPool">
        <arguments>
            <argument name="settings" xsi:type="array">
                <item name="channel/export_directory" xsi:type="array">
                    <item name="normalise"
                          xsi:type="object">Arlanix\Core\Model\Settings\Normaliser\StringNormaliser</item>
                </item>
            </argument>
        </arguments>
    </virtualType>
    

    For an integer, use Arlanix\Core\Model\Settings\Normaliser\IntNormaliser.

  2. Add the field to the Channel section in view/adminhtml/ui_component/arlanix_product_feed_form.xml. variants lists the channel types the field belongs to; the form shows it only while Channel is one of them. Add the export directory field as follows:

    <form xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd">
        <fieldset name="channel">
            <field name="export_directory" formElement="input" sortOrder="100">
                <argument name="data" xsi:type="array">
                    <item name="config" xsi:type="array">
                        <item name="variants" xsi:type="array">
                            <item name="0" xsi:type="string">export_directory</item>
                        </item>
                    </item>
                </argument>
                <settings>
                    <label translate="true">Export directory</label>
                    <notice translate="true">A directory under var/export, such as marketplace.</notice>
                    <dataType>text</dataType>
                    <validation>
                        <rule name="required-entry" xsi:type="boolean">true</rule>
                    </validation>
                </settings>
            </field>
        </fieldset>
    </form>
    
  3. Optional: check the settings when the feed is saved. A validator that adds messages refuses the save and shows them. Check only feeds of your channel, and only when the save carries the settings:

    <?php
    declare(strict_types=1);
    
    namespace Vendor\Module\Model\Feed;
    
    use Arlanix\ProductFeed\Model\Feed;
    use Magento\Framework\Phrase;
    use Magento\Framework\Validator\AbstractValidator;
    use Vendor\Module\Model\Delivery\ExportDirectoryAdapter;
    
    class ExportDirectoryValidator extends AbstractValidator
    {
        public function isValid($value): bool
        {
            $this->_clearMessages();
            if (!$value instanceof Feed || $value->getChannelType() !== 'export_directory'
                || !$value->hasSection(Feed::SETTINGS)) {
                return true;
            }
            $directory = (string)$value->getSetting(ExportDirectoryAdapter::DIRECTORY);
            if (str_contains($directory, '..')) {
                $this->_addMessages([(string)new Phrase('The export directory must stay under var/export.')]);
            }
    
            return !$this->hasMessages();
        }
    }
    

    Add the validator to the feed inside the same <config> element in etc/di.xml:

    <type name="Arlanix\ProductFeed\Model\Feed">
        <arguments>
            <argument name="validators" xsi:type="array">
                <item name="export_directory" xsi:type="object">Vendor\Module\Model\Feed\ExportDirectoryValidator</item>
            </argument>
        </arguments>
    </type>
    

Then run bin/magento setup:upgrade and bin/magento cache:clean config. Open a feed, set Channel to Export directory, fill in Export directory, save, and choose Export now in the row's Select menu.

Add a push channel

A push channel is for a platform whose API can update individual products. The module stores each valid mapped row as a JSON payload, together with its hash. It records the external ID the adapter supplies after a successful send and the error code and message after a refusal. Pending product changes are queued separately, once per product, so every variant is read together and a delivery acknowledgement cannot erase a newer change. Each run sends the rows that changed, retries refused rows, and takes down rows the feed no longer has.

Implement Arlanix\ProductFeed\Model\Channel\Push\PlatformAdapterInterface in your adapter. For an adapter named Vendor\Module\Model\Channel\MarketplaceApi, register the push channel in your module's etc/di.xml:

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <virtualType name="Vendor\Module\Model\Channel\MarketplaceChannel"
                 type="Arlanix\ProductFeed\Model\Channel\Push\Channel">
        <arguments>
            <argument name="label" xsi:type="string" translate="true">Marketplace (API)</argument>
            <argument name="platformAdapter" xsi:type="object">Vendor\Module\Model\Channel\MarketplaceApi\Proxy</argument>
            <argument name="deletedNotice" xsi:type="string" translate="true">The products of feed "%1" stay on the marketplace until you remove them there.</argument>
        </arguments>
    </virtualType>

    <type name="Arlanix\ProductFeed\Model\Channel\ChannelPool">
        <arguments>
            <argument name="channels" xsi:type="array">
                <item name="marketplace_api" xsi:type="object">Vendor\Module\Model\Channel\MarketplaceChannel</item>
            </argument>
        </arguments>
    </type>
</config>

A push channel takes label and deletedNotice as a file channel does. Set refreshAfterDays to a positive whole number of days to resend unchanged rows. The refresh can fall up to four days earlier depending on the product ID. Omit it to leave refresh disabled. The nightly arlanix_product_feed_refresh_delivered job picks the rows; Google's channel sets 25. It has no onDemandLabel or onDemandMessage arguments and no publishesFile argument: its feeds run whenever their products change, and the form hides Format and Schedule for them. Its settings are added as for a file channel; see Add the channel's settings.

Push persistence lives in Arlanix\ProductFeed\Model\ResourceModel: ProductChange records product events and acknowledges their captured tokens; ChannelItem stores staged rows and delivery state. Bulk product events are written in bounded batches, with one token per call, so queuing a large update does not build one SQL payload for the whole list. ProductChange::hasPending() checks for mapping events, while ChannelItem::hasPendingWork() checks delivery work ready for sending or removal. After any retry wait, the push channel checks both, along with the build version, to decide whether it is due. Arlanix\ProductFeed\Model\Indexer\ChangeQueue::readBatch() reads Magento view events without removing them. Arlanix\ProductFeed\Model\Schedule\RetryLadder::retryAt() returns an absolute timestamp.

What the interface asks

Every push session supports individual product removal through remove(). An API that only accepts complete files uses a file delivery adapter.

An adapter may also implement Arlanix\ProductFeed\Model\Channel\Push\PrepareDeliveryInterface. Its prepare(Feed $feed): void is called under the feed's run lock before row comparison, even when no row needs sending. Use it to reconcile a destination's settings or register a destination and mark its products for resending. Skip remote calls when the destination is already up to date. An exception fails the run before mapping; no session has been opened to discard. For an adapter implementing only PlatformAdapterInterface, the first adapter call is start().

Cron first collects product IDs from the feed views into the product-change queue. Run\Runner holds the feed lock and calls the channel's deliver(), which builds pending rows before sending them. Direct callers of deliver() get the same build and delivery sequence. A run goes in this order:

  1. It maps changed products into the staging table. When the feed's rules change, it rebuilds the table from the catalogue, resuming from the saved product cursor if the deadline stops it.
  2. Once the full catalogue pass finishes, it marks rows no longer in the feed for removal and completes that build, then processes queued product changes. Products with pending events stay protected until read again; their events do not block other products' removals.
  3. If time remains and there is work ready to send or remove, it checks that removals would not empty the feed unless the feed allows it. It then calls start() to open the run's SessionInterface.
  4. It reads ready payloads from the table and calls accept() in batches of 25 by default. Set the push channel's slice argument to change the batch size. If a row changes its external ID, the channel also calls remove() for the old ID when no present row holds it. Refused payloads wait for their retry time; changed values replace the payload and end its wait. Retrying does not read or map the product again.
  5. If the complete mapping permits removals, it calls remove() for rows no longer in the feed, unless a present row still holds the same external ID. Every session that completes calls finish().

The feed's version is its current configuration version, and build_version is the last fully built version. A partial catalogue build keeps build_version unchanged and saves its cursor in build_after_id. Each staged row records the build_version used for its payload.

Changed-product batches share one store emulation. ProductChange::readChanges() reads each batch's product IDs and event tokens together; an event is acknowledged only after its mapped page is saved. A newer event for the same product remains queued. The deadline is checked between batches. buildPendingRows() remains available to callers that only need to stage rows.

A response acknowledges the hash actually sent. A late response to an older payload leaves a newer payload pending.

If accept(), remove() or finish() throws, the run calls the session's discard() and fails. If start() throws, the run fails with no session to discard. A run with nothing to send or take down calls none of them.

What a run holds, the account it signed in to, the platform's name for the feed, what it counted, lives on the session, so nothing of one feed's run is left on the channel for the next feed's: the channel is one object for every feed of its type, the session one per run.

Method Does
start(Feed $feed, Deadline $deadline): SessionInterface Starts a run and returns its session. Read the feed ID and settings from $feed; $deadline limits how long a retry may wait. Throw from here, for an account that cannot sign in for instance, to fail the run before anything is sent.

Feed is Arlanix\ProductFeed\Model\Feed and Deadline is Arlanix\Core\Model\Deadline. The returned SessionInterface is in the same namespace as PlatformAdapterInterface. Its methods are:

Method Does
accept(array $rows): BatchResult Sends Arlanix\ProductFeed\Model\Mapping\BuiltRow objects. $row->getValues() gives field to value; $row->getKey() identifies the row, the product id or the product id with a variant key.
remove(array $externalIds): BatchResult Takes down rows, given as row key to the identity accept() returned for them.
finish(): array Ends a run that went through. What it returns is recorded with the run. If it throws, discard() follows.
discard(): void Ends a run that failed while sending, or whose finish() threw.

accept() and remove() answer for each row with an Arlanix\ProductFeed\Model\Channel\Push\BatchResult, keyed by the row's key. For example, if accept() sends row 42 and the platform refuses row 43, its result is:

<?php
use Arlanix\ProductFeed\Model\Channel\Push\BatchResult;

return new BatchResult([
    '42' => ['status' => BatchResult::SYNCED, 'external_id' => 'offer/42'],
    '43' => ['status' => BatchResult::FAILED,
             'error_code' => 'invalid_gtin', 'error_message' => 'The GTIN is not valid.'],
]);
  • SYNCED marks a row as sent. Its external_id, the platform's name for it, can occupy up to 255 bytes and is given back to remove() when the row is taken down. Without a stored external ID, the channel has nothing to pass to remove().
  • For a pending send or removal, FAILED marks the row as refused. It is offered again on the waits of a failed run for as long as it is refused, and on the next run once its values change; see When Google refuses a product. The feed's products list shows the message as The channel refused it: …, and Health in the grid counts the row as refused.
  • From remove(), DELETED marks a row as taken down, or already gone. An outcome for a row the call was not handed is ignored.
  • A pending send or removal with no outcome counts as refused unless the batch stopped part way. When cleaning up a replaced external ID, any result other than DELETED, including no answer for that ID, produces a warning. Remove the old ID manually. The channel does not retry that cleanup.

When the platform fails as a whole, rather than for one product, stop instead of refusing every row: return what was done so far with a reason as the second argument, stoppedBecause: new BatchResult($results, 'The account was suspended.'). For pending sends and removals, the rows already answered keep their outcome, the rows not reached keep their place for the next run, and the run fails with Stopped part way: and the reason. The feed then waits as after any failure; saving the feed ends the wait.

Do not throw from accept() or remove() once the platform has answered for some rows. An exception fails the run with its own message, and the module records no outcomes for that call. Pending sends or removals can therefore reach the platform again.

Cron shares a 50-second deadline across feeds. The channel checks it before starting each send or removal batch. Cleanup of a replaced external ID is part of the send batch. The arlanix:product-feed:generate command passes a deadline with no time limit. Google's adapter hands each batch to its API client once. The channel records refusals for retry. An adapter that needs to wait inside a call must respect the $deadline passed to start().

When the feed is saved

The feed form's Controller\Adminhtml\Feed\Save calls Service\FeedDataSourceService directly for an active Merchant API feed, after storing it. Registration holds the feed's run lock, and a failure is reported through the admin's message manager while the feed stays saved. Other channels can register their remote resources from PrepareDeliveryInterface::prepare() before a run; see What the interface asks.

When only a person can settle it

When the platform has lost something only the store can put right, throw Arlanix\ProductFeed\Model\Run\SaveRequiredException, a ChannelException, from prepare(), start() or a session's send, removal or finish method. The run fails once with its message and The feed is not run again until it is saved., the grid's Schedule says waits for the feed to be saved, and cron waits until the feed is saved. Google's channel throws it when the feed's data source was deleted in Merchant Center.

ProductFeed's Merchant API implementation is a complete push channel: Arlanix\ProductFeed\Model\Channel\MerchantApiAdapter and its MerchantApiSession in vendor/arlanix/module-product-feed. The reusable API clients and account services are in vendor/arlanix/module-google-merchant.