skyward-api 0.1.0 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +4 -4
- data/README.md +185 -47
- data/lib/skyward/api/assembly/application.rb +26 -0
- data/lib/skyward/api/assembly/boot.rb +533 -0
- data/lib/skyward/api/assembly/builder.rb +83 -0
- data/lib/skyward/api/assembly/dispatcher.rb +121 -0
- data/lib/skyward/api/assembly/static.rb +115 -0
- data/lib/skyward/api/assembly.rb +4 -0
- data/lib/skyward/api/cli/app_file.rb +38 -0
- data/lib/skyward/api/cli/check.rb +145 -0
- data/lib/skyward/api/cli/executable.rb +15 -0
- data/lib/skyward/api/cli/routes.rb +30 -0
- data/lib/skyward/api/cli/serve/reloader.rb +77 -0
- data/lib/skyward/api/cli/serve.rb +137 -0
- data/lib/skyward/api/cli/serve.ru +16 -0
- data/lib/skyward/api/cli.rb +4 -0
- data/lib/skyward/api/commands.rb +38 -0
- data/lib/skyward/api/endpoints/declarations.rb +124 -0
- data/lib/skyward/api/endpoints/helpers.rb +49 -0
- data/lib/skyward/api/endpoints/route.rb +13 -0
- data/lib/skyward/api/endpoints.rb +4 -0
- data/lib/skyward/api/inputs/coercer.rb +425 -0
- data/lib/skyward/api/inputs.rb +164 -0
- data/lib/skyward/api/middleware/line_logger.rb +20 -0
- data/lib/skyward/api/middleware/request_id.rb +26 -0
- data/lib/skyward/api/middleware/request_log.rb +46 -0
- data/lib/skyward/api/middleware/rescue.rb +81 -0
- data/lib/skyward/api/middleware.rb +4 -0
- data/lib/skyward/api/openapi/docs.rb +39 -0
- data/lib/skyward/api/openapi.rb +393 -0
- data/lib/skyward/api/request.rb +127 -0
- data/lib/skyward/api/responses/bad_request.rb +18 -0
- data/lib/skyward/api/responses/conflict.rb +18 -0
- data/lib/skyward/api/responses/created.rb +19 -0
- data/lib/skyward/api/responses/forbidden.rb +18 -0
- data/lib/skyward/api/responses/no_content.rb +13 -0
- data/lib/skyward/api/responses/not_found.rb +18 -0
- data/lib/skyward/api/responses/redirect.rb +25 -0
- data/lib/skyward/api/responses/unauthorized.rb +18 -0
- data/lib/skyward/api/responses/unprocessable.rb +18 -0
- data/lib/skyward/api/responses.rb +4 -0
- data/lib/skyward/api/return_type_error.rb +4 -0
- data/lib/skyward/api/routing/percent_encoding.rb +15 -0
- data/lib/skyward/api/routing/router.rb +115 -0
- data/lib/skyward/api/routing.rb +4 -0
- data/lib/skyward/api/serializer/writers.rb +230 -0
- data/lib/skyward/api/serializer.rb +139 -0
- data/lib/skyward/api/test/client.rb +160 -0
- data/lib/skyward/api/test.rb +8 -0
- data/lib/skyward/api/version.rb +5 -1
- data/lib/skyward/api.rb +118 -1
- data/sig/generated/skyward/api/assembly/application.rbs +22 -0
- data/sig/generated/skyward/api/assembly/boot.rbs +217 -0
- data/sig/generated/skyward/api/assembly/builder.rbs +77 -0
- data/sig/generated/skyward/api/assembly/dispatcher.rbs +84 -0
- data/sig/generated/skyward/api/assembly/static.rbs +47 -0
- data/sig/generated/skyward/api/assembly.rbs +4 -0
- data/sig/generated/skyward/api/cli/app_file.rbs +15 -0
- data/sig/generated/skyward/api/cli/check.rbs +76 -0
- data/sig/generated/skyward/api/cli/executable.rbs +11 -0
- data/sig/generated/skyward/api/cli/routes.rbs +19 -0
- data/sig/generated/skyward/api/cli/serve/reloader.rbs +46 -0
- data/sig/generated/skyward/api/cli/serve.rbs +56 -0
- data/sig/generated/skyward/api/cli.rbs +4 -0
- data/sig/generated/skyward/api/commands.rbs +2 -0
- data/sig/generated/skyward/api/endpoints/declarations.rbs +81 -0
- data/sig/generated/skyward/api/endpoints/helpers.rbs +49 -0
- data/sig/generated/skyward/api/endpoints/route.rbs +24 -0
- data/sig/generated/skyward/api/endpoints.rbs +4 -0
- data/sig/generated/skyward/api/inputs/coercer.rbs +231 -0
- data/sig/generated/skyward/api/inputs.rbs +75 -0
- data/sig/generated/skyward/api/middleware/line_logger.rbs +13 -0
- data/sig/generated/skyward/api/middleware/request_id.rbs +17 -0
- data/sig/generated/skyward/api/middleware/request_log.rbs +18 -0
- data/sig/generated/skyward/api/middleware/rescue.rbs +41 -0
- data/sig/generated/skyward/api/middleware.rbs +4 -0
- data/sig/generated/skyward/api/openapi/docs.rbs +17 -0
- data/sig/generated/skyward/api/openapi.rbs +198 -0
- data/sig/generated/skyward/api/request.rbs +65 -0
- data/sig/generated/skyward/api/responses/bad_request.rbs +14 -0
- data/sig/generated/skyward/api/responses/conflict.rbs +14 -0
- data/sig/generated/skyward/api/responses/created.rbs +15 -0
- data/sig/generated/skyward/api/responses/forbidden.rbs +14 -0
- data/sig/generated/skyward/api/responses/no_content.rbs +10 -0
- data/sig/generated/skyward/api/responses/not_found.rbs +14 -0
- data/sig/generated/skyward/api/responses/redirect.rbs +20 -0
- data/sig/generated/skyward/api/responses/unauthorized.rbs +14 -0
- data/sig/generated/skyward/api/responses/unprocessable.rbs +14 -0
- data/sig/generated/skyward/api/responses.rbs +4 -0
- data/sig/generated/skyward/api/return_type_error.rbs +4 -0
- data/sig/generated/skyward/api/routing/percent_encoding.rbs +11 -0
- data/sig/generated/skyward/api/routing/router.rbs +158 -0
- data/sig/generated/skyward/api/routing.rbs +4 -0
- data/sig/generated/skyward/api/serializer/writers.rbs +126 -0
- data/sig/generated/skyward/api/serializer.rbs +79 -0
- data/sig/generated/skyward/api/test/client.rbs +117 -0
- data/sig/generated/skyward/api/test.rbs +6 -0
- data/sig/generated/skyward/api.rbs +38 -0
- data/sig/manual/skyward/api/assembly/boot.rbs +3 -0
- data/sig/manual/skyward/api/cli/app_file.rbs +3 -0
- data/sig/manual/skyward/api/cli/check.rbs +3 -0
- data/sig/manual/skyward/api/cli/executable.rbs +3 -0
- data/sig/manual/skyward/api/cli/routes.rbs +3 -0
- data/sig/manual/skyward/api/cli/serve.rbs +3 -0
- data/sig/manual/skyward/api/inputs/coercer.rbs +3 -0
- data/sig/manual/skyward/api/openapi/docs.rbs +3 -0
- data/sig/manual/skyward/api/openapi.rbs +3 -0
- data/sig/manual/skyward/api/routing/percent_encoding.rbs +3 -0
- data/sig/manual/skyward/api/serializer/writers.rbs +3 -0
- data/sig/manual/skyward/api/test.rbs +3 -0
- data/sig/manual/skyward/api.rbs +21 -0
- data/sig/manual/zeitwerk/loader.rbs +6 -0
- metadata +110 -3
checksums.yaml
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
---
|
|
2
2
|
SHA256:
|
|
3
|
-
metadata.gz:
|
|
4
|
-
data.tar.gz:
|
|
3
|
+
metadata.gz: a18b8e4d32a2a63f2fc6b92cd355834b77e2aecacf318df6f8aef501c8af2455
|
|
4
|
+
data.tar.gz: 2c9ef850c2e8e7f468356d9be9fa192bd55c0ec6430382de4afce74358d3b24d
|
|
5
5
|
SHA512:
|
|
6
|
-
metadata.gz:
|
|
7
|
-
data.tar.gz:
|
|
6
|
+
metadata.gz: 2ee0573f5a24f90e57aeade33b2358c01f6dc41b43405f217408d1b64e3a0e423f9cb4f8ca55edf5b655a956eb0a8d4d8ad0bdd892f3154330801d44aca6d538
|
|
7
|
+
data.tar.gz: ae07e3a5b84e74596a83666f461060cc0eb3fce0283447f01ae1e324c75febc1d4afc98b3d07db61d1e0b135118b1fd89e25c80c2488ede26ede728ebc6adf7f
|
data/README.md
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
# Skyward API
|
|
2
2
|
|
|
3
3
|
> [!CAUTION]
|
|
4
|
-
> **Work in progress: Skyward API
|
|
4
|
+
> **Work in progress: Skyward API is barely started.** Version 0.1 is a skeleton. The gems install and load, but only the parts listed under [Status](#status) are built. This README is the spec for what's coming, not documentation of what exists. Don't depend on it yet.
|
|
5
5
|
|
|
6
6
|
A small, fast Ruby web framework where **an endpoint is a method**.
|
|
7
7
|
|
|
@@ -91,7 +91,7 @@ end
|
|
|
91
91
|
```
|
|
92
92
|
|
|
93
93
|
- `Skyward::API` gives the class `get`, `post`, `put`, `patch` and `delete`, and gives its instances the response helpers below. It has no initializer or state of its own, so the initializer is yours, and so are the instance variables.
|
|
94
|
-
- Routes go at the top of the class, so it opens with a table of everything it serves. Each names its method with `to:`, and two routes can name the same one. Below the routes, an endpoint is an ordinary method, written and typed like any other.
|
|
94
|
+
- Routes go at the top of the class, so it opens with a table of everything it serves. Each names its method with `to:`, and two routes can name the same one, except in an app that serves [docs](#names-in-the-document). Below the routes, an endpoint is an ordinary method, written and typed like any other.
|
|
95
95
|
- A route that names a method the class doesn't have, or a path parameter the method doesn't take, fails at boot.
|
|
96
96
|
- An API class doesn't know where it lives. You choose the prefix when you mount it (`at: "/todos"`).
|
|
97
97
|
- Each API object is created **once**, at boot, and shared by every request. Per-request data arrives as arguments, never as instance state, so your handlers are thread- and fiber-safe by default.
|
|
@@ -103,13 +103,13 @@ end
|
|
|
103
103
|
|
|
104
104
|
Skyward API fills each keyword argument by its name:
|
|
105
105
|
|
|
106
|
-
| Keyword | Filled from
|
|
107
|
-
| ----------------------------------------------- |
|
|
108
|
-
| a path parameter (`id:` for `/:id`) | the URL path
|
|
109
|
-
| `body:` | the parsed JSON request body
|
|
110
|
-
| `request:` | the raw `Skyward::Request` (an escape hatch for headers, cookies and the IP) |
|
|
111
|
-
| a [provided](#providers) name (`current_user:`) | your provider
|
|
112
|
-
| anything else | the query string
|
|
106
|
+
| Keyword | Filled from |
|
|
107
|
+
| ----------------------------------------------- | --------------------------------------------------------------------------------- |
|
|
108
|
+
| a path parameter (`id:` for `/:id`) | the URL path |
|
|
109
|
+
| `body:` | the parsed JSON request body |
|
|
110
|
+
| `request:` | the raw `Skyward::API::Request` (an escape hatch for headers, cookies and the IP) |
|
|
111
|
+
| a [provided](#providers) name (`current_user:`) | your provider |
|
|
112
|
+
| anything else | the query string |
|
|
113
113
|
|
|
114
114
|
Ruby already has syntax for required and optional, so Skyward API uses it. A keyword with no default is required: if it's missing, the request fails with a 422 before your method runs. A keyword with a default is optional.
|
|
115
115
|
|
|
@@ -126,6 +126,8 @@ def create(body:)
|
|
|
126
126
|
end
|
|
127
127
|
```
|
|
128
128
|
|
|
129
|
+
`request:` is the escape hatch for what typed inputs don't cover. It's a frozen `Skyward::API::Request`, built only when an endpoint or a provider asks for it, with the request's `headers` by lowercase name (`request.headers["authorization"]`), its `cookies`, the client's `ip`, its `request_id`, and `env`, the raw Rack env, for anything else. Its type is `Skyward::API::Request`, it never comes from the query string, and it never appears in the docs.
|
|
130
|
+
|
|
129
131
|
---
|
|
130
132
|
|
|
131
133
|
## Responses
|
|
@@ -135,15 +137,15 @@ Return a value and Skyward API turns it into a response. There's no `render`, no
|
|
|
135
137
|
| Return | Status | Helper |
|
|
136
138
|
| -------------------------------------------------- | ------------------ | ------------------------- |
|
|
137
139
|
| a `Hash`, `Array`, `Data`, or anything with `to_h` | 200, JSON | — |
|
|
138
|
-
| `Skyward::Created[T]`
|
|
139
|
-
| `Skyward::NoContent`
|
|
140
|
-
| `Skyward::BadRequest`
|
|
141
|
-
| `Skyward::Unauthorized`
|
|
142
|
-
| `Skyward::Forbidden`
|
|
143
|
-
| `Skyward::NotFound`
|
|
144
|
-
| `Skyward::Conflict`
|
|
145
|
-
| `Skyward::Unprocessable`
|
|
146
|
-
| `Skyward::Redirect`
|
|
140
|
+
| `Skyward::API::Responses::Created[T]` | 201, JSON | `created(value)` |
|
|
141
|
+
| `Skyward::API::Responses::NoContent` | 204 | `no_content` |
|
|
142
|
+
| `Skyward::API::Responses::BadRequest` | 400, problem+json | `bad_request(detail)` |
|
|
143
|
+
| `Skyward::API::Responses::Unauthorized` | 401, problem+json | `unauthorized(detail)` |
|
|
144
|
+
| `Skyward::API::Responses::Forbidden` | 403, problem+json | `forbidden(detail)` |
|
|
145
|
+
| `Skyward::API::Responses::NotFound` | 404, problem+json | `not_found(detail = nil)` |
|
|
146
|
+
| `Skyward::API::Responses::Conflict` | 409, problem+json | `conflict(detail)` |
|
|
147
|
+
| `Skyward::API::Responses::Unprocessable` | 422, problem+json | `unprocessable(detail)` |
|
|
148
|
+
| `Skyward::API::Responses::Redirect` | 303 (or `status:`) | `redirect(to)` |
|
|
147
149
|
| a Rack triple `[status, headers, body]` | as given | — |
|
|
148
150
|
|
|
149
151
|
Every helper takes `headers:`:
|
|
@@ -163,6 +165,19 @@ Error responses use [RFC 9457](https://www.rfc-editor.org/rfc/rfc9457) `applicat
|
|
|
163
165
|
}
|
|
164
166
|
```
|
|
165
167
|
|
|
168
|
+
A Rack triple is the escape hatch for anything a value can't express: streaming, files, or a content type other than JSON. Its status, headers and body are sent as given, so a body that streams through `each` or `call` works. Rack 3 wants lowercase header names, and Skyward API doesn't rewrite them. A typed endpoint sends a triple only when its return type says so, with `Skyward::API::rack`, which is `[Integer, Hash[String, String], untyped]`, written `rack` under the [`# @rbs use` line](#types-the-bonus-that-pays-rent):
|
|
169
|
+
|
|
170
|
+
```ruby
|
|
171
|
+
# @rbs id: Integer
|
|
172
|
+
# @rbs return: rack | Responses::NotFound
|
|
173
|
+
def export(id:)
|
|
174
|
+
todo = @todos.find(id)
|
|
175
|
+
todo ? [200, { "content-type" => "text/csv" }, [todo.to_csv]] : not_found
|
|
176
|
+
end
|
|
177
|
+
```
|
|
178
|
+
|
|
179
|
+
Nothing checks what a triple sends: that's the point of an escape hatch, and why it's opt-in through the return type. An `Array[T]` return is always JSON, even with three items.
|
|
180
|
+
|
|
166
181
|
---
|
|
167
182
|
|
|
168
183
|
## Types: the bonus that pays rent
|
|
@@ -176,9 +191,11 @@ Everything above works without types. Add a signature and it does more:
|
|
|
176
191
|
|
|
177
192
|
Signatures are plain [RBS](https://github.com/ruby/rbs). Write them inline with [rbs-inline](https://github.com/soutaro/rbs-inline), or in `sig/*.rbs` files. Skyward API reads both, from the `.rbs` files under `sig/` (or the directory you pass as `Skyward.app(signatures:)`), so run rbs-inline before you boot. There's no schema DSL to learn and nothing to keep in sync: **the type you write for Steep is the API contract.**
|
|
178
193
|
|
|
194
|
+
A file whose signatures name Skyward API's types starts with `# @rbs use Skyward::API::*`, so they can write `Responses::NotFound`, `Responses::Created[Todo]` and `Request`: RBS doesn't look names up through the superclass, so without the line even an API class's signatures would need `Skyward::API::Responses::NotFound`. The line reaches only signatures, so Ruby code writes the full name, and so does a `#:` after an expression, which Steep also reads as Ruby.
|
|
195
|
+
|
|
179
196
|
```ruby
|
|
180
197
|
# rbs_inline: enabled
|
|
181
|
-
# @rbs use Skyward::*
|
|
198
|
+
# @rbs use Skyward::API::*
|
|
182
199
|
|
|
183
200
|
Todo = Data.define(
|
|
184
201
|
:id, #: Integer
|
|
@@ -223,32 +240,32 @@ class TodosAPI < Skyward::API
|
|
|
223
240
|
end
|
|
224
241
|
|
|
225
242
|
# @rbs id: Integer
|
|
226
|
-
# @rbs return: Todo | NotFound
|
|
243
|
+
# @rbs return: Todo | Responses::NotFound
|
|
227
244
|
def show(id:)
|
|
228
245
|
@todos.find(id) || not_found
|
|
229
246
|
end
|
|
230
247
|
|
|
231
248
|
# @rbs body: NewTodo
|
|
232
|
-
# @rbs return: Created[Todo]
|
|
249
|
+
# @rbs return: Responses::Created[Todo]
|
|
233
250
|
def create(body:)
|
|
234
251
|
created @todos.create(**body.to_h)
|
|
235
252
|
end
|
|
236
253
|
|
|
237
254
|
# @rbs id: Integer
|
|
238
|
-
# @rbs return: Todo | NotFound
|
|
255
|
+
# @rbs return: Todo | Responses::NotFound
|
|
239
256
|
def complete(id:)
|
|
240
257
|
@todos.complete(id) || not_found
|
|
241
258
|
end
|
|
242
259
|
|
|
243
260
|
# @rbs id: Integer
|
|
244
|
-
# @rbs return: NoContent | NotFound
|
|
261
|
+
# @rbs return: Responses::NoContent | Responses::NotFound
|
|
245
262
|
def destroy(id:)
|
|
246
263
|
@todos.delete(id) ? no_content : not_found
|
|
247
264
|
end
|
|
248
265
|
end
|
|
249
266
|
```
|
|
250
267
|
|
|
251
|
-
`body:` is now a real `NewTodo`, not a `Hash`. `id:` is an `Integer`. The union return type `Todo | NotFound` tells the docs this endpoint can answer with a 200 or a 404.
|
|
268
|
+
`body:` is now a real `NewTodo`, not a `Hash`. `id:` is an `Integer`. The union return type `Todo | Responses::NotFound` tells the docs this endpoint can answer with a 200 or a 404.
|
|
252
269
|
|
|
253
270
|
### How types map
|
|
254
271
|
|
|
@@ -305,7 +322,7 @@ Skyward.app(docs: true) { ... }
|
|
|
305
322
|
Skyward API builds the document from:
|
|
306
323
|
|
|
307
324
|
- **Routes**, which become paths and operations.
|
|
308
|
-
- **Signatures**, which become parameters, request bodies, and one response per
|
|
325
|
+
- **Signatures**, which become parameters, request bodies, and one response per status of the return type's members, `oneOf` them where several share one. A `Skyward::API::rack` member becomes a `default` response with no schema, because its status and content are known only at runtime.
|
|
309
326
|
- **The documentation you write in Ruby**, shown below.
|
|
310
327
|
- **Classes with typed readers**, such as `Data` classes or Skyward ORM records, which become reusable components.
|
|
311
328
|
- **Providers**, whose failure responses are added to every endpoint that uses them (see below).
|
|
@@ -348,12 +365,46 @@ A `summary:` is one line, and Skyward API refuses to boot if it has a line break
|
|
|
348
365
|
|
|
349
366
|
Comments are never read. They're for people reading the Ruby, and they never reach your docs, so documentation can't hide in a comment, and a comment can't change what you publish.
|
|
350
367
|
|
|
351
|
-
Docs are served only when you pass `docs: true`, so leave it out to hide them.
|
|
368
|
+
Docs are served only when you pass `docs: true`, so leave it out to hide them. With it, a route or a static file at `/openapi.json` or `/docs` fails boot. The document and the page at `/docs` are built once, at boot, and the same app always writes the same bytes. The document is your API's contract with the code that calls it. Skyward API doesn't write clients: write the document at build time, and generate a client from it with whatever tooling suits that code:
|
|
352
369
|
|
|
353
370
|
```sh
|
|
354
371
|
$ skyward openapi > openapi.json
|
|
355
372
|
```
|
|
356
373
|
|
|
374
|
+
### Names in the document
|
|
375
|
+
|
|
376
|
+
A client generated from the document takes its names from it, so every name is one you chose in Ruby, and stays the same until you change it. Skyward API never guesses a name with English rules, such as singularising `Statuses` into `Status`.
|
|
377
|
+
|
|
378
|
+
- Each API class is a tag, named by its constant path with `::` as `.`, so `Admin::TodosAPI` is `Admin.TodosAPI`.
|
|
379
|
+
- Each operation's ID is its tag and its method, joined by `_`, such as `Admin.TodosAPI_index`. Each operation needs its own, so with `docs: true` Skyward API refuses to boot when two routes name the same method, or one class is mounted twice.
|
|
380
|
+
- Each class with typed readers is a schema under `components`, named by its constant path the same way, so `Statuses::Record` is `Statuses.Record`. `Problem` is Skyward API's own, the schema of every problem+json response.
|
|
381
|
+
|
|
382
|
+
To name a schema yourself, pass `schema_names:`. It needs no change to the class, so it works for Skyward ORM records and other gems' classes too:
|
|
383
|
+
|
|
384
|
+
```ruby
|
|
385
|
+
Skyward.app(docs: true, schema_names: { Statuses::Record => "Status" }) { ... }
|
|
386
|
+
```
|
|
387
|
+
|
|
388
|
+
A schema name has only letters, digits, `.`, `-` and `_`, as OpenAPI requires, and no two schemas share one, including `Problem`. Skyward API refuses to boot otherwise.
|
|
389
|
+
|
|
390
|
+
A class is one schema, wherever it's used. A nullable field is optional in a request, which can leave it out, and required but nullable in a response, which always writes it, so a class used in both gets the request form.
|
|
391
|
+
|
|
392
|
+
### The API reference
|
|
393
|
+
|
|
394
|
+
`/docs` is a small HTML page, titled with `title:`, on which [Scalar](https://github.com/scalar/scalar) renders the document. The page finds the document by a relative URL, so it still works when the app is mounted under a prefix in a larger Rack app: `/api/docs` reads `/api/openapi.json`.
|
|
395
|
+
|
|
396
|
+
By default the page loads Scalar from the jsDelivr CDN at a pinned version, with a Subresource Integrity hash, so a browser won't run a copy the CDN has changed. `scalar_url:` loads it from anywhere else, such as a copy your app serves itself, so `/docs` works offline, behind a strict Content Security Policy, and when the CDN is down:
|
|
397
|
+
|
|
398
|
+
```ruby
|
|
399
|
+
# public/scalar.js is dist/browser/standalone.js from the @scalar/api-reference package.
|
|
400
|
+
Skyward.app(docs: true, scalar_url: "/scalar.js") do |app|
|
|
401
|
+
app.static "/", from: "public"
|
|
402
|
+
# ...
|
|
403
|
+
end
|
|
404
|
+
```
|
|
405
|
+
|
|
406
|
+
A URL you pass gets no integrity hash, because Skyward API can't know it. A relative one, such as `scalar.js`, is found beside `/docs`, like the document. The page has no inline JavaScript, and it turns off Scalar's default web fonts, so with a copy you serve yourself it makes no request to any other host. A Content Security Policy needs to allow only Scalar's source in `script-src`: `'self'` for your own copy, or `https://cdn.jsdelivr.net` for the default. The page also needs `'self'` in `connect-src`, to fetch the document, and `'unsafe-inline'` in `style-src`, because Scalar adds its styles inline.
|
|
407
|
+
|
|
357
408
|
---
|
|
358
409
|
|
|
359
410
|
## Building an app
|
|
@@ -382,10 +433,21 @@ run App
|
|
|
382
433
|
```
|
|
383
434
|
|
|
384
435
|
- `mount` attaches an API object at a prefix.
|
|
385
|
-
- `use` is ordinary Rack middleware.
|
|
436
|
+
- `use` is ordinary Rack middleware, and takes the same arguments as `Rack::Builder#use`. It wraps the whole app, in declaration order: the first `use` is outermost, wherever it sits among the other calls.
|
|
386
437
|
- `static` serves files from a directory.
|
|
387
438
|
- `Skyward.app` returns a frozen Rack app. Nothing about it changes after boot.
|
|
388
439
|
|
|
440
|
+
Skyward API doesn't build CORS, compression or sessions, because Rack already has them. CORS, for example, is [rack-cors](https://github.com/cyu/rack-cors) through `use`, which answers a preflight `OPTIONS` before it reaches your routes:
|
|
441
|
+
|
|
442
|
+
```ruby
|
|
443
|
+
app.use Rack::Cors do
|
|
444
|
+
allow do
|
|
445
|
+
origins "https://todos.example"
|
|
446
|
+
resource "*", headers: :any, methods: %i[get post delete]
|
|
447
|
+
end
|
|
448
|
+
end
|
|
449
|
+
```
|
|
450
|
+
|
|
389
451
|
---
|
|
390
452
|
|
|
391
453
|
## Providers
|
|
@@ -393,6 +455,8 @@ run App
|
|
|
393
455
|
Some inputs don't come from the request directly. The current user is one. Register a provider, and any endpoint that asks for that keyword gets its value:
|
|
394
456
|
|
|
395
457
|
```ruby
|
|
458
|
+
# @rbs use Skyward::API::*
|
|
459
|
+
|
|
396
460
|
class CurrentUser
|
|
397
461
|
# @rbs @sessions: Sessions
|
|
398
462
|
|
|
@@ -402,8 +466,8 @@ class CurrentUser
|
|
|
402
466
|
@sessions = sessions
|
|
403
467
|
end
|
|
404
468
|
|
|
405
|
-
# @rbs request:
|
|
406
|
-
# @rbs return: User |
|
|
469
|
+
# @rbs request: Request
|
|
470
|
+
# @rbs return: User | Responses::Unauthorized
|
|
407
471
|
def call(request)
|
|
408
472
|
@sessions.user_for(request.cookies["session"]) || Skyward.unauthorized("Sign in first")
|
|
409
473
|
end
|
|
@@ -426,8 +490,8 @@ def index(current_user:)
|
|
|
426
490
|
end
|
|
427
491
|
```
|
|
428
492
|
|
|
429
|
-
- A provider is anything that responds to `call(request)`, such as an object, a lambda or a method.
|
|
430
|
-
- If a provider returns a response (like `Unauthorized`), the request stops there and your method never runs. Authentication is just a provider.
|
|
493
|
+
- A provider is anything that responds to `call(request)`, such as an object, a lambda or a method. Pass an instance of a class: a module with `extend self`, or a class with `def self.call`, has no signature Skyward API can read, so boot refuses it.
|
|
494
|
+
- If a provider returns a response (like `Skyward::API::Responses::Unauthorized`), the request stops there and your method never runs. Authentication is just a provider.
|
|
431
495
|
- Because the provider has a signature, Skyward API knows that every endpoint asking for `current_user:` can respond with a 401, and documents it.
|
|
432
496
|
- Provided values never appear as query parameters.
|
|
433
497
|
|
|
@@ -438,7 +502,7 @@ end
|
|
|
438
502
|
Skyward API checks your app thoroughly at boot, so mistakes surface when you start it, not at 3am:
|
|
439
503
|
|
|
440
504
|
```
|
|
441
|
-
Skyward::BootError: TodosAPI#show (GET /todos/:id)
|
|
505
|
+
Skyward::Core::BootError: TodosAPI#show (GET /todos/:id)
|
|
442
506
|
The route has a path parameter :id, but the method has no `id:` keyword.
|
|
443
507
|
|
|
444
508
|
get "/:id", to: :show
|
|
@@ -448,10 +512,33 @@ Skyward::BootError: TodosAPI#show (GET /todos/:id)
|
|
|
448
512
|
Did you mean `def show(id:)`?
|
|
449
513
|
```
|
|
450
514
|
|
|
451
|
-
Boot also catches a route that names a method the class doesn't have, a route that shadows another, an unknown type in a signature, and a keyword that matches nothing. With `strict: true`, it also catches
|
|
515
|
+
Boot also catches a route that names a method the class doesn't have, a route that shadows another, an unknown type in a signature, and a keyword that matches nothing. With `strict: true`, it also catches every untyped endpoint: one that has no signature at all, or whose signature types a keyword or the return as `untyped`.
|
|
452
516
|
|
|
453
517
|
When your code raises at runtime, Skyward API responds with a 500 problem+json that carries the request ID and logs the exception. In development, the response also includes the backtrace.
|
|
454
518
|
|
|
519
|
+
```json
|
|
520
|
+
{
|
|
521
|
+
"type": "about:blank",
|
|
522
|
+
"title": "Internal Server Error",
|
|
523
|
+
"status": 500,
|
|
524
|
+
"request_id": "5f0c6e1a-7a4e-4a43-9a8e-2f1d3c4b5a69"
|
|
525
|
+
}
|
|
526
|
+
```
|
|
527
|
+
|
|
528
|
+
To send exceptions to Sentry or a similar service, pass `on_error:`. It's called once per exception, after it's logged, with the exception and the Rack env, and takes anything that responds to `call(exception, env)`:
|
|
529
|
+
|
|
530
|
+
```ruby
|
|
531
|
+
report = ->(exception, env) { Sentry.capture_exception(exception, tags: { request_id: env["skyward.request_id"] }) }
|
|
532
|
+
|
|
533
|
+
App = Skyward.app(on_error: report) do |app|
|
|
534
|
+
app.mount TodosAPI.new(todos:), at: "/todos"
|
|
535
|
+
end
|
|
536
|
+
```
|
|
537
|
+
|
|
538
|
+
If the hook raises, that's logged too, and the client still gets the original 500. A returned error like `not_found` is a response, not an exception, so it's never reported.
|
|
539
|
+
|
|
540
|
+
The app is in development when `RACK_ENV`, or `APP_ENV` if `RACK_ENV` isn't set, is `development`, as `skyward serve` sets it. Anything else, including neither being set, is production.
|
|
541
|
+
|
|
455
542
|
---
|
|
456
543
|
|
|
457
544
|
## Testing
|
|
@@ -463,7 +550,7 @@ describe TodosAPI do
|
|
|
463
550
|
it "answers 404 for a todo that doesn't exist" do
|
|
464
551
|
api = TodosAPI.new(todos: FakeTodos.new)
|
|
465
552
|
|
|
466
|
-
assert_instance_of Skyward::NotFound, api.show(id: 404)
|
|
553
|
+
assert_instance_of Skyward::API::Responses::NotFound, api.show(id: 404)
|
|
467
554
|
end
|
|
468
555
|
end
|
|
469
556
|
```
|
|
@@ -474,7 +561,7 @@ When you want the whole stack, including routing, coercion, providers and middle
|
|
|
474
561
|
|
|
475
562
|
```ruby
|
|
476
563
|
describe "POST /todos" do
|
|
477
|
-
let(:client) { Skyward::Test.client(App) }
|
|
564
|
+
let(:client) { Skyward::API::Test.client(App) }
|
|
478
565
|
|
|
479
566
|
it "rejects a priority that doesn't exist" do
|
|
480
567
|
response = client.post "/todos", json: { title: "Ship it", priority: "urgent" }
|
|
@@ -485,7 +572,7 @@ describe "POST /todos" do
|
|
|
485
572
|
end
|
|
486
573
|
```
|
|
487
574
|
|
|
488
|
-
`Skyward::Test.client` works with Minitest and RSpec, and with any Rack app.
|
|
575
|
+
`Skyward::API::Test.client` works with Minitest and RSpec, and with any Rack app.
|
|
489
576
|
|
|
490
577
|
---
|
|
491
578
|
|
|
@@ -494,10 +581,13 @@ end
|
|
|
494
581
|
Here's what you get without configuring anything:
|
|
495
582
|
|
|
496
583
|
- **Boot does the work. Requests don't.** Routes are compiled into a single matcher, and signatures are compiled into coercers and validators, all at boot. API objects are created once. A request is a route lookup, a coercion and a method call.
|
|
584
|
+
- **Bounded request bodies.** A body is read only for an endpoint that takes `body:`, and only up to `Skyward.app(max_body_size:)` bytes, 1 MiB (`1_048_576`) by default. A larger `Content-Length`, or a body that runs past the limit, answers 413 without reading the rest, and a body whose `Content-Type` isn't `application/json` or `*+json` answers 415.
|
|
585
|
+
- **Bounded error lists.** A 422 lists at most 1,000 problems, and coercion stops once it has found them. Each message writes its expected type in at most 200 characters, worked out at boot, so a small body can't produce a large response.
|
|
586
|
+
- **Bounded coercion.** A union's members only find whether a value fits, without writing errors, and a union nested in several members coerces each value once, so overlapping members don't multiply the cost of coercing a body by the type's depth.
|
|
497
587
|
- **Request IDs.** Skyward API honours an incoming `X-Request-Id`, generates one when it's missing, and returns it on every response.
|
|
498
|
-
- **Structured logs.** Every request logs one JSON line with its method, path, status, duration and request ID
|
|
499
|
-
- **Safe errors.** In production, a 500 never leaks a backtrace.
|
|
500
|
-
- **Strict mode.** Use `Skyward.app(strict: true)` and the app refuses to boot if any endpoint is untyped.
|
|
588
|
+
- **Structured logs.** Every request logs one JSON line with its method, path, status, duration and request ID, to standard output. Pass `Skyward.app(logger: ...)` to send it elsewhere: any object with `info(String)` will do, such as a stdlib `Logger` whose formatter writes the message alone, so each line stays one JSON object. `logger: nil` turns logging off.
|
|
589
|
+
- **Safe errors.** In production, a 500 never leaks a backtrace or an exception's message.
|
|
590
|
+
- **Strict mode.** Use `Skyward.app(strict: true)` and the app refuses to boot if any endpoint is untyped. `SKYWARD_STRICT=1` in the environment turns it on whatever `strict:` says, which is how `skyward check` boots the app.
|
|
501
591
|
- **YJIT-friendly.** Hot paths are plain method calls with stable object shapes, with no `instance_exec` and no `method_missing`.
|
|
502
592
|
|
|
503
593
|
Skyward API doesn't manage processes. Run it under Falcon or Puma like any Rack app.
|
|
@@ -517,22 +607,50 @@ Skyward API and Skyward ORM share one `skyward` command. Each adds its own comma
|
|
|
517
607
|
|
|
518
608
|
```
|
|
519
609
|
$ skyward routes
|
|
520
|
-
GET /todos
|
|
521
|
-
GET /todos/:id
|
|
522
|
-
POST /todos
|
|
523
|
-
POST /todos/:id/complete
|
|
524
|
-
DELETE /todos/:id
|
|
610
|
+
GET /todos TodosAPI#index (?done: bool?, ?limit: Integer) -> Array[Todo]
|
|
611
|
+
GET /todos/:id TodosAPI#show (id: Integer) -> (Todo | Responses::NotFound)
|
|
612
|
+
POST /todos TodosAPI#create (body: NewTodo) -> Responses::Created[Todo]
|
|
613
|
+
POST /todos/:id/complete TodosAPI#complete (id: Integer) -> (Todo | Responses::NotFound)
|
|
614
|
+
DELETE /todos/:id TodosAPI#destroy (id: Integer) -> (Responses::NoContent | Responses::NotFound)
|
|
525
615
|
```
|
|
526
616
|
|
|
527
617
|
The executable comes with Skyward Core, which every Skyward gem depends on. It finds each gem's `lib/skyward/<gem>/commands.rb` with `Gem.find_files` and loads it, and that file registers the gem's commands:
|
|
528
618
|
|
|
529
619
|
```ruby
|
|
530
|
-
Skyward::
|
|
620
|
+
Skyward::Core::CLI.register("routes", "List every route and the method that serves it") do |args|
|
|
531
621
|
# ...
|
|
532
622
|
end
|
|
533
623
|
```
|
|
534
624
|
|
|
535
|
-
Skyward API's commands run in your app's directory
|
|
625
|
+
Skyward API's commands run in your app's directory. `skyward serve` runs `config.ru`, and the others load `app.rb`, which assigns `App = Skyward.app { ... }`.
|
|
626
|
+
|
|
627
|
+
### `skyward check` in CI
|
|
628
|
+
|
|
629
|
+
Run `skyward check` as a required CI step in every Skyward app. Skyward API reads signatures at boot, and `rbs` stays one of its runtime dependencies through 0.x, so a deploy with stale signatures quietly validates requests against the old contract. `check` is what catches it. It checks three things, in order, and checks all three even after one fails, then exits 1 if any failed:
|
|
630
|
+
|
|
631
|
+
1. **Signatures.** It runs rbs-inline over the app's Ruby, outside `test/`, `spec/`, `vendor/`, `tmp/` and hidden directories, and fails if the result differs from `sig/generated`, listing the files that differ and the command that regenerates them.
|
|
632
|
+
2. **Strict boot.** It loads `app.rb` with `SKYWARD_STRICT=1`, so an untyped endpoint, or any other boot error, fails it.
|
|
633
|
+
3. **Steep.** It runs `steep check` with the app's `Steepfile`, and passes its output through.
|
|
634
|
+
|
|
635
|
+
It needs rbs-inline and Steep in the app's bundle, and a `Steepfile`:
|
|
636
|
+
|
|
637
|
+
```ruby
|
|
638
|
+
# Gemfile
|
|
639
|
+
group :development, :test do
|
|
640
|
+
gem "rbs-inline", require: false
|
|
641
|
+
gem "steep", require: false
|
|
642
|
+
end
|
|
643
|
+
```
|
|
644
|
+
|
|
645
|
+
```
|
|
646
|
+
$ bundle exec skyward check
|
|
647
|
+
Signatures: passed
|
|
648
|
+
Strict boot: passed
|
|
649
|
+
Steep: passed
|
|
650
|
+
# Type checking files:
|
|
651
|
+
...
|
|
652
|
+
No type error detected.
|
|
653
|
+
```
|
|
536
654
|
|
|
537
655
|
---
|
|
538
656
|
|
|
@@ -558,4 +676,24 @@ Skyward API's commands run in your app's directory, and load `app.rb`, which ass
|
|
|
558
676
|
|
|
559
677
|
## Status
|
|
560
678
|
|
|
561
|
-
This README is the spec. Skyward 0.1 is a skeleton: the gem installs and loads, and
|
|
679
|
+
This README is the spec. Skyward 0.1 is a skeleton: the gem installs and loads, and only the parts listed here are built. Skyward API is built first, and this section lists each part as it lands.
|
|
680
|
+
|
|
681
|
+
- **Route declarations.** An API class subclasses `Skyward::API` and lists its routes with `get`, `post`, `put`, `patch` and `delete`, each with an optional `summary:` and `description:`, and describes itself with `description`. A subclass starts with its parent's routes. A path that doesn't start with `/`, a path parameter that isn't a valid keyword name or appears twice, or a `to:` that isn't a Symbol raises `ArgumentError` where it's declared. The rest is checked at boot, below.
|
|
682
|
+
- **Building an app.** `Skyward.app` yields a builder and returns a frozen Rack app, and the builder is frozen once the block returns. `mount` attaches an API object at a prefix (`at:`, `/` by default), and raises `Skyward::Core::BootError` given anything but a `Skyward::API` instance. One object can be mounted at several prefixes. A request matches a route when its method and whole path match, trailing slash included, with each path parameter matching one non-empty segment, percent-decoded. Routes are tried in mount order, then declaration order. The method is called with its inputs, below, and its return value is answered by its return type, as Responses below describes. A request whose path no route matches gets a 404 problem+json.
|
|
683
|
+
- **Checks at boot.** `Skyward.app` loads the RBS signatures under `signatures:` (`"sig"` by default, relative to the current directory) along with Skyward API's own, so an app's signatures can subclass `Skyward::API`. It refuses to boot with a `Skyward::Core::BootError` on the first problem it finds, and the message starts with the route's label, such as `TodosAPI#show (GET /todos/:id)`, then says what's wrong and how to fix it. It refuses a `summary:` with a line break; a route that an earlier one with the same verb, in any mount, matches every path of, as `/todos/:id` does `/todos/new`; a method that isn't public, or that takes positional arguments or `**rest`; a signature whose keywords differ from the method's, in name or in being required, which means it's stale; a path parameter with no keyword of its name; a path parameter whose name is provided; a `request:` keyword typed as anything but `Skyward::API::Request`; a provided keyword whose type isn't its provider's value, as Providers below describes; a type that can't be read; and a path or query keyword typed as a record, a hash, a class, or an array in a path or inside an array. Each endpoint keeps its method type as its signature file writes it, or for an untyped endpoint, below, as rbs-inline would, and its keywords, with each one's name, its source (the path for a path parameter, the body for `body:`, the request for `request:`, and otherwise the query string), whether it's required and its type, keeps the provider of each provided keyword apart from them, in keyword order, and keeps the members of its return type, reading `Skyward::API::Responses::Created[T]` with the type of its value, the other response values by their class, and `Skyward::API::rack`, or the tuple it names, as a Rack triple, and refusing a `Skyward::API::Responses::Created` without one. A class or method with no signature, including when there's no `signatures:` directory at all, is an untyped endpoint: each keyword is `untyped`, required as the method requires it, and so is its return type, which is what rbs-inline writes for a method with no annotations. `request:` may be typed `untyped` too, and is still the request. With `Skyward.app(strict: true)`, or with `SKYWARD_STRICT=1` in the environment whatever `strict:` says, once the other checks pass, boot refuses every untyped endpoint, not just the first, each starting with its label: one with no signature, or one whose signature types a keyword or a member of its return type as `untyped`, naming which. `untyped` inside a type, as in `Array[untyped]`, isn't refused, and nor is `request:`. Source excerpts and "Did you mean" are still to come.
|
|
684
|
+
- **Inputs.** Each endpoint's keywords are compiled into coercers at boot, and filled on each request before the method runs: a path parameter from the path, `body:` from the JSON body, `request:` with the request, below, a provided keyword from its provider, below, and any other keyword from the query string, each but `request:` and a provided keyword coerced to its type. In a path or query, `Integer` matches `-?\d+`, `Float` is parsed with `Float()` and must be finite, and `bool` takes `true`, `false`, `1` and `0`. In a body, a number or boolean must already be one, and an Integer is accepted as a Float. `Date` is `YYYY-MM-DD` and must exist, and `Time` is ISO 8601 with `T`, seconds, an optional fraction and `Z` or `±HH:MM`. A symbol union takes a symbol's name and gives the Symbol, and a union takes its first member that fits, in declared order. `Array[T]` in a query comes from repeated keys, one value is a one-item array, and `tag[]` is a different key; an `untyped` keyword takes the last value of a key given more than once, and any other keyword given more than once doesn't fit. A record becomes a Hash with Symbol keys, and a class with typed readers is built with `new(**fields)`, both ignoring undeclared keys. `Hash[String, T]` takes a JSON object, empty or not, and coerces each value by `T`, keeping its key a String. An `untyped` path or query value is its String, and an `untyped` part of a body, such as an untyped endpoint's `body:`, is the JSON as it's parsed, with Symbol keys at every level. An empty query value is a value, so `?limit=` doesn't fit `Integer`. A missing required keyword or field is `nil` when it's nullable, and otherwise `is required`. An absent optional keyword isn't passed, so Ruby's default applies, and an absent optional record field is left out. A request that doesn't fit answers a 422 problem+json titled `Unprocessable Content`, whose `errors` list every problem, up to the first 1,000, after which coercion stops, each with where it is (`path.id`, `query.limit`, `body.priority`, `body.tags[1]`, `body.scores["alice"]`, with a hash's key JSON-quoted so a dot or bracket in it is unambiguous, and a key longer than 200 characters cut to 200, ending `…`) and a message, such as `expected :low | :normal | :high, got "urgent"`, whose expected type, when longer than 200 characters, is cut to 200, ending `…`. A query string with unescaped bytes outside ASCII is a 422 at `query`, and a body that isn't JSON, or isn't UTF-8, is a 422 at `body`. The body is read only for an endpoint with `body:`, as [Production](#production) describes, and a missing or empty one is absent.
|
|
685
|
+
- **The request.** An endpoint that takes `request:` is passed a frozen `Skyward::API::Request`, built from the Rack env once on each request, only for an endpoint that takes it or a provided keyword, and passed even when the keyword has a default. It wraps the env rather than subclassing `Rack::Request`, because Skyward API doesn't depend on Rack. `headers` is a frozen Hash of every `HTTP_` variable in the env, named in lowercase with dashes (`request.headers["authorization"]`), along with `content-type` and `content-length`. `cookies` is a frozen Hash read from the `cookie` header, each value percent-decoded with a `+` left as it is, and the first of two cookies with one name wins. `ip` is the client's address as Rack finds it: the remote address, unless it's a trusted proxy (a loopback or private address, `localhost` or a Unix socket), and otherwise the last `X-Forwarded-For` address that isn't one, or the first when every one is, or the remote address when there's no `X-Forwarded-For`, or `nil` with neither. The `Forwarded` header isn't read. `request_id` is the request's ID, and `env` is the env itself.
|
|
686
|
+
- **Providers.** The builder's `provide(name, provider)` registers anything that responds to `call(request)`, such as an object, a lambda or a `Method`, under a Symbol name, and raises `Skyward::Core::BootError` for a name that's already provided, or for `body` or `request`, which Skyward API fills itself. A keyword with a provided name is filled by its provider, never from the query string, and passed even when it has a default. On each request, once a route matches, each provider the endpoint asks for runs once, in keyword order, with the request, the same `Skyward::API::Request` that `request:` gets, before the body is read or any input is coerced, so a caller a provider turns away gets its response rather than a 422 that shows the inputs' shape. When a provider returns a response value (`Skyward::API::Responses::NoContent`, `Skyward::API::Responses::BadRequest`, `Skyward::API::Responses::Unauthorized`, `Skyward::API::Responses::Forbidden`, `Skyward::API::Responses::NotFound`, `Skyward::API::Responses::Conflict`, `Skyward::API::Responses::Unprocessable` or `Skyward::API::Responses::Redirect`), no later provider runs, the method never runs, and the value is answered as Responses below describes, written by the provider's return type, or by its own status for a provider with no signature; anything else it returns, `nil` and a `Skyward::API::Responses::Created` included, is the keyword's value. At boot, Skyward API reads the provider's signature: the `call` of its class, which may be inherited, or a `Method`'s own name, in either case read from the module that defines it. A provider whose `call` is defined on a single object, such as a module with `extend self` or a class with `def self.call`, has no signature Skyward API can read, so boot refuses it: provide an instance of a class. The response values in its return type are added to the document's responses of every endpoint that asks for its name, and the rest of the return type's members must be exactly the keyword's type's members, compared as RBS types in any order, with a `T?` as `T` and `nil`, so several members are compared as their union, and a return type of only response values matches no keyword; boot refuses a keyword that doesn't match. A provider with no signature, or whose `call` returns `untyped`, as a lambda's does, adds no responses and its value isn't checked. A provider that raises is answered with a 500, as Errors below describes, and so is a typed provider's response value that its return type doesn't list, which raises `Skyward::API::ReturnTypeError` naming the provider. A keyword typed `untyped`, nullable or not, as each of an untyped endpoint's keywords is, takes any provider's value unchecked, since untyped code isn't checked anywhere else, and is still filled by its provider, never from the query string, with the provider's responses still added to the endpoint's. With `strict: true`, a signature that types a provided keyword as `untyped`, nullable or not, is refused like one that types any other keyword so, but a provider with no signature, or whose `call` returns `untyped`, doesn't make the endpoints that ask for it untyped, since `strict:` refuses untyped endpoints, not providers.
|
|
687
|
+
- **Responses.** An API's instances have private helpers that return frozen response values, each taking `headers:`: `created(value)` returns a `Skyward::API::Responses::Created[T]`, `no_content` a `Skyward::API::Responses::NoContent`, `bad_request(detail)` a `Skyward::API::Responses::BadRequest`, `unauthorized(detail)` a `Skyward::API::Responses::Unauthorized`, `forbidden(detail)` a `Skyward::API::Responses::Forbidden`, `not_found(detail = nil)` a `Skyward::API::Responses::NotFound`, `conflict(detail)` a `Skyward::API::Responses::Conflict`, `unprocessable(detail)` a `Skyward::API::Responses::Unprocessable` and `redirect(to, status: 303)` a `Skyward::API::Responses::Redirect`. `bad_request`, `unauthorized`, `forbidden` and `redirect` are also public module functions on `Skyward`, such as `Skyward.unauthorized("Sign in first")`, for code outside an API class. `redirect` raises `ArgumentError` for a `status:` other than 301, 302, 303, 307 or 308, or a `to` with a line break. At boot, each endpoint compiles a serializer for every member of its return type, and a returned value goes to the first member it fits: by class for a class with typed readers and for a response value, and by shape otherwise. A class with typed readers is written by calling each reader it declares, never `to_h`, and a record is read from a Hash by its declared keys, leaving out an optional key that's absent, so nothing undeclared is ever written. Integers, Floats, Strings and booleans are written as JSON, an enum's Symbol as its name, a `Date` as `YYYY-MM-DD`, a `Time` in UTC as ISO 8601 with six fractional digits (`2026-10-18T09:30:00.123456Z`), and `nil` only where the type is nullable. A `Hash[String, T]` writes each value as `T`, so a value's undeclared fields are dropped too, and String or Symbol keys as strings; a Hash with any other key doesn't fit it. A plain value answers 200 with `content-type: application/json`; `Skyward::API::Responses::Created[T]` answers 201 with its value written as `T`; `Skyward::API::Responses::NoContent` answers 204 with no body; `Skyward::API::Responses::BadRequest`, `Skyward::API::Responses::Unauthorized`, `Skyward::API::Responses::Forbidden`, `Skyward::API::Responses::NotFound`, `Skyward::API::Responses::Conflict` and `Skyward::API::Responses::Unprocessable` answer 400, 401, 403, 404, 409 and 422 with RFC 9457 `application/problem+json`, whose `detail` appears only when given; and `Skyward::API::Responses::Redirect` answers its status with a `location` header and no body. A response value's `headers:` are added to its response, and Skyward adds no `WWW-Authenticate` to a 401, so pass it in `headers:`. A part typed `untyped` is written as untyped code's is: scalars as themselves, Symbols as their names, dates and times as above, Hashes and Arrays item by item, and anything else through `to_h`; a return type of `untyped` also answers each response value with its own status. A value, or any part of it, that doesn't fit its type raises `Skyward::API::ReturnTypeError` before anything is written, naming the endpoint's label, what came back (a scalar's value, or else only its class) and where, and the type it should have been, so it's answered with a 500 as Errors below describes. Skyward API's signatures declare `Skyward::API::rack` as `[Integer, Hash[String, String], untyped]`, and a member typed with it, or with that tuple written out, takes an Array of an Integer, a Hash and a body, and sends it as given, without checking or rewriting any of it, so a body that streams through `each` or `call` works. An `Array[T]` member is always JSON, even for three items. The request ID is still added to a triple, and `HEAD` drops its body, closing it when it responds to `close`. An untyped endpoint's return type is `untyped`, so it's answered the same way. An untyped endpoint's Rack triples are still to come.
|
|
688
|
+
- **OpenAPI document.** With `Skyward.app(docs: true)`, the app builds its OpenAPI 3.1 document once, at boot, and answers GET and HEAD at `/openapi.json` with it as `application/json`, before any route or static file. The same app always writes the same bytes. Its `info` has `Skyward.app`'s `title:` (`"API"` by default), `version:` (`"0.1.0"` by default) and, when given, `description:`. Each API class is a tag, in mount order, with its `description`, and each route is an operation under its path, with each path parameter as `{name}`, tagged with its class, with its `summary:` and `description:` when given and the operation ID `<Tag>_<method>`; a tag is the class's constant path with `::` as `.`. A path keyword is a required parameter, and a query keyword is a parameter, required when the method requires it and it isn't nullable, whose schema leaves out `null`. `body:` is an `application/json` request body, required on the same terms. Each member of the return type is a response: a plain type a 200 `application/json`, `Skyward::API::Responses::Created[T]` a 201 of `T`, `Skyward::API::Responses::NoContent` a 204, each problem its status with the `Problem` schema as `application/problem+json`, `Skyward::API::Responses::Redirect` a `3XX` with a `location` header, and `Skyward::API::rack` a `default` with no schema. The response values of each provider the endpoint asks for are its responses too. Members with the same status are one response, `oneOf` their schemas. `request:` and a provided keyword aren't part of the HTTP contract, so neither is a parameter, schema or component, or counts as an input. An endpoint with other keywords also lists 422, and one with `body:` 413 and 415, and the responses are ordered by status. `Integer`, `Float`, `String` and `bool` are `integer`, `number`, `string` and `boolean`, `Date` and `Time` are strings of format `date` and `date-time`, `untyped` is any value, a literal is a `const`, an enum is a string `enum`, `Array[T]` is an `array` of `T`, `Hash[String, T]` is an `object` whose `additionalProperties` is `T`'s schema, so `{}` for `untyped`, a record is an inline `object` with `required` naming its required keys, a union is `oneOf` its members, and a nullable type adds `null` to its `type`, except that a nullable enum, literal, union, class or `untyped` is `anyOf` it and `null`. A class with typed readers is a `$ref` to an `object` component named by its constant path with `::` as `.`, or by `Skyward.app(schema_names:)`. A nullable field is required in a response but not in a request, and a class reached from any keyword gets the request form. The components are ordered by name, and always include `Problem`, with `type`, `title` and `status` required and an optional `detail` and `errors`. With `docs: true`, boot refuses a route whose path is `/openapi.json`, a static file there, two operations with the same ID (which two routes to one method, or a class mounted twice, have), a schema name with anything but letters, digits, `.`, `-` and `_`, and two types with the same schema name, including `Problem`. An `untyped` path or query keyword is a `string`, since that's all either carries, and an untyped endpoint's body and 200 response are any value, `{}`.
|
|
689
|
+
- **API reference.** With `docs: true`, the app also answers GET and HEAD at `/docs`, before any route or static file, with an HTML page built once, at boot, as `text/html; charset=utf-8`. Its title is `Skyward.app`'s `title:`, HTML-escaped. It points Scalar at the document by the relative URL `openapi.json`, so it works under a prefix, and loads Scalar from jsDelivr, as `@scalar/api-reference` 1.75.1's `dist/browser/standalone.js` with its `sha384` integrity hash and `crossorigin="anonymous"`, or else from `Skyward.app(scalar_url:)`, HTML-escaped, with no hash. It has no inline JavaScript: Scalar is configured through `data-url` and `data-configuration`, which turns off its default fonts. Another method at `/docs` is answered as if there were no page, and `/docs/` isn't served. With `docs: true`, boot refuses a route whose path is `/docs`, and a static file there.
|
|
690
|
+
- **Request IDs.** The app `Skyward.app` returns gives every request an ID: an incoming `X-Request-Id` of 1 to 200 visible ASCII characters with no spaces, or else a random UUID from `SecureRandom`. The ID is stored in the Rack env as `skyward.request_id` before anything else runs, and every response carries it as `x-request-id`, replacing one the app set.
|
|
691
|
+
- **HTTP's own answers.** A path that matches routes only under other methods gets a 405 problem+json with an `allow` header listing the methods of every route matching it, in the order `GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS`, with `HEAD` wherever there's `GET` and always `OPTIONS`. `HEAD` runs the GET route and answers its status and headers with an empty body. `OPTIONS` on a routed path answers 204 with `allow`, and on any other path 404. CORS is still to come.
|
|
692
|
+
- **`skyward serve`.** Skyward API registers it with the `skyward` command. It runs the current directory's `config.ru`, needing no `app.rb`, under one Falcon process bound to `localhost`, on `PORT` (9292 by default), with `RACK_ENV=development` unless it's already set. It writes no files. With no `config.ru`, or no Falcon in the bundle `skyward` runs in, it exits 1 saying what to do. Under `bundle exec` that's the app's bundle; run bare, `skyward` sees every installed gem. It reloads the app when a `.rb`, `.rbs` or `config.ru` file under the directory is added, changed or removed, outside `tmp/`, `log/`, `vendor/`, `node_modules/` and hidden directories such as `.git/` and `.bundle/`, polling modification times at most once every half second. The first request after a change clears the routes and description of every API class defined in those files, drops those files from `$LOADED_FEATURES` so their `require`s run again, unloads and unregisters each Zeitwerk loader that manages only directories there (so `config.ru` can set it up again), reloads any other Zeitwerk loader with reloading enabled, and builds a new app from `config.ru`. A loader of the app's own needs reloading enabled: Zeitwerk can't unload one without it, or enable it after setup, so the reload fails saying to call `loader.enable_reloading` in development and restart. One reload runs at a time and requests wait for it, while a request in flight finishes on the app it started with. A load that raises, at boot or on a reload, including a `Skyward::Core::BootError` or a `SyntaxError`, answers every request until the next change retries it with the development 500 described under Errors: `type`, `title`, `status`, `detail` and `backtrace`, and an empty body for `HEAD`. It has no `request_id`, because the app that assigns request IDs is the one that failed to load, and nothing is logged. Only `skyward serve` reloads.
|
|
693
|
+
- **`skyward routes` and `skyward openapi`.** Skyward API registers them with the `skyward` command too. Each loads the current directory's `app.rb`, which must assign `App = Skyward.app { ... }`. With no `app.rb`, or no `App` that's a Skyward app, it exits 1 naming the file and what it must assign, and a `Skyward::Core::BootError` exits 1 with its message and no backtrace. `skyward routes` prints a line per endpoint, in mount order and then declaration order: its verb, full path, `Class#method` and its method type as the signature file writes it, with a type wrapped over several lines put on one, or for an untyped endpoint as `(id: untyped, ?done: untyped) -> untyped`. Each column but the last is as wide as its widest entry, then two spaces. An app with no routes prints nothing. `skyward openapi` writes the document the OpenAPI document bullet above describes, as pretty JSON with a trailing newline, whether or not the app passed `docs: true`, so the same app always writes the same bytes. Without `docs: true`, a route or static file at `/openapi.json` or `/docs` doesn't stop it, but the document's other problems exit 1 with their message.
|
|
694
|
+
- **`skyward check`.** Skyward API registers it with the `skyward` command. It checks the current directory's app three ways, in this order, writing `Signatures:`, `Strict boot:` or `Steep:` and then `passed` or `failed` as each finishes, followed by what it found, and runs every check even after one fails, then exits 1 if any failed and 0 otherwise. rbs-inline, the boot and Steep each run in a Ruby of their own, in the app's directory, with the gems of the bundle `skyward` runs in, as `skyward serve` describes, and nothing is written to the directory. **Signatures** runs rbs-inline, in its default opt-in mode, which reads only files marked `# rbs_inline: enabled`, over every `.rb` file in the directory outside `test/`, `spec/`, `vendor/`, `tmp/` and hidden directories, into a temporary directory. It fails when there's no `sig/generated`, or when the result differs from it, listing each file under `sig/generated` that's missing, out of date or not generated from any file, and either way gives the rbs-inline command that regenerates `sig/generated`. It also fails when rbs-inline does, with its output. **Strict boot** loads `app.rb` as `skyward routes` does, with `SKYWARD_STRICT=1` in the environment, and fails where `skyward routes` would exit 1, with the same message, or on any other error, with its backtrace. It shows the boot's output even when it passes. **Steep** runs `steep check --no-daemon` with the app's `Steepfile`, and passes or fails as Steep does, with its output. Without rbs-inline or Steep in the bundle, or without a `Steepfile`, that check fails saying what to add.
|
|
695
|
+
- **The test client.** `Skyward::API::Test.client(app)` drives any object with `call(env)` in-process, with no server, and never loads Minitest or RSpec. Its `get`, `post`, `put`, `patch`, `delete`, `head` and `options` each take a path, which may include a query string. `json:` sends a JSON body with `content-type: application/json`, and without it no body is sent. `headers:` sends request headers by their HTTP names, and `cookies:` sends a Hash as a `cookie` header. Each returns a frozen response with `status`, `headers` as the app returned them, `body` as text, and `json`, the body parsed with Symbol keys when the content type is JSON or `+json` and the body isn't empty, and `nil` otherwise. The client reads the whole body and closes it when it responds to `close`.
|
|
696
|
+
- **Middleware.** `use` adds Rack middleware, with the same arguments as `Rack::Builder#use`, so CORS comes from rack-cors. Middleware wraps the routes in declaration order, the first `use` outermost, wherever it sits relative to `mount`. Request IDs and request logs sit outside it, so a response from middleware still carries an ID and is logged. The stack is built once, at boot, and the app stays frozen, though the middleware objects themselves aren't frozen. Error handling sits outside it too, so an exception from middleware is still answered with a 500.
|
|
697
|
+
- **Request logs.** Unless `Skyward.app` is given `logger: nil`, every request logs one JSON object on one line, whatever answered it, including a 404 or a 500: `time` (when the request arrived, ISO 8601 in UTC to the millisecond), `method`, `path` (Rack's `SCRIPT_NAME` and `PATH_INFO`, so never the query string), `status`, `duration_ms` (until the app returns its response, to two decimal places) and `request_id`. It writes to `$stdout`, or calls `info` on the `logger:` it's given.
|
|
698
|
+
- **Errors.** A `StandardError` raised inside the app, from an endpoint, serializing its return value, or middleware, is caught just inside the request log, so the request still logs with status 500 and the ID. Other exceptions, like `Interrupt`, aren't caught. The response is a 500 `application/problem+json` with `type`, `title`, `status` and `request_id`, and an empty body for `HEAD`. The exception is logged first, as one JSON line through the `logger:` with `level` (`"error"`), `request_id`, `class`, `message` and `backtrace`, unless `logger: nil`. Then it's handed to `Skyward.app(on_error:)`, anything with `call(exception, env)`; if that raises, its exception is logged the same way and the client still gets the original 500. In development, when `RACK_ENV`, or else `APP_ENV`, is `development`, the body adds `detail` (the exception's class and message) and `backtrace` (an array of lines). Under `skyward serve`, an app that fails to load or reload answers this development 500 too, without a `request_id`, as the `skyward serve` bullet above says.
|
|
699
|
+
- **Static files.** `static` serves a directory's files under a URL prefix, for GET and HEAD, inside the middleware. Its `from:` is resolved against the current directory at boot, and a directory that doesn't exist raises `Skyward::Core::BootError`. A matching route takes precedence over a file, and several `static` calls are tried in order until one has the file. A path routed only under other methods still serves its file to GET and HEAD, and answers the rest with the 405. The prefix itself, or any path ending in `/`, serves that directory's `index.html`. A missing file, a directory without a trailing slash, or a path with a `..` segment, escaped or not, is answered as if there were no `static`: a 404, or a 405 on a path routed under other methods. A file carries a `content-type` from its extension (`application/octet-stream` when unknown), its `content-length`, `last-modified`, an `etag` built from its modification time in nanoseconds and its size, and `cache-control: no-cache`, and `HEAD` answers them with no body. A matching `If-None-Match`, or an `If-Modified-Since` no earlier than the modification time, answers 304 with no body.
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
class Skyward::API::Assembly::Application
|
|
4
|
+
# @rbs @app: Skyward::API::_RackApp
|
|
5
|
+
# @rbs @openapi: ^() -> Skyward::API::OpenAPI::schema
|
|
6
|
+
|
|
7
|
+
# @dynamic endpoints
|
|
8
|
+
attr_reader :endpoints #: Array[Skyward::API::Routing::Router::Endpoint]
|
|
9
|
+
|
|
10
|
+
# @rbs (Skyward::API::_RackApp app, endpoints: Array[Skyward::API::Routing::Router::Endpoint],
|
|
11
|
+
# openapi: ^() -> Skyward::API::OpenAPI::schema) -> void
|
|
12
|
+
def initialize(app, endpoints:, openapi:)
|
|
13
|
+
@app = app
|
|
14
|
+
@endpoints = endpoints
|
|
15
|
+
@openapi = openapi
|
|
16
|
+
freeze
|
|
17
|
+
end
|
|
18
|
+
|
|
19
|
+
# @rbs env: Hash[String, untyped]
|
|
20
|
+
# @rbs return: Skyward::API::rack_response
|
|
21
|
+
def call(env) = @app.call(env)
|
|
22
|
+
|
|
23
|
+
# Built when asked for, because only an app with docs: true refuses to boot over a document that can't be built.
|
|
24
|
+
# @rbs return: Skyward::API::OpenAPI::schema
|
|
25
|
+
def openapi = @openapi.call
|
|
26
|
+
end
|