You are here

class FastlyPurger in Fastly 8.3

Fastly purger.

Plugin annotation


@PurgePurger(
  id = "fastly",
  label = @Translation("Fastly"),
  description = @Translation("Purger for Fastly."),
  types = {"tag", "url", "everything"},
  multi_instance = FALSE,
)

Hierarchy

Expanded class hierarchy of FastlyPurger

File

modules/fastlypurger/src/Plugin/Purge/Purger/FastlyPurger.php, line 24

Namespace

Drupal\fastlypurger\Plugin\Purge\Purger
View source
class FastlyPurger extends PurgerBase implements PurgerInterface {

  /**
   * Fastly API.
   *
   * @var \Drupal\fastly\Api
   */
  protected $api;

  /**
   * The settings configuration.
   *
   * @var \Drupal\Core\Config\Config
   */
  protected $config;

  /**
   * CacheTagsHash service.
   *
   * @var \Drupal\fastly\CacheTagsHash
   */
  protected $cacheTagsHash;

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static($configuration, $plugin_id, $plugin_definition, $container
      ->get('config.factory'), $container
      ->get('fastly.api'), $container
      ->get('fastly.cache_tags.hash'));
  }

  /**
   * Constructs a \Drupal\Component\Plugin\FastlyPurger.
   *
   * @param array $configuration
   *   A configuration array containing information about the plugin instance.
   * @param string $plugin_id
   *   The plugin_id for the plugin instance.
   * @param mixed $plugin_definition
   *   The plugin implementation definition.
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config
   *   The factory for configuration objects.
   * @param \Drupal\fastly\Api $api
   *   Fastly API for Drupal.
   * @param \Drupal\fastly\CacheTagsHash $cache_tags_hash
   *   CacheTagsHash service.
   *
   * @throws \LogicException
   *   Thrown if $configuration['id'] is missing, see Purger\Service::createId.
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, ConfigFactoryInterface $config, Api $api, CacheTagsHash $cache_tags_hash) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
    $this->config = $config
      ->get('fastly.settings');
    $this->api = $api;
    $this->cacheTagsHash = $cache_tags_hash;
  }

  /**
   * {@inheritdoc}
   */
  public function hasRuntimeMeasurement() {
    return TRUE;
  }

  /**
   * {@inheritdoc}
   */
  public function routeTypeToMethod($type) {
    $methods = [
      'tag' => 'invalidateTags',
      'url' => 'invalidateUrls',
      'everything' => 'invalidateAll',
    ];
    return isset($methods[$type]) ? $methods[$type] : 'invalidate';
  }

  /**
   * {@inheritdoc}
   */
  public function invalidate(array $invalidations) {
    throw new \LogicException('This should not execute.');
  }

  /**
   * Invalidate a set of urls.
   *
   * @param \Drupal\purge\Plugin\Purge\Invalidation\InvalidationInterface[] $invalidations
   *   The invalidator instance.
   *
   * @throws \Exception
   */
  public function invalidateUrls(array $invalidations) {
    $urls = [];

    // Set all invalidation states to PROCESSING before kick off purging.

    /* @var \Drupal\purge\Plugin\Purge\Invalidation\InvalidationInterface $invalidation */
    foreach ($invalidations as $invalidation) {
      $invalidation
        ->setState(InvalidationInterface::PROCESSING);
      $urls[] = $invalidation
        ->getExpression();
    }
    if (empty($urls)) {
      foreach ($invalidations as $invalidation) {
        $invalidation
          ->setState(InvalidationInterface::FAILED);
        throw new \Exception('No url found to purge');
      }
    }

    // Fastly only allows purging of a single URL per request.
    $urls_each = array_chunk($urls, 1);
    foreach ($urls_each as $url) {

      // Invalidate and update the item state.
      $invalidation_state = $this
        ->invalidateItems('urls', $url);
    }
    $this
      ->updateState($invalidations, $invalidation_state);
  }

  /**
   * Invalidate a set of tags.
   *
   * @param \Drupal\purge\Plugin\Purge\Invalidation\InvalidationInterface[] $invalidations
   *   The invalidator instance.
   *
   * @throws \Exception
   */
  public function invalidateTags(array $invalidations) {
    $tags = [];

    // Set all invalidation states to PROCESSING before kick off purging.

    /* @var \Drupal\purge\Plugin\Purge\Invalidation\InvalidationInterface $invalidation */
    foreach ($invalidations as $invalidation) {
      $invalidation
        ->setState(InvalidationInterface::PROCESSING);
      $tags[] = $invalidation
        ->getExpression();
    }
    if (empty($tags)) {
      foreach ($invalidations as $invalidation) {
        $invalidation
          ->setState(InvalidationInterface::FAILED);
        throw new \Exception('No tag found to purge');
      }
    }

    // Invalidate and update the item state.
    // @TODO: Does Fastly have a limit per purge we need to consider (32k)?
    // Also invalidate the cache tags as hashes, to automatically also work for
    // responses that exceed the 16 KB header limit.
    $hashes = $this->cacheTagsHash
      ->cacheTagsToHashes($tags);
    $invalidation_state = $this
      ->invalidateItems('tags', $hashes);
    $this
      ->updateState($invalidations, $invalidation_state);
  }

  /**
   * Invalidate everything.
   *
   * @param \Drupal\purge\Plugin\Purge\Invalidation\InvalidationInterface[] $invalidations
   *   The invalidator instance.
   */
  public function invalidateAll(array $invalidations) {
    $this
      ->updateState($invalidations, InvalidationInterface::PROCESSING);

    // Invalidate and update the item state.
    $invalidation_state = $this
      ->invalidateItems();
    $this
      ->updateState($invalidations, $invalidation_state);
  }

  /**
   * Invalidate Fastly cache.
   *
   * @param mixed $type
   *   Type to purge like tags/url. If null, will purge everything.
   * @param string[] $invalidates
   *   A list of items to invalidate.
   *
   * @return int
   *   Returns invalidate items.
   */
  protected function invalidateItems($type = NULL, array $invalidates = []) {
    try {
      if ($type === 'tags') {
        $purged = $this->api
          ->purgeKeys($invalidates);
      }
      elseif ($type === 'urls') {

        // $invalidates should be an array with one URL.
        foreach ($invalidates as $invalidate) {
          $purged = $this->api
            ->purgeUrl($invalidate);
        }
      }
      else {
        $purged = $this->api
          ->purgeAll();
      }
      if ($purged) {
        return InvalidationInterface::SUCCEEDED;
      }
      return InvalidationInterface::FAILED;
    } catch (\Exception $e) {
      return InvalidationInterface::FAILED;
    } finally {

      // @TODO: Check/increment API limits - https://docs.fastly.com/api/#rate-limiting.
    }
  }

  /**
   * Update the invalidation state of items.
   *
   * @param \Drupal\purge\Plugin\Purge\Invalidation\InvalidationInterface[] $invalidations
   *   The invalidator instance.
   * @param int $invalidation_state
   *   The invalidation state.
   */
  protected function updateState(array $invalidations, $invalidation_state) {

    // Update the state.
    foreach ($invalidations as $invalidation) {
      $invalidation
        ->setState($invalidation_state);
    }
  }

}

Members

Namesort descending Modifiers Type Description Overrides
DependencySerializationTrait::$_entityStorages protected property An array of entity type IDs keyed by the property name of their storages.
DependencySerializationTrait::$_serviceIds protected property An array of service IDs keyed by property name used for serialization.
DependencySerializationTrait::__sleep public function 1
DependencySerializationTrait::__wakeup public function 2
FastlyPurger::$api protected property Fastly API.
FastlyPurger::$cacheTagsHash protected property CacheTagsHash service.
FastlyPurger::$config protected property The settings configuration.
FastlyPurger::create public static function Creates an instance of the plugin. Overrides PurgerBase::create
FastlyPurger::hasRuntimeMeasurement public function Indicates whether your purger utilizes dynamic runtime measurement. Overrides PurgerCapacityDataInterface::hasRuntimeMeasurement
FastlyPurger::invalidate public function Invalidate content from external caches. Overrides PurgerInterface::invalidate
FastlyPurger::invalidateAll public function Invalidate everything.
FastlyPurger::invalidateItems protected function Invalidate Fastly cache.
FastlyPurger::invalidateTags public function Invalidate a set of tags.
FastlyPurger::invalidateUrls public function Invalidate a set of urls.
FastlyPurger::routeTypeToMethod public function Route certain type of invalidations to other methods. Overrides PurgerBase::routeTypeToMethod
FastlyPurger::updateState protected function Update the invalidation state of items.
FastlyPurger::__construct public function Constructs a \Drupal\Component\Plugin\FastlyPurger. Overrides PurgerBase::__construct
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
PluginBase::$configuration protected property Configuration information passed into the plugin. 1
PluginBase::$pluginDefinition protected property The plugin implementation definition. 1
PluginBase::$pluginId protected property The plugin_id.
PluginBase::DERIVATIVE_SEPARATOR constant A string which is used to separate base plugin IDs from the derivative ID.
PluginBase::getBaseId public function Gets the base_plugin_id of the plugin instance. Overrides DerivativeInspectionInterface::getBaseId
PluginBase::getDerivativeId public function Gets the derivative_id of the plugin instance. Overrides DerivativeInspectionInterface::getDerivativeId
PluginBase::getPluginDefinition public function Gets the definition of the plugin implementation. Overrides PluginInspectionInterface::getPluginDefinition 3
PluginBase::getPluginId public function Gets the plugin_id of the plugin instance. Overrides PluginInspectionInterface::getPluginId
PluginBase::isConfigurable public function Determines if the plugin is configurable.
PurgeLoggerAwareTrait::$logger protected property Channel logger.
PurgeLoggerAwareTrait::logger public function
PurgerBase::$id protected property Unique instance ID for this purger.
PurgerBase::$runtimeMeasurement protected property The runtime measurement counter.
PurgerBase::delete public function The current instance of this purger plugin is about to be deleted. Overrides PurgerInterface::delete 1
PurgerBase::getCooldownTime public function Get the time in seconds to wait after invalidation. Overrides PurgerCapacityDataInterface::getCooldownTime
PurgerBase::getId public function Retrieve the unique instance ID for this purger instance. Overrides PurgerInterface::getId
PurgerBase::getIdealConditionsLimit public function Get the maximum number of invalidations that this purger can process. Overrides PurgerCapacityDataInterface::getIdealConditionsLimit 1
PurgerBase::getLabel public function Retrieve the user-readable label for this purger instance. Overrides PurgerInterface::getLabel
PurgerBase::getRuntimeMeasurement public function Get the runtime measurement counter. Overrides PurgerCapacityDataInterface::getRuntimeMeasurement
PurgerBase::getTimeHint public function Get the maximum number of seconds, processing a single invalidation takes. Overrides PurgerCapacityDataInterface::getTimeHint
PurgerBase::getTypes public function Retrieve the list of supported invalidation types. Overrides PurgerInterface::getTypes
PurgerBase::setRuntimeMeasurement public function Inject the runtime measurement counter. Overrides PurgerCapacityDataInterface::setRuntimeMeasurement
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.