Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Probe Bundle Laravel Package

arty/probe-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps to First Use

  1. Install the Bundle

    composer require arty/probe-bundle
    

    Register the bundle in config/bundles.php if not using Symfony Flex:

    Arty\ProbeBundle\ArtyProbeBundle::class => ['all' => true],
    
  2. Configure the Bundle Create config/packages/arty_probe.yaml:

    arty_probe:
        probe_status_history_class: App\Entity\ProbeStatusHistory
        alerting:
            enabled: true
            channel: email  # or 'chat'
            to: "admin@example.com"
    
  3. Set Up Alerting

    • For email, install Symfony Mailer and configure MAILER_DSN in .env.
    • For chat (e.g., Slack), install the appropriate notifier (e.g., symfony/slack-notifier) and configure the DSN in .env:
      SLACK_DSN=slack://TOKEN@default?channel=CHANNEL
      
  4. Create the Database Entity Extend BaseProbeStatusHistory in App\Entity\ProbeStatusHistory:

    use Arty\ProbeBundle\Entity\ProbeStatusHistory as BaseProbeStatusHistory;
    use Doctrine\ORM\Mapping as ORM;
    
    #[ORM\Entity(repositoryClass: ProbeStatusHistoryRepository::class)]
    class ProbeStatusHistory extends BaseProbeStatusHistory {}
    

    Run migrations:

    php bin/console doctrine:migrations:diff
    php bin/console doctrine:migrations:migrate
    
  5. Write Your First Probe Implement ProbeInterface and annotate with #[Probe]:

    use Arty\ProbeBundle\Attribute\Probe;
    use Arty\ProbeBundle\Model\ProbeInterface;
    
    #[Probe(name: 'database_connectivity', description: 'Checks DB reachability')]
    class DatabaseProbe implements ProbeInterface {
        public function check(): int {
            return $this->isDatabaseReachable() ? Probe::SUCCESS : Probe::FAILURE;
        }
    }
    
  6. Run Probes Execute all probes via CLI:

    php bin/console arty:probe:run
    

Implementation Patterns

Common Workflows

  1. Probe Development

    • Strategy 1 (Threshold-Based): Use Probe::SUCCESS, Probe::WARNING, or Probe::FAILURE constants for simple pass/fail logic.
      public function check(): int {
          return $this->apiResponseValid() ? Probe::SUCCESS : Probe::FAILURE;
      }
      
    • Strategy 2 (Custom Thresholds): Return raw metrics (e.g., error counts) and define thresholds in #[Probe]:
      #[Probe(
          name: 'cache_hit_rate',
          successThreshold: 0.8,
          warningThreshold: 0.6,
          failureThreshold: 0.4,
          description: 'Monitors cache efficiency'
      )]
      class CacheProbe implements ProbeInterface {
          public function check(): float {
              return $this->getCacheHitRate();
          }
      }
      
  2. Alerting Integration

    • Email: Configure MAILER_DSN and set channel: email in arty_probe.yaml.
    • Chat: Install the notifier (e.g., Slack) and configure the DSN in .env:
      arty_probe:
          alerting:
              channel: chat
      
    • Disable Alerts: Set notify: false in #[Probe] or alerting.enabled: false in config.
  3. Probe Scheduling

    • Use Symfony’s CronBundle or EasyAdmin to schedule arty:probe:run:
      # config/packages/easy_admin.yaml
      easy_admin:
          cronjobs:
              - command: 'arty:probe:run'
                schedule: '0 * * * *'  # Run hourly
      
  4. Probe Results in Templates Inject ProbeManagerInterface into controllers to fetch statuses:

    public function dashboard(ProbeManagerInterface $probeManager): Response {
        $statuses = $probeManager->findAllLastStatuses();
        return $this->render('dashboard.html.twig', ['statuses' => $statuses]);
    }
    

    Display in Twig:

    {% for probe, status in statuses %}
        <div class="probe {{ status.status }}">
            {{ probe.name }}: {{ status.status|humanize }}
        </div>
    {% endfor %}
    
  5. Testing Probes Use PHPUnit to mock dependencies and test probe logic:

    public function testDatabaseProbeFails() {
        $probe = new DatabaseProbe($this->createMock(DbConnection::class));
        $this->assertEquals(Probe::FAILURE, $probe->check());
    }
    

Gotchas and Tips

Pitfalls

  1. Threshold Mismatches

    • If using custom thresholds, ensure the returned value type (e.g., int, float) aligns with the thresholds. For example, comparing a float (e.g., 0.8) with int thresholds (e.g., 80) will fail silently.
    • Fix: Use consistent types or cast values:
      return (int)($this->getCacheHitRate() * 100); // Convert to percentage
      
  2. Alerting Delays

    • Alerts are sent asynchronously by default (via Symfony Messenger). If testing locally, set message_bus: false in notifier.yaml to force synchronous delivery:
      framework:
          notifier:
              message_bus: false
      
  3. Entity Mapping Issues

    • If ProbeStatusHistory isn’t properly mapped, migrations may fail. Ensure:
      • The entity extends BaseProbeStatusHistory.
      • The table name is correct (default: probe_status_history).
      • Doctrine annotations are valid (e.g., #[ORM\Entity]).
  4. Probe Registration

    • Probes must be tagged as services. If using autowiring, ensure the class is discoverable. For manual registration:
      # config/services.yaml
      services:
          App\Probe\DatabaseProbe:
              tags: ['arty.probe']
      
  5. Performance Overhead

    • Running many probes with heavy logic (e.g., DB queries) can slow down arty:probe:run. Optimize by:
      • Caching probe results (e.g., Redis).
      • Running probes in parallel (e.g., using Symfony\Component\Process\Process).

Debugging Tips

  1. Check Probe Execution Enable debug mode to see probe output:

    php bin/console arty:probe:run --env=dev
    

    Or log results manually:

    public function check(): int {
        $result = $this->isHealthy() ? Probe::SUCCESS : Probe::FAILURE;
        $this->logger->info("Probe result: {$result}");
        return $result;
    }
    
  2. Verify Alerts

    • For email, check the mail log or test with a local SMTP server (e.g., MailHog).
    • For chat, verify the DSN is correct and the channel is active:
      php bin/console debug:notifier
      
  3. Inspect Database Query the probe_status_history table to verify records are saved:

    SELECT * FROM probe_status_history ORDER BY created_at DESC;
    

Extension Points

  1. Custom Probe Statuses Extend the ProbeStatus enum to add custom states (e.g., DEGRADED):

    namespace App\Enum;
    
    use Arty\ProbeBundle\Model\ProbeStatus;
    
    enum CustomProbeStatus: string {
        case DEGRADED = 'degraded';
    
        public function isValid(): bool {
            return in_array($this->value, [ProbeStatus::SUCCESS->value, ProbeStatus::WARNING->value, ...]);
        }
    }
    
  2. Dynamic Probe Configuration Load probe thresholds from a config file or database:

    # config/probes.yaml
    probes:
        database:
            success_threshold: 0
            warning_threshold: 1
    

    Inject the config into the probe:

    #[Probe(name: 'database')]
    class DatabaseProbe implements ProbeInterface {
        public function __construct(private array $config) {}
    
        public function check(): int {
            return $this->getErrorCount();
        }
    }
    
  3. Probe Metadata Add metadata (e.g., severity, owner) to probes via the #[Probe] attribute:

    #[Probe(
        name: 'payment_gateway',
        description: 'Checks payment processing',
        severity: 'high',
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours