### Incoming HTTP Request with Baggage Header Example (HTTP) Source: https://context7.com/macpaw/schema-context-bundle/llms.txt An example of an incoming HTTP request demonstrating the structure of a W3C baggage header used for passing schema and context information. ```http GET /api/users HTTP/1.1 Host: example.com baggage: X-Tenant=tenant_a,user-id=12345,trace-id=abc-def-123,request-id=req-789 # The bundle automatically extracts: # - Schema: "tenant_a" (from X-Tenant key) # - Full baggage context: ["X-Tenant" => "tenant_a", "user-id" => "12345", "trace-id" => "abc-def-123", "request-id" => "req-789"] ``` -------------------------------- ### Configure Schema Context Bundle (YAML & ENV) Source: https://context7.com/macpaw/schema-context-bundle/llms.txt Configuration example for the Schema Context Bundle, specifying environment details, header names, default schemas, and override permissions. ```yaml # config/packages/schema_context.yaml schema_context: environment_name: '%env(APP_ENV)%' header_name: 'X-Tenant' environment_schema: '%env(ENVIRONMENT_SCHEMA)%' overridable_environments: ['develop', 'staging', 'test'] # .env file APP_ENV=develop ENVIRONMENT_SCHEMA=public ``` -------------------------------- ### Install and Register Schema Context Bundle (Bash & PHP) Source: https://context7.com/macpaw/schema-context-bundle/llms.txt Instructions for installing the Schema Context Bundle using Composer and manually registering it within a Symfony application's configuration. ```bash # Install via Composer composer require macpaw/schema-context-bundle # If not using Symfony Flex, manually register in config/bundles.php ``` ```php ['all' => true], ]; ``` -------------------------------- ### Install Schema Context Bundle with Composer Source: https://github.com/macpaw/schema-context-bundle/blob/develop/README.md Installs the Schema Context Bundle package using Composer, the standard dependency manager for PHP. ```bash composer require macpaw/schema-context-bundle ``` -------------------------------- ### EnvironmentSchemaMismatchException Example Source: https://github.com/macpaw/schema-context-bundle/blob/develop/README.md Shows an example error message for `EnvironmentSchemaMismatchException`, which is thrown when attempting to override the schema in a non-overridable environment. This exception helps prevent accidental schema changes in production or staging. ```text Schema mismatch in "production" environment: expected "public", got "tenant_a". Allowed override environments: [develop, staging, test]. ``` -------------------------------- ### Example HTTP Request with Baggage in Production Source: https://context7.com/macpaw/schema-context-bundle/llms.txt Illustrates an HTTP request made in a production environment where the baggage context attempts to set a different schema ('tenant_private') than the default ('public'). This scenario is typically blocked by the schema override protection. ```http # Request in production environment with different schema GET /api/users HTTP/1.1 Host: example.com baggage: X-Tenant=tenant_private,user-id=12345 ``` -------------------------------- ### Example Baggage Header Format Source: https://github.com/macpaw/schema-context-bundle/blob/develop/README.md Illustrates the W3C standard `baggage` header format used by the bundle for passing contextual information, including schema identifiers and other trace-related data. The bundle extracts the schema using a configurable header name. ```http GET /api/endpoint HTTP/1.1 Host: example.com baggage: X-Tenant=tenant_a,user-id=12345,trace-id=abc123 ``` -------------------------------- ### Run Tests (Bash) Source: https://github.com/macpaw/schema-context-bundle/blob/develop/README.md Command to execute the project's tests using PHPUnit. ```bash vendor/bin/phpunit ``` -------------------------------- ### Test Tenant-Aware Service with Schema and Baggage Management (PHP) Source: https://context7.com/macpaw/schema-context-bundle/llms.txt Demonstrates how to programmatically set and reset schema and baggage context within a PHPUnit test. It initializes `BaggageSchemaResolver` and `BaggageCodec`, tests setting different schemas and baggage data, verifies context retrieval, and asserts the correct behavior after resetting the context. Handles empty baggage and schema inputs gracefully. ```php schemaResolver = new BaggageSchemaResolver( environmentSchema: 'public', environmentName: 'test', schemaOverridableEnvironments: ['test', 'develop'], ); $this->codec = new BaggageCodec(); } public function testServiceWithDifferentSchemas(): void { // Test with schema "tenant_a" $this->schemaResolver->setSchema('tenant_a'); $this->schemaResolver->setBaggage([ 'X-Tenant' => 'tenant_a', 'user-id' => '111', ]); $service = new TenantAwareService($this->schemaResolver); $result = $service->getData(); $this->assertEquals('tenant_a', $this->schemaResolver->getSchema()); $this->assertArrayHasKey('user-id', $this->schemaResolver->getBaggage()); // Reset context between tests $this->schemaResolver->reset(); // Verify reset $this->assertNull($this->schemaResolver->getBaggage()); $this->assertEquals('public', $this->schemaResolver->getSchema()); // Falls back to environment schema // Test with different schema $this->schemaResolver->setSchema('tenant_b'); $this->schemaResolver->setBaggage([ 'X-Tenant' => 'tenant_b', 'user-id' => '222', 'feature-flags' => 'experimental', ]); $result = $service->getData(); $this->assertEquals('tenant_b', $this->schemaResolver->getSchema()); } public function testEmptyBaggageHandling(): void { // Setting empty array results in null $this->schemaResolver->setBaggage([]); $this->assertNull($this->schemaResolver->getBaggage()); // Setting empty string schema results in null $this->schemaResolver->setSchema(' '); $this->assertEquals('public', $this->schemaResolver->getSchema()); // Falls back to environment schema // Explicit null $this->schemaResolver->setSchema(null); $this->schemaResolver->setBaggage(null); $this->assertNull($this->schemaResolver->getBaggage()); $this->assertEquals('public', $this->schemaResolver->getSchema()); } } ``` -------------------------------- ### Configure Baggage Propagation in HTTP Client (Symfony YAML) Source: https://context7.com/macpaw/schema-context-bundle/llms.txt Shows how to configure the BaggageAwareHttpClient in Symfony's `services.yaml` to automatically decorate an existing HTTP client. It includes how to disable decoration for testing environments. ```yaml # config/services.yaml services: # Decorate your HTTP client to add baggage propagation baggage_aware_payment_http_client: class: Macpaw\SchemaContextBundle\HttpClient\BaggageAwareHttpClient decorates: payment_http_client # Your original HTTP client service arguments: - '@baggage_aware_payment_http_client.inner' - '@Macpaw\SchemaContextBundle\Service\BaggageSchemaResolver' - '@Macpaw\SchemaContextBundle\Service\BaggageCodec' # For testing environments, disable decoration to use mocks when@test: baggage_aware_payment_http_client: class: Macpaw\SchemaContextBundle\HttpClient\BaggageAwareHttpClient decorates: null # Disable decoration in tests ``` -------------------------------- ### Dispatch Message with Schema Context from Controller Source: https://context7.com/macpaw/schema-context-bundle/llms.txt Demonstrates how to dispatch a message from a controller while ensuring the schema and baggage context from the current request are propagated to the message handler. The BaggageSchemaMiddleware automatically handles this context transfer. ```php getSchema(); // "tenant_a" // Dispatch message - middleware automatically adds BaggageSchemaStamp $bus->dispatch(new ProcessOrder(orderId: 123, amount: 99.99)); // When worker processes this message, it will have schema "tenant_a" // even though worker has no HTTP request context } } ``` -------------------------------- ### Configure Schema Override Protection for Production Source: https://context7.com/macpaw/schema-context-bundle/llms.txt Sets up environment-specific schema configurations to prevent accidental schema changes in production. The `overridable_environments` list specifies which environments allow schema overrides, excluding 'production' by default. ```yaml # config/packages/schema_context.yaml schema_context: environment_name: 'production' environment_schema: 'public' overridable_environments: ['develop', 'staging', 'test'] # Production NOT in list ``` -------------------------------- ### Encode and Decode W3C Baggage Headers with PHP Source: https://context7.com/macpaw/schema-context-bundle/llms.txt Demonstrates encoding an associative array into a W3C baggage header string and decoding a baggage header string back into an associative array using the BaggageCodec service. It highlights how null values and spaces are handled. ```php 'tenant_b', 'user-id' => '67890', 'trace-id' => 'xyz-123', 'feature-flag' => null, // Null values are encoded without the "=" sign ]; $encoded = $codec->encode($baggageArray); // Returns: "X-Tenant=tenant_b,user-id=67890,trace-id=xyz-123,feature-flag" // Decode baggage header string to array $baggageString = 'X-Tenant=tenant_c,user-id=11111,session-id=sess-456,debug'; $decoded = $codec->decode($baggageString); // Returns: [ // 'X-Tenant' => 'tenant_c', // 'user-id' => '11111', // 'session-id' => 'sess-456', // 'debug' => null // Keys without values are decoded as null // ] // The codec handles edge cases $messy = ' X-Tenant = tenant_d , user-id = 99999 , , empty-spaces '; $cleaned = $codec->decode($messy); // Returns: ['X-Tenant' => 'tenant_d', 'user-id' => '99999', 'empty-spaces' => null] ``` -------------------------------- ### Automatic Baggage Propagation in PHP HTTP Requests Source: https://context7.com/macpaw/schema-context-bundle/llms.txt Illustrates a PHP service class that utilizes a decorated HTTP client (`BaggageAwareHttpClient`) to automatically propagate baggage context in outgoing HTTP requests. It shows how the baggage header is added and how to merge custom baggage data. ```php paymentHttpClient->request('POST', '/api/payments', [ 'json' => [ 'amount' => 100.00, 'currency' => 'USD', ], // Baggage header is automatically added: // headers: ['baggage' => 'X-Tenant=tenant_a,user-id=12345,trace-id=abc-def-123'] ]); // You can also merge additional baggage data $response = $this->paymentHttpClient->request('GET', '/api/balance', [ 'headers' => [ 'baggage' => 'custom-key=custom-value', // Merged with existing baggage ], ]); // Final baggage header will contain both existing and custom baggage data } } ``` -------------------------------- ### Handle EnvironmentSchemaMismatchException in Symfony Source: https://context7.com/macpaw/schema-context-bundle/llms.txt This PHP code demonstrates how to create a Symfony event subscriber that listens for exceptions. It specifically catches `EnvironmentSchemaMismatchException`, logs the error, and returns a JSON response with a 500 status code to the client. This is useful for preventing schema overrides in production environments. ```php 'onKernelException', ]; } public function onKernelException(ExceptionEvent $event): void { $exception = $event->getThrowable(); if ($exception instanceof EnvironmentSchemaMismatchException) { // Exception message format: // "Schema mismatch in \"production\" environment: expected \"public\", got \"tenant_private\". // Allowed override environments: [develop, staging, test]." $this->logger->error('Schema mismatch detected', [ 'message' => $exception->getMessage(), 'code' => $exception->getCode(), // 500 ]); $response = new JsonResponse([ 'error' => 'Schema Override Not Allowed', 'message' => 'Cannot override schema in production environment', 'details' => $exception->getMessage(), ], 500); $event->setResponse($response); } } } ``` -------------------------------- ### Use BaggageSchemaResolver in Symfony Controller (PHP) Source: https://context7.com/macpaw/schema-context-bundle/llms.txt Demonstrates how to inject and utilize the BaggageSchemaResolver service within a Symfony controller to retrieve schema context information. ```php getSchema(); // Get all baggage context data $baggage = $schemaResolver->getBaggage(); // Check if current environment allows schema override $canOverride = $schemaResolver->isSchemaOverridableEnvironment(); // Get the environment default schema $defaultSchema = $schemaResolver->getEnvironmentSchema(); // Get the schema provided via baggage (null if none provided) $providedSchema = $schemaResolver->getProvidedSchema(); return new JsonResponse([ 'schema' => $schema, 'baggage' => $baggage, 'can_override' => $canOverride, 'default_schema' => $defaultSchema, 'provided_schema' => $providedSchema, ]); } } ``` -------------------------------- ### Process Incoming Baggage Header in Symfony Service (PHP) Source: https://context7.com/macpaw/schema-context-bundle/llms.txt Illustrates how the BaggageRequestListener automatically processes incoming baggage headers and how to access the extracted schema and context within a Symfony service. ```php schemaResolver->getSchema(); // Returns: "tenant_a" // Access all baggage data $baggage = $this->schemaResolver->getBaggage(); // Returns: ["X-Tenant" => "tenant_a", "user-id" => "12345", "trace-id" => "abc-def-123", "request-id" => "req-789"] $userId = $baggage['user-id'] ?? null; // "12345" $traceId = $baggage['trace-id'] ?? null; // "abc-def-123" } } ``` -------------------------------- ### Configure Schema Context Bundle in Symfony Source: https://github.com/macpaw/schema-context-bundle/blob/develop/README.md Configures the Schema Context Bundle by defining key parameters such as environment name, header name for schema extraction, and the default schema for the environment. This is done in the `config/packages/schema_context.yaml` file. ```yaml schema_context: environment_name: '%env(APP_ENV)%' header_name: 'X-Tenant' environment_schema: '%env(ENVIRONMENT_SCHEMA)%' overridable_environments: ['develop', 'staging', 'test'] ``` -------------------------------- ### Safely Change Schema with EnvironmentSchemaMismatchException Handling Source: https://context7.com/macpaw/schema-context-bundle/llms.txt This PHP code defines a service class that attempts to change the schema using `BaggageSchemaResolver`. It includes a `safeSchemaChange` method that wraps the `setSchema` call in a try-catch block. If an `EnvironmentSchemaMismatchException` occurs (e.g., in production), it logs the issue and returns false, ensuring the application uses the default schema instead of crashing. ```php schemaResolver->setSchema($newSchema); return true; } catch (EnvironmentSchemaMismatchException $e) { // Handle the exception gracefully // In production: log and use default schema // In development: the exception won't be thrown $defaultSchema = $this->schemaResolver->getEnvironmentSchema(); error_log("Schema override blocked, using default: {$defaultSchema}"); return false; } } } ``` -------------------------------- ### Configure Messenger Bus with Schema Middleware Source: https://context7.com/macpaw/schema-context-bundle/llms.txt Configures the Symfony Messenger bus to use the BaggageSchemaMiddleware. This middleware automatically handles the propagation and restoration of schema and baggage context across message dispatches and consumption. ```yaml framework: messenger: buses: messenger.bus.default: middleware: - Macpaw\SchemaContextBundle\Messenger\Middleware\BaggageSchemaMiddleware transports: async: '%env(MESSENGER_TRANSPORT_DSN)%' routing: 'App\Message\ProcessOrder': async ``` -------------------------------- ### Process Order Message with Schema Context Source: https://context7.com/macpaw/schema-context-bundle/llms.txt Defines a message and its handler, demonstrating how the BaggageSchemaMiddleware automatically restores schema and baggage context when processing messages. The handler can access the original schema and baggage from the dispatch time. ```php schemaResolver->getSchema(); // Original schema from dispatch time $baggage = $this->schemaResolver->getBaggage(); // Original baggage context // Process order with correct schema context echo "Processing order {$message->orderId} in schema: {$schema}\n"; // The middleware automatically: // 1. Adds BaggageSchemaStamp when dispatching (before transport) // 2. Restores schema/baggage when consuming (after transport) // 3. Resets context after handling (prevents leakage) } } ``` -------------------------------- ### Integrate Monolog with Baggage Processor Source: https://context7.com/macpaw/schema-context-bundle/llms.txt Configures Monolog to use the BaggageProcessor service. This allows baggage context, such as tenant ID or trace ID, to be automatically included in log records, aiding in distributed tracing and debugging. ```yaml # config/services.yaml services: Macpaw\SchemaContextBundle\Monolog\BaggageProcessor: tags: - { name: monolog.processor } ``` -------------------------------- ### Log Request with Automatic Baggage Context Source: https://context7.com/macpaw/schema-context-bundle/llms.txt Shows how to use the PSR-3 logger within a controller. The BaggageProcessor automatically enriches log entries with the current request's baggage context, providing valuable information for tracking requests across different services. ```php logger->info('Processing API request', [ 'endpoint' => '/api/data', ]); // BaggageProcessor automatically adds baggage to log record: // { // "message": "Processing API request", // "context": {"endpoint": "/api/data"}, // "extra": { // "baggage": { // "X-Tenant": "tenant_a", // "user-id": "12345", // "trace-id": "abc-123" // } // } // } try { $schema = $this->schemaResolver->getSchema(); // ... process request $this->logger->info('Request completed successfully'); // Baggage is automatically included in this log entry too } catch (\Exception $e) { $this->logger->error('Request failed', [ 'error' => $e->getMessage(), ]); // Baggage context helps trace the error across services } return new Response('OK'); } } ``` -------------------------------- ### Resolve Schema and Baggage using BaggageSchemaResolver Source: https://github.com/macpaw/schema-context-bundle/blob/develop/README.md Demonstrates how to inject and use the `BaggageSchemaResolver` service within a Symfony controller to retrieve the current schema and baggage context. This allows application logic to adapt based on the resolved context. ```php use Macpaw\SchemaContextBundle\Service\BaggageSchemaResolver; public function index(BaggageSchemaResolver $schemaResolver) { $schema = $schemaResolver->getSchema(); $baggage = $schemaResolver->getBaggage(); // Use schema in logic } ``` -------------------------------- ### Decorate HTTP Client for Baggage Propagation Source: https://github.com/macpaw/schema-context-bundle/blob/develop/README.md Configures a Symfony service to decorate an existing HTTP client with `BaggageAwareHttpClient`. This ensures that baggage context, including schema information, is automatically propagated when making outgoing HTTP requests. ```yaml services: baggage_aware_payment_http_client: class: Macpaw\SchemaContextBundle\HttpClient\BaggageAwareHttpClient decorates: payment_http_client #http client to decorate arguments: - '@baggage_aware_payment_http_client.inner' ``` -------------------------------- ### Define Environment Variables for Schema Context Bundle Source: https://github.com/macpaw/schema-context-bundle/blob/develop/README.md Sets environment variables necessary for the Schema Context Bundle configuration. `APP_ENV` specifies the current application environment, and `ENVIRONMENT_SCHEMA` defines the default schema for that environment. ```env APP_ENV=develop ENVIRONMENT_SCHEMA=public ``` -------------------------------- ### Enable Monolog Integration (YAML) Source: https://github.com/macpaw/schema-context-bundle/blob/develop/README.md Adds the BaggageProcessor to Monolog's service configuration. This processor automatically adds baggage context to log records, including it in the 'extra' field. ```yaml services: Macpaw\SchemaContextBundle\Monolog\BaggageProcessor: tags: - { name: monolog.processor } ``` -------------------------------- ### Register Schema Context Bundle Manually in Symfony Source: https://github.com/macpaw/schema-context-bundle/blob/develop/README.md Manually registers the Schema Context Bundle in a Symfony application if Symfony Flex is not being used. This involves adding the bundle class to the `config/bundles.php` file. ```php // config/bundles.php return [ Macpaw\SchemaContextBundle\SchemaContextBundle::class => ['all' => true], ]; ``` -------------------------------- ### Enable Messenger Integration (YAML) Source: https://github.com/macpaw/schema-context-bundle/blob/develop/README.md Enables the BaggageSchemaMiddleware for the default Messenger bus. This middleware automatically adds a BaggageSchemaStamp to dispatched messages and restores schema and baggage context on message handling. ```yaml framework: messenger: buses: messenger.bus.default: middleware: - Macpaw\SchemaContextBundle\Messenger\Middleware\BaggageSchemaMiddleware ``` -------------------------------- ### Disable BaggageAwareHttpClient in Tests (YAML) Source: https://github.com/macpaw/schema-context-bundle/blob/develop/README.md This configuration snippet disables the BaggageAwareHttpClient decoration for test environments. It's useful when replacing or mocking HTTP clients with libraries like extended-mock-http-client. ```yaml when@test: services: baggage_aware_payment_http_client: class: Macpaw\SchemaContextBundle\HttpClient\BaggageAwareHttpClient ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.