Channels
On this page

This page is for version 1.0. Read the current version.

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/feeds/.
sftp SFTP A file uploaded to an SFTP server, from Arlanix_FeedSftp.
google_api Google Merchant Center (API) Products sent one by one to Google's Merchant API, from Arlanix_FeedGoogleMerchant.

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. Most destinations are this kind.
  • A push channel sends products one by one, whenever one changes, and records what the platform did with each. Choose it only for an API that takes products individually.

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\Feed\Model\Channel\ChannelException;
use Arlanix\Feed\Model\Channel\File\DeliveryAdapterInterface;
use Arlanix\Feed\Model\Channel\File\FileReceipt;
use Arlanix\Feed\Model\Channel\File\StagedFile;
use Arlanix\Feed\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 $file): FileReceipt
    {
        $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() . '.' . $file->getExtension();

        $source = $file->open();
        $target = $this->filesystem->getDirectoryWrite(DirectoryList::VAR_EXPORT)->openFile($path, 'w');
        try {
            while (!$source->eof()) {
                $target->write($source->read(1048576));
            }
        } finally {
            $source->close();
            $target->close();
        }

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

deliver() is called once per run, with the file already written:

  • $file is the feed's file, written whole in the module's temporary storage. $file->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('channel/…') reads the feed's settings; see Add the channel's settings.
  • To fail the delivery, throw Arlanix\Feed\Model\Channel\ChannelException. The run fails with its message, and the feed is tried again later, each failure in a row waiting longer; see When a run fails.
  • Return a FileReceipt. 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 FileChannel with your adapter, and add it to ChannelPool under its type:

<virtualType name="Vendor\Module\Model\Delivery\ExportDirectoryChannel"
             type="Arlanix\Feed\Model\Channel\File\FileChannel">
    <arguments>
        <argument name="deliveryAdapter"
                  xsi:type="object">Vendor\Module\Model\Delivery\ExportDirectoryAdapter</argument>
    </arguments>
</virtualType>

<type name="Arlanix\Feed\Model\Channel\ChannelPool">
    <arguments>
        <argument name="channels" xsi:type="array">
            <item name="export_directory" xsi:type="array">
                <item name="label" xsi:type="string" translate="true">Export directory</item>
                <item name="channel"
                      xsi:type="string">Vendor\Module\Model\Delivery\ExportDirectoryChannel</item>
                <item name="on_demand" xsi:type="array">
                    <item name="label" xsi:type="string" translate="true">Export now</item>
                    <item name="queued" xsi:type="string" translate="true">Feed "%1" is queued. Its file is exported by the feed cron, usually within a minute.</item>
                </item>
                <item name="deleted" xsi:type="string" translate="true">Files already exported were left in the export directory.</item>
            </item>
        </argument>
    </arguments>
</type>

The item's name is the channel's type, which a feed stores. Its keys:

Key Value
label The name in the Channel field and the grid.
channel The class or virtual type that delivers the feeds, as a string: it is made the first time a feed of the type is delivered, so a grid or form that only shows the label builds none of it.
on_demand Optional. The row action in the grid's Select menu that runs the feed at once: label names it, queued is the message after it is chosen, %1 being the feed's identifier. Without it, the feed runs at its schedule only.
publishes_file 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.
deleted 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.
refresh_after_days Optional, for a push channel whose platform drops a product it is not sent again. A row sent and unchanged for this many days is sent again, up to four days sooner by product, so that a catalogue sent in one day is not sent again in one. The nightly arlanix_feed_refresh_delivered job picks the rows. Google's channel sets 25.

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(). Each one takes three pieces in your module.

  1. Register the setting in etc/di.xml, with the normaliser that cleans what the form sends. getSetting() throws for a path that is not registered.

    <virtualType name="Arlanix\Feed\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 a number, use Arlanix\Core\Model\Settings\Normaliser\IntNormaliser.

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

    <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\Feed\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();
        }
    }
    

    Register it on the feed in etc/di.xml:

    <type name="Arlanix\Feed\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 takes products one at a time. The module keeps a record per product row: what was sent, what the platform answered, and what has changed since. Each run sends the rows that changed, retries refused rows, and takes down rows the feed no longer has.

Implement Arlanix\Feed\Model\Channel\Push\PushChannelInterface, then register it in etc/di.xml as a PushChannel:

<virtualType name="Vendor\Module\Model\Channel\MarketplaceChannel"
             type="Arlanix\Feed\Model\Channel\Push\PushChannel">
    <arguments>
        <argument name="pushChannel" xsi:type="object">Vendor\Module\Model\Channel\MarketplaceApi</argument>
    </arguments>
</virtualType>

<type name="Arlanix\Feed\Model\Channel\ChannelPool">
    <arguments>
        <argument name="channels" xsi:type="array">
            <item name="marketplace_api" xsi:type="array">
                <item name="label" xsi:type="string" translate="true">Marketplace (API)</item>
                <item name="channel" xsi:type="string">Vendor\Module\Model\Channel\MarketplaceChannel</item>
                <item name="deleted" xsi:type="string" translate="true">The products of feed "%1" stay on the marketplace until you remove them there.</item>
            </item>
        </argument>
    </arguments>
</type>

A push channel has no on_demand and no publishes_file: 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.

What the interface asks

A run goes in this order:

  1. It maps again any products mapped under the feed's older rules.
  2. Once all of them are, it asks supportsDelete(). A run whose minute ran out before this point takes nothing down.
  3. It calls start(), which returns the run's session, Arlanix\Feed\Model\Channel\Push\PushSessionInterface.
  4. On that session it calls remove() for the rows to take down and accept() for the rows to send, 25 rows a call, then finish().

If a call on the session 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
supportsDelete(): bool Whether the platform can remove one product on its own. It is asked every minute, when the cron looks for feeds with work, and on each run, so answer it without calling the platform. false: rows the feed no longer has stay on the platform, do not make the feed due, and the feed is never refused for being empty. true: a run in which every product is left out while the platform holds rows of the feed is refused with Nothing taken down: …, unless the feed allows an empty one, and the feed waits as after a failure.
start(ChannelRunContext $context): PushSessionInterface Starts a run and returns its session. The context gives getFeed(), getFeedId(), getSetting('channel/…') and getDeadline(). Throw from here, for an account that cannot sign in for instance, to fail the run before anything is sent.

And on the session:

Method Does
accept(array $rows): RowOutcomes Sends 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): RowOutcomes 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\Feed\Model\Channel\Push\RowOutcomes, keyed by the row's key:

return new RowOutcomes([
    '42' => ['status' => RowOutcomes::SYNCED, 'external_id' => 'offer/42'],
    '43' => ['status' => RowOutcomes::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, is given back to remove() when the row is taken down. A row sent without one is never taken down, whatever supportsDelete() answers.
  • FAILED marks a row as refused: the platform said no to this product. 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 row with no outcome counts as refused.

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 RowOutcomes($outcomes, 'The account was suspended.'). 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 outcomes of that call are lost: the rows the platform took in it are sent again, and the rows it refused are offered again with nothing recorded against them, both on the next run.

A push run has about a minute. The module starts no call to accept() or remove() once it is up, and sends the rest on the next run. A channel that retries a call to the platform hands $context->getDeadline() from start() to its session, so that it stops waiting when the run's minute ends.

When the feed is saved

A channel that keeps something on the platform for the feed, such as Google's data source, can make or update it when the store saves the feed. The feed form's Save dispatches arlanix_feed_form_saved with feed, the feed as stored, its settings readable with getSetting(); a save from anywhere else does not. Observe it in etc/adminhtml/events.xml, and act only on feeds of your channel. The feed is stored by then: say what went wrong with the admin's message manager rather than throwing. An observer that throws is reported as an error message, and the save stands.

When only a person can settle it

When the platform has lost something only the store can put right, throw Arlanix\Feed\Model\Run\SaveRequiredException, a ChannelException, from start() or the session. 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 no wait on the retry ladder ends it. Saving the feed does. Google's channel throws it when the feed's data source was deleted in Merchant Center.

Arlanix_FeedGoogleMerchant is a complete push channel: Arlanix\FeedGoogleMerchant\Model\Channel\MerchantApiChannel and its MerchantApiSession in vendor/arlanix/module-feed-google-merchant.