### Start Falcon Server Source: https://github.com/socketry/falcon/blob/main/examples/websockets/readme.md Starts the Falcon web server, which will host the WebSocket endpoint. This command assumes you have installed the project dependencies. ```bash bundle exec falcon serve ``` -------------------------------- ### Install Dependencies with Bundler Source: https://github.com/socketry/falcon/blob/main/examples/websockets/readme.md Installs the necessary Ruby gems for the project using the Bundler package manager. This is a prerequisite for running the Falcon server and the WebSocket example. ```bash bundle install ``` -------------------------------- ### Falcon Preload Script Example Source: https://context7.com/socketry/falcon/llms.txt A simple `preload.rb` script used by Falcon to load application code before the server starts. This is useful for optimizing startup time in production environments. ```ruby # preload.rb # frozen_string_literal: true require_relative "config/environment" ``` -------------------------------- ### Client example using async-websocket Source: https://context7.com/socketry/falcon/llms.txt A client-side example demonstrating how to connect to a WebSocket server using the async-websocket library. It sends a text message and prints the received response. ```ruby # Client example using async-websocket require "async" require "async/websocket/client" Async do endpoint = Async::HTTP::Endpoint.parse("wss://localhost:9292") Async::WebSocket::Client.connect(endpoint) do |connection| # Send a message connection.write(Protocol::WebSocket::TextMessage.generate({text: "Hello"})) connection.flush # Receive response if message = connection.read puts "Received: #{message.to_h}" end end end ``` -------------------------------- ### Install and Run Falcon with Pushback Source: https://github.com/socketry/falcon/blob/main/examples/pushback/readme.md Installs project dependencies using Bundler and starts the Falcon server with a specified number of concurrent requests allowed. This command is essential for enabling the pushback functionality. ```bash bundle install bundle exec falcon -n 1 --bind http://localhost:9292 ``` -------------------------------- ### Install Falcon via Bundler Source: https://context7.com/socketry/falcon/llms.txt Adds the Falcon gem to your project's Gemfile using the `bundle add` command. This is the recommended way to install Falcon for project-specific dependencies. ```bash bundle add falcon ``` -------------------------------- ### Kubernetes Deployment for Falcon Source: https://github.com/socketry/falcon/blob/main/context/deployment.md Example Kubernetes Deployment manifest for running Falcon. It defines replicas, container image, environment variables, ports, and readiness/liveness probes. ```yaml apiVersion: apps/v1 kind: Deployment metadata: name: falcon spec: replicas: 1 selector: matchLabels: app: falcon template: metadata: labels: app: falcon spec: containers: - name: my-app image: my-app-image:latest env: - name: NOTIFY_LOG value: "/tmp/notify.log" ports: - containerPort: 9292 readinessProbe: exec: command: ["bundle", "exec", "bake", "async:container:notify:log:ready?"] initialDelaySeconds: 5 periodSeconds: 5 failureThreshold: 12 # Assuming you are running Rails and have bound to port 3000: livenessProbe: httpGet: path: /up port: 3000 initialDelaySeconds: 10 periodSeconds: 10 failureThreshold: 3 ``` -------------------------------- ### Install Falcon Gem Globally Source: https://github.com/socketry/falcon/blob/main/context/getting-started.md This command installs the Falcon gem globally on your system. This allows you to use Falcon without needing to add it to a specific project's Gemfile. ```bash $ gem install falcon ``` -------------------------------- ### Heroku Procfile for Falcon Host Source: https://github.com/socketry/falcon/blob/main/context/deployment.md This Procfile specifies the command to run for the 'web' process on Heroku, which is to bundle and execute the Falcon host command. This assumes a standard Ruby on Rails or Rack application setup. ```bash # Procfile web: bundle exec falcon host ``` -------------------------------- ### Install Dependencies and Run Elixir App Source: https://github.com/socketry/falcon/blob/main/examples/hello-elixir/readme.md Commands to install project dependencies using Mix and then run the Elixir application. Assumes Mix is installed and configured. ```shell mix deps.get mix run --no-halt ``` -------------------------------- ### Connect to WebSocket Server with Websocat Source: https://github.com/socketry/falcon/blob/main/examples/websockets/readme.md Connects to the running Falcon WebSocket server using the `websocat` command-line tool. It demonstrates sending and receiving JSON messages. ```bash websocat wss://localhost:9292/ ``` -------------------------------- ### Start Falcon Server Source: https://github.com/socketry/falcon/blob/main/examples/tls-client-verify/readme.md This bash command starts the Falcon server. It assumes that the necessary configurations, including TLS settings, have been applied. This is the command to run on the server-side to make the service available. ```bash $ bundle exec falcon host ``` -------------------------------- ### Serve Rack Application on Custom Port Source: https://github.com/socketry/falcon/blob/main/context/getting-started.md This command starts the Falcon web server and allows you to specify a custom port for the application to run on. ```bash $ falcon serve --port 3000 ``` -------------------------------- ### systemd Service File for Falcon Virtual Source: https://github.com/socketry/falcon/blob/main/context/deployment.md Example systemd service file to manage the Falcon virtual service. It configures the service to run as a specific user, set the working directory, and restart automatically. ```ini [Unit] Description=Falcon Virtual Service After=network.target [Service] Type=notify User=http WorkingDirectory=/srv/http ExecStart=/usr/local/bin/falcon virtual /srv/http/*/falcon.rb Restart=always [Install] WantedBy=multi-user.target ``` -------------------------------- ### Configure Falcon Rack Application for Localhost with HTTP/2 (Ruby) Source: https://github.com/socketry/falcon/blob/main/context/deployment.md This Ruby configuration sets up a Falcon Rack application to bind to localhost on port 3000 using HTTP/2. It includes basic TLS setup and a supervisor for monitoring. This is useful for local development or specific virtual host setups. ```ruby #!/usr/bin/env falcon host # frozen_string_literal: true require "falcon/environment/rack" require "falcon/environment/supervisor" hostname = File.basename(__dir__) service hostname do include Falcon::Environment::Rack include Falcon::Environment::LetsEncryptTLS endpoint do Async::HTTP::Endpoint .parse('http://localhost:3000') .with(protocol: Async::HTTP::Protocol::HTTP2) end end service "supervisor" do include Falcon::Environment::Supervisor end ``` -------------------------------- ### Run Falcon Server Source: https://github.com/socketry/falcon/blob/main/examples/streaming_upload/readme.md Command to start the Falcon server for testing. It specifies the host and the application file to run. ```bash > bundle exec falcon host ./falcon.rb ``` -------------------------------- ### Preloading Gems in Falcon Source: https://github.com/socketry/falcon/blob/main/context/performance-tuning.md Demonstrates how to specify gems for preloading in Falcon by defining a `preload` group in the `gems.rb` file. This helps reduce overhead and improve instance start-up time by loading necessary gems before the Falcon process forks. ```ruby source "https://rubygems.org" group :preload do # List any gems you want to be pre-loaded into the falcon process before forking. end ``` -------------------------------- ### Heroku Procfile for Falcon Deployment Source: https://context7.com/socketry/falcon/llms.txt Defines the web process for deploying a Falcon application on Heroku. It uses `falcon host` to start the server. ```text # Procfile web: bundle exec falcon host ``` -------------------------------- ### Serve Rack Application with Falcon Source: https://github.com/socketry/falcon/blob/main/context/getting-started.md This command starts the Falcon web server to serve a Rack application. By default, it runs on https://localhost:9292 with TLS enabled. ```bash $ falcon serve ``` -------------------------------- ### Start Falcon Virtual Host Proxy Source: https://context7.com/socketry/falcon/llms.txt Commands to start the Falcon virtual host proxy, which allows hosting multiple applications. It can automatically manage TLS certificates and HTTP-to-HTTPS redirection based on hostnames. ```bash # Start virtual host proxy for all applications falcon virtual /srv/http/*/falcon.rb # Custom bind addresses falcon virtual --bind-insecure "http://[::]:80" --bind-secure "https://[::]:443" /srv/http/*/falcon.rb ``` -------------------------------- ### Start Falcon Development Server Source: https://context7.com/socketry/falcon/llms.txt Commands to start the Falcon development server. By default, it runs on localhost:9292 with HTTPS. Options allow specifying the port, binding address, and protocol (HTTP/HTTPS). ```bash # Start the development server (HTTPS on localhost:9292) falcon serve # Start on a custom port falcon serve --port 3000 # Start with HTTP instead of HTTPS falcon serve --bind http://localhost:3000 ``` -------------------------------- ### Falcon Server Process Title Example Source: https://github.com/socketry/falcon/blob/main/releases.md Illustrates the format of the Falcon server process title, which is updated periodically to show connection and request statistics. This helps in monitoring server activity. ```shell 12211 ttys002 0:00.28 /Users/samuel/.gem/ruby/3.4.1/bin/falcon serve --bind http://localhost:8000 12213 ttys002 0:04.14 http://localhost:8000 (C=2/2 R=0/49.45K L=0.353) 12214 ttys002 0:07.22 http://localhost:8000 (C=5/6 R=0/112.97K L=0.534) 12215 ttys002 0:05.41 http://localhost:8000 (C=3/3 R=0/71.7K L=0.439) 12216 ttys002 0:06.46 http://localhost:8000 (C=4/5 R=0/93.22K L=0.493) 12217 ttys002 0:02.58 http://localhost:8000 (C=1/1 R=0/24.9K L=0.251) 12218 ttys002 0:05.44 http://localhost:8000 (C=3/3 R=0/72.12K L=0.439) 12219 ttys002 0:06.47 http://localhost:8000 (C=4/4 R=0/93.13K L=0.493) 12220 ttys002 0:04.03 http://localhost:8000 (C=2/2 R=0/47.37K L=0.357) 12221 ttys002 0:06.41 http://localhost:8000 (C=4/4 R=0/92.46K L=0.494) 12222 ttys002 0:06.38 http://localhost:8000 (C=4/4 R=0/91.71K L=0.495) ``` -------------------------------- ### Implement Echo WebSocket Server using async-websocket Source: https://context7.com/socketry/falcon/llms.txt An example of an Echo WebSocket server implemented using the async-websocket library. It handles incoming WebSocket connections, echoes back received messages, and supports standard Rack requests. ```ruby # config.ru # frozen_string_literal: true require "async/websocket" require "async/websocket/adapters/rack" class WebSocketApp def handle_normal_request(env) [200, {"content-type" => "text/plain"}, ["WebSocket endpoint - connect via ws://"]] end def call(env) Async::WebSocket::Adapters::Rack.open(env) do |connection| # Echo server: receive messages and send them back while message = connection.read connection.write(message) connection.flush end end or handle_normal_request(env) end end run WebSocketApp.new ``` -------------------------------- ### Serve Rack Application with Unencrypted HTTP Source: https://github.com/socketry/falcon/blob/main/context/getting-started.md This command starts the Falcon web server and binds it to an unencrypted HTTP endpoint on a specified port. This is useful for local development when TLS is not required. ```bash $ falcon serve --bind http://localhost:3000 ``` -------------------------------- ### Preload Script for Falcon Source: https://github.com/socketry/falcon/blob/main/context/deployment.md A simple Ruby script used by Falcon to preload the application environment. It requires the application's environment configuration. ```ruby # preload.rb # frozen_string_literal: true require_relative "config/environment" ``` -------------------------------- ### Send Early Hints (103) for Resource Preloading Source: https://context7.com/socketry/falcon/llms.txt Configures a Rack application to send interim 103 Early Hints responses for resource preloading. This allows browsers to start fetching critical resources before the main response is ready. ```ruby # config.ru # frozen_string_literal: true run do |env| # Access the underlying HTTP request to send interim responses if request = env["protocol.http.request"] request.send_interim_response(103, [ ["link", "; rel=preload; as=style"], ["link", "; rel=preload; as=script"] ]) end # Simulate processing time sleep 0.5 [200, {"content-type" => "text/html"}, ["Hello"]] end ``` -------------------------------- ### Async::Container::Supervisor Configuration in Ruby Source: https://github.com/socketry/falcon/blob/main/releases.md Demonstrates how to configure and use Async::Container::Supervisor for managing services within a Falcon application. It includes examples of including supervisor modules and defining monitors for resource usage. ```ruby service "hello.localhost" do # Configure server... include Async::Container::Supervisor::Supervised end service "supervisor" do include Async::Container::Supervisor::Environment monitors do [ # Limit total memory usage to 512MiB: Async::Container::Supervisor::MemoryMonitor.new(interval: 10, limit: 1024 * 1024 * 512), ] end end ``` -------------------------------- ### Start Local Development Server with Falcon Source: https://github.com/socketry/falcon/blob/main/guides/rails-integration/readme.md Starts a local development server for a Rails application using Falcon. By default, Falcon serves over HTTPS. To use HTTP in development, specify the binding address and protocol. ```bash falcon serve ``` ```bash falcon serve -b http://localhost:3000 ``` -------------------------------- ### Install Localhost Development Certificate Source: https://github.com/socketry/falcon/blob/main/context/rails-integration.md Installs self-signed certificates for local development using the `localhost` gem. This enables running Falcon with HTTPS in development without browser security warnings. Requires `bake` command. ```bash > bundle exec bake localhost:install ``` -------------------------------- ### Kubernetes Deployment for Falcon Source: https://github.com/socketry/falcon/blob/main/guides/deployment/readme.md Example Kubernetes deployment configuration for Falcon. It defines the deployment, container image, environment variables, ports, and readiness/liveness probes for monitoring the application's health. ```yaml apiVersion: apps/v1 kind: Deployment metadata: name: falcon spec: replicas: 1 selector: matchLabels: app: falcon template: metadata: labels: app: falcon spec: containers: - name: my-app image: my-app-image:latest env: - name: NOTIFY_LOG value: "/tmp/notify.log" ports: - containerPort: 9292 readinessProbe: exec: command: ["bundle", "exec", "bake", "async:container:notify:log:ready?"] initialDelaySeconds: 5 periodSeconds: 5 failureThreshold: 12 # Assuming you are running Rails and have bound to port 3000: livenessProbe: httpGet: path: /up port: 3000 initialDelaySeconds: 10 periodSeconds: 10 failureThreshold: 3 ``` -------------------------------- ### Preload Script for Falcon Source: https://github.com/socketry/falcon/blob/main/guides/deployment/readme.md A simple preload script for Falcon, typically used to load the application's environment before starting the server. It ensures that the application's configuration is loaded. ```ruby # preload.rb # frozen_string_literal: true require_relative "config/environment" ``` -------------------------------- ### Enabling and Managing systemd Falcon Service Source: https://context7.com/socketry/falcon/llms.txt Commands to enable, start, and check the status of the Falcon systemd service. These commands are used to manage the Falcon application as a background service. ```bash # Enable and start the service sudo systemctl enable falcon-virtual sudo systemctl start falcon-virtual sudo systemctl status falcon-virtual ``` -------------------------------- ### Configure Falcon Rack Application with TLS and Supervisor (Ruby) Source: https://github.com/socketry/falcon/blob/main/context/deployment.md This Ruby configuration sets up a Falcon Rack application with automatic Let's Encrypt TLS certificate management and integrates with an Async Supervisor for monitoring and restarts. It includes caching and defines memory limits for the supervisor. ```ruby #!/usr/bin/env falcon-host # frozen_string_literal: true require "falcon/environment/rack" require "falcon/environment/lets_encrypt_tls" require "falcon/environment/supervisor" hostname = File.basename(__dir__) service hostname do include Falcon::Environment::Rack include Falcon::Environment::LetsEncryptTLS # Insert an in-memory cache in front of the application (using async-http-cache). cache true # Connect to the supervisor for monitoring. include Async::Container::Supervisor::Supervised end service "supervisor" do include Falcon::Environment::Supervisor monitors do [ MemoryMonitor.new( # Check every 10 seconds: interval: 10, # Per-supervisor (cluster) limit: total_size_limit: 1000*1024*1024, # Per-process limit: maximum_size_limit: 200*1024*1024 ) ] end end ``` -------------------------------- ### Supervisor with Memory Monitoring Configuration Source: https://context7.com/socketry/falcon/llms.txt A placeholder for configuring a supervisor process using Falcon. This setup is intended for monitoring application memory usage and automatically restarting workers if they exceed limits. ```ruby #!/usr/bin/env falcon-host # falcon.rb ``` -------------------------------- ### Implement WebSocket Echo Server in Ruby with Falcon Source: https://github.com/socketry/falcon/blob/main/context/websockets.md This Ruby code snippet demonstrates how to set up a basic WebSocket echo server within a Falcon application. It utilizes the async-websocket gem to handle incoming connections and messages, echoing back any received data. This serves as a foundational example for real-time communication. ```ruby # config.ru require "async/websocket/adapters/rack" run do |env| Async::WebSocket::Adapters::Rack.open(env, protocols: ['ws']) do |connection| # Simple echo server: while message = connection.read connection.write(message) connection.flush end end or [200, {}, ["Hello World"]] end ``` -------------------------------- ### Run Rails Development Server with Falcon Source: https://context7.com/socketry/falcon/llms.txt Commands to run a Rails application using Falcon in development mode and to install self-signed certificates for HTTPS. ```bash # Development server falcon serve -b http://localhost:3000 # Install self-signed certificates for HTTPS development bundle exec bake localhost:install ``` -------------------------------- ### Verify Elixir App with Curl Source: https://github.com/socketry/falcon/blob/main/examples/hello-elixir/readme.md Demonstrates how to use `curl` to send an HTTP GET request to the running Elixir application and inspect the response. This helps verify the application is accessible and responding correctly. ```shell curl -v http://localhost:3000 ``` -------------------------------- ### Custom Preload Script for Falcon Source: https://context7.com/socketry/falcon/llms.txt A custom Ruby script to preload application code and initialize necessary components before Falcon workers start. This includes loading the Rails environment and warming up database connections. ```ruby # preload.rb - Custom preload file # frozen_string_literal: true # Load Rails environment require_relative "config/environment" # Preload ActiveRecord connections ActiveRecord::Base.connection_pool.with_connection do |connection| # Warm up connection end # Preload any expensive initializations Rails.application.eager_load! ``` -------------------------------- ### Run Local Development Server Source: https://github.com/socketry/falcon/blob/main/context/rails-integration.md Starts a local development server for a Rails application using Falcon. By default, Falcon serves over HTTPS. To use HTTP, specify the binding address and protocol. ```bash falcon serve ``` ```bash falcon serve -b http://localhost:3000 ``` -------------------------------- ### Configure Falcon Rack Environment Source: https://github.com/socketry/falcon/blob/main/context/deployment.md Configures the Falcon web server to use the Rack environment, setting worker count, preload script, port, and endpoint protocol. It includes logic to fetch configuration from environment variables. ```ruby require "falcon/environment/rack" hostname = File.basename(__dir__) service hostname do include Falcon::Environment::Rack # By default, Falcon uses Etc.nprocessors to set the count, which is likely incorrect on shared hosts like Heroku. # Review the following for guidance about how to find the right value for your app: # https://help.heroku.com/88G3XLA6/what-is-an-acceptable-amount-of-dyno-load # https://devcenter.heroku.com/articles/deploying-rails-applications-with-the-puma-web-server#workers count ENV.fetch("WEB_CONCURRENCY", 1).to_i # If using count > 1 you may want to preload your app to reduce memory usage and increase performance: preload "preload.rb" # The default port should be 3000, but you can change it to match your Heroku configuration. port {ENV.fetch("PORT", 3000).to_i} # Heroku only supports HTTP/1.1 at the time of this writing. Review the following for possible updates in the future: # https://devcenter.heroku.com/articles/http-routing#http-versions-supported # https://github.com/heroku/roadmap/issues/34 endpoint do Async::HTTP::Endpoint .parse("http://0.0.0.0:#{port}") .with(protocol: Async::HTTP::Protocol::HTTP11) end ``` -------------------------------- ### Connect to Server with Client Certificate using OpenSSL Source: https://github.com/socketry/falcon/blob/main/examples/tls-client-verify/readme.md This OpenSSL command connects to a server running on localhost:9292 using a client certificate and private key. The `-cert` and `-key` flags specify the client's certificate and key files, respectively. This is used to test the TLS client verification setup from the client-side. ```bash $ openssl s_client -connect localhost:9292 -cert client.crt -key client.key ``` -------------------------------- ### Basic Rack Application Configuration Source: https://github.com/socketry/falcon/blob/main/context/getting-started.md This Ruby code snippet defines a minimal Rack application that responds with 'Hello, World!'. It's typically saved in a 'config.ru' file and can be served by Falcon. ```ruby # config.ru run do |env| [200, {'Content-Type' => 'text/plain'}, ['Hello, World!']] end ``` -------------------------------- ### Configure Falcon Development Server Options Source: https://context7.com/socketry/falcon/llms.txt Demonstrates various command-line options for the `falcon serve` command to customize the development server. Options include port, binding, caching, preloading, worker count, threading, timeouts, and verbosity. ```bash # Default HTTPS server on localhost:9292 falcon serve # Specify port falcon serve --port 3000 # Bind to specific address with HTTP falcon serve --bind http://localhost:3000 # Enable response caching falcon serve --cache # Preload application code before forking falcon serve --preload preload.rb # Set number of worker processes falcon serve --count 4 # Use threaded container instead of forked falcon serve --threaded # Use hybrid container (multiple forks with threads) falcon serve --hybrid --forks 2 --threads 4 # Set connection timeout falcon serve --timeout 30 # Verbose output falcon serve --verbose ``` -------------------------------- ### Run Falcon via Rackup Source: https://github.com/socketry/falcon/blob/main/context/getting-started.md This command invokes Falcon as the server for the `rackup` command. While functional, it's not recommended for performance-critical applications as it runs a single-threaded instance. ```bash $ rackup --server falcon ``` -------------------------------- ### Run ApacheBench for Concurrent Uploads Source: https://github.com/socketry/falcon/blob/main/examples/streaming_upload/readme.md Command to execute ApacheBench (ab) for performance testing. It sets the number of requests, concurrency level, specifies the test file for POST data, and includes a 'Expect: 100-continue' header for upload testing. ```bash > time ab -n 1000 -c 32 -p ./testfile -H "Expect: 100-continue" http://localhost:9292/ ``` -------------------------------- ### Add Falcon::Rails Gem Source: https://github.com/socketry/falcon/blob/main/context/rails-integration.md Installs the `falcon-rails` gem, which simplifies the integration of Falcon as the web server for Rails applications. This gem offers convenient configurations for running Rails with Falcon. ```bash > bundle add falcon-rails ``` -------------------------------- ### Stream Request Body Processing with Falcon Source: https://context7.com/socketry/falcon/llms.txt An example of processing large request bodies efficiently by streaming them using Falcon. The `EchoBody` class reads the request input in chunks and yields them. ```ruby # config.ru # frozen_string_literal: true class EchoBody def initialize(input) @input = input end def each(&output) while chunk = @input.read(1024) output.call(chunk) end end end run lambda { |env| [200, {"content-type" => "application/octet-stream"}, EchoBody.new(env["rack.input"])] } ``` -------------------------------- ### Create Test File for ApacheBench Source: https://github.com/socketry/falcon/blob/main/examples/streaming_upload/readme.md Command to create a large test file using dd for use with ApacheBench. This file simulates the data to be uploaded. ```bash > dd if=/dev/zero of=./testfile bs=82078050 count=1 ``` -------------------------------- ### Run Production Server Source: https://github.com/socketry/falcon/blob/main/context/rails-integration.md Executes the Falcon production server using the `falcon.rb` configuration file. Ensures the configuration file is executable before running. ```bash > bundle exec falcon.rb ``` -------------------------------- ### Run Falcon Production Server Source: https://context7.com/socketry/falcon/llms.txt Commands to execute the Falcon production server. It can be run using `bundle exec falcon host` or by making the `falcon.rb` file executable and running it directly. ```bash # Run the production server bundle exec falcon host # Or make falcon.rb executable and run directly chmod +x falcon.rb ./falcon.rb ``` -------------------------------- ### Configure Falcon Host Service Source: https://github.com/socketry/falcon/blob/main/releases.md Demonstrates the new service definition format for `falcon host` using `async-service`. It replaces the older direct inclusion of Rack and SelfSignedTLS with a block-based service definition. ```ruby service "hello.localhost" do include Falcon::Environment::Rack include Falcon::Environment::SelfSignedTLS end ``` -------------------------------- ### Running Falcon with Preload Option Source: https://context7.com/socketry/falcon/llms.txt Command to serve a Falcon application with a custom preload script. The `--preload` flag tells Falcon to execute the specified script before forking. ```bash # Use with falcon serve falcon serve --preload preload.rb ``` -------------------------------- ### Configure Falcon Service with Rack and LetsEncryptTLS Source: https://context7.com/socketry/falcon/llms.txt Configures a Falcon service for a given hostname, including Rack environment for application serving and automatic TLS certificate management using LetsEncryptTLS. ```ruby # frozen_string_literal: true require "falcon/environment/rack" require "falcon/environment/lets_encrypt_tls" service "myapp.example.com" do include Falcon::Environment::Rack include Falcon::Environment::LetsEncryptTLS # Application will be accessible via HTTPS with automatic certificate end ``` -------------------------------- ### Configure Falcon Host for Rack Application with TLS and Supervisor (Ruby) Source: https://github.com/socketry/falcon/blob/main/guides/deployment/readme.md This Ruby code configures the Falcon host to serve a Rack application. It includes automatic Let's Encrypt TLS certificate management and integrates with a supervisor for process monitoring and restarts. The configuration uses the async-service gem for defining services and environments. ```ruby #!/usr/bin/env falcon-host # frozen_string_literal: true require "falcon/environment/rack" require "falcon/environment/lets_encrypt_tls" require "falcon/environment/supervisor" hostname = File.basename(__dir__) service hostname do include Falcon::Environment::Rack include Falcon::Environment::LetsEncryptTLS # Insert an in-memory cache in front of the application (using async-http-cache). cache true # Connect to the supervisor for monitoring. include Async::Container::Supervisor::Supervised end service "supervisor" do include Falcon::Environment::Supervisor monitors do [ MemoryMonitor.new( # Check every 10 seconds: interval: 10, # Per-supervisor (cluster) limit: total_size_limit: 1000*1024*1024, # Per-process limit: maximum_size_limit: 200*1024*1024 ) ] end end ``` -------------------------------- ### Add Falcon Gem to Project Source: https://github.com/socketry/falcon/blob/main/context/getting-started.md This command adds the Falcon gem to your project's Gemfile. It's a prerequisite for using Falcon to serve Ruby web applications. ```bash $ bundle add falcon ``` -------------------------------- ### Kubernetes Deployment YAML for Falcon Application Source: https://context7.com/socketry/falcon/llms.txt Defines a Kubernetes Deployment for a Falcon application. It includes settings for replicas, container ports, environment variables, readiness and liveness probes, and resource requests/limits. ```yaml # deployment.yaml apiVersion: apps/v1 kind: Deployment metadata: name: falcon-app spec: replicas: 3 selector: matchLabels: app: falcon-app template: metadata: labels: app: falcon-app spec: containers: - name: app image: myapp:latest env: - name: PORT value: "3000" - name: WEB_CONCURRENCY value: "2" - name: NOTIFY_LOG value: "/tmp/notify.log" ports: - containerPort: 3000 readinessProbe: exec: command: ["bundle", "exec", "bake", "async:container:notify:log:ready?"] initialDelaySeconds: 5 periodSeconds: 5 failureThreshold: 12 livenessProbe: httpGet: path: /up port: 3000 initialDelaySeconds: 10 periodSeconds: 10 failureThreshold: 3 resources: requests: memory: "256Mi" cpu: "100m" limits: memory: "512Mi" cpu: "500m" ``` -------------------------------- ### Basic Falcon Production Configuration Source: https://context7.com/socketry/falcon/llms.txt A `falcon.rb` file for production deployments, configuring worker count, preloading, and port. It uses environment variables for flexibility and specifies an HTTP/1.1 endpoint. ```ruby #!/usr/bin/env falcon-host # falcon.rb # frozen_string_literal: true require "falcon/environment/rack" hostname = File.basename(__dir__) service hostname do include Falcon::Environment::Rack # Number of worker processes count ENV.fetch("WEB_CONCURRENCY", 4).to_i # Preload application code preload "preload.rb" # Port configuration port { ENV.fetch("PORT", 3000).to_i } # HTTP/1.1 endpoint (common for load balancer setups) endpoint do Async::HTTP::Endpoint .parse("http://0.0.0.0:#{port}") .with(protocol: Async::HTTP::Protocol::HTTP11) end end ``` -------------------------------- ### Verify HTTP/2 with nghttp (Bash) Source: https://context7.com/socketry/falcon/llms.txt This bash command uses the `nghttp` utility to verify if HTTP/2 is working for a given URL. It sends a verbose request to the specified HTTPS endpoint. ```bash # Verify HTTP/2 is working nghttp -v https://myapp.example.com/ ``` -------------------------------- ### ApacheBench Results Summary Source: https://github.com/socketry/falcon/blob/main/examples/streaming_upload/readme.md A summary of the ApacheBench test results, showing metrics like requests per second, time per request, and failed requests. It indicates that 94 requests failed due to non-2xx responses. ```text This is ApacheBench, Version 2.3 <$Revision: 1903618 $> Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/ Licensed to The Apache Software Foundation, http://www.apache.org/ Benchmarking localhost (be patient) Completed 100 requests Completed 200 requests Completed 300 requests Completed 400 requests Completed 500 requests Completed 600 requests Completed 700 requests Completed 800 requests Completed 900 requests Completed 1000 requests Finished 1000 requests Server Software: Server Hostname: localhost Server Port: 9292 Document Path: / Document Length: 163 bytes Concurrency Level: 32 Time taken for tests: 23.320 seconds Complete requests: 1000 Failed requests: 94 (Connect: 0, Receive: 0, Length: 94, Exceptions: 0) Non-2xx responses: 25 Total transferred: 180172 bytes Total body sent: 83232690408 HTML transferred: 162798 bytes Requests per second: 42.88 [#/sec] (mean) Time per request: 746.253 [ms] (mean) Time per request: 23.320 [ms] (mean, across all concurrent requests) Transfer rate: 7.54 [Kbytes/sec] received 3485442.37 kb/s sent 3485449.92 kb/s total Connection Times (ms) min mean[+/-sd] median max Connect: 0 43 8.1 44 61 Processing: 185 690 93.6 679 1064 Waiting: 0 43 6.4 44 59 Total: 185 733 93.6 723 1081 Percentage of the requests served within a certain time (ms) 50% 723 66% 759 75% 787 80% 806 90% 853 95% 907 98% 963 99% 989 100% 1081 (longest request) ________________________________________________________ Executed in 23.36 secs fish external usr time 0.07 secs 242.00 micros 0.07 secs sys time 20.28 secs 104.00 micros 20.28 secs ``` -------------------------------- ### Interim Responses with Expect Header Source: https://github.com/socketry/falcon/blob/main/guides/interim-responses/readme.md Demonstrates how to send an interim response (103) with a Link header for preloading resources, and how to handle the 'expect' header to signal readiness for the request body. ```APIDOC ## POST /resource ### Description This endpoint demonstrates how to send an interim response (103) with a Link header for preloading resources. It also shows how to handle the `expect` header to signal that the server is ready to receive the request body. ### Method POST ### Endpoint /resource ### Parameters #### Query Parameters - **expect** (string) - Optional - The value '100-continue' to trigger the interim response mechanism. #### Request Body - **data** (object) - Required - The main payload of the request. - **message** (string) - A message string. ### Request Example ```json { "message": "This is the request body." } ``` ### Response #### Success Response (200) - **status** (string) - Indicates the success status. - **data** (object) - The processed data. - **received_message** (string) - The message received from the client. #### Interim Response (103) - **Headers** - **Link** (string) - Contains preload directives, e.g., `; rel=preload; as=style`. #### Response Example (200) ```json { "status": "success", "data": { "received_message": "This is the request body." } } ``` ### Code Example (config.ru) ```ruby # config.ru run do |env| request = env["protocol.http.request"] if request && env["HTTP_EXPECT"] == "100-continue" request.send_interim_response(103, [["link", "; rel=preload; as=style"]]) end # Process the actual request body after the interim response if needed # For simplicity, this example doesn't fully process the body after 103 [200, {"Content-Type" => "application/json"}, [{"status": "success", "data": {"received_message": "Request processed"}}.to_json]] end ``` ``` -------------------------------- ### Production Rails Configuration with Falcon Source: https://context7.com/socketry/falcon/llms.txt A production configuration file (`falcon.rb`) for a Rails application using Falcon. It sets up the service hostname, includes Rack environment, specifies preloading, port, and endpoint. ```ruby #!/usr/bin/env -S falcon-host # falcon.rb - Production configuration for Rails # frozen_string_literal: true require "falcon/environment/rack" hostname = File.basename(__dir__) service hostname do include Falcon::Environment::Rack preload "preload.rb" port { ENV.fetch("PORT", 3000).to_i } endpoint do Async::HTTP::Endpoint .parse("http://0.0.0.0:#{port}") .with(protocol: Async::HTTP::Protocol::HTTP11) end end ``` -------------------------------- ### Production Falcon with Let's Encrypt TLS Source: https://context7.com/socketry/falcon/llms.txt A `falcon.rb` configuration for production that includes automatic Let's Encrypt TLS certificate management and supervisor for monitoring. It enables response caching and connects to a supervisor for process management. ```ruby #!/usr/bin/env falcon-host # falcon.rb # frozen_string_literal: true require "falcon/environment/rack" require "falcon/environment/lets_encrypt_tls" require "falcon/environment/supervisor" hostname = File.basename(__dir__) service hostname do include Falcon::Environment::Rack include Falcon::Environment::LetsEncryptTLS # Enable response caching cache true # Connect to supervisor for monitoring include Async::Container::Supervisor::Supervised end service "supervisor" do include Falcon::Environment::Supervisor monitors do [ MemoryMonitor.new( interval: 10, total_size_limit: 1000*1024*1024, maximum_size_limit: 200*1024*1024 ) ] end end ``` -------------------------------- ### Configure Rails Gemfile for Falcon Integration Source: https://context7.com/socketry/falcon/llms.txt Adds the Falcon gem to a Rails application's Gemfile, enabling its use as a web server. Optionally includes `falcon-rails` for enhanced integration. ```ruby # Gemfile gem "falcon" # Optionally for enhanced Rails integration: gem "falcon-rails" ``` -------------------------------- ### Test Falcon Pushback with ApacheBench (ab) Source: https://github.com/socketry/falcon/blob/main/examples/pushback/readme.md Uses ApacheBench (ab) to send a specified number of concurrent requests to the running Falcon server. This helps in testing the pushback functionality by simulating high traffic and observing the 429 responses. ```bash ab -c 17 -n 17 localhost:9292/1 ``` -------------------------------- ### systemd Service Configuration for Falcon Source: https://context7.com/socketry/falcon/llms.txt Configures a systemd service unit file for running a Falcon application. It specifies the service description, user, working directory, execution command, and restart policy. ```ini # /etc/systemd/system/falcon-virtual.service [Unit] Description=Falcon Virtual Service After=network.target [Service] Type=notify User=http WorkingDirectory=/srv/http ExecStart=/usr/local/bin/falcon virtual /srv/http/*/falcon.rb Restart=always RestartSec=5 [Install] WantedBy=multi-user.target ```