### Running Locally with a Sandbox Conductor Source: https://context7.com/holochain/hc-http-gw/llms.txt This multi-step example demonstrates how to set up a local development environment for the Holochain HTTP Gateway. It covers entering a Nix shell, starting a sandbox conductor, building and installing a fixture hApp, running the gateway, and performing health checks and zome calls. ```bash # 1. Enter the Nix dev shell (or ensure rustup + holochain-cli are installed) nix develop ``` ```bash # 2. Start a sandboxed Holochain conductor hc sandbox clean hc sandbox create --in-process-lair # note the admin_port printed here hc sandbox run # e.g. admin_port: 41191 ``` ```bash # 3. In a second terminal: build and install the fixture hApp ./fixture/package.sh hc sandbox call install-app fixture/package/happ1/fixture1.happ ``` ```bash # 4. Start the gateway (replace port with the one from step 2) HC_GW_ADMIN_WS_URL="ws://localhost:41191" \ HC_GW_ALLOWED_APP_IDS="fixture1" \ HC_GW_ALLOWED_FNS_fixture1="coordinator1/get_all_1" \ cargo run ``` ```bash # 5. In a third terminal: verify health and make a zome call curl -i localhost:8090/health # HTTP/1.1 200 OK ... Ok DNA_HASH=$(hc sandbox call list-dnas | grep -oP 'DnaHash\(\K[^)]+') curl -i "localhost:8090/${DNA_HASH}/fixture1/coordinator1/get_all_1" # HTTP/1.1 200 OK # [] ``` ```bash # 6. Authorize zome calls and create data via the sandbox CLI hc sandbox zome-call-auth fixture1 hc sandbox zome-call fixture1 "${DNA_HASH}" coordinator1 create_1 'null' ``` ```bash # 7. Retrieve the created data through the gateway curl -i "localhost:8090/${DNA_HASH}/fixture1/coordinator1/get_all_1" # HTTP/1.1 200 OK # [{"value":"create_1_2025-03-12T17:54:06.337428Z"}] ``` -------------------------------- ### Install Test Fixture hApp Source: https://github.com/holochain/hc-http-gw/blob/main/README.md Installs the test fixture hApp into the Holochain sandbox. ```bash hc sandbox call install-app fixture/package/happ1/fixture1.happ ``` -------------------------------- ### Build and Package Test Fixture Source: https://github.com/holochain/hc-http-gw/blob/main/README.md Builds and packages the test fixture (`fixture1`) so it can be installed. ```bash ./fixture/package.sh ``` -------------------------------- ### Start the HTTP Server with `HcHttpGatewayService` Source: https://context7.com/holochain/hc-http-gw/llms.txt Creates and runs the Axum-based HTTP server. Configures the server with specified addresses, app IDs, and function allowlists. Manages admin and app WebSocket connections. ```rust use holochain_http_gateway::{ AdminConn, AllowedFns, AppConnPool, Configuration, HcHttpGatewayService, ZomeFn, }; use std::{ collections::{HashMap, HashSet}, net::{Ipv4Addr, SocketAddr}, sync::Arc, }; #[tokio::main] async fn main() -> anyhow::Result<()> { let mut allowed_fns = HashMap::new(); allowed_fns.insert( "my_happ".to_string(), AllowedFns::Restricted(HashSet::from([ ZomeFn { zome_name: "coordinator".to_string(), fn_name: "get_entries".to_string() }, ])), ); let config = Configuration::try_new( SocketAddr::new(Ipv4Addr::LOCALHOST.into(), 41191), "", // use default payload limit "my_happ", allowed_fns, "", // use default max connections "", // use default zome call timeout )?; // AdminConn manages the single persistent admin WebSocket connection let admin_call = Arc::new(AdminConn::new(config.admin_socket_addr)); // AppConnPool manages one app WebSocket per allowed app, with reconnection let app_call = Arc::new(AppConnPool::new(config.clone(), admin_call.clone())); // Bind to 0.0.0.0:8090 let service = HcHttpGatewayService::new( [0, 0, 0, 0], // listen on all interfaces 8090, config, admin_call, app_call, ) .await?; println!("Gateway listening on {}", service.address()?); service.run().await?; Ok(()) } ``` -------------------------------- ### List Installed DNAs Source: https://github.com/holochain/hc-http-gw/blob/main/README.md Lists the DNA hashes of the installed hApps in the Holochain sandbox. The DNA hash is required for making direct calls to zomes. ```bash hc sandbox call list-dnas ``` -------------------------------- ### Run HTTP Gateway Source: https://github.com/holochain/hc-http-gw/blob/main/README.md Runs the HTTP Gateway. Ensure HC_GW_ADMIN_WS_URL points to the conductor's admin port, and HC_GW_ALLOWED_APP_IDS and HC_GW_ALLOWED_FNS are configured for your installed hApp. ```bash HC_GW_ADMIN_WS_URL="ws://localhost:41191" HC_GW_ALLOWED_APP_IDS="fixture1" HC_GW_ALLOWED_FNS_fixture1="coordinator1/get_all_1" cargo run ``` -------------------------------- ### GET /{dna_hash}/{coordinator_identifier}/{zome_name}/{fn_name} Source: https://context7.com/holochain/hc-http-gw/llms.txt The primary endpoint for routing HTTP GET requests to Holochain zome function calls. It requires base64url-encoded DNA hash and app ID, along with zome and function names. An optional base64url-encoded JSON payload can be provided. ```APIDOC ## `GET /{dna_hash}/{coordinator_identifier}/{zome_name}/{fn_name}` — Zome Call Endpoint The primary endpoint. Routes an HTTP GET into a Holochain zome function call. The `dna_hash` is a base64url-encoded DNA hash. The `coordinator_identifier` must match an installed app ID. The optional `payload` query parameter must be a base64url-encoded JSON value. Responses are JSON-encoded zome return values. ### Example Usage ```bash DNA_HASH="uhC0kwgZaQK05lgFwcYb_LrtAXTAckaS41nxNVO_zRMdpsuAeA0uN" APP_ID="fixture1" ZOME="coordinator1" FN="get_all_1" # Call with no payload curl -i "http://localhost:8090/${DNA_HASH}/${APP_ID}/${ZOME}/${FN}" # HTTP/1.1 200 OK # [{\"value\":\"create_1_2025-03-12T17:54:06.337428Z\"}] # Call with a base64url-encoded JSON payload # Encode payload: echo -n '{"limit":5}' | base64 -w0 | tr '+/' '-_' | tr -d '=' PAYLOAD=$(echo -n '{"limit":5}' | base64 | tr '+/' '-_' | tr -d '=') curl -i "http://localhost:8090/${DNA_HASH}/${APP_ID}/${ZOME}/get_limited?payload=${PAYLOAD}" # HTTP/1.1 200 OK # [{\"value\":\"...\"},{\"value\":\"...\"},{\"value\":\"...\"},{\"value\":\"...\"},{\"value\":\"...\"}] # Error: function not in allowlist → 403 curl -i "http://localhost:8090/${DNA_HASH}/${APP_ID}/${ZOME}/create_1" # HTTP/1.1 403 Forbidden # {"error":"Function create_1 in zome coordinator1 in app fixture1 is not allowed"} # Error: app/DNA not found → 404 curl -i "http://localhost:8090/invalid_dna_hash/${APP_ID}/${ZOME}/${FN}" # HTTP/1.1 400 Bad Request # {"error":"Request is malformed: Invalid DNA hash"} # Error: non-GET method → 405 curl -i -X POST "http://localhost:8090/${DNA_HASH}/${APP_ID}/${ZOME}/${FN}" # HTTP/1.1 405 Method Not Allowed ``` ``` -------------------------------- ### Zome Call Endpoint `GET /{dna_hash}/{coordinator_identifier}/{zome_name}/{fn_name}` Source: https://context7.com/holochain/hc-http-gw/llms.txt Routes HTTP GET requests to Holochain zome functions. Supports base64url-encoded DNA hashes and JSON payloads. Responses are JSON-encoded zome return values. Handles errors for disallowed functions, missing apps/D NAs, and incorrect methods. ```bash DNA_HASH="uhC0kwgZaQK05lgFwcYb_LrtAXTAckaS41nxNVO_zRMdpsuAeA0uN" APP_ID="fixture1" ZOME="coordinator1" FN="get_all_1" # Call with no payload curl -i "http://localhost:8090/${DNA_HASH}/${APP_ID}/${ZOME}/${FN}" # HTTP/1.1 200 OK # [{"value":"create_1_2025-03-12T17:54:06.337428Z"}] # Call with a base64url-encoded JSON payload # Encode payload: echo -n '{"limit":5}' | base64 -w0 | tr '+/' '-_' | tr -d '=' PAYLOAD=$(echo -n '{"limit":5}' | base64 | tr '+/' '-_' | tr -d '=') curl -i "http://localhost:8090/${DNA_HASH}/${APP_ID}/${ZOME}/get_limited?payload=${PAYLOAD}" # HTTP/1.1 200 OK # [{"value":"..."},{"value":"..."},{"value":"..."},{"value":"..."},{"value":"..."}] # Error: function not in allowlist → 403 curl -i "http://localhost:8090/${DNA_HASH}/${APP_ID}/${ZOME}/create_1" # HTTP/1.1 403 Forbidden # {"error":"Function create_1 in zome coordinator1 in app fixture1 is not allowed"} # Error: app/DNA not found → 404 curl -i "http://localhost:8090/invalid_dna_hash/${APP_ID}/${ZOME}/${FN}" # HTTP/1.1 400 Bad Request # {"error":"Request is malformed: Invalid DNA hash"} # Error: non-GET method → 405 curl -i -X POST "http://localhost:8090/${DNA_HASH}/${APP_ID}/${ZOME}/${FN}" # HTTP/1.1 405 Method Not Allowed ``` -------------------------------- ### Zome Call via HTTP GET Source: https://github.com/holochain/hc-http-gw/blob/main/spec.md This endpoint allows you to invoke zome functions within a Holochain DNA using an HTTP GET request. The request URL includes details to identify the target DNA, coordinator, zome, and function, along with a base64 encoded JSON payload. ```APIDOC ## GET /holochain/hc-http-gw ### Description Invoke a zome function via an HTTP GET request. ### Method GET ### Endpoint `http://{host}/{dna-hash}/{coordinator-identifier}/{zome-name}/{function-name}?payload={payload}` ### Parameters #### Path Parameters - **dna-hash** (string) - Required - The base64 url encoded DNA hash of the DHT to retrieve data from. - **coordinator-identifier** (string) - Required - Identifies the coordinator zome to invoke. Recommended to be a UUID or UTF-8 string (max 100 chars). - **zome-name** (string) - Required - The name of the zome to invoke. - **function-name** (string) - Required - The name of the function within the zome to invoke. #### Query Parameters - **payload** (string) - Required - Base64 url encoded JSON string to be used as the zome call payload. ### Response #### Success Response (200) - **response** (JSON) - JSON encoded zome call response. #### Error Responses - **400 Bad Request**: Malformed request. Payload is a JSON message with an `error` field. - **403 Forbidden**: Request requires access to an app or function not exposed by the gateway. Payload is a JSON message with an `error` field. - **404 Not Found**: Unknown path or resource not found (e.g., no app matching `dna-hash`). Payload is a JSON message with an `error` field. - **405 Method Not Allowed**: Request uses a method other than GET for a valid path. - **500 Internal Server Error**: Internal error or error raised by the target hApp. Payload is a JSON error response with an `error` field. ``` -------------------------------- ### Make a Zome Call via Gateway Source: https://context7.com/holochain/hc-http-gw/llms.txt Perform a zome call to a specific function within an installed hApp through the HTTP Gateway. Ensure the DNA_HASH and function path are correct. The response will be JSON-encoded. ```bash DNA_HASH=$(hc sandbox call list-dnas | grep -oP 'DnaHash\(\K[^)]+') curl -i "localhost:8090/${DNA_HASH}/fixture1/coordinator1/get_all_1" ``` -------------------------------- ### Health Check Endpoint `GET /health` Source: https://context7.com/holochain/hc-http-gw/llms.txt Provides a basic health check for the gateway process. Returns `200 OK` with `Ok` body when running. Does not verify Holochain conductor connectivity. Non-GET methods are rejected. ```bash # Basic health check curl -i http://localhost:8090/health # Expected response: # HTTP/1.1 200 OK # content-type: text/plain; charset=utf-8 # content-length: 2 # # Ok # Non-GET methods are rejected with 405 curl -i -X POST http://localhost:8090/health # HTTP/1.1 405 Method Not Allowed ``` -------------------------------- ### GET /health Source: https://context7.com/holochain/hc-http-gw/llms.txt A health check endpoint that returns `200 OK` with the body `Ok` if the gateway is running. It serves as a liveness probe and does not check connectivity to the Holochain conductor. ```APIDOC ## `GET /health` — Health Check Endpoint Returns `200 OK` with body `Ok` when the gateway process is running. Does not verify connectivity to the Holochain conductor. Useful as a liveness probe in containerized deployments. ### Request Example ```bash # Basic health check curl -i http://localhost:8090/health # Expected response: # HTTP/1.1 200 OK # content-type: text/plain; charset=utf-8 # content-length: 2 # # Ok # Non-GET methods are rejected with 405 curl -i -X POST http://localhost:8090/health # HTTP/1.1 405 Method Not Allowed ``` ``` -------------------------------- ### Managed App WebSocket Connection Pool Source: https://context7.com/holochain/hc-http-gw/llms.txt Manages a pool of WebSocket connections to installed Holochain applications, ensuring at most one connection per app ID. It handles discovery, provisioning, authentication, and authorization. The pool automatically attempts reconnections up to three times on errors and evicts stale connections when capacity is exceeded. ```rust use holochain_http_gateway::{ AdminConn, AllowedFns, AppConnPool, Configuration, }; use std::collections::HashMap; use std::net::{Ipv4Addr, SocketAddr}; use std::sync::Arc; // Build the pool — typically done once at startup let mut allowed_fns = HashMap::new(); allowed_fns.insert("my_happ".to_string(), AllowedFns::All); let config = Configuration::try_new( SocketAddr::new(Ipv4Addr::LOCALHOST.into(), 41191), "", "my_happ", allowed_fns, "10", "", // max 10 connections ).unwrap(); let admin_call = Arc::new(AdminConn::new(config.admin_socket_addr)); let pool = Arc::new(AppConnPool::new(config.clone(), admin_call.clone())); // The pool is passed into HcHttpGatewayService and used via the AppCall trait. // Internally, each zome call goes through: // pool.handle_zome_call(app_id, cell_id, zome_name, fn_name, payload) // which calls pool.call(app_id, |app_ws| async { app_ws.call_zome(...).await }) // with up to 3 reconnection attempts on WebSocket errors. // In tests, inspect pool state with the test-utils feature: // let inner = pool.get_inner_pool(); // let connections = inner.read().await; // assert_eq!(connections.len(), 1); // one connection for "my_happ" ``` -------------------------------- ### HcHttpGatewayService::new and run Source: https://context7.com/holochain/hc-http-gw/llms.txt Initializes and runs the HTTP server. `HcHttpGatewayService::new` creates the server instance bound to a specified address and port, configuring admin and app connections. The `run` method keeps the server active until termination. ```APIDOC ## `HcHttpGatewayService::new` and `run` — Start the HTTP Server Creates the Axum-based HTTP server bound to the specified address and port, wiring up the admin connection and app connection pool. `run()` drives the server until the process is terminated. ### Example Usage ```rust use holochain_http_gateway::{ AdminConn, AllowedFns, AppConnPool, Configuration, HcHttpGatewayService, ZomeFn, }; use std::collections::{HashMap, HashSet}; use std::net::{Ipv4Addr, SocketAddr}; use std::sync::Arc; #[tokio::main] async fn main() -> anyhow::Result<()> { let mut allowed_fns = HashMap::new(); allowed_fns.insert( "my_happ".to_string(), AllowedFns::Restricted(HashSet::from([ ZomeFn { zome_name: "coordinator".to_string(), fn_name: "get_entries".to_string() }, ])), ); let config = Configuration::try_new( SocketAddr::new(Ipv4Addr::LOCALHOST.into(), 41191), "", // use default payload limit "my_happ", allowed_fns, "", // use default max connections "", // use default zome call timeout )?; // AdminConn manages the single persistent admin WebSocket connection let admin_call = Arc::new(AdminConn::new(config.admin_socket_addr)); // AppConnPool manages one app WebSocket per allowed app, with reconnection let app_call = Arc::new(AppConnPool::new(config.clone(), admin_call.clone())); // Bind to 0.0.0.0:8090 let service = HcHttpGatewayService::new( [0, 0, 0, 0], // listen on all interfaces 8090, config, admin_call, app_call, ) .await?; println!("Gateway listening on {}", service.address()?); service.run().await?; Ok(()) } ``` ``` -------------------------------- ### Programmatically Build and Validate Gateway Configuration Source: https://context7.com/holochain/hc-http-gw/llms.txt Use `Configuration::try_new` to construct and validate gateway configuration in Rust. This method requires the admin WebSocket address and app IDs, and accepts a map for per-app function restrictions. Empty numeric fields fall back to default values. ```rust use holochain_http_gateway::{ AllowedFns, Configuration, ZomeFn, }; use std::{ collections::{HashMap, HashSet}, net::{Ipv4Addr, SocketAddr}, str::FromStr, }; let mut allowed_fns = HashMap::new(); // Restrict mewsfeed to two read-only functions allowed_fns.insert( "mewsfeed".to_string(), AllowedFns::Restricted( HashSet::from([ ZomeFn { zome_name: "main".to_string(), fn_name: "list_mews".to_string() }, ZomeFn { zome_name: "main".to_string(), fn_name: "count_likes".to_string() }, ]), ), ); // Allow all functions for zipzap allowed_fns.insert("zipzap".to_string(), AllowedFns::All); let config = Configuration::try_new( SocketAddr::new(Ipv4Addr::new(127, 0, 0, 1).into(), 41191), // admin WebSocket address "10240", // HC_GW_PAYLOAD_LIMIT_BYTES — empty string uses DEFAULT_PAYLOAD_LIMIT_BYTES "mewsfeed,zipzap", // HC_GW_ALLOWED_APP_IDS allowed_fns, "50", // HC_GW_MAX_APP_CONNECTIONS — empty string uses DEFAULT_MAX_APP_CONNECTIONS "10000", // HC_GW_ZOME_CALL_TIMEOUT_MS — empty string uses DEFAULT_ZOME_CALL_TIMEOUT ) .expect("Configuration is valid"); assert!(config.is_app_allowed("mewsfeed")); assert!(config.is_function_allowed("mewsfeed", "main", "list_mews")); assert!(!config.is_function_allowed("mewsfeed", "main", "create_mew")); // write fn blocked assert!(config.is_function_allowed("zipzap", "any_zome", "any_fn")); // AllowedFns::All ``` -------------------------------- ### Create Sandboxed Conductor with Lair Keystore Source: https://github.com/holochain/hc-http-gw/blob/main/README.md Creates a new sandboxed conductor with the lair keystore running in the Holochain process. You will be prompted to enter a passphrase. ```bash hc sandbox create --in-process-lair ``` -------------------------------- ### Retrieve Created Data via Gateway Source: https://context7.com/holochain/hc-http-gw/llms.txt After creating data using the sandbox CLI, retrieve it through the HTTP Gateway. This verifies that the data creation was successful and is accessible. ```bash curl -i "localhost:8090/${DNA_HASH}/fixture1/coordinator1/get_all_1" ``` -------------------------------- ### Run All Tests Source: https://github.com/holochain/hc-http-gw/blob/main/README.md Executes all tests, including integration tests, for the Holochain HTTP Gateway. ```bash cargo test ``` -------------------------------- ### Configure Holochain HTTP Gateway via Environment Variables Source: https://context7.com/holochain/hc-http-gw/llms.txt Set environment variables to configure the gateway's behavior, including admin WebSocket URL, allowed applications and functions, payload limits, and server binding. Ensure all allowed app IDs have a corresponding allowed functions variable. ```bash # Minimal required configuration export HC_GW_ADMIN_WS_URL="ws://localhost:41191" # Comma-separated list of installed app IDs the gateway may access export HC_GW_ALLOWED_APP_IDS="mewsfeed,zipzap" # Per-app allowed functions: / pairs, or "*" for all export HC_GW_ALLOWED_FNS_mewsfeed="main/list_mews,main/count_likes" export HC_GW_ALLOWED_FNS_zipzap="*" # Optional tuning (shown with their defaults) export HC_GW_PAYLOAD_LIMIT_BYTES="10240" # 10 KB export HC_GW_MAX_APP_CONNECTIONS="50" export HC_GW_ZOME_CALL_TIMEOUT_MS="10000" # 10 seconds # Optional server binding (defaults shown) export HC_GW_ADDRESS="127.0.0.1" export HC_GW_PORT="8090" # Start the gateway cargo run --bin hc-http-gw # or, if installed: hc-http-gw ``` -------------------------------- ### Create Data via Zome Call Source: https://github.com/holochain/hc-http-gw/blob/main/README.md Creates data by calling the `create_1` function on the `coordinator1` zome. This requires prior authorization using `hc sandbox zome-call-auth`. ```bash hc sandbox zome-call fixture1 uhC0kwgZaQK05lgFwcYb_LrtAXTAckaS41nxNVO_zRMdpsuAeA0uN coordinator1 create_1 'null' ``` -------------------------------- ### Create Data via Sandbox CLI Source: https://context7.com/holochain/hc-http-gw/llms.txt Authorize and execute a zome call to create data using the Holochain sandbox CLI. This is a prerequisite for retrieving data that has been modified. ```bash hc sandbox zome-call-auth fixture1 hc sandbox zome-call fixture1 "${DNA_HASH}" coordinator1 create_1 'null' ``` -------------------------------- ### Run Sandboxed Conductor Source: https://github.com/holochain/hc-http-gw/blob/main/README.md Runs the sandboxed conductor. You will need to enter the same passphrase used during creation. ```bash hc sandbox run ``` -------------------------------- ### Environment Variable Configuration Source: https://context7.com/holochain/hc-http-gw/llms.txt Configure the Holochain HTTP Gateway using environment variables at startup. Key variables include the admin WebSocket URL, allowed app IDs, and per-app function allowlists. Optional variables control payload limits, connection pooling, timeouts, and server binding. ```APIDOC ## Environment Variable Configuration All gateway configuration is loaded from environment variables at startup. `HC_GW_ADMIN_WS_URL` is required; all others are optional and fall back to documented defaults. Every app ID listed in `HC_GW_ALLOWED_APP_IDS` must have a corresponding `HC_GW_ALLOWED_FNS_` variable, or the process will fail to start. ```bash # Minimal required configuration export HC_GW_ADMIN_WS_URL="ws://localhost:41191" # Comma-separated list of installed app IDs the gateway may access export HC_GW_ALLOWED_APP_IDS="mewsfeed,zipzap" # Per-app allowed functions: / pairs, or "*" for all export HC_GW_ALLOWED_FNS_mewsfeed="main/list_mews,main/count_likes" export HC_GW_ALLOWED_FNS_zipzap="*" # Optional tuning (shown with their defaults) export HC_GW_PAYLOAD_LIMIT_BYTES="10240" # 10 KB export HC_GW_MAX_APP_CONNECTIONS="50" export HC_GW_ZOME_CALL_TIMEOUT_MS="10000" # 10 seconds # Optional server binding (defaults shown) export HC_GW_ADDRESS="127.0.0.1" export HC_GW_PORT="8090" # Start the gateway cargo run --bin hc-http-gw # or, if installed: hc-http-gw ``` ``` -------------------------------- ### Configuration::try_new Source: https://context7.com/holochain/hc-http-gw/llms.txt Constructs and validates a `Configuration` struct programmatically. This method ensures that every app ID specified in `allowed_app_ids` has a corresponding entry in the `allowed_fns` map, returning an error otherwise. Numeric configuration fields can accept empty strings to use library defaults. ```APIDOC ## `Configuration::try_new` — Build and Validate Gateway Configuration Programmatically Constructs and validates a `Configuration` struct from parsed inputs. Every app ID in the `allowed_app_ids` string must have a corresponding entry in the `allowed_fns` map or `try_new` returns a `ConfigParseError`. Empty strings for numeric fields fall back to library defaults (`DEFAULT_PAYLOAD_LIMIT_BYTES`, `DEFAULT_MAX_APP_CONNECTIONS`, `DEFAULT_ZOME_CALL_TIMEOUT`). ```rust use holochain_http_gateway::{ AllowedFns, Configuration, ZomeFn, }; use std::{ collections::{HashMap, HashSet}, net::{Ipv4Addr, SocketAddr}, str::FromStr, }; let mut allowed_fns = HashMap::new(); // Restrict mewsfeed to two read-only functions allowed_fns.insert( "mewsfeed".to_string(), AllowedFns::Restricted( HashSet::from([ ZomeFn { zome_name: "main".to_string(), fn_name: "list_mews".to_string() }, ZomeFn { zome_name: "main".to_string(), fn_name: "count_likes".to_string() }, ]), ), ); // Allow all functions for zipzap allowed_fns.insert("zipzap".to_string(), AllowedFns::All); let config = Configuration::try_new( SocketAddr::new(Ipv4Addr::new(127, 0, 0, 1).into(), 41191), // admin WebSocket address "10240", // HC_GW_PAYLOAD_LIMIT_BYTES — empty string uses DEFAULT_PAYLOAD_LIMIT_BYTES "mewsfeed,zipzap", // HC_GW_ALLOWED_APP_IDS allowed_fns, "50", // HC_GW_MAX_APP_CONNECTIONS — empty string uses DEFAULT_MAX_APP_CONNECTIONS "10000", // HC_GW_ZOME_CALL_TIMEOUT_MS — empty string uses DEFAULT_ZOME_CALL_TIMEOUT ) .expect("Configuration is valid"); assert!(config.is_app_allowed("mewsfeed")); assert!(config.is_function_allowed("mewsfeed", "main", "list_mews")); assert!(!config.is_function_allowed("mewsfeed", "main", "create_mew")); // write fn blocked assert!(config.is_function_allowed("zipzap", "any_zome", "any_fn")); // AllowedFns::All ``` ``` -------------------------------- ### Clean Holochain Conductor Sandbox Source: https://github.com/holochain/hc-http-gw/blob/main/README.md Use this command to clean the Holochain conductor sandbox before creating a new one. ```bash hc sandbox clean ``` -------------------------------- ### Call get_all_1 Function Source: https://github.com/holochain/hc-http-gw/blob/main/README.md Calls the `get_all_1` function on the fixture hApp using its DNA hash. This is used to retrieve data, initially returning an empty array if no data exists. ```bash curl -i localhost:8090/uhC0kwgZaQK05lgFwcYb_LrtAXTAckaS41nxNVO_zRMdpsuAeA0uN/fixture1/coordinator1/get_all_1 ``` -------------------------------- ### Run Tests Excluding Integration Tests Source: https://github.com/holochain/hc-http-gw/blob/main/README.md Runs tests for the library and binaries but excludes the slower integration tests. ```bash cargo test --lib --bins ``` -------------------------------- ### Base64 JSON to Holochain ExternIO Transcoding Source: https://context7.com/holochain/hc-http-gw/llms.txt Utility functions for converting between Base64URL-encoded JSON and Holochain's native ExternIO (MessagePack) format. `base64_json_to_hsb` decodes Base64URL JSON and re-encodes it as ExternIO. `hsb_to_json` performs the reverse. These are primarily used internally by the zome call handler but are exposed via the `test-utils` feature. ```rust use base64::{prelude::BASE64_URL_SAFE, Engine}; use holochain_http_gateway::test; // requires `features = ["test-utils"]` // Access transcode functions via the internal path in tests: use holochain_types::prelude::ExternIO; use serde::{Deserialize, Serialize}; // --- base64_json_to_hsb --- // Simulate the ?payload= query parameter #[derive(Debug, PartialEq, Serialize, Deserialize)] struct MyPayload { limit: u32 } let payload = MyPayload { limit: 5 }; let json = serde_json::to_string(&payload).unwrap(); // {"limit":5} let b64 = BASE64_URL_SAFE.encode(&json); // eyJsaW1pdCI6NX0= // This is what the zome call handler does internally: let extern_io = ExternIO::encode( serde_json::from_str::(&json).unwrap() ).unwrap(); let decoded: MyPayload = extern_io.decode().unwrap(); assert_eq!(decoded, payload); // --- hsb_to_json --- // Simulate a zome return value coming back from Holochain #[derive(Serialize, Deserialize, Clone)] struct Entry { value: String } let entries = vec![ Entry { value: "item_a".into() }, Entry { value: "item_b".into() }, ]; let encoded = ExternIO::encode(entries.clone()).unwrap(); // Decode back to a JSON string (what the gateway returns as HTTP body) let json_value: serde_json::Value = encoded.decode().unwrap(); let json_str = json_value.to_string(); // json_str == "[\"item_a\",\"item_b\"]" println!("{}", json_str); ``` -------------------------------- ### Parse Per-App Function Allowlists with `AllowedFns::from_str` Source: https://context7.com/holochain/hc-http-gw/llms.txt Parses a comma-separated string of zome/function pairs into an `AllowedFns::Restricted` set. Use `"*"` for `AllowedFns::All`. Handles wildcard and restricted list formats, as well as error cases for malformed input. ```rust use holochain_http_gateway::AllowedFns; use std::str::FromStr; // Wildcard — allow all functions for this app let all = AllowedFns::from_str("*" ).unwrap(); assert!(matches!(all, AllowedFns::All)); // Restricted list — only these two zome/function pairs are permitted let restricted = AllowedFns::from_str("coordinator1/get_all_1,coordinator1/get_mine").unwrap(); if let AllowedFns::Restricted(fns) = &restricted { assert_eq!(fns.len(), 2); } // Error cases assert!(AllowedFns::from_str("/fn1").is_err()); // empty zome name assert!(AllowedFns::from_str("zome1/").is_err()); // empty function name assert!(AllowedFns::from_str("zome1").is_err()); // missing separator ``` -------------------------------- ### Authorize Zome Call Source: https://github.com/holochain/hc-http-gw/blob/main/README.md Authorizes a zome call for the specified hApp. This is a prerequisite before creating or modifying data. ```bash hc sandbox zome-call-auth fixture1 ``` -------------------------------- ### Resolve WebSocket URL to Socket Address Source: https://context7.com/holochain/hc-http-gw/llms.txt Parses a WebSocket or HTTP URL and performs DNS resolution to produce a SocketAddr. Used internally to convert environment variables into usable socket addresses. It handles basic URL parsing and DNS lookup, returning an error for malformed URLs. ```rust use holochain_http_gateway::resolve_address_from_url; #[tokio::main] async fn main() -> std::io::Result<()> { let addr = resolve_address_from_url("ws://localhost:41191").await?; println!("Resolved: {}", addr); // e.g. "127.0.0.1:41191" // Works with http:// URLs too (scheme is not enforced) let addr = resolve_address_from_url("http://localhost:8888").await?; assert_eq!(addr.port(), 8888); // Errors assert!(resolve_address_from_url("http:///no-host:8080").await.is_err()); // missing host assert!(resolve_address_from_url("http://no-port-here").await.is_err()); // missing port Ok(()) } ``` -------------------------------- ### AllowedFns::from_str Source: https://context7.com/holochain/hc-http-gw/llms.txt Parses a string representation into an `AllowedFns` enum, which can be either `AllowedFns::All` (wildcard) or `AllowedFns::Restricted` (a specific set of functions). This is used for configuring function access via environment variables. ```APIDOC ## `AllowedFns::from_str` — Parse Per-App Function Allowlists Parses a comma-separated `zome_name/fn_name` string into an `AllowedFns::Restricted` set, or the wildcard `"*"` into `AllowedFns::All`. Both forms are used directly by the binary when reading `HC_GW_ALLOWED_FNS_` environment variables. ### Example Usage ```rust use holochain_http_gateway::AllowedFns; use std::str::FromStr; // Wildcard — allow all functions for this app let all = AllowedFns::from_str("*" ).unwrap(); assert!(matches!(all, AllowedFns::All)); // Restricted list — only these two zome/function pairs are permitted let restricted = AllowedFns::from_str("coordinator1/get_all_1,coordinator1/get_mine").unwrap(); if let AllowedFns::Restricted(fns) = &restricted { assert_eq!(fns.len(), 2); } // Error cases assert!(AllowedFns::from_str("/fn1").is_err()); // empty zome name assert!(AllowedFns::from_str("zome1/").is_err()); // empty function name assert!(AllowedFns::from_str("zome1").is_err()); // missing separator ``` ``` -------------------------------- ### Health Check HTTP Gateway Source: https://github.com/holochain/hc-http-gw/blob/main/README.md Checks if the HTTP Gateway is running and accessible by sending a request to the /health endpoint. ```bash curl -i localhost:8090/health ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.