### Run Phlow HTTP Server Source: https://phlow.dev/docs/examples/http-api Command to execute a Phlow application file, in this case, starting the simple HTTP server defined in `simple-server.phlow`. ```bash phlow simple-server.phlow ``` -------------------------------- ### Phlow Module Logic Example Source: https://phlow.dev/docs/phlow-structure/modules Demonstrates a basic step within a Phlow module, including an assertion based on setup and main variables, and defining a payload for subsequent steps. It highlights the use of Phlow's setup (`setup`) and main (`main`) variables for configuration and runtime data. ```Phlow steps: - assert: !phs setup.path == main.path && setup.method == main.method then: payload: !phs setup.default_response ``` -------------------------------- ### Install Phlow using wget Source: https://phlow.dev/docs/install Installs Phlow by downloading and executing an installation script from a GitHub repository using wget. The `|| true` ensures that the script continues even if the download or execution fails. ```shell wget -qO- https://raw.githubusercontent.com/phlowdotdev/phlow/refs/heads/main/scripts/install-phlow.sh | { bash || true; } ``` -------------------------------- ### HTTP Client Example Source: https://phlow.dev/docs/examples/http-api An example of making an HTTP GET request to an external API using the http_request module. ```APIDOC ## Make External API Request ### Description Fetches weather information from an external API and logs the response. ### Method GET ### Endpoint https://httpbin.org/json ### Headers - **User-Agent** (string) - Client identifier. ### Response #### Success Response (200) - The response body from the external API is processed and logged. The `payload` variable contains the processed response, including `slideshow` data, a processing timestamp, and a status. #### Response Example ```json { "slideshow": { "author": "Yours Truly", "date": "date of publication", "slides": [ { "title": "Wake up to WonderWidgets!", "type": "all" }, { "items": [ "Why WonderWidgets are great", "Who buys WonderWidgets" ], "title": "Overview" } ], "title": "Sample Slide Show" }, "processed_at": "2023-10-27T10:00:00.000Z", "status": "success" } ``` ``` -------------------------------- ### Phlow CLI Usage Examples for RPC Client Source: https://phlow.dev/docs/examples/messaging-rpc Provides command-line examples for using the Phlow RPC client to perform various mathematical operations. These examples demonstrate how to specify the method and parameters for the RPC calls. ```Shell # Add two numbers phlow rpc-client.phlow add '{"a": 5, "b": 3}' # Multiply numbers phlow rpc-client.phlow multiply '{"a": 4, "b": 6}' # Calculate factorial phlow rpc-client.phlow factorial '{"n": 5}' # Calculate Fibonacci phlow rpc-client.phlow fibonacci '{"n": 10}' ``` -------------------------------- ### Phlow Module: Descriptive Configuration Example Source: https://phlow.dev/docs/packages-and-modules/phlow-modules Provides an example of descriptive configuration parameters for a Phlow module, including a database URL and an optional timeout setting. ```Phlow with: type: object properties: database_url: type: string description: "PostgreSQL connection string" required: true timeout_seconds: type: number description: "Query timeout in seconds" default: 30 required: false ``` -------------------------------- ### Simple HTTP Server Source: https://phlow.dev/docs/examples/http-api A basic HTTP server that responds to different routes and methods, including GET and POST for /api/users. ```APIDOC ## GET / ### Description Responds with a welcome message to the root path. ### Method GET ### Endpoint / ### Response #### Success Response (200) - **message** (string) - Welcome message. - **version** (string) - API version. #### Response Example ```json { "message": "Welcome to Phlow API", "version": "1.0.0" } ``` ## GET /health ### Description Responds with the health status of the server. ### Method GET ### Endpoint /health ### Response #### Success Response (200) - **status** (string) - Health status (e.g., "healthy"). - **timestamp** (string) - ISO formatted timestamp of the health check. #### Response Example ```json { "status": "healthy", "timestamp": "2023-10-27T10:00:00.000Z" } ``` ## GET /api/users ### Description Retrieves a list of users. ### Method GET ### Endpoint /api/users ### Response #### Success Response (200) - **users** (array) - An array of user objects. - **id** (integer) - User ID. - **name** (string) - User's name. - **email** (string) - User's email. #### Response Example ```json { "users": [ { "id": 1, "name": "John Doe", "email": "john@example.com" }, { "id": 2, "name": "Jane Smith", "email": "jane@example.com" } ] } ``` ## POST /api/users ### Description Creates a new user. ### Method POST ### Endpoint /api/users ### Request Body - **name** (string) - Required - User's name. - **email** (string) - Required - User's email. ### Request Example ```json { "name": "Alice Johnson", "email": "alice@example.com" } ``` ### Response #### Success Response (201) - **message** (string) - Confirmation message. - **user** (object) - The created user object. - **id** (integer) - The ID of the newly created user. #### Response Example ```json { "message": "User created successfully", "user": { "name": "Alice Johnson", "email": "alice@example.com" }, "id": 123 } ``` ## Default Response (404) ### Description Handles requests for undefined routes or methods. ### Method ANY ### Endpoint /* ### Response #### Error Response (404) - **error** (string) - Error message. - **path** (string) - The requested path. - **method** (string) - The requested HTTP method. #### Response Example ```json { "error": "Route not found", "path": "/unknown", "method": "GET" } ``` ``` -------------------------------- ### Testing the Proxy Source: https://phlow.dev/docs/examples/http-api Examples using curl to test the API proxy, demonstrating how to forward GET and POST requests to an external service. ```APIDOC ## Testing the Proxy ### Description Examples using curl to test the API proxy. ### Method GET, POST ### Endpoint /proxy/{path} ### Parameters #### Path Parameters - **path** (string) - Required - The path to be proxied. #### Query Parameters None #### Request Body - **data** (any) - Optional - The request body to be sent. ### Request Example ``` # Proxy a GET request curl http://localhost:8081/proxy/get # Proxy a POST request curl -X POST http://localhost:8081/proxy/post \ -H "Content-Type: application/json" \ -d '{"test": "data"}' ``` ### Response #### Success Response (200) - **The response from the target API** #### Response Example (Response examples depend on the proxied endpoint) ``` -------------------------------- ### Command-Line Usage Examples Source: https://phlow.dev/docs/modules/cli Provides examples of how to use the file-processor CLI tool, demonstrating basic processing, using optional flags, short flag equivalents, dry runs, and requesting help. ```bash # Basic processing ./file-processor process data.txt ``` ```bash # With options ./file-processor process data.txt --output ./results --format xml --batch-size 50 --verbose ``` ```bash # Using short flags ./file-processor convert input.csv -o ./converted -f json -b 25 -v ``` ```bash # Dry run ./file-processor validate config.yaml --dry-run --verbose ``` ```bash # Help ./file-processor --help ``` -------------------------------- ### Practical Examples: Organization and Development Workflows Source: https://phlow.dev/docs/remote-projects/git-repositories Showcases practical examples of running Phlow workflows from organizational repositories and for development purposes, including specific file and branch targeting. ```bash # Run a deployment flow from your organization PHLOW_MAIN_FILE='deployment/staging.phlow' phlow git@github.com:your-org/devops-flows.git ``` ```bash # Run a monitoring flow PHLOW_MAIN_FILE='monitoring/health-check.phlow' phlow git@github.com:your-org/ops-flows.git#production ``` ```bash # Test a development branch PHLOW_MAIN_FILE='test/integration.phlow' phlow git@github.com:your-org/project.git#feature/new-api ``` ```bash # Run a specific workflow PHLOW_MAIN_FILE='workflows/data-processing.phlow' phlow git@github.com:your-org/project.git ``` -------------------------------- ### Testing the Proxy API with cURL Source: https://phlow.dev/docs/examples/http-api Demonstrates how to test the API proxy using cURL. It shows how to proxy a GET request to '/proxy/get' and a POST request to '/proxy/post', including sending a JSON payload for the POST request. ```Shell # Proxy a GET request curl http://localhost:8081/proxy/get # Proxy a POST request curl -X POST http://localhost:8081/proxy/post \ -H "Content-Type: application/json" \ -d '{"test": "data"}' ``` -------------------------------- ### Example Phlow Application Structure Source: https://phlow.dev/docs/vscode-extension An example of a basic Phlow application defining an HTTP server, using modules, and defining steps for handling requests and returning responses. ```phlow main: http_server modules: - module: http_server version: latest - module: echo version: latest steps: - use: echo input: message: "Hello, World!" - return: status_code: 200 body: message: !phs payload.message ``` -------------------------------- ### Run Phlow Basic Math Test Source: https://phlow.dev/docs/testing/basic-examples Command to execute the basic math test using the Phlow CLI. ```bash phlow --test math-test.phlow ``` -------------------------------- ### Install Phlow using curl Source: https://phlow.dev/docs/install Installs Phlow by downloading and executing an installation script from a GitHub repository using curl. The `|| true` ensures that the script continues even if the download or execution fails. ```shell curl -fsSL https://raw.githubusercontent.com/phlowdotdev/phlow/refs/heads/main/scripts/install-phlow.sh | { bash || true; } ``` -------------------------------- ### CLI Usage Examples Source: https://phlow.dev/docs/modules/cli Demonstrates how to use the CLI application with various combinations of long flags, short flags, and positional arguments. ```shell # Using long flags ./myapp --input file.txt --output result.txt --verbose --count 5 # Using short flags ./myapp -i file.txt -o result.txt -v -c 5 # Mixing flags ./myapp --input file.txt -o result.txt -v ``` ```shell # Positional arguments ./myapp create user --debug # Equivalent to: # command = "create" # target = "user" # debug = true ``` ```shell ./myapp --help ./myapp -h ./myapp -H ``` -------------------------------- ### Complete Order Processing System Example Source: https://phlow.dev/docs/modules/amqp A full example of an order processing system using the Phlow AMQP module, including consumer and notification sender configurations. ```yaml name: "order-processing-system" version: "1.0.0" main: "order_consumer" modules: - name: "order_consumer" module: "amqp" with: host: "rabbitmq.company.com" port: 5672 username: "app_user" password: "secure_password" vhost: "production" exchange: "orders" exchange_type: "topic" routing_key: "order.created" queue_name: "order_processing" consumer_tag: "order_processor_1" definition: exchanges: - name: "orders" type: "topic" durable: true vhost: "production" queues: - name: "order_processing" durable: true vhost: "production" bindings: - source: "orders" destination: "order_processing" routing_key: "order.created" vhost: "production" - name: "notification_sender" module: "amqp" with: host: "rabbitmq.company.com" exchange: "notifications" routing_key: "notification.email" steps: - name: "process_order" # Processes the received order - name: "send_notification" use: "notification_sender" input: message: '{"type": "order_processed", "order_id": "{{ $input.order_id }}"}' headers: content-type: "application/json" priority: "normal" ``` -------------------------------- ### Phlow CLI Command Examples Source: https://phlow.dev/docs/examples/database-operations Examples of using the Phlow CLI to interact with the dynamic query builder. Demonstrates how to perform search, create, and update operations with various parameters including WHERE clauses and JSON data. ```bash # Search users phlow dynamic-queries.phlow search users # Search with WHERE clause phlow dynamic-queries.phlow search users --where "age > 25" # Create new user phlow dynamic-queries.phlow create users --data '{"name": "Alice", "email": "alice@example.com", "age": 28}' # Update user phlow dynamic-queries.phlow update users --data '{"age": 29}' --where "email = 'alice@example.com'" ``` -------------------------------- ### Create and Run Phlow Module Test Source: https://phlow.dev/docs/packages-and-modules/create-module Steps to create a test Phlow file, install a local module, and execute the test using the `phlow test` command. This involves defining module dependencies and configurations within the test file. ```Shell # test.phlow main: your_module modules: - module: your_module with: # your configuration steps: - use: your_module input: # your test input # Copy module to phlow_packages mkdir -p phlow_packages/your_module cp target/debug/libyour_module.so phlow_packages/your_module/module.so cp phlow.yaml phlow_packages/your_module/ # Run test phlow test.phlow ``` -------------------------------- ### Phlow Module Usage Example Source: https://phlow.dev/docs/phlow-structure/modules Illustrates how to define and use a module instance within a Phlow workflow. It shows referencing a local module (e.g., './route'), configuring it with 'with' parameters (which become 'setup'), and then using that configured instance in a subsequent step. ```Phlow modules: - module: ./route # References route.phlow name: route_get_users # Instance name with: # Configuration (becomes 'setup') path: /users method: GET default_response: status_code: 200 body: [] steps: - use: route_get_users # Uses the configured module instance input: !phs main # Runtime data (becomes 'main') ``` -------------------------------- ### Phlow CLI Usage Examples Source: https://phlow.dev/docs/examples/cli-applications Demonstrates how to execute the Phlow Project Manager CLI with different commands and arguments. ```Bash # Create a new project phlow project-manager.phlow create my-new-app --template web # List all projects phlow project-manager.phlow list # Delete a project phlow project-manager.phlow delete old-project --force # Show status phlow project-manager.phlow status ``` -------------------------------- ### Phlow Modules Configuration Example Source: https://phlow.dev/docs/phlow-structure/modules Provides an example of defining configurations for different modules, such as the 'cli' and 'postgres' modules, within a `modules.phlow` file. It showcases how to specify module versions, define arguments with types and descriptions for the CLI module, and configure database connection details for the PostgreSQL module, including environment variable fallbacks. ```Phlow - module: cli version: latest with: additional_args: false args: - name: name description: Student name index: 1 type: string required: true - name: age description: Student age index: 2 type: number required: true - name: force long: force description: Force assertion short: f type: boolean default: false - module: postgres version: latest with: host: !phs envs.POSTGRES_HOST ?? 'localhost' user: !phs envs.POSTGRES_USER ?? 'postgres' password: !phs envs.POSTGRES_PASSWORD ``` -------------------------------- ### Phlow REST API with CRUD Operations Source: https://phlow.dev/docs/examples/http-api This Phlow script defines a complete REST API with in-memory storage, supporting CRUD operations. It initializes data, and defines handlers for GET (list all, get one), POST (create), PUT (update), and DELETE requests for '/api/items'. It also includes default 404 handling for unknown routes. Dependencies include the 'http_server' module. ```Phlow name: CRUD API Example version: 1.0.0 description: Complete CRUD API with in-memory storage main: http_server modules: - module: http_server version: latest with: port: 3000 host: "0.0.0.0" steps: # Initialize in-memory storage - payload: !phs { items: [ { id: 1, name: "Item 1", description: "First item" }, { id: 2, name: "Item 2", description: "Second item" } ] } # GET /api/items - List all items - assert: !phs main.path == "/api/items" && main.method == "GET" then: return: status_code: 200 body: items: !phs payload.items total: !phs payload.items.length headers: Content-Type: application/json # POST /api/items - Create new item - assert: !phs main.path == "/api/items" && main.method == "POST" then: - payload: !phs { ...payload, newItem: { id: Math.max(...payload.items.map(item => item.id)) + 1, ...JSON.parse(main.body), created_at: new Date().toISOString() } } - payload: !phs { ...payload, items: [...payload.items, payload.newItem] } - return: status_code: 201 body: message: "Item created successfully" item: !phs payload.newItem headers: Content-Type: application/json # GET /api/items/{id} - Get specific item - assert: !phs main.path.startsWith("/api/items/") && main.method == "GET" && main.path.split("/").length == 4 then: - payload: !phs { ...payload, requestedId: parseInt(main.path.split("/")[3]) } - payload: !phs { ...payload, foundItem: payload.items.find(item => item.id === payload.requestedId) } - assert: !phs payload.foundItem then: return: status_code: 200 body: !phs payload.foundItem headers: Content-Type: application/json else: return: status_code: 404 body: error: "Item not found" headers: Content-Type: application/json # PUT /api/items/{id} - Update item - assert: !phs main.path.startsWith("/api/items/") && main.method == "PUT" && main.path.split("/").length == 4 then: - payload: !phs { ...payload, requestedId: parseInt(main.path.split("/")[3]) } - payload: !phs { ...payload, items: payload.items.map(item => item.id === payload.requestedId ? { ...item, ...JSON.parse(main.body), updated_at: new Date().toISOString() } : item ) } - return: status_code: 200 body: message: "Item updated successfully" item: !phs payload.items.find(item => item.id === payload.requestedId) headers: Content-Type: application/json # DELETE /api/items/{id} - Delete item - assert: !phs main.path.startsWith("/api/items/") && main.method == "DELETE" && main.path.split("/").length == 4 then: - payload: !phs { ...payload, requestedId: parseInt(main.path.split("/")[3]) } - payload: !phs { ...payload, items: payload.items.filter(item => item.id !== payload.requestedId) } - return: status_code: 200 body: message: "Item deleted successfully" deletedId: !phs payload.requestedId headers: Content-Type: application/json # Default response for unknown routes - return: status_code: 404 body: error: "Route not found" path: !phs main.path method: !phs main.method headers: Content-Type: application/json ``` -------------------------------- ### Phlow PostgreSQL Database Testing Setup Source: https://phlow.dev/docs/examples/database-operations Sets up a PostgreSQL database for testing by creating a table and defining test cases for connection, user creation, and retrieval. It includes setup, cleanup, and assertion logic. ```Phlow name: Database Tests version: 1.0.0 description: Testing database operations modules: - module: postgres version: latest with: host: localhost port: 5432 database: test_db user: test_user password: test_password tests: # Test database connection - main: {} payload: null assert: !phs payload.length > 0 # Test user creation - main: name: "Test User" email: "test@example.com" age: 25 payload: null assert: !phs payload.user.name == "Test User" # Test user retrieval - main: email: "test@example.com" payload: null assert: !phs payload.user.email == "test@example.com" steps: # Setup test database - postgres: query: | CREATE TABLE IF NOT EXISTS test_users ( id SERIAL PRIMARY KEY, name VARCHAR(100), email VARCHAR(100), age INTEGER ) # Clean up before tests - postgres: query: "DELETE FROM test_users" # Test connection - postgres: query: "SELECT 1 as connection_test" - assert: !phs payload.length > 0 then: # Test user creation - assert: !phs main.name && main.email then: - postgres: query: "INSERT INTO test_users (name, email, age) VALUES ($1, $2, $3) RETURNING *" params: - !phs main.name - !phs main.email - !phs main.age - return: !phs { user: payload[0] } # Test user retrieval - assert: !phs main.email && !main.name then: - postgres: query: "SELECT * FROM test_users WHERE email = $1" params: - !phs main.email - return: !phs { user: payload[0] } # Default: return connection test - return: !phs payload ``` -------------------------------- ### Create a Simple HTTP Server with Phlow Source: https://phlow.dev/docs/examples/http-api Defines a basic HTTP server using the `http_server` module that responds to different routes like '/', '/health', and '/api/users'. It handles GET and POST requests for user data and provides a 404 response for unknown routes. The server listens on port 8080. ```phlow name: Simple HTTP Server version: 1.0.0 description: A basic HTTP server example main: http_server modules: - module: http_server version: latest with: port: 8080 host: "0.0.0.0" steps: - assert: !phs main.path == "/" then: return: status_code: 200 body: message: "Welcome to Phlow API" version: "1.0.0" headers: Content-Type: application/json - assert: !phs main.path == "/health" then: return: status_code: 200 body: status: "healthy" timestamp: !phs new Date().toISOString() headers: Content-Type: application/json - assert: !phs main.path == "/api/users" && main.method == "GET" then: return: status_code: 200 body: users: - id: 1 name: "John Doe" email: "john@example.com" - id: 2 name: "Jane Smith" email: "jane@example.com" headers: Content-Type: application/json - assert: !phs main.path == "/api/users" && main.method == "POST" then: return: status_code: 201 body: message: "User created successfully" user: !phs JSON.parse(main.body) id: !phs Math.floor(Math.random() * 1000) headers: Content-Type: application/json # Default response for unknown routes - return: status_code: 404 body: error: "Route not found" path: !phs main.path method: !phs main.method headers: Content-Type: application/json ``` -------------------------------- ### Run Phlow Projects from Remote Sources (CLI Examples) Source: https://phlow.dev/docs/remote-projects Examples demonstrating how to execute Phlow projects from various remote sources including Git repositories (SSH and HTTPS), ZIP archives, and TAR.GZ archives. These commands show the basic invocation for each type of remote source. ```shell # Git via SSH phlow git@github.com:phlowdotdev/phlow-mirror-request.git # Git via HTTPS phlow https://github.com/phlowdotdev/phlow-mirror-request.git # ZIP archive phlow https://github.com/phlowdotdev/phlow-mirror-request/archive/refs/heads/main.zip # Tarball (GZIP) phlow https://github.com/phlowdotdev/phlow-mirror-request/tarball/main ``` -------------------------------- ### Complete Workflow Example with Sleep Module Source: https://phlow.dev/docs/modules/sleep An example of a complete workflow demonstrating batch processing with delays between batches using the sleep module. ```yaml name: "batch-processor" version: "1.0.0" description: "Processamento em lote com delays" modules: - name: "sleep_module" module: "sleep" version: "0.0.1" - name: "http_client" module: "http_request" - name: "logger" module: "log" steps: - name: "start_processing" use: "logger" input: message: "Iniciando processamento em lote" - name: "process_batch_1" use: "http_client" input: method: "POST" url: "https://api.example.com/process" body: '{"batch": 1, "items": [1, 2, 3]}' - name: "log_batch_1" use: "logger" input: message: "Lote 1 processado, aguardando..." - name: "wait_between_batches" use: "sleep_module" input: seconds: 30 - name: "process_batch_2" use: "http_client" input: method: "POST" url: "https://api.example.com/process" body: '{"batch": 2, "items": [4, 5, 6]}' - name: "log_batch_2" use: "logger" input: message: "Lote 2 processado, aguardando..." - name: "final_wait" use: "sleep_module" input: minutes: 5 - name: "finalize_processing" use: "http_client" input: method: "POST" url: "https://api.example.com/finalize" body: '{"status": "completed"}' - name: "completion_log" use: "logger" input: message: "Processamento completo!" ``` -------------------------------- ### Run Phlow Test with Failures Source: https://phlow.dev/docs/testing/basic-examples Command to execute the Phlow test that includes expected failures. ```bash phlow --test fail-test.phlow ``` -------------------------------- ### Install Phlow VS Code Extension via Command Line Source: https://phlow.dev/docs/vscode-extension Installs the Phlow VS Code extension using the VS Code command-line interface. This command is useful for automated installations or scripting. ```bash code --install-extension phlow.phlow ``` -------------------------------- ### API Proxy Configuration (Phlow) Source: https://phlow.dev/docs/examples/http-api Configures an API proxy to forward requests to external APIs. It sets up an HTTP server on port 8081, logs incoming requests, and conditionally proxies requests starting with '/proxy' to a target URL. It handles request methods, headers, and bodies, returning appropriate status codes and responses. ```Phlow name: API Proxy version: 1.0.0 description: Proxy requests to external APIs main: http_server modules: - module: http_server version: latest with: port: 8081 host: "0.0.0.0" - module: http_request version: latest - module: log version: latest steps: - log: message: !phs `Proxying ${main.method} request to: ${main.path}` # Only proxy requests that start with /proxy - assert: !phs main.path.startsWith('/proxy') then: - payload: !phs { targetUrl: `https://httpbin.org${main.path.replace('/proxy', '')}`, method: main.method, headers: main.headers || {}, body: main.body } - http_request: url: !phs payload.targetUrl method: !phs payload.method headers: !phs payload.headers body: !phs payload.body - log: message: !phs `Proxy response received` - return: status_code: 200 body: !phs payload headers: Content-Type: application/json else: - return: status_code: 404 body: error: "Proxy endpoint not found" message: "Use /proxy/{path} to proxy requests" headers: Content-Type: application/json ``` -------------------------------- ### Phlow Assertions: Using `assert_eq` (Direct comparison) Source: https://phlow.dev/docs/testing/basic-examples Examples of using `assert_eq` in Phlow for direct value comparison, including arithmetic results and string concatenation. ```phlow tests: - main: multiplier: 2 payload: 10 assert_eq: 20 - main: prefix: "Hello" payload: "World" assert_eq: "Hello World" steps: - payload: !phs main.multiplier * payload - payload: !phs `${main.prefix} ${payload}` ``` -------------------------------- ### Simple String Echo Example Source: https://phlow.dev/docs/modules/echo A straightforward example showing the Echo module processing a simple string input, useful for basic pipeline validation. ```yaml steps: - name: "simple_echo" use: "echo_module" input: "Esta mensagem serĂ¡ ecoada" ``` -------------------------------- ### Advanced File and Branch Selection Examples Source: https://phlow.dev/docs/remote-projects/git-repositories Provides advanced examples of selecting specific flow files and branches from Git repositories, including flows located in subdirectories or with different extensions. ```bash # Execute a flow from a subdirectory PHLOW_MAIN_FILE='flows/api/webhook.phlow' phlow git@github.com:your-org/flows-repo.git ``` ```bash # Execute from a specific branch and file PHLOW_MAIN_FILE='deployment/prod.phlow' phlow git@github.com:your-org/flows-repo.git#production ``` ```bash # Execute a flow with a different extension PHLOW_MAIN_FILE='workflows/data-processing.phlow' phlow git@github.com:your-org/flows-repo.git ``` -------------------------------- ### Run Phlow String Concatenation Test Source: https://phlow.dev/docs/testing/basic-examples Command to execute the string concatenation test using the Phlow CLI. ```bash phlow --test string-test.phlow ``` -------------------------------- ### Phlow 'log' Module Usage Source: https://phlow.dev/docs/phlow-structure/steps A simple example of using the 'log' module with the 'use' and 'input' syntax to log a message for tracing or debugging. ```yaml steps: - use: log input: message: !phs `Logging a message for tracing` ``` -------------------------------- ### List All Items Source: https://phlow.dev/docs/examples/http-api Retrieves a list of all available items from the in-memory storage. Includes the total count of items. ```APIDOC ## GET /api/items ### Description Retrieves a list of all items and their total count. ### Method GET ### Endpoint /api/items ### Parameters #### Query Parameters None #### Request Body None ### Response #### Success Response (200) - **items** (array) - An array of item objects. - **total** (integer) - The total number of items. #### Response Example ```json { "items": [ { "id": 1, "name": "Item 1", "description": "First item" }, { "id": 2, "name": "Item 2", "description": "Second item" } ], "total": 2 } ``` ``` -------------------------------- ### Phlow 'postgres' Module Usage Source: https://phlow.dev/docs/phlow-structure/steps An example of using the 'postgres' module to execute a SQL query. It includes the SQL query string as input. ```yaml steps: - use: postgres input: query: "SELECT * FROM users WHERE active = true" ``` -------------------------------- ### Get Specific Item Source: https://phlow.dev/docs/examples/http-api Retrieves a single item by its unique identifier. ```APIDOC ## GET /api/items/{id} ### Description Retrieves a specific item based on its ID. ### Method GET ### Endpoint /api/items/{id} ### Parameters #### Path Parameters - **id** (integer) - Required - The unique identifier of the item to retrieve. #### Query Parameters None #### Request Body None ### Response #### Success Response (200) - **id** (integer) - The unique identifier of the item. - **name** (string) - The name of the item. - **description** (string) - The description of the item. - **created_at** (string) - The timestamp when the item was created. - **updated_at** (string) - The timestamp when the item was last updated. #### Error Response (404) - **error** (string) - Error message indicating the item was not found. #### Response Example (Success) ```json { "id": 1, "name": "Item 1", "description": "First item", "created_at": "2023-10-27T09:00:00.000Z" } ``` #### Response Example (Not Found) ```json { "error": "Item not found" } ``` ``` -------------------------------- ### Example Route Module (.phlow) Source: https://phlow.dev/docs/packages-and-modules/phlow-modules A sample Phlow module demonstrating how to match HTTP routes. It defines configuration, input, and output schemas, and includes logic for matching requests against configured paths and methods. ```Phlow # Configuration schema - parameters passed via 'with' with: type: object required: true properties: path: type: string description: "HTTP path to match (e.g., /users)" required: true method: type: enum description: "HTTP method to match" enum: [GET, POST, DELETE, PUT, PATCH, OPTIONS] required: true default_response: type: object description: "Default response when route matches" required: false properties: status_code: type: number default: 200 body: type: object default: {} headers: type: object default: {} # Input schema - runtime data structure input: type: object required: true properties: request: type: object required: true properties: path: type: string description: "Incoming request path" required: true method: type: string description: "Incoming request method" required: true headers: type: object description: "Request headers" required: false body: type: object description: "Request body" required: false # Output schema - what the module returns output: type: object required: true properties: matched: type: boolean description: "Whether the route matched" required: true response: type: object description: "HTTP response data" required: false properties: status_code: type: number required: true body: type: object required: false headers: type: object required: false # Module implementation steps: - assert: !phs setup.path == main.request.path && setup.method == main.request.method then: payload: matched: true response: !phs setup.default_response || { status_code: 200, body: {} } else: payload: matched: false response: null ``` -------------------------------- ### Run Jaeger All-in-One with OTLP Support Source: https://phlow.dev/docs/opentelemetry Starts a Docker container for Jaeger, which includes an OpenTelemetry-compatible collector. This setup is ideal for local development to visualize traces, metrics, and logs. ```bash docker run -d \ -p4318:4318 \ -p4317:4317 \ -p16686:16686 \ jaegertracing/all-in-one:latest ``` -------------------------------- ### Test Phlow HTTP API Endpoints with curl Source: https://phlow.dev/docs/examples/http-api Demonstrates how to test various endpoints of the Phlow HTTP server using `curl`. It includes testing the root, health, GET users, and POST users endpoints, including setting headers and request bodies. ```bash # Test the root endpoint curl http://localhost:8080/ # Test the health endpoint curl http://localhost:8080/health # Test GET users curl http://localhost:8080/api/users # Test POST users curl -X POST http://localhost:8080/api/users \ -H "Content-Type: application/json" \ -d '{"name": "Alice Johnson", "email": "alice@example.com"}' ``` -------------------------------- ### Phlow CLI Execution Commands Source: https://phlow.dev/docs/examples/simple-flows Demonstrates how to execute Phlow scripts using the command-line interface, including running a simple flow and enabling debug logging. ```bash # Run the flow phlow simple-flow.phlow ``` ```bash # With debug logging PHLOW_LOG=debug phlow simple-flow.phlow ``` -------------------------------- ### Implement AMQP Producer in Rust Source: https://phlow.dev/docs/packages-and-modules/create-module Sets up an AMQP producer that listens for step operations and publishes messages to a configured exchange. It creates a module channel for communication, notifies setup completion, and handles incoming messages by publishing them to the AMQP exchange, providing feedback on success or failure. ```rust use super::Config; use phlow_sdk::prelude::*; use lapin::{options::*, BasicProperties, Channel}; pub async fn start_producer( setup_sender: SetupSender, config: Config, channel: Channel, ) -> Result<(), Box> { log::debug!("Producer ready for step operations"); // Create module channel for step operations let (tx, rx) = module_channel(); // Notify setup completion sender_safe!(setup_sender, Some(tx)); // Listen for step operations listen!(rx, move |package: ModulePackage| async { let channel = channel.clone(); let config = config.clone(); // Get input message let input = package.input().unwrap_or(Value::Null); let message = input.to_string(); // Publish message match channel .basic_publish( &config.exchange, &config.routing_key, BasicPublishOptions::default(), message.as_bytes(), BasicProperties::default(), ) .await { Ok(_) => { log::debug!("Message published successfully"); let response = json!({ "success": true, "error_message": null }); sender_safe!(package.sender, response.to_value().into()); } Err(e) => { log::error!("Failed to publish message: {}", e); let response = json!({ "success": false, "error_message": e.to_string() }); sender_safe!(package.sender, response.to_value().into()); } } }); Ok(()) } ``` -------------------------------- ### Implement AMQP Consumer in Rust Source: https://phlow.dev/docs/packages-and-modules/create-module Starts an AMQP consumer that listens to a specified queue. It declares the queue, begins consuming messages, and handles each message by parsing it, sending it to the phlow pipeline, and acknowledging or negatively acknowledging it based on processing success. Dependencies include `phlow_sdk` and `lapin`. ```rust use super::Config; use phlow_sdk::prelude::*; use lapin::{options::*, types::FieldTable, BasicProperties, Channel}; use lapin::message::DeliveryResult; pub async fn start_consumer( id: ModuleId, main_sender: MainRuntimeSender, config: Config, channel: Channel, dispatch: phlow_sdk::tracing::Dispatch, ) -> Result<(), Box> { log::debug!("Starting AMQP consumer on queue: {}", config.queue_name); // Declare queue let _queue = channel .queue_declare( &config.queue_name, QueueDeclareOptions::default(), FieldTable::default(), ) .await?; // Start consuming let consumer = channel .basic_consume( &config.queue_name, &config.consumer_tag, BasicConsumeOptions::default(), FieldTable::default(), ) .await?; // Handle messages consumer.set_delegate(move |delivery: DeliveryResult| { let sender = main_sender.clone(); let module_id = id.clone(); let dispatch = dispatch.clone(); Box::pin(async move { match delivery { Ok(Some(delivery)) => { // Parse message let message = String::from_utf8_lossy(&delivery.data).to_string(); let data = json!({"message": message}).to_value(); // Send to pipeline match sender_package!(dispatch, module_id, sender, Some(data)).await { Ok(_) => { // Acknowledge message let _ = delivery.ack(BasicAckOptions::default()).await; log::debug!("Message processed and acknowledged"); } Err(e) => { log::error!("Pipeline processing error: {}", e); let _ = delivery.nack(BasicNackOptions::default()).await; } } } Ok(None) => { log::debug!("No message received"); } Err(e) => { log::error!("Consumer error: {}", e); } } }) }); Ok(()) } ```