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

Agtp Symfony Laravel Package

agtp/agtp-symfony

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Install the Bundle

    composer require agtp/agtp-symfony
    

    Enable the bundle in config/bundles.php (Symfony Flex handles this automatically).

  2. Set Up agtpd Ensure the AGTP daemon (agtpd) is running locally or on the same host, typically via:

    # Example: Running agtpd in a Docker container
    docker run -p 4480:4480 -v /etc/agtpd:/etc/agtpd nomoticai/agtpd
    
  3. Create a Handler Define a service class with an #[AgtpEndpoint]-annotated method:

    use Agtp\AgtpEndpoint;
    
    final class GreetingHandler
    {
        #[AgtpEndpoint(method: 'GREET', path: '/hello')]
        public function greet(): string {
            return "Hello, AGTP!";
        }
    }
    
  4. Register the Service Tag the handler in config/services.yaml:

    services:
        App\Agtp\GreetingHandler:
            tags: ['agtp.endpoint']
    
  5. Export the Manifest Generate the daemon manifest:

    bin/console agtp:export-manifest --output=/etc/agtpd/endpoints
    
  6. Run the Worker Start the AGTP worker:

    bin/console agtp:serve --gateway-socket=/var/run/agtpd/gateway.sock
    

First Use Case

Build a lightweight, high-performance API endpoint (e.g., a booking system) without the overhead of HTTP request/response cycles. AGTP’s long-lived workers reduce kernel boot time to a one-time cost, making it ideal for:

  • Microservices with frequent, low-latency calls.
  • Systems requiring strict identity/scope enforcement (e.g., IoT devices, internal tools).

Implementation Patterns

Core Workflow

  1. Handler Development

    • Use #[AgtpEndpoint] attributes to define endpoints (method, path, scopes, errors).
    • Inject Symfony services (e.g., EntityManager, Logger) via constructor.
    • Return EndpointResponse or EndpointError for success/failure.
    #[AgtpEndpoint(
        method: 'CREATE',
        path: '/user',
        requiredScopes: ['user:create'],
        errors: ['user_exists']
    )]
    public function createUser(EndpointContext $ctx): EndpointResponse|EndpointError {
        if ($this->userExists($ctx->input['email'])) {
            return new EndpointError('user_exists', 'Email already registered.');
        }
        return new EndpointResponse(['user_id' => $this->saveUser($ctx->input)]);
    }
    
  2. Service Tagging

    • Tag services with agtp.endpoint via:
      • YAML (tags: ['agtp.endpoint']).
      • Attribute (#[AutoconfigureTag('agtp.endpoint')]).
    • Best Practice: Group related handlers in a single service class for clarity.
  3. Manifest Management

    • Run agtp:export-manifest after every handler change to update agtpd.
    • Use --dry-run to preview changes:
      bin/console agtp:export-manifest --dry-run
      
  4. Worker Deployment

    • Local/Dev: Run agtp:serve manually.
    • Production: Deploy as a systemd service or Kubernetes Deployment:
      [Service]
      ExecStart=/usr/bin/php bin/console agtp:serve --gateway-socket=/run/agtpd.sock
      Restart=always
      
    • Scaling: Run multiple worker instances (e.g., 3–5) for concurrency.
  5. Testing

    • Use Agtp\Testing to mock EndpointContext and assert responses:
      public function testCreateUserSuccess() {
          $handler = new UserHandler($this->createMock(EntityManagerInterface::class));
          $ctx = Testing::makeContext(['email' => 'test@example.com']);
          $response = Testing::assertOk($handler->createUser($ctx));
          $this->assertArrayHasKey('user_id', $response->body);
      }
      

Integration Tips

  • Database Access: Inject EntityManagerInterface or repositories into handlers.
  • Authentication: Leverage $ctx->agentId and $ctx->authorityScope for pre-verified identity/scope.
  • Error Handling: Define custom error codes in #[AgtpEndpoint] and return EndpointError with details.
  • Logging: Use Symfony’s LoggerInterface for debugging:
    public function __construct(private readonly LoggerInterface $logger) {}
    $this->logger->info('Handler invoked', ['input' => $ctx->input]);
    

Gotchas and Tips

Pitfalls

  1. Manifest Staleness

    • Issue: Forgetting to run agtp:export-manifest after adding/updating handlers causes agtpd to ignore changes.
    • Fix: Add a post-commit hook or CI step to auto-generate manifests:
      # Example Git hook (in .git/hooks/post-commit)
      php bin/console agtp:export-manifest --output=/etc/agtpd/endpoints
      
  2. Worker Crashes

    • Issue: Unhandled exceptions in handlers crash the worker process.
    • Fix: Wrap handler logic in try-catch or use a global exception handler:
      try {
          return $handler->method($ctx);
      } catch (\Throwable $e) {
          return new EndpointError('internal_error', $e->getMessage());
      }
      
  3. Socket Permissions

    • Issue: agtp:serve fails with "Permission denied" on /var/run/agtpd/gateway.sock.
    • Fix: Ensure the socket path is writable by the worker user (e.g., www-data):
      sudo chown www-data:www-data /var/run/agtpd/gateway.sock
      
  4. Scope Mismatches

    • Issue: Handlers reject requests due to missing requiredScopes.
    • Fix: Verify scopes in agtpd config and test with:
      bin/console agtp:export-manifest --dry-run | grep requiredScopes
      
  5. Testing Context

    • Issue: Tests fail because $ctx->input is empty or malformed.
    • Fix: Always mock EndpointContext with Testing::makeContext() and validate input:
      $ctx = Testing::makeContext(['room_type' => 'single']);
      $this->assertEquals('single', $ctx->input['room_type']);
      

Debugging Tips

  • Worker Logs: Check agtp:serve output for errors (e.g., missing socket, invalid TOML).
  • Daemon Logs: Inspect agtpd logs (journalctl -u agtpd or container logs) for protocol-level issues.
  • Manifest Validation: Use --dry-run to validate TOML syntax before deployment.

Extension Points

  1. Custom Error Handlers

    • Override Agtp\EndpointError or create a middleware-like service to transform errors:
      $errorHandler = new CustomErrorHandler();
      return $errorHandler->handle($error);
      
  2. Context Enhancement

    • Extend EndpointContext by adding properties to the TOML manifest or via a custom context class.
  3. Dynamic Endpoints

    • Generate #[AgtpEndpoint] attributes dynamically (e.g., from a database) using reflection or a compiler pass.
  4. Cross-Protocol Integration

    • Combine AGTP with HTTP by routing requests via a proxy (e.g., Nginx) or using Symfony’s Router to dispatch to AGTP handlers.

Configuration Quirks

  • Gateway Socket Path: Must match agtpd’s configured socket (default: /var/run/agtpd/gateway.sock).
  • TOML Formatting: agtp:export-manifest requires valid TOML. Use a linter like tomal to validate.
  • Worker Isolation: Each agtp:serve process handles all endpoints. For isolation, use separate processes or namespaces.

Performance Notes

  • Kernel Boot: Paid once per worker (not per request), making AGTP ideal for high-throughput systems.
  • Memory Usage: Long-lived workers retain state (e.g., Doctrine connections). Monitor memory with php -m or htop.
  • Concurrency: agtpd supports multiple module connections. Scale workers horizontally by running multiple instances.
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.
nasirkhan/laravel-sharekit
directorytree/privacy-filter-classifier
directorytree/privacy-filter
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata
splash/openapi
splash/scopes
splash/toolkit
testo/output-teamcity
testo/bridge-symfony