Routing
OpenRun routes requests with the chi routing library. An app declares its routes in the routes array of ace.app. There are three route types:
| Route | Function | Response |
|---|---|---|
| HTML | ace.html | A page, with optional fragments for partial HTMX updates |
| API | ace.api | JSON (default) or plain text |
| Proxy | ace.proxy | Forwarded to another service |
HTML routing is built for hypermedia exchange: routes are defined in terms of pages and fragments within the pages. This makes it clear which API does what and gives an easy way to deal with partial HTMX driven requests and full page refreshes. A simple application might have one page with some interactions within it. Larger applications are composed of multiple pages, each with some interactive fragments.
Routes
The app contains a routes array, which defines all the routes for the app. For example, the app definition
app = ace.app("hello1",
routes = [
ace.html("/"),
ace.html("/help", "help.go.html")
]
)defines two routes. / routes to the default index page, /help routes to the help page. Routes can be of three types: HTML, API and Proxy.
HTML Route
An HTML route defined using ace.html defines the properties for an HTML page. The response is HTML text. The data returned by the handler function is passed to the template. If the handler returns an ace.response or ace.redirect, then that takes effect, otherwise the template is rendered.
An HTML route can have fragments defined within it. These are sub-APIs used for hypermedia driven interactions from the main page.
The parameters for ace.html are:
| Property | Optional | Type | Default | Notes |
|---|---|---|---|---|
| path | False | string | The route, should start with a / | |
| full | True | string | index.go.html if custom layout, else index_gen.go.html | The template to use for full page requests |
| partial | True | string | None | The template to use for partial page requests |
| handler | True | function | handler (if defined) | The handler function to use for the route |
| fragments | True | ace.fragment[] | [] | The fragment array |
| method | True | string | GET | The HTTP method type: GET,POST,PUT,DELETE etc, for example ace.GET |
Fragment
The fragments array in the html page definition defines the API interactions within the page. The parameters for ace.fragment are:
| Property | Optional | Type | Default | Notes |
|---|---|---|---|---|
| path | False | string | The route, should not start with a / | |
| partial | True | string | Inherited from page | The template to use for partial requests |
| handler | True | function | Inherited from page | The handler function to use for the route |
| method | True | string | GET | The HTTP method type: GET,POST,PUT,DELETE etc, for example ace.GET |
partial and handler are inherited from the page level, unless overridden for the fragment.A fragment with an empty path ("") registers on the page path itself, defining a method variant of the page. This expresses a form page’s POST without repeating the page’s template:
ace.html("/items/create", full="item_form.go.html", handler=create_page_handler,
fragments=[
ace.fragment("", method=ace.POST, handler=create_submit_handler),
]
)For example, in this page definition
ace.html("/game/{game_id}", full="game.go.html", partial="game_info_tmpl", handler=game_handler,
fragments=[
ace.fragment(
"submit", method=ace.POST, handler=lambda req: post_game_update(req, "submit")),
ace.fragment(
"refresh", partial="refresh_tmpl")
]
)there are three APIs defined:
| API | Handler | Full page response | Partial (HTMX) response |
|---|---|---|---|
| GET /game/{game_id} | game_handler | game.go.html | game_info_tmpl template |
| POST /game/{game_id}/submit | The lambda function | game_info_tmpl template, inherited from the page | |
| GET /game/{game_id}/refresh | game_handler, inherited from the page | game.go.html | refresh_tmpl template |
API Route
An API route defines a route which returns JSON (default) or plain text response. The handler response is converted to the desired format and returned. The parameters for ace.api are:
| Property | Optional | Type | Default | Notes |
|---|---|---|---|---|
| path | False | string | The route, should start with a / | |
| handler | True | function | handler (if defined) | The handler function to use for the route |
| method | True | string | GET | The HTTP method type: GET,POST,PUT,DELETE etc, for example ace.GET |
| type | True | string | JSON | The response type, ace.JSON or ace.TEXT |
For example
def handler(req):
return {"a": 1}
app = ace.app("api",
routes = [
ace.api("/myapi")
]
)A GET request to /myapi endpoint will return JSON {"a": 1}.
Proxy Route
A Proxy route defines a route which has to be proxied to another service. All API calls under that route are proxied (all methods and all sub-routes). Websocket connections are also proxied. Proxy uses a plugin based config, the app has to be authorized to do the proxying. The parameters for ace.proxy are:
| Property | Optional | Type | Default | Notes |
|---|---|---|---|---|
| path | False | string | The route, should start with a / | |
| config | False | ProxyConfig | The proxy configuration to use |
The proxy configuration proxy.config has the options:
| Property | Optional | Type | Default | Notes |
|---|---|---|---|---|
| url | False | string | The url to forward the requests to | |
| strip_path | True | string | Additional path components to strip from the request path. The app installation path is always stripped. | |
| preserve_host | True | boolean | false | Whether to preserve the Host header. Default false, the Host header is set to the target host value |
| strip_app | True | boolean | true | Whether to strip the app installation path from the proxied request path. Default true |
| response_headers | True | dict | {} | Headers to set on the proxied response, header name to string value. $url in a value is replaced with the request path |
For example, an app which forwards requests to www.google.com is
load("proxy.in", "proxy")
app = ace.app("Proxy",
routes=[
ace.proxy("/", proxy.config("https://www.google.com")),
],
permissions=[
ace.permission("proxy.in", "config", ["https://www.google.com"]),
],
)The plugin is authorized to allow proxying to https://www.google.com. Any request to the app is forwarded after stripping the app path. With the app installed at /test:
| Config | Request | Forwarded as |
|---|---|---|
| Default | /test/abc/def | /abc/def |
strip_path="/abc" | /test/abc/def | /def |
strip_app=False | /test/abc/def | /test/abc/def (the app path is kept) |
- Static files: if proxying is enabled for the
/route,/staticfile serving is disabled for the app since requests to the static path are also forwarded to the upstream service./static_rootserving is available and overrides the proxy config. - Forwarding headers: OpenRun sanitizes forwarding headers before proxying. Inbound
ForwardedandX-Forwarded-*/X-Real-IPheaders are not passed through as-is. OpenRun computes the client IP usingsecurity.trusted_proxiesand sends a clean forwarding header set to the upstream service.
See proxy plugin for details about the proxy config.
example.com: instead of example.com:/test. If the service uses absolute paths including the domain name, then the client will see the absolute paths and those requests will not come through the proxy. The HTML body is not rewritten by OpenRun to rewrite path references. The upstream service needs to use relative paths to ensure that all requests come through OpenRun.Request Flow
The API flow is
- The API is first sent to the matching app
- Within the app, the API is routed based on the routes defined
- If there is a handler defined for the matched route, the handler function is called with the request as argument
- The response template is invoked, with an input map containing a
Dataproperty as returned by the handler function - If the API type is set to JSON, the handler response is directly returned, with no template being used
- If automatic error handling is enabled (
error_handleris defined), then the error handler function is called if there is an error during the handler invocation. The error handler does the response processing, the templates defined in the route are not used.
Notes
- For HTMX requests, the
partialtemplate is used. For regular requests, the page-levelfulltemplate is used - With structured templates (a
base_templatesfolder is present),fullnormally names a template file. It can instead name a{{define}}block from the base templates, which is useful for endpoints whose response is only a fragment (for example an HTMX component update), so no dedicated template file is needed. Template names passed toace.responseresolve the same way - If there is a function called
handlerdefined, that is the default handler function for all APIs - For non-HTMX update requests (POST/PUT/DELETE), the Post-Redirect-Get pattern is automatically implemented by redirecting to the location pointed to by the
Refererheader.