diff --git a/.github/workflows/code_quality.yaml b/.github/workflows/code_quality.yaml
index d841d80..7ecf82f 100644
--- a/.github/workflows/code_quality.yaml
+++ b/.github/workflows/code_quality.yaml
@@ -1,53 +1,73 @@
name: Code Quality
-on: [push]
+on:
+ push:
jobs:
- coverage:
- name: Coverage
+ format-check:
+ name: Format Check
runs-on: ubuntu-latest
- env:
- COVERAGE: 90
steps:
- - name: Checkout source code
- uses: actions/checkout@v4
+ - uses: actions/checkout@v4
- name: Set up Python 3.12
- uses: actions/setup-python@v4
+ uses: actions/setup-python@v5
with:
python-version-file: pyproject.toml
- - name: Install Poetry
- uses: snok/install-poetry@v1.3.4
- with:
- version: 1.8.2
- virtualenvs-create: true
- virtualenvs-in-project: true
-
- - name: Load cached venv
- id: cached-poetry-dependencies
- uses: actions/cache@v3
- with:
- path: .venv
- key: venv-${{ runner.os }}-${{ steps.setup-python.outputs.python-version }}-1.7.1-${{ hashFiles('**/poetry.lock') }}
+ - name: Install Hatch
+ uses: pypa/hatch@257e27e51a6a5616ed08a39a408a21c35c9931bc
- - name: Install dependencies
- if: steps.cached-poetry-dependencies.outputs.cache-hit != 'true'
- run: poetry install --no-interaction --no-root
+ - name: Run checks
+ run: |
+ hatch fmt --check
+ type-check:
+ name: Type Check
+ needs: [format-check]
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
- - name: Install library
- run: poetry install --no-interaction
+ - name: Set up Python 3.12
+ uses: actions/setup-python@v5
+ with:
+ python-version-file: pyproject.toml
- # - name: Check coverage
- # run: poetry run pytest --cov=smyth --cov-fail-under=${{ env.COVERAGE }} src
+ - name: Install Hatch
+ uses: pypa/hatch@257e27e51a6a5616ed08a39a408a21c35c9931bc
- - name: mypy
- run: poetry run mypy src
- Ruff:
- name: Ruff
+ - name: Run type checks
+ run: |
+ hatch run types:check
+ unit-test:
+ name: Unit Test
+ needs: [format-check, type-check]
+ strategy:
+ fail-fast: false
+ matrix:
+ python-version: ["3.10", "3.11", "3.12"]
runs-on: ubuntu-latest
steps:
- - name: Ruff Check
- uses: jpetrucciani/ruff-check@main
+ - uses: actions/checkout@v4
+
+ - name: Set up Python ${{ matrix.python-version }}
+ uses: actions/setup-python@v5
with:
- path: "."
+ python-version: ${{ matrix.python-version }}
+
+ - name: Install Hatch
+ uses: pypa/hatch@257e27e51a6a5616ed08a39a408a21c35c9931bc
+
+ - name: Run tests
+ if: ${{ matrix.python-version != '3.12' }}
+ run: |
+ hatch test -i python=${{ matrix.python-version }}
+
+ - name: Run tests with coverage
+ if: ${{ matrix.python-version == '3.12' }}
+ run: |
+ hatch test --cover -i python=${{ matrix.python-version }}
+
+concurrency:
+ group: ${{ github.workflow }}-${{ github.ref }}
+ cancel-in-progress: ${{ !contains(github.ref, 'release/')}}
diff --git a/.github/workflows/deploy_docs.yaml b/.github/workflows/deploy_docs.yaml
new file mode 100644
index 0000000..14dd6da
--- /dev/null
+++ b/.github/workflows/deploy_docs.yaml
@@ -0,0 +1,32 @@
+name: Deploy documentation
+
+on:
+ push:
+ branches:
+ - main
+
+jobs:
+ docs-publish:
+ name: publish documentation
+ runs-on: ubuntu-latest
+ permissions:
+ contents: write
+ steps:
+ - name: Checkout source code
+ uses: actions/checkout@v4
+
+ - name: Configure Git Credentials
+ run: |
+ git config user.name github-actions[bot]
+ git config user.email 41898282+github-actions[bot]@users.noreply.github.com
+
+ - name: Set up Python 3.12
+ uses: actions/setup-python@v5
+ with:
+ python-version-file: pyproject.toml
+
+ - name: Install Hatch
+ uses: pypa/hatch@257e27e51a6a5616ed08a39a408a21c35c9931bc
+
+ - name: Build documentation
+ run: hatch run docs:deploy
diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml
index 227bfc7..403862b 100644
--- a/.github/workflows/publish.yml
+++ b/.github/workflows/publish.yml
@@ -1,15 +1,10 @@
-name: release
+name: Publish
on:
release:
types:
- published
-env:
- STABLE_PYTHON_VERSION: '3.12'
- PYTHONUNBUFFERED: "1"
- FORCE_COLOR: "1"
-
jobs:
pypi-publish:
name: upload release to PyPI
@@ -23,19 +18,15 @@ jobs:
uses: actions/checkout@v4
- name: Set up Python 3.12
- uses: actions/setup-python@v4
+ uses: actions/setup-python@v5
with:
python-version-file: pyproject.toml
- - name: Install Poetry
- uses: snok/install-poetry@v1.3.4
- with:
- version: 1.8.2
- virtualenvs-create: true
- virtualenvs-in-project: true
+ - name: Install Hatch
+ uses: pypa/hatch@257e27e51a6a5616ed08a39a408a21c35c9931bc
- name: Build package
- run: poetry build
+ run: hatch build
- name: Publish package distributions to PyPI
uses: pypa/gh-action-pypi-publish@release/v1
diff --git a/.gitignore b/.gitignore
index c20967a..d50861f 100644
--- a/.gitignore
+++ b/.gitignore
@@ -27,3 +27,5 @@ __pycache__
package
*.zip
+.mypy_cache
+.coverage
diff --git a/README.md b/README.md
index 195345a..78cd555 100644
--- a/README.md
+++ b/README.md
@@ -1,86 +1,30 @@
# Smyth
-A versatile tool that enhances your AWS Lambda development experience.
-
-## Rationale
-
-Despite extensive testing, nothing matched the efficiency we experienced when developing ASGI (e.g., FastAPI) applications. Below is an overview of the alternatives we evaluated:
-
-- **Serverless (with the serverless-offline plugin)**: This seemed promising, deploying a Node.js server to invoke the lambda in a subprocess, effectively simulating the AWS Lambda runtime through an AWS API Gateway V2 proxy. However, its maintenance is lacking; for instance, a pending pull request to add Python 3.12 as a supported runtime has been unresolved for nearly three months. Additionally, the development experience is hindered by the absence of Python Debugger support.
-
-- **Localstack**: While Localstack offers useful features, its lambda functionality is less satisfactory. Testing code requires building and "uploading" the lambda to Localstack for invocation, a process that takes about a minute—far too slow for efficient local development.
-
-- **AWS SAM**: Although newer and of higher quality than Serverless, AWS SAM offers fewer plugins and only supports pip for dependency management. While faster than Localstack, it still necessitates building the lambda for invocation.
-
-- **Running the code locally**: We also explored using pytest to directly invoke lambda handlers. This approach is viable, but our specific needs require exposing lambdas over HTTP to interact with a remote (or local) instance of Saleor.
-
-- **CDK**: a tool or framework that allows one to define the Lambda stack in Python, it can spin up local Lambda invocations quickly and with many different events. The lacking feature is the HTTP exposure of the Lambda, which is critical when working with Saleor Apps.
-
-- **Flask**: Flask could be used to invoke a handler from an endpoint, we've tried that. After a while of trying to make it work from a single entrypoint (i.e. one Docker container) we ended up with... well this, just that we are using a modern ASGI framework with Uvicorn as the HTTP server.
+Smyth is a versatile tool designed to enhance your AWS Lambda development experience. It is a pure Python tool that allows for easy customization and state persistence, making your Lambda development more efficient and developer-friendly.
## Features
-- **Pure Python**: The tool is entirely written in Python, offering the flexibility to tailor it to your specific requirements.
-- **Customizability**: You have the ability to modify both the `event` and `context` data structures to suit your needs.
-- **State Persistence**: Simulating both cold and warm starts, Lambda Processes retain their state across invocations, mimicking the behavior of actual AWS Lambdas. The state is reset only when code changes trigger Uvicorn to reload.
-- **Efficiency**: The tool is streamlined and efficient, relying solely on Python to execute the code.
-- **Inspired by Serverless Framework**: Its design takes cues from the Serverless framework, known for its effectiveness in managing serverless applications.
-- **Developer-Friendly**: Tailored for Python web developers, it integrates seamlessly with common development tools and practices, such as PDB, iPDB, VSCode debugging, and .env file support, ensuring a familiar and productive environment.
-
-## How Smyth Works
-
-Understanding the components involved in the Smyth environment is crucial for effective development. Here's a breakdown of the key terms:
-
-- **Uvicorn**: This is an ASGI server responsible for translating incoming HTTP requests into Python callable formats that ASGI applications can understand. It serves as the interface between the web and your application, enabling asynchronous web server capabilities for Python.
-
-- **Starlette**: A lightweight ASGI framework designed to catch and handle incoming requests. In the context of the Smyth, Starlette facilitates communication with Lambda Processes, effectively acting as a bridge that routes requests to the appropriate handlers.
-
-- **Lambda Process**: This refers to a dedicated Python process that runs a specific Lambda Handler. The primary purpose of maintaining separate processes for each Lambda Handler is to simulate the "warm" state of AWS Lambda functions, allowing them to retain their state between invocations. This setup mirrors the behavior of AWS Lambda in a local development environment.
-
-- **Lambda Handler**: The core component of your Lambda function, written as part of your project. This is the code you craft to respond to Lambda invocations, typically defined as a Python function that accepts an `event` dictionary and a `context` object. The `event` contains information about the invocation, such as the triggering event or data passed to the function, while the `context` provides runtime information about the invocation, the function, and the execution environment.
-
-Smyth operates similarly to Serverless (offline) but is implemented in pure Python with minimal dependencies. It utilizes a Starlette endpoint to provide a catch-all route. Uvicorn, in reload mode, runs Starlette, which automatically restarts the server and refreshes all Lambda processes. At startup, Starlette reads a TOML configuration file, initializing a process for each defined lambda handler. These processes import the handlers and start listening on a `multiprocessing.Queue`. When a request is received, Starlette's endpoint converts it into a Lambda event and places it in the queue. The subprocess then picks it up, invokes the handler, and returns the result to the main process via the queue, which then converts it back into an HTTP response.
-
-```mermaid
-sequenceDiagram
- actor User
- participant UVIC as Uvicorn
- participant STAR as Starlette
- participant PROC as Lambda Process
- participant HAND as Lambda Handler
-
- UVIC->>+STAR: Start
- STAR->>+PROC: Start
-
- User->>+UVIC: HTTP Request
- UVIC->>+STAR: ASGI Request
-
- STAR->>STAR: Lookup handlers by path
- STAR->>+PROC: Send event and context
- PROC->>+HAND: Invoke handler
- HAND->>-PROC: Result
- PROC->>-STAR: Result
-
- STAR->>-UVIC: ASGI Response
- UVIC->>-User: HTTP Response
-
- PROC->>-STAR: Terminate
- STAR->>-UVIC: End
-```
+- **Pure Python**: Entirely written in Python, allowing flexibility to tailor it to your specific requirements.
+- **Customizability**: Modify both the `event` and `context` data structures as needed.
+- **State Persistence**: Simulates both cold and warm starts, retaining state across invocations, mimicking actual AWS Lambda behavior.
+- **Efficiency**: Streamlined and efficient, relying solely on Python for code execution.
+- **Inspired by Serverless Framework**: Designed with insights from the Serverless framework, effectively managing serverless applications.
+- **Developer-Friendly**: Integrates seamlessly with common development tools and practices, such as PDB, iPDB, VSCode debugging, and .env file support.
## Installation
-It's recommended to install this tool in your Lambda project virtual environment with pip, due to its rapid development phase and absence from PyPi. Ensure your `GH_TOKEN` is configured if necessary:
+Install Smyth as a development dependency using Poetry or pip:
-```sh
-pip install git+https://github.com/mirumee/smyth@main
+### Poetry
+```bash
+poetry add --group dev smyth
```
-Or git submodule it into your project and install with `poetry -G dev -e ../libs/smyth`.
-
-## Configuration
+### pip
+```bash
+pip install smyth
+```
-### TOML
Define the following settings in your Lambda project's `pyproject.toml` file:
```toml
@@ -89,85 +33,15 @@ host = "0.0.0.0"
port = 8080
[tool.smyth.handlers.saleor_handler]
-handler_path = "marina_adyen.handlers.saleor.handler.saleor_http_handler"
+handler_path = "my_project.handlers.saleor.handler.saleor_http_handler"
url_path = "/saleor/{path:path}"
```
-### CLI
-
-TOML configuration can be overloaded with `--host` and `--port`. You can also use the `--only` flag to specifically pick handlers defined in the TOML. This is useful if you'd like to run your separate handlers in separate Docker containers (to for example limit their CPU and MEM).
-
-```
-python -m smyth run --help
-Usage: python -m smyth run [OPTIONS]
-
-Options:
- -h, --host TEXT Bind socket to this host.
- -p, --port INTEGER Bind socket to this port.
- --only TEXT Run only the handler of this name. [list]
- --log-level TEXT Log level.
- --help Show this message and exit.
-```
-
-Run the server with:
-
-```
-python -m smyth run
-```
-
-### `tool.smyth` Section
-
-| Key | Default | Description |
-|-----------|-----------|----------------------------------------------------------------------------------------------------------------|
-| host | `"0.0.0.0"` | `str` The host address for the Uvicorn server to bind to. |
-| port | `8080` | `int` The port for the Uvicorn server to bind to. If set to 0, an available port will be chosen automatically. |
-| log_level | `"INFO"` | `str` The log level for the main ASGI server process. |
-
-### `tool.smyth.handlers.{handler_name}` Section
-
-| Key | Default | Description |
-|-----------------------------|----------------------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
-| **handler_path** | (Required) | `str` The Python path to the Lambda handler to be invoked. |
-| **url_path** | (Required) | `str` The Starlette-like URL path for routing requests to the Lambda handler. |
-| timeout | `None` | `float \| None` The maximum duration (in seconds) before the Lambda times out. |
-| event_data_generator_path | `"smyth.event.generate_event_data"` | `str` Python path to a custom Lambda event data generator. |
-| context_data_generator_path | `"smyth.context.generate_context_data"` | `str` Python path to a custom Lambda context data generator. |
-| fake_coldstart_time | `false` | `bool` If set to true first start will mock the warmup time (0.5 to 1.0 second) - this does nothing but keeps one's brain from forgetting how this lambda will behave in production. |
-| log_level | `"INFO"` | `str` The log level for the LambdaProcesses. |
-| concurrency | `1` | `int` Number of processes the dispatcher is allowed to spawn |
-| dispatch_strategy_path | `"smyth.dispatcher.strategy.RoundRobinDispatchStrategy"` | `str` Python path to a DispatchStrategy class |
-
-### Dispatch Strategies
-
-Smyth offers two dispatch strategies to manage how requests are handled by Lambda Processes:
-
-- **Round Robin (`smyth.dispatcher.strategy.RoundRobinDispatchStrategy`)**: This strategy, not typical for AWS Lambda's behavior, is beneficial during development. It rotates among Lambda Processes for each request, given that concurrency is set higher than `1`. This approach encourages developers to avoid relying on global state across requests, promoting best practices in serverless application design.
-
-- **First Warm (`smyth.dispatcher.strategy.FirstWarmDispatchStrategy`)**: This strategy prioritizes the use of the first available Lambda Process in a "warm" state to handle incoming requests. If no warm instances are available, it initiates a "cold start". This behavior more closely mimics the operational dynamics of AWS Lambda, where reusing warm instances can lead to faster response times.
-
-It's important to note that Smyth is intended for local development and not for production use or load testing. The dispatcher and Lambda Process instances are not designed to handle high volumes of concurrent requests and will likely falter under heavy load. This limitation is deliberate, reflecting the tool's focus on local development scenarios where high concurrency is uncommon.
-
-## Customizing Event and Lambda Context Data
-
-Customization of Lambda event and context data allows developers to tailor the runtime environment to their specific needs, enhancing the local development experience. For event data customization:
-
-```python
-from smyth.event import generate_event_data
-
-async def generate_custom_event_data(request: Request):
- original_event = await generate_event_data(request)
- original_event["my_custom_data"] = "data"
- return original_event
+Run Smyth with:
+```bash
+python -m smyth
```
-This example demonstrates how to modify the default event payload generation process to include custom data. Developers can leverage the [AWS Serverless Application Model CLI (SAM)](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/install-sam-cli.html) to generate accurate [example payloads](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/sam-cli-command-reference-sam-local-generate-event.html) for different AWS services, aiding in the creation of realistic local testing scenarios.
-
-For context data customization, the configuration allows specifying a coroutine that takes additional arguments such as `process_def: ProcessDefinition` and `process: LambdaProcess`. The output from this coroutine is used to create a customized `smyth.dispatcher.runner.FakeLambdaContext`, which can include information about the Smyth runtime environment. This capability is crucial for simulating the full spectrum of AWS Lambda execution contexts, facilitating a more comprehensive and realistic development experience.
-
-## Status endpoint
-
-There is a `GET /__/status` endpoint available on the Starlette server, it will present runtime data about the Lambda processes and used configuration.
-
## Working with Docker
Assuming you have this already installed by Poetry you can use the `Dockerfile.example` and `docker-compose.example.yml` files from this repository to get started.
@@ -199,7 +73,7 @@ The combination of Uvicorn reload process and HTTP server process with what is b
- [ ] Write tests
- [ ] Properly handle Uvicorn exit, kill the LambdaProcesses gracefully
-- [ ] Publish on PyPi
+- [x] Publish on PyPi
## Name
diff --git a/docs/assets/mirumee.png b/docs/assets/mirumee.png
new file mode 100644
index 0000000..d3375f8
Binary files /dev/null and b/docs/assets/mirumee.png differ
diff --git a/docs/index.md b/docs/index.md
new file mode 100644
index 0000000..9901e83
--- /dev/null
+++ b/docs/index.md
@@ -0,0 +1,112 @@
+# Smyth
+
+A versatile tool that enhances your AWS Lambda development experience.
+
+## Installation
+
+It's recommended to install Smyth into your project as a development dependency to use the same Python interpreter as your project:
+
+=== "Poetry"
+ ```bash
+ poetry add --group dev smyth
+ ```
+
+=== "pip"
+ ```bash
+ pip install smyth
+ ```
+
+Define the following settings in your Lambda project's `pyproject.toml` file:
+
+```toml
+[tool.smyth]
+host = "0.0.0.0"
+port = 8080
+
+[tool.smyth.handlers.saleor_handler]
+handler_path = "my_project.handlers.saleor.handler.saleor_http_handler"
+url_path = "/saleor/{path:path}"
+```
+
+!!! tip "See [configuration](user_guide/all_settings.md) for more settings and features."
+
+Run Smyth with:
+
+```bash
+python -m smyth
+```
+
+!!! note "Also see"
+ Make sure to check out the [links below](#others-from-mirumee) for more serverless-oriented tools.
+
+## Features
+
+- **Pure Python**: The tool is entirely written in Python, offering flexibility to tailor it to your specific requirements.
+- **Customizability**: Modify both the `event` and `context` data structures to suit your needs.
+- **State Persistence**: Simulates both cold and warm starts. Lambda processes retain their state across invocations, mimicking the behavior of actual AWS Lambdas. The state is reset only when code changes trigger Uvicorn to reload.
+- **Efficiency**: Streamlined and efficient, relying solely on Python to execute the code.
+- **Inspired by Serverless Framework**: Takes cues from the Serverless framework, known for its effectiveness in managing serverless applications.
+- **Developer-Friendly**: Tailored for Python web developers, it integrates seamlessly with common development tools and practices such as PDB, iPDB, VSCode debugging, and .env file support, ensuring a familiar and productive environment.
+
+## Rationale
+
+Despite extensive testing, nothing matched the efficiency we experienced when developing ASGI (e.g., FastAPI) applications. Here is an overview of the alternatives we evaluated:
+
+- **Serverless (with the serverless-offline plugin)**: This seemed promising, deploying a Node.js server to invoke the lambda in a subprocess, effectively simulating the AWS Lambda runtime through an AWS API Gateway V2 proxy. However, its maintenance is lacking; for instance, a pending pull request to add Python 3.12 as a supported runtime has been unresolved for nearly three months. Additionally, the development experience is hindered by the absence of Python Debugger support.
+
+- **Localstack**: While Localstack offers useful features, its lambda functionality is less satisfactory. Testing code requires building and "uploading" the lambda to Localstack for invocation, a process that takes about a minute—far too slow for efficient local development.
+
+- **AWS SAM**: Although newer and of higher quality than Serverless, AWS SAM offers fewer plugins and only supports pip for dependency management. While faster than Localstack, it still necessitates building the lambda for invocation.
+
+- **Running the code locally**: We also explored using pytest to directly invoke lambda handlers. This approach is viable, but our specific needs require exposing lambdas over HTTP to interact with a remote (or local) instance of Saleor.
+
+- **CDK**: A tool or framework that allows defining the Lambda stack in Python. It can spin up local Lambda invocations quickly and with many different events. However, it lacks the feature of HTTP exposure of the Lambda, which is critical when working with Saleor Apps.
+
+- **Flask**: Flask could be used to invoke a handler from an endpoint. After a while of trying to make it work from a single entry point (i.e., one Docker container), we ended up with... well, this, but using a modern ASGI framework with Uvicorn as the HTTP server.
+
+## How Smyth Works
+
+Understanding the components involved in the Smyth environment is crucial for effective development. Here's a breakdown of the key terms:
+
+- **Uvicorn**: An ASGI server responsible for translating incoming HTTP requests into Python callable formats that ASGI applications can understand. It serves as the interface between the web and your application, enabling asynchronous web server capabilities for Python.
+
+- **Starlette**: A lightweight ASGI framework designed to catch and handle incoming requests. In the context of Smyth, Starlette facilitates communication with Lambda Processes, effectively acting as a bridge that routes requests to the appropriate handlers.
+
+- **Lambda Process**: A dedicated Python process that runs a specific Lambda Handler. The primary purpose of maintaining separate processes for each Lambda Handler is to simulate the "warm" state of AWS Lambda functions, allowing them to retain their state between invocations. This setup mirrors the behavior of AWS Lambda in a local development environment.
+
+- **Lambda Handler**: The core component of your Lambda function, written as part of your project. This is the code you craft to respond to Lambda invocations, typically defined as a Python function that accepts an `event` dictionary and a `context` object. The `event` contains information about the invocation, such as the triggering event or data passed to the function, while the `context` provides runtime information about the invocation, the function, and the execution environment.
+
+Smyth operates similarly to Serverless (offline) but is implemented in pure Python with minimal dependencies. It utilizes a Starlette endpoint to provide a catch-all route. Uvicorn, in reload mode, runs Starlette, which automatically restarts the server and refreshes all Lambda processes. At startup, the Smyth Starlette application reads a TOML configuration file, initializing a process for each defined lambda handler. These processes import the handlers and start listening on a `multiprocessing.Queue`. When a request is received, Starlette's endpoint converts it into a Lambda event and places it in the queue. The subprocess then picks it up, invokes the handler, and returns the result to the main process via the queue, which then converts it back into an HTTP response.
+
+```mermaid
+sequenceDiagram
+ actor User
+ participant UVIC as Uvicorn
+ participant STAR as Starlette
+ participant PROC as Lambda Process
+ participant HAND as Lambda Handler
+
+ UVIC->>+STAR: Start
+ STAR->>+PROC: Start
+
+ User->>+UVIC: HTTP Request
+ UVIC->>+STAR: ASGI Request
+
+ STAR->>STAR: Lookup handlers by path
+ STAR->>+PROC: Send event and context
+ PROC->>+HAND: Invoke handler
+ HAND->>-PROC: Result
+ PROC->>-STAR: Result
+
+ STAR->>-UVIC: ASGI Response
+ UVIC->>-User: HTTP Response
+
+ PROC->>-STAR: Terminate
+ STAR->>-UVIC: End
+```
+
+## Others from Mirumee
+
+- [Lynara](https://github.com/mirumee/lynara){target="_blank"} - Allows deploying ASGI (FastAPI, Django) applications on Lambda
+- [Ariadne](https://ariadnegraphql.org/){target="_blank"} - Schema-first, Python GraphQL server
+- [Ariadne Codegen](https://github.com/mirumee/ariadne-codegen){target="_blank"} - GraphQL Python code generator
diff --git a/docs/javascripts/tablesort.js b/docs/javascripts/tablesort.js
new file mode 100644
index 0000000..6a5afcf
--- /dev/null
+++ b/docs/javascripts/tablesort.js
@@ -0,0 +1,6 @@
+document$.subscribe(function() {
+ var tables = document.querySelectorAll("article table:not([class])")
+ tables.forEach(function(table) {
+ new Tablesort(table)
+ })
+})
diff --git a/docs/overrides/partials/copyright.html b/docs/overrides/partials/copyright.html
new file mode 100644
index 0000000..a0ecf70
--- /dev/null
+++ b/docs/overrides/partials/copyright.html
@@ -0,0 +1,22 @@
+
+ {% if config.copyright %}
+
+ {{ config.copyright }}
+
+ {% endif %}
+ {% if not config.extra.generator == false %}
+ Made with
+
+ Material for MkDocs
+
+ {% endif %}
+
+
+ Smyth is crafted with by
+
+
diff --git a/docs/stylesheets/extra.css b/docs/stylesheets/extra.css
new file mode 100644
index 0000000..6c327b1
--- /dev/null
+++ b/docs/stylesheets/extra.css
@@ -0,0 +1,75 @@
+:root {
+ --md-primary-fg-color: rgb(245, 192, 59);
+ --md-primary-fg-color--light: #ecb7b7;
+ --md-primary-fg-color--dark: #90030c;
+ --md-accent-fg-color: rgb(245, 192, 59);
+ --md-accent-fg-color--light: #ecb7b7;
+ --md-accent-fg-color--dark: #90030c;
+}
+
+.md-header {
+ background-color: var(--md-primary-fg-color);
+ color: black;
+}
+.md-search__input + .md-search__icon {
+ color: black;
+}
+.md-search__input::placeholder {
+ color: black;
+}
+.md-nav__link[for]:focus,
+.md-nav__link[for]:hover,
+.md-nav__link[href]:focus,
+.md-nav__link[href]:hover {
+ text-decoration: underline;
+}
+
+.md-typeset a:focus,
+.md-typeset a:hover {
+ text-decoration: underline;
+}
+
+header {
+ border-bottom: 4px solid black;
+}
+
+.md-copyright {
+ width: 100%;
+}
+
+.md-copyright .made-with-love {
+ float: right;
+ line-height: 24px;
+}
+
+.md-copyright .made-with-love a img {
+ height: 24px;
+ vertical-align: top;
+ opacity: 0.7;
+ transition: all 0.3s ease-in-out;
+}
+
+.md-copyright .made-with-love a:hover img {
+ opacity: 1;
+}
+
+tr.benchmarks-best-result {
+ background-color: var(--md-typeset-ins-color);
+}
+
+tr.benchmarks-worst-result {
+ background-color: var(--md-typeset-del-color);
+}
+
+@keyframes heart {
+ 0%, 40%, 80%, 100% {
+ transform: scale(1);
+ }
+ 20%, 60% {
+ transform: scale(1.15);
+ }
+}
+.heart {
+ animation: heart 1000ms infinite;
+ color: #90030c;
+}
diff --git a/docs/user_guide/all_settings.md b/docs/user_guide/all_settings.md
new file mode 100644
index 0000000..5b83c7d
--- /dev/null
+++ b/docs/user_guide/all_settings.md
@@ -0,0 +1,59 @@
+# All Settings
+
+Here's a list of all the settings, including those that are simpler but equally valuable, consolidated on one page:
+
+## Smyth Settings
+
+### Host
+
+`host` - `str` (default: `"0.0.0.0"`) Used by Uvicorn to bind to an address.
+
+### Port
+
+`port` - `int` (default: `8080`) Used by Uvicorn as the bind port.
+
+### Log Level
+
+`log_level` - `str` (default: `"INFO"`) Sets the logging level for the `uvicorn` and `smyth` logging handlers.
+
+### Smyth Path Prefix
+
+`smyth_path_prefix` - `str` (default: `"/smyth"`) The path prefix used for Smyth's status endpoint. Change this if, for any reason, it collides with your path routing.
+
+## Handler Settings
+
+### Handler Path
+
+`handler_path` - `str` (required) The Python path to your Lambda function.
+
+### URL Path
+
+`url_path` - `str` (required) The Starlette routing path on which your handler will be exposed.
+
+### Timeout
+
+`timeout` - `float` (default: `None`, which means no timeout) The time in seconds after which the Lambda Handler raises a Timeout Exception, simulating Lambda's real-life timeouts.
+
+### Event Data Generator
+
+`event_data_generator_path` - `str` (default: `"smyth.event.generate_api_gw_v2_event_data"`) Read more about [event generators here](event_generators.md).
+
+### Context Data Generator
+
+`context_data_generator_path` - `str` (default: `"smyth.context.generate_context_data"`) A function similar to the [event generator](event_generators.md), but it constructs the `context`, adding some metadata from Smyth's runtime. You can create and use your own.
+
+### Fake Coldstart
+
+`fake_coldstart` - `bool` (default: `False`) Makes the subprocess `time.sleep` for a random time between 0.5 and 1 second when a subprocess is cold, imitating the longer first response time of real Lambdas.
+
+### Log Level
+
+`log_level` - `str` (default: `"INFO"`) Log level for Smyth's runner function, which is still part of Smyth but already running in the subprocess. Note that the logging of your Lambda handler code should be set separately.
+
+### Concurrency
+
+`concurrency` - `int` (default: `1`) Read more about [concurrency here](concurrency.md).
+
+### Strategy Function
+
+`strategy_function_path` - `str` (default: `"smyth.runner.strategy.first_warm"`) Read more about [dispatch strategies here](concurrency.md/#dispatch-strategy).
diff --git a/docs/user_guide/concurrency.md b/docs/user_guide/concurrency.md
new file mode 100644
index 0000000..174da78
--- /dev/null
+++ b/docs/user_guide/concurrency.md
@@ -0,0 +1,44 @@
+# Concurrency
+
+Smyth can also simulate the behavior of real Lambdas in terms of multiprocessing. For instance, every Lambda invocation can be run on a different machine, not holding the state between different runtimes. To simulate this, you can set the `concurrency` setting. Don't think of it in terms of web server performance - Smyth is not meant for production to demand high performance. Instead, consider it a method to keep you in check when developing your Lambda. It serves as a reminder that not everything can be stored in globals, and that in-memory cache might not persist between runs.
+
+??? example "Cold vs warm starts"
+
+ If we take our code with one handler:
+
+ ```python linenums="1"
+ COUNT = 0
+
+ def order_handler(event, context):
+ global COUNT
+ COUNT += 1
+ print(event, context)
+ return {"statusCode": 200, "body": f"Orders requests: {COUNT}"}
+ ```
+
+ Upon a cold start, the code outside of the handler function (the `COUNT` declaration in this case) will be interpreted. After that, each warm run of that Lambda will maintain the state of the `COUNT`. If the load is high enough, AWS will run more Lambdas for you, which might start from a cold state.
+
+To set up Smyth to run your handler in more than one subprocess, use the `concurrency` setting (by default it's `1`).
+
+```toml title="myproject/pyproject.toml" linenums="1" hl_lines="4 9"
+[tool.smyth.handlers.order_handler]
+handler_path = "smyth_test_app.handlers.order_handler"
+url_path = "/orders/{path:path}"
+concurrency = 2
+
+[tool.smyth.handlers.product_handler]
+handler_path = "smyth_test_app.handlers.product_handler"
+url_path = "/products/{path:path}"
+concurrency = 2
+fake_coldstart = true
+strategy_function_path = "smyth.runner.strategy.round_robin"
+```
+
+## Dispatch Strategy
+
+Dispatch strategy is controlled by a function that tells Smyth which subprocess from the pool of processes running a handler should be used. There are two built-in strategy functions:
+
+- `smyth.runner.strategy.first_warm` - (the default) tries to act like AWS, using a warmed-up Lambda (handler) if available. It only thaws a cold one if there is nothing warm or they are busy.
+- `smyth.runner.strategy.round_robin` - this one might keep you more in check as it picks the subprocess that was not used for the longest time, effectively using each subprocess one by one.
+
+You can choose the strategy function (including your own, in the same way as you would an event or context generator) with the `strategy_function_path` setting.
diff --git a/docs/user_guide/custom_entrypoint.md b/docs/user_guide/custom_entrypoint.md
new file mode 100644
index 0000000..60b997b
--- /dev/null
+++ b/docs/user_guide/custom_entrypoint.md
@@ -0,0 +1,73 @@
+# Custom Entrypoint
+
+Starting from Smyth 0.4.0, you can use it outside of the provided entrypoint (`python -m smyth`). You can build your own entrypoint for Smyth, which would not require a TOML config but instead have a Python script living in your project like any other development helper script.
+
+## Example
+
+### Project Structure
+
+Let's assume you have an `etc` directory that is not part of the final production package. Put your `smyth_conf.py` file there.
+
+```hl_lines="3-4"
+myproject
+├── pyproject.toml
+├── etc
+│ └── smyth_conf.py
+└── src
+ └── my_app
+ └── handlers.py
+```
+
+### Your Smyth Configuration
+
+Here's an example `smyth_conf.py` file:
+
+```python title="my_project/etc/smyth_conf.py" linenums="1"
+import uvicorn
+from starlette.requests import Request
+from smyth.smyth import Smyth
+from smyth.server.app import SmythStarlette
+
+def my_handler(event, context):
+ return {"statusCode": 200, "body": "Hello, World!"}
+
+async def my_event_data_generator(request: Request):
+ return {
+ "requestContext": {
+ "http": {
+ "method": "GET",
+ "path": "/hello",
+ }
+ }
+ }
+
+smyth = Smyth()
+
+smyth.add_handler(
+ name="hello",
+ path="/hello",
+ lambda_handler=my_handler,
+ timeout=1,
+ concurrency=1,
+ event_data_generator=my_event_data_generator,
+)
+
+app = SmythStarlette(smyth=smyth, smyth_path_prefix="/smyth")
+
+if __name__ == "__main__":
+ uvicorn.run("smyth_conf:app", host="0.0.0.0", port=8080, reload=True)
+```
+
+Normally, the handler would be imported, but including the custom event generator in this file is a good use case. Use the `SmythStarlette` subclass of `Starlette` - it ensures all subprocesses are run at server start and killed on stop (using ASGI Lifetime). Create a Smyth instance and pass it to your `SmythStarlette` instance. Here, you can fine-tune logging, change Uvicorn settings, etc.
+
+After that, run your script:
+
+
+ python etc/smyth_conf.py
+ INFO: Will watch for changes in these directories: ['/Users/pkucmus/Development/mirumee/smyth_test_app']
+ INFO: Uvicorn running on http://0.0.0.0:8080 (Press CTRL+C to quit)
+ INFO: Started reloader process [29441] using StatReload
+ INFO: Started server process [29443]
+ INFO: Waiting for application startup.
+ INFO: Application startup complete.
+
diff --git a/docs/user_guide/event_generators.md b/docs/user_guide/event_generators.md
new file mode 100644
index 0000000..53ca9ea
--- /dev/null
+++ b/docs/user_guide/event_generators.md
@@ -0,0 +1,78 @@
+# Event Generators
+
+An event generator is a simple coroutine used by Smyth to transform a Starlette `Request` instance into an `event` dictionary that is eventually used when invoking the Lambda handler.
+
+Smyth comes with two built-in event generators: `smyth.event.generate_api_gw_v2_event_data` (used by default) and `smyth.event.generate_lambda_invocation_event_data`, which is used in the [invocation endpoint](invoke.md).
+
+The first one builds a minimal API Gateway Proxy V2 event to simulate a Lambda being triggered by one. The other deserializes the request body (assumes it's proper JSON) and returns just that.
+
+## Custom Event Generators
+
+### Example Generator
+
+If you need to work with events not covered by Smyth, you can create and provide your own. Assuming a simplified API Gateway V1 event, you can create a generator like this:
+
+```python title="my_project/src/smyth_utils/event.py" linenums="1"
+async def generate_api_gw_v1_event_data(request: Request):
+ source_ip = None
+ if request.client:
+ source_ip = request.client.host
+
+ return {
+ "resource": request.url.path,
+ "path": request.url.path,
+ "httpMethod": request.method,
+ "headers": dict(request.headers),
+ "queryStringParameters": dict(request.query_params),
+ "pathParameters": {}, # You may need to populate this based on your routing
+ "stageVariables": None,
+ "requestContext": {
+ "resourceId": "offlineContext_resourceId",
+ "resourcePath": request.url.path,
+ "httpMethod": request.method,
+ "extendedRequestId": "offlineContext_extendedRequestId",
+ "requestTime": "21/Nov/2020:20:13:27 +0000",
+ "path": request.url.path,
+ "accountId": "offlineContext_accountId",
+ "protocol": request.url.scheme,
+ "stage": "dev",
+ "domainPrefix": "offlineContext_domainPrefix",
+ "requestTimeEpoch": int(request.timestamp().timestamp() * 1000),
+ "requestId": "offlineContext_requestId",
+ "identity": {
+ ...
+ },
+ "domainName": "offlineContext_domainName",
+ "apiId": "offlineContext_apiId"
+ },
+ "body": (await request.body()).decode("utf-8"),
+ "isBase64Encoded": False
+ }
+```
+
+!!! warning "This is example code; a proper API Gateway V1 generator might need to be different."
+
+### Configuration
+
+```toml title="myproject/pyproject.toml" linenums="1" hl_lines="8"
+[tool.smyth]
+host = "0.0.0.0"
+port = 8080
+
+[tool.smyth.handlers.order_handler]
+handler_path = "my_app.handlers.order_handler"
+url_path = "/orders/{path:path}"
+event_data_generator_path = "smyth_utils.event.generate_api_gw_v1_event_data"
+
+[tool.smyth.handlers.product_handler]
+handler_path = "my_app.handlers.product_handler"
+url_path = "/products/{path:path}"
+```
+
+Note that `smyth_utils` needs to be in your Python path.
+
+From this point on, the `order_handler` will receive a different `event` than the `product_handler`.
+
+## Limited Built-in Generators
+
+We provided a limited number of generators because there are many possibilities for event simulation. Simulating DynamoDB streams or SQS events locally might be appealing, but we were unsure how these would be used in real-life scenarios. We'd love to hear from the community about this - please don't hesitate to report [:material-github: GitHub issues](https://github.com/mirumee/smyth/issues){target="_blank"} with proposals on what event generators we should include in Smyth.
diff --git a/docs/user_guide/index.md b/docs/user_guide/index.md
new file mode 100644
index 0000000..2f3e648
--- /dev/null
+++ b/docs/user_guide/index.md
@@ -0,0 +1,90 @@
+# User Guide
+
+Smyth is built to have minimal or no impact on the project you are working on. That said, it comes with features that allow you to customize Smyth to the needs of your Lambda project.
+
+Following this guide will help you understand how to set up your development environment with Smyth.
+
+## Example Application
+
+Throughout this guide, we will use two lambda handlers as an example application.
+
+```python title="my_project/src/my_app/handlers.py" linenums="1"
+COUNT = 0
+
+def order_handler(event, context):
+ global COUNT
+ COUNT += 1
+ print(event, context)
+ return {"statusCode": 200, "body": f"Orders requests: {COUNT}"}
+
+def product_handler(event, context):
+ global COUNT
+ COUNT += 1
+ print(event, context)
+ return {"statusCode": 200, "body": f"Products requests: {COUNT}"}
+```
+
+These handlers do the exact same thing, and the global `COUNT` is there to illustrate how Smyth handles state between different requests (more about that in [concurrency](concurrency.md)).
+
+??? question "What is the project's structure?"
+
+ If this is in question, here is the example project's directory structure:
+
+ ```
+ myproject
+ ├── pyproject.toml
+ └── src
+ └── my_app
+ └── handlers.py
+ ```
+
+## Configuration
+
+Now, in our project's `pyproject.toml`, we can set up Smyth to instruct how the Lambdas will be executed. This setup reflects how your Lambdas will be deployed on AWS behind, for example, an API Gateway.
+
+```toml title="myproject/pyproject.toml" linenums="1" hl_lines="6-7 10-11"
+[tool.smyth]
+host = "0.0.0.0" # (1)!
+port = 8080
+
+[tool.smyth.handlers.order_handler]
+handler_path = "my_app.handlers.order_handler"
+url_path = "/orders/{path:path}"
+
+[tool.smyth.handlers.product_handler]
+handler_path = "my_app.handlers.product_handler"
+url_path = "/products/{path:path}"
+```
+
+1. Define the host and port on which you want Uvicorn to listen.
+
+Under `tool.smyth.handlers`, you name and define your handlers. The only two required options are:
+
+- `handler_path` - the Python path to the Lambda handler.
+- `url_path` - the path with which the handler is to be reached by Starlette - uses [Starlette's URL resolving](https://www.starlette.io/routing/#path-parameters){target="_blank"}.
+
+!!! tip "Custom Smyth Entrypoint"
+
+ You don't have to use the TOML config - read more about [Custom Entrypoint](custom_entrypoint.md).
+
+## Run It
+
+At this point, you can start Smyth from your project's root directory:
+
+
+
+ python -m smyth
+ [14:12:00] INFO [MainProcess] Uvicorn running on http://0.0.0.0:8080 (Press CTRL+C to quit) config.py:523
+ INFO [MainProcess] Started reloader process [22786] using StatReload basereload.py:79
+ [14:12:00] DEBUG [SpawnProcess-1] Using selector: KqueueSelector selector_events.py:64
+ INFO [SpawnProcess-1] Started server process [22788] server.py:82
+ INFO [SpawnProcess-1] Waiting for application startup. on.py:48
+ INFO [SpawnProcess-1] Started process order_handler:0 smyth.py:66
+ INFO [SpawnProcess-1] Started process order_handler:1 smyth.py:66
+ INFO [SpawnProcess-1] Started process product_handler:0 smyth.py:66
+ INFO [SpawnProcess-1] Started process product_handler:1 smyth.py:66
+ INFO [SpawnProcess-1] Application startup complete. on.py:62
+