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

Influxdb2 Bundle Laravel Package

babymarkt/influxdb2-bundle

View on GitHub
Deep Wiki
Context7
## Getting Started

### Minimal Setup
1. **Install the package**:
   ```bash
   composer require babymarkt/influxdb2-bundle

Ensure the bundle is enabled in config/bundles.php:

Babymarkt\Symfony\Influxdb2Bundle\BabymarktInfluxdb2Bundle::class => ['all' => true],
  1. Configure InfluxDB2: Add minimal config to config/packages/babymarkt_influxdb2.yaml:

    babymarkt_influxdb2:
      client:
        url: https://your-influxdb-url:8086
        token: your-token-here
        org: your-org
        bucket: your-bucket
    
  2. First Use Case: Inject the default WriteApi into a service to write metrics:

    use InfluxDB2\WriteApi;
    
    class MetricsLogger {
        public function __construct(private WriteApi $writeApi) {}
    
        public function log(string $measurement, array $tags, array $fields) {
            $point = \InfluxDB2\Point::measurement($measurement)
                ->addTags($tags)
                ->addFields($fields)
                ->timestamp(time(), \InfluxDB2\WritePrecision::MS);
    
            $this->writeApi->writePoint($point);
        }
    }
    

Implementation Patterns

Common Workflows

1. Multi-Environment Configuration

Use environment variables for sensitive data (e.g., token) and override config per environment:

# config/packages/babymarkt_influxdb2.yaml
babymarkt_influxdb2:
  client:
    url: '%env(INFLUXDB_URL)%'
    token: '%env(INFLUXDB_TOKEN)%'
    org: '%env(INFLUXDB_ORG)%'
    bucket: '%env(INFLUXDB_BUCKET)%'

2. Connection-Specific Services

Define multiple connections (e.g., production, staging) and inject specific APIs:

babymarkt_influxdb2:
  client:
    connections:
      production:
        url: https://prod-influxdb:8086
        token: %env(INFLUXDB_PROD_TOKEN)%
        org: prod-org
        bucket: prod-bucket
      staging:
        url: https://staging-influxdb:8086
        token: %env(INFLUXDB_STAGING_TOKEN)%
        org: staging-org
        bucket: staging-bucket

Inject via service definition:

services:
  App\Service\StagingMetricsLogger:
    arguments:
      - '@babymarkt_influxdb.staging_write_api'

3. Querying Data

Use QueryApi to fetch data with Flux queries:

use InfluxDB2\QueryApi;

class AnalyticsService {
    public function __construct(private QueryApi $queryApi) {}

    public function getUserActivity(string $userId, string $timeRange) {
        $query = sprintf(
            'from(bucket: "your-bucket")
             |> range(%s)
             |> filter(fn: (r) => r._measurement == "user_activity" and r.user_id == "%s")',
            $timeRange,
            $userId
        );
        $result = $this->queryApi->query($query);
        return $result->records();
    }
}

4. Batch Writing

Configure batching for high-throughput writes:

babymarkt_influxdb2:
  api:
    write:
      option_sets:
        high_throughput:
          options:
            write_type: BATCHING
            batch_size: 10000
            retry_interval: 5000
            max_retries: 5

Inject the custom option set:

services:
  App\Service\HighVolumeLogger:
    arguments:
      - '@babymarkt_influxdb.high_throughput_write_api'

5. Tag Defaults

Set default tags per connection to avoid repetition:

babymarkt_influxdb2:
  client:
    connections:
      default:
        tags:
          environment: production
          application: your-app

6. Async Processing

Use Symfony’s Messenger to queue writes for async processing:

use Symfony\Component\Messenger\MessageBusInterface;

class AsyncMetricsLogger {
    public function __construct(
        private WriteApi $writeApi,
        private MessageBusInterface $bus
    ) {}

    public function logAsync(string $measurement, array $data) {
        $this->bus->dispatch(new LogMetricsMessage($measurement, $data));
    }
}

Gotchas and Tips

Pitfalls

  1. Token Security:

    • Never hardcode tokens in config files. Use environment variables or Symfony’s ParameterBag.
    • Avoid committing .env files to version control.
  2. Connection Timeouts:

    • Default timeout: 10 may be too short for slow networks. Increase if writes fail intermittently:
      babymarkt_influxdb2:
        client:
          connections:
            default:
              timeout: 30
      
  3. SSL Verification:

    • Disabling verifySSL (e.g., for self-signed certs) is insecure. Use proper certificates instead:
      babymarkt_influxdb2:
        client:
          connections:
            default:
              verifySSL: false  # Avoid this in production!
      
  4. Query Timeouts:

    • Long-running Flux queries may time out. Use timeout in the query:
      $query = '... | range(...)';
      $result = $this->queryApi->query($query, ['timeout' => '1m']);
      
  5. Bucket/Org Mismatch:

    • Ensure the org and bucket in config match the InfluxDB instance. Errors like 404 Not Found often indicate this.
  6. Precision Handling:

    • Default precision: 'ns' may cause issues with some time libraries. Use 's' (seconds) for simplicity:
      babymarkt_influxdb2:
        client:
          connections:
            default:
              precision: 's'
      

Debugging Tips

  1. Enable Debug Logging:

    babymarkt_influxdb2:
      client:
        connections:
          default:
            debug: true
            logFile: '%kernel.logs_dir%/influxdb.log'
    

    Check logs for HTTP request/response details.

  2. Ping Command: Use the babymarkt_influxdb:ping command to verify connectivity:

    php bin/console babymarkt_influxdb:ping -c=default
    
  3. Ready Service: Check InfluxDB instance health programmatically:

    $readyService = $client->createService(\InfluxDB2\Service\ReadyService::class);
    $status = $readyService->getReady()->getStatus(); // "ready" or "not_ready"
    
  4. Query Validation: Test Flux queries in the InfluxDB UI first to catch syntax errors early.

Extension Points

  1. Custom Services: Extend the bundle by creating your own services that wrap InfluxDB2 APIs:

    namespace App\Service;
    
    use InfluxDB2\Client;
    use InfluxDB2\Service\BucketsService;
    
    class BucketManager {
        public function __construct(private Client $client) {}
    
        public function createBucket(string $name, string $org, int $duration = 0) {
            $bucketsService = $this->client->createService(BucketsService::class);
            return $bucketsService->createBucket($name, $org, $duration);
        }
    }
    
  2. Event Listeners: Listen for InfluxDB events (e.g., write failures) using Symfony’s event system:

    namespace App\EventListener;
    
    use InfluxDB2\WriteApi;
    use Psr\Log\LoggerInterface;
    
    class WriteFailureListener {
        public function __construct(private LoggerInterface $logger) {}
    
        public function onWriteFailure(WriteApi $writeApi, \Throwable $exception) {
            $this->logger->error('InfluxDB write failed', [
                'exception' => $exception->getMessage(),
            ]);
        }
    }
    
  3. Console Command Extensions: Extend existing commands (e.g., babymarkt_influxdb:buckets:list) by overriding their logic:

    namespace App\Command;
    
    use Babymarkt\Symfony\Influxdb2Bundle\Command\BucketsListCommand;
    use Symfony\Component\Console\Input\InputInterface;
    use Symfony\Component\Console\Output\OutputInterface;
    
    class CustomBuckets
    
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.
comsave/common
alecsammon/php-raml-parser
chrome-php/wrench
lendable/composer-license-checker
typhoon/reflection
mesilov/moneyphp-percentage
mike42/gfx-php
bookdown/themes
aura/view
aura/html
aura/cli
povils/phpmnd
nayjest/manipulator
omnipay/tests
psr-mock/http-message-implementation
psr-mock/http-factory-implementation
psr-mock/http-client-implementation
voku/email-check
voku/urlify
rtheunissen/guzzle-log-middleware