Skip to content

Conversation

@adam-vessey
Copy link
Contributor

@adam-vessey adam-vessey commented Aug 25, 2025

Misc fixes:

  • avoid accumulating multiples of the same job in the queue
  • switch user back more consistently

Summary by CodeRabbit

  • Bug Fixes

    • Background fixity jobs run more reliably: invalid items/accounts are safely skipped and account context is always cleaned up to prevent stuck processes.
    • Scheduled runs now clear and rebuild the processing queue to avoid stale or duplicate tasks.
  • New Features

    • Periodic checks are explicitly enabled during processing so recurring checks are scheduled correctly.
  • Refactor

    • Broadened inputs to accept optional/empty values across batch operations, forms, and actions; minor formatting adjustments.

@adam-vessey adam-vessey added the patch Backwards compatible bug fixes. label Aug 25, 2025
Was all fixable via phpcbf.
@coderabbitai
Copy link

coderabbitai bot commented Aug 25, 2025

Walkthrough

Cron now deletes and recreates the dgi_fixity.process_source queue before enqueuing sources. Multiple method signatures were changed to accept nullable types. A command method was reformatted. The ProcessSourceWorker centralizes account switchBack with try/finally, adds early-return guards, and enables periodic checks during processing.

Changes

Cohort / File(s) Summary
Cron queue reset
dgi_fixity.module
Cron now calls deleteQueue() and createQueue() on dgi_fixity.process_source before enqueuing, clearing pre-existing jobs.
Nullable parameter signatures
src/FixityCheckBatchCheck.php, src/Form/RevisionDeleteForm.php, src/Plugin/Action/FixityCheckActionBase.php
Method signatures broadened to accept nullable types: ?array and ?int for build(), ?FixityCheckInterface for buildForm(), and ?AccountInterface for access(). Behavior unchanged.
Command signature formatting
src/Commands/FixityCheck.php
FixityCheck::check() signature reformatted to multi-line with trailing comma; no behavioral change.
Queue worker control-flow hardening
src/Plugin/QueueWorker/ProcessSourceWorker.php
Added early-return when account is not AccountInterface, wrapped processing in try { ... } finally { switchBack(); }, added guard if (!$view) { return; }, and set periodic checks on retrieved check entities inside the processing loop. Cleanup centralized; core processing and requeue behavior preserved.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant Cron
  participant Queue as dgi_fixity.process_source
  participant SourceProvider

  Cron->>Queue: deleteQueue()
  Cron->>Queue: createQueue()
  Cron->>SourceProvider: enumerate sources
  loop per source
    Cron->>Queue: createItem(source)
  end
Loading
sequenceDiagram
  autonumber
  participant Worker as ProcessSourceWorker
  participant AccSwitch as AccountSwitcher
  participant Views as ViewLoader
  participant Fixity as FixityService
  participant QueueAPI as Queue API

  Worker->>AccSwitch: switchTo(account)
  alt account invalid
    Worker->>AccSwitch: (finally) switchBack()
    Worker-->>Worker: return
  else account valid
    rect rgba(230,245,255,0.6)
      Worker->>Views: load view
      alt view not found
        Worker->>AccSwitch: (finally) switchBack()
        Worker-->>Worker: return
      else view found
        Worker->>Fixity: source(view, chunkSize)
        Worker->>Views: iterate rows
        loop per row
          Worker->>Fixity: mark periodic on check entity
        end
        alt needs requeue
          Worker->>QueueAPI: throw RequeueException
        end
      end
    end
    Worker->>AccSwitch: finally switchBack()
  end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Poem

I hop through queues and tidy the lot,
Delete, recreate, then line up the lot.
I switch my paws, then switch them back,
Return early where views lack.
Little checks hum — carrots in stock 🥕

Warning

Review ran into problems

🔥 Problems

Errors were encountered while retrieving linked issues.

Errors (1)
  • JIRA integration encountered authorization issues. Please disconnect and reconnect the integration in the CodeRabbit UI.
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fix/misc

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (3)
src/Plugin/Action/FixityCheckActionBase.php (1)

76-83: Nullability introduced but $account is dereferenced without a guard

$account can now be NULL, yet $account->hasPermission() is called unconditionally. This will fatally error when invoked without an account (e.g., from a queue/CLI context).

Apply this diff to guard null and preserve the original semantics (default to the current user when none is provided):

-  public function access($object, ?AccountInterface $account = NULL, $return_as_object = FALSE) {
-    // If it exists and the user has permission to administer fixity checks.
-    $result = $this->getCheck($object) && $account->hasPermission('administer fixity checks') ?
-      AccessResult::allowed() :
-      AccessResult::forbidden();
-
-    return $return_as_object ? $result : $result->isAllowed();
-  }
+  public function access($object, ?AccountInterface $account = NULL, $return_as_object = FALSE) {
+    // Default to current user if no account was provided.
+    $account = $account ?? \Drupal::currentUser();
+    $check = $this->getCheck($object);
+
+    $result = ($check && $account->hasPermission('administer fixity checks'))
+      ? AccessResult::allowed()
+      : AccessResult::forbidden();
+
+    return $return_as_object ? $result : $result->isAllowed();
+  }
src/Form/RevisionDeleteForm.php (1)

101-106: buildForm allows NULL revision but later dereferences it; add a guard

$this->revision is used without null checks (e.g., getQuestion(), submitForm()). If buildForm receives NULL, this will fatal. Throw 404 on missing revision to fail safely.

Apply this diff:

-  public function buildForm(array $form, FormStateInterface $form_state, ?FixityCheckInterface $fixity_check_revision = NULL) {
-    $this->revision = $fixity_check_revision;
+  public function buildForm(array $form, FormStateInterface $form_state, ?FixityCheckInterface $fixity_check_revision = NULL) {
+    if ($fixity_check_revision === NULL) {
+      throw new \Symfony\Component\HttpKernel\Exception\NotFoundHttpException();
+    }
+    $this->revision = $fixity_check_revision;
     $form = parent::buildForm($form, $form_state);
 
     return $form;
   }
src/Plugin/QueueWorker/ProcessSourceWorker.php (1)

114-121: Double accountSwitcher->switchBack() causes an unbalanced account stack

You call switchBack() before throwing RequeueException, and then call it again in finally. This will unbalance the switcher stack and can trigger errors.

Apply this diff to rely solely on the finally block:

       // Not finished processing.
       if (count($view->result) !== 0) {
-        $this->accountSwitcher->switchBack();
         throw new RequeueException();
       }
     }
     finally {
       $this->accountSwitcher->switchBack();
     }
🧹 Nitpick comments (5)
src/FixityCheckBatchCheck.php (1)

27-32: Nullable parameters accepted; ensure type safety and documentation match

  • The config value for batch size may be a string; cast it to int to avoid accidental string math.
  • Docblocks above still state non-null types; they should reflect int[]|null and int|null.

Apply this diff for the cast:

-  public static function build(?array $fids = NULL, bool $force = FALSE, ?int $batch_size = NULL) {
-    $batch_size = is_null($batch_size) ? \Drupal::config(SettingsForm::CONFIG_NAME)->get(SettingsForm::BATCH_SIZE) : $batch_size;
+  public static function build(?array $fids = NULL, bool $force = FALSE, ?int $batch_size = NULL) {
+    $batch_size = is_null($batch_size)
+      ? (int) \Drupal::config(SettingsForm::CONFIG_NAME)->get(SettingsForm::BATCH_SIZE)
+      : (int) $batch_size;
     return is_null($fids) ?
       static::buildPeriodic($force, $batch_size) :
       static::buildFixed($fids, $force, $batch_size);
   }

Docblock suggestion (outside the changed hunk):

/**
 * @param int[]|null $fids
 * @param bool $force
 * @param int|null $batch_size
 */
src/Plugin/QueueWorker/ProcessSourceWorker.php (3)

98-101: Prefer injected service over \Drupal::service for testability and consistency

You already inject FixityCheckServiceInterface as $this->fixity. Use it instead of the service locator.

Apply this diff:

-      /** @var \Drupal\dgi_fixity\FixityCheckServiceInterface $fixity */
-      $fixity = \Drupal::service('dgi_fixity.fixity_check');
-      $view = $fixity->source($data, 1000);
+      $view = $this->fixity->source($data, 1000);

101-105: Abort on missing view should be logged for observability

Silently returning hides misconfiguration. Log a warning to aid operators.

Apply this diff:

       if (!$view) {
-        // Failed to load view? Abort.
-        return;
+        // Failed to load view? Log and abort.
+        \Drupal::logger('dgi_fixity')->warning('ProcessSourceWorker: failed to load fixity view for source "@source".', ['@source' => $data]);
+        return;
       }

91-94: Early return when account #1 is missing; consider logging

If user 1 doesn't exist or can't be loaded, the worker exits silently. Emit a log so site operators understand why nothing is processed.

Apply this diff:

-    if (!($account instanceof AccountInterface)) {
-      return;
-    }
+    if (!($account instanceof AccountInterface)) {
+      \Drupal::logger('dgi_fixity')->warning('ProcessSourceWorker: unable to load account 1; skipping.');
+      return;
+    }
dgi_fixity.module (1)

122-125: Resetting the queue on each cron run: confirm operational intent and concurrency effects

Calling deleteQueue() will purge all items, including any that were requeued but not yet processed. Given you immediately repopulate from configuration, this seems intentional to prevent duplicates, but it can drop in-flight requeues if cron overlaps worker execution. Verify this aligns with your operational expectations (especially on multi-webhead setups).

Consider alternatives if you want to avoid wholesale purges:

  • Deduplicate by using a side-channel (e.g., a keyed state or a custom “unique queue” table) so each source is enqueued at most once per window.
  • Have the worker idempotently no-op on already-processed sources and leave cron to only enqueue new sources without deleting the queue.
  • If you keep the reset, document that this queue is ephemeral and rebuilt each cron run; this helps future maintainers.
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 1d63318 and 02be424.

📒 Files selected for processing (6)
  • dgi_fixity.module (1 hunks)
  • src/Commands/FixityCheck.php (1 hunks)
  • src/FixityCheckBatchCheck.php (1 hunks)
  • src/Form/RevisionDeleteForm.php (1 hunks)
  • src/Plugin/Action/FixityCheckActionBase.php (1 hunks)
  • src/Plugin/QueueWorker/ProcessSourceWorker.php (2 hunks)

@adam-vessey adam-vessey mentioned this pull request Aug 25, 2025
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/Plugin/QueueWorker/ProcessSourceWorker.php (1)

95-120: Protect switchBack() with a flag; use injected service; add exception logging.

Prevents a possible LogicException if switchTo() fails mid-flight, removes service locator usage, and logs failures.

-    try {
-      $this->accountSwitcher->switchTo($account);
-
-      /** @var \Drupal\dgi_fixity\FixityCheckServiceInterface $fixity */
-      $fixity = \Drupal::service('dgi_fixity.fixity_check');
-      $view = $fixity->source($data, 1000);
-      if (!$view) {
-        // Failed to load view? Abort.
-        return;
-      }
+    $switched = FALSE;
+    try {
+      $this->accountSwitcher->switchTo($account);
+      $switched = TRUE;
+
+      $view = $this->fixity->source($data, 1000);
+      if ($view === NULL) {
+        \Drupal::logger('dgi_fixity')->warning('ProcessSourceWorker: failed to load view for source "@source"; skipping.', ['@source' => (string) $data]);
+        return;
+      }
       $view->execute();
+      if (!isset($view->field['periodic'])) {
+        \Drupal::logger('dgi_fixity')->error('ProcessSourceWorker: expected "periodic" field missing on view for source "@source"; skipping.', ['@source' => (string) $data]);
+        return;
+      }
       // Only processes those which have not already enabled periodic checks.
       foreach ($view->result as $row) {
         /** @var \Drupal\dgi_fixity\FixityCheckInterface $check */
         $check = $view->field['periodic']->getEntity($row);
         $check->setPeriodic(TRUE);
         $check->save();
       }
       // Not finished processing.
       if (count($view->result) !== 0) {
         throw new RequeueException();
       }
-    }
-    finally {
-      $this->accountSwitcher->switchBack();
-    }
+    }
+    catch (\Throwable $e) {
+      \Drupal::logger('dgi_fixity')->error('ProcessSourceWorker exception for source "@source": @message', [
+        '@source' => (string) $data,
+        '@message' => $e->getMessage(),
+      ]);
+      throw $e;
+    }
+    finally {
+      if ($switched) {
+        $this->accountSwitcher->switchBack();
+      }
+    }
🧹 Nitpick comments (2)
src/Plugin/QueueWorker/ProcessSourceWorker.php (2)

91-94: Log and avoid hardcoding uid 1 (consider configurability).

Early-return is fine. Add a log entry for diagnostics, and consider making the admin UID configurable instead of hardcoding 1.

-    if (!($account instanceof AccountInterface)) {
-      return;
-    }
+    if (!($account instanceof AccountInterface)) {
+      \Drupal::logger('dgi_fixity')->error('ProcessSourceWorker: failed to load administrative account (uid 1); skipping item.');
+      return;
+    }

101-104: Nit: keep the early-return, but log the reason.

The guard is good; logging improves traceability (covered in the previous diff).

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 02be424 and aca6366.

📒 Files selected for processing (1)
  • src/Plugin/QueueWorker/ProcessSourceWorker.php (2 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
src/Plugin/QueueWorker/ProcessSourceWorker.php (2)
src/FixityCheckServiceInterface.php (1)
  • source (94-94)
src/FixityCheckService.php (1)
  • source (168-188)

@nchiasson-dgi nchiasson-dgi merged commit c3a5efc into main Aug 28, 2025
2 checks passed
@nchiasson-dgi nchiasson-dgi deleted the fix/misc branch August 28, 2025 13:47
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

patch Backwards compatible bug fixes.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants