96 Commits

Author SHA1 Message Date
Bob Farrell
7339641401 Refactoring 2024-06-01 16:20:16 +01:00
Froxcey
f538b0ddce Fix Compression Middleware
Checks "Accept-Encoding" header, add deflate encoding, rename the
middleware, and avoid unnecessary encoding.
2024-06-01 16:17:45 +01:00
Froxcey
4ea023ee5a Use gzip in demo 2024-06-01 16:17:45 +01:00
Bob Farrell
887e4e551b Middleware request resolution
Allow middleware to resolve a request by calling `request.redirect` or
`request.render` - after this point, the request stops processing and
renders immediately.
2024-05-27 16:38:11 +01:00
Bob Farrell
b6b67f8dd6 Use http.zig arena pool 2024-05-26 21:37:48 +01:00
Bob Farrell
80ca764c0f Update Zmpl for template inheritance
Permit setting template during view render with `request.setTemplate()`

Permit middleware to define custom routes to static content with
`pub const Routes` (implemented for something no longer needed but seems
useful anyway).

Implement globbing on custom routes, `/foo/:bar*` will glob all path
segments including and after `/foo/...`, e.g. `/foo/bar/baz/qux` will
pass invoke the custom view function with an array of `bar`, `baz`,
`qux` as first argument (instead of typical resource ID).
2024-05-26 17:20:21 +01:00
Bob Farrell
77794cd34d Implement custom routes
In `main()`:

```zig
    app.route(.GET, "/custom/:id/foo/bar", @import("app/views/custom/foo.zig"), .bar);
```

Routes `GET` request with path (e.g.) `/custom/1234/foo/bar` to `bar()`
defined in `src/app/views/custom/foo.zig`.

Routes with an `:id` segment expect a function with three parameters,
routes without an `:id` segment expect a function with two parameters
(i.e. the same as `get` vs `index`).
2024-05-22 20:49:41 +01:00
Bob Farrell
3b30ab4625 Update build.zig and deps for 0.13 build system 2024-05-21 19:42:56 +01:00
Bob Farrell
3519483f34 Switch to http.zig
Use Karl Seguin's http.zig as HTTP server backend:
https://github.com/karlseguin/http.zig

Update loggers to use new `jetzig.loggers.LogQueue` to offload logging
to a background thread.

Numerous other optimizations to remove unneeded allocs.

Performance jump on a simple request from approx. 2k requests/second to
approx. 40k requests/second (Intel(R) Core(TM) i7-6700K CPU @ 4.00GHz).

Color support for Windows

Zmpl partial arg type coercion
2024-05-12 21:33:26 +01:00
Bob Farrell
65edd20092 Allow mailers to modify mail template params
Remove need to add all mail template params to view response data. This
was originally intended functionality but the wrong value was passed to
the `deliver` function, and no `data` argument was given, making it
cumbersome to create new values.
2024-05-05 20:04:57 +01:00
Bob Farrell
b7d750c54f Formalise JetKV interface for store, cache, jobs
Provide configuration for JetKV backend (memory or file allocator).
2024-05-05 12:27:59 +01:00
Bob Farrell
1ea3f6c4ff Fix session nonce re-use
Use a new secure-random nonce for each session encryption.

Many thanks to @Trundle for writing [this gist](https://gist.github.com/Trundle/76c0d8f80999617f4d8373c03f86391a)
highlighting the severity of this issue.
2024-05-01 20:51:39 +01:00
Bob Farrell
1c7df8a91d Custom error pages
Render `src/app/views/errors.zig` view (`index` action) when an
unexpected error occurs. If the view does not exist, try rendering
`public/404.html`, `public/500.html` (etc.), finally falling back to a
standard basic HTML/JSON response.
2024-04-28 11:54:05 +01:00
Bob Farrell
6b940e8a53 0.13 support
Add support for 0.13. For now, we can be compatible with both 0.12 and
0.13. We will drop 0.12 after a while.
2024-04-27 23:03:53 +01:00
Bob Farrell
9d12b5c717 Update Zmpl, adds Markdown mode formatters
Also adds support for `.md.zmpl` templates - root node is Markdown.
2024-04-27 22:22:30 +01:00
Bob Farrell
47c35632b5 Email framework
Create mailers with `jetzig generate mailer <name>`. Mailers define
default values for email fields (e.g. subject, from address, etc.).
Mailers use Zmpl for rendering text/HTML parts.

Send an email from a request with `request.mail()`. Call
`deliver(.background, .{})` on the return value to use the built-in
mail job to send the email asynchronously.

Improve query/HTTP request body param parsing - unescape `+` and `%XX`
characters.
2024-04-21 21:00:03 +01:00
Bob Farrell
3f6c1a4919 Remove temporary test file 2024-04-15 21:16:02 +01:00
Bob Farrell
0c7a11497f Background jobs
Use in-memory KV store (JetKV) for simple job queue.

Build script generates an array of Zig modules in `src/app/jobs/` and
stores their name + run function (`run(allocator, params, logger)`).

View functions schedule jobs with arbitrary params.

Thread pool spawns a (configurable) number of workers and pops jobs from
the queue, then invokes the appropriate run function.
2024-04-15 18:12:40 +01:00
Bob Farrell
16204a4832 Zmpl v2
Update to Zmpl v2, update demo app to be compatible with v2 syntax. Add
deprecation warning for v1 (v1 is default for now - will force v2 soon).
2024-04-07 10:34:34 +01:00
Bob Farrell
4579d6c029 Closes #53: Add support for empty HTTP query param
When query param is empty, use `jetzig.data.Data.NullType` - this way
the value is still non-null (i.e. can be captured) and is still a
`jetzig.data.Value` so is consistent with previous implementation.

Add very weird bugfix for 404 responses.

Fix `Bad Request` response code.
2024-04-06 20:20:47 +01:00
Bob Farrell
116668be3e Closes #48: Simplify route generation
Generate an array of `jetzig.views.Route` in `GenerateRoutes.zig` exe
instead of a meta-route that we later translate into an actual route.
This makes things much simpler for static routes at build time and
dynamic routes at run time as we no longer need to use comptime - we
just have an array of routes ready-made.
2024-04-02 21:02:27 +01:00
Bob Farrell
29d13917a6 Add a dependency to demo app
Use as a regression test to ensure dependencies always work.
2024-03-28 21:07:16 +00:00
Bob Farrell
13e77b4520 Implement nested routes
Allow creating routes nested in sub directories of arbitrary depth in
`src/app/views/`.
2024-03-27 19:58:20 +00:00
Bob Farrell
0e29934718 Implement Markdown
Create `.md` files instead of `.zmpl` files to render static markdown
content.
2024-03-26 22:20:27 +00:00
Froxcey
0de6445539
Add DS_Store to gitignore 2024-03-25 00:55:37 +08:00
Bob Farrell
cc0a1c5792 Document default config values in init project 2024-03-20 21:26:59 +00:00
Bob Farrell
381c38d85d Overhaul logging, implement JSON logger
Log errors to separate files, specify minimum log level, implement JSON
logging.
2024-03-20 21:17:14 +00:00
Bob Farrell
87bcc4c9e0 Provide tooling for running Jetzig in deployment 2024-03-19 23:03:55 +00:00
Bob Farrell
993caa5d3f Implement redirects + htmx redirect support 2024-03-17 18:37:45 +00:00
Bob Farrell
60d27d9a6c Implement htmx middleware
When `HX-Target` header is present, bypass any configured layout for the
request. This allows a full page reload to render with a layout, i.e.
render the entire page, while a request from htmx will load just the
content directly generated by the view.
2024-03-17 18:36:32 +00:00
Bob Farrell
aa036fde8b Implement layouts
Latest Zmpl provides `template.renderWithLayout(other_template, data)`,
allowing a template to be renedered within another template.

Create layouts in `src/app/views/layouts/` or use
`jetzig generate layout [name]` and set `pub const layout = "name";` in
each view file.
2024-03-11 22:36:18 +00:00
Bob Farrell
a78d53a19a Allow importing .zig files from src/ in views
Views are copied to zig-cache, meaning that any files in `src/` are not
available for `@import` by default. Copy all .zig files from `src/` into
zig-cache so that relative imports work as expected. This also removes
the need to specifically copy views into zig-cache as the full tree is
now present.

Also fix a bug in static route fallback - remove superfluous underscore
so static routes with non-matching params render default HTML/JSON
content.
2024-03-10 14:10:53 +00:00
Bob Farrell
97d66aa6be Streamline project build.zig
Offload as much work as possible into new `jetzigInit` function provided
by Jetzig's `build.zig`. This means that a new Jetzig project's
`build.zig` is now almost completely vanilla with the exception of two
extra lines:

```zig
const jetzig = @import("jetzig");
```

```zig
    try jetzig.jetzigInit(b, exe, .{});
```
2024-03-10 10:06:36 +00:00
Bob Farrell
f954439489 CLI generate command
Provide `jetzig generate ...` commands for views, middleware, and
partials.
2024-03-09 18:47:08 +00:00
Bob Farrell
d5a8f247d7 Fix HTML bug in project init source template
Typo - remove unwanted closing div tag. Tag is a multi-line block,
resulting in a superfluous `</div>` and generating incoherent HTML.
2024-03-09 13:03:57 +00:00
Bob Farrell
3a91bbea48 Skip parsing functions that are not in Route.Action enum
Allow custom functions with arbitrary signatures and avoid any issues of
trying to parse functions that are not Jeztig route action functions
(i.e. index, get, post, put, patch, delete).
2024-03-09 11:43:44 +00:00
Bob Farrell
d3a3582136 Implement init command, get rid of old init script/artifacts
Remove old bash script for setting up a new project, do everything in
Zig to make it platform agnostic and give us an easy place to add
scaffolding commands in future.
2024-03-06 22:57:11 +00:00
Bob Farrell
29f4771264 Upgrade Zmpl (latest version provides partials), fix mime map memory leak 2024-03-03 14:12:35 +00:00
Bob Farrell
6ea210259d std.http overhaul
Andrew overhauled std.http to avoid allocations and put control of
connection + stream into hands of users. For now, do a barebones
implementation to restore compatibility, later we can do keepalive and
pipelining. For now, still getting decent enough performance the "slow"
way.

Relevant commit: 6395ba852a

Commit message copied here for posterity:

> Author: Andrew Kelley <andrew@ziglang.org>
> Date:   Tue Feb 20 03:30:51 2024 -0700
> std.http.Server: rework the API entirely
> Mainly, this removes the poorly named `wait`, `send`, `finish`
> functions, which all operated on the same "Response" object, which was
> actually being used as the request.
>
> Now, it looks like this:
> 1. std.net.Server.accept() gives you a std.net.Server.Connection
> 2. std.http.Server.init() with the connection
> 3. Server.receiveHead() gives you a Request
> 4. Request.reader() gives you a body reader
> 5. Request.respond() is a one-shot, or Request.respondStreaming() creates
>    a Response
> 6. Response.writer() gives you a body writer
> 7. Response.end() finishes the response; Response.endChunked() allows
>    passing response trailers.
>
> In other words, the type system now guides the API user down the correct
> path.
>
> receiveHead allows extra bytes to be read into the read buffer, and then
> will reuse those bytes for the body or the next request upon connection
> reuse.
>
> respond(), the one-shot function, will send the entire response in one
> syscall.
>
> Streaming response bodies no longer wastefully wraps every call to write
> with a chunk header and trailer; instead it only sends the HTTP chunk
> wrapper when flushing. This means the user can still control when it
> happens but it also does not add unnecessary chunks.
>
> Empirically, in my example project that uses this API, the usage code is
> significantly less noisy, it has less error handling while handling
> errors more correctly, it's more obvious what is happening, and it is
> syscall-optimal.
>
> Additionally:
> * Uncouple std.http.HeadParser from protocol.zig
> * Delete std.Server.Connection; use std.net.Server.Connection instead.
>   - The API user supplies the read buffer when initializing the
>     http.Server, and it is used for the HTTP head as well as a buffer
>     for reading the body into.
> * Replace and document the State enum. No longer is there both "start"
>   and "first".
2024-03-01 22:47:11 +00:00
Bob Farrell
d855b9f703 Implement MIME type inference
When serving content from `public/`, use MIME type lookup to provide an
appropriate content-type header.

MIME types borrowed from:

  https://mimetype.io/all-types
  https://github.com/patrickmccallum/mimetype-io/blob/master/src/mimeData.json
2024-02-26 22:38:43 +00:00
Bob Farrell
be85c13369 Provide interface for adding response headers 2024-02-25 14:20:22 +00:00
Bob Farrell
a07c71e725 Refactor response interface
Create `jetzig.http.Response` when `std.http.Server.Response` is created
and delegate all management of `std.http.Server.Response` to
`jetzig.http.Response`. Using this internally means we use the same
internal interface for the `Response` as the user, which gives us things
like response headers management in views for free (user simply calls
`request.response.headers.append()` etc.).
2024-02-25 10:32:34 +00:00
Bob Farrell
216b86c235 JSON and query param parsing/SSG params
Implement `jetzig.http.Request.params()` which parses either a JSON
request body or a query param string into a `jetzig.data.Value`.

Allow configuring params for static site generation - configure an array
of params for each endpoint which is then parsed at build time and a
separate JSON and HTML output is generated for each by invoking the
relevant view function and passing in resource ID/params. Params are
stored in generated `routes.zig` for route matching at run time.
2024-02-25 09:25:00 +00:00
Bob Farrell
280f1eaadd Update to latest Zmpl version
Fix a few bits of breakage with build - Jetzig does not have an
executable, use `demo/` which links to local Jetzig to test features.
2024-02-18 18:42:46 +00:00
Bob Farrell
d52aed8a9b PR feedback
Remove `anyerror` from example definitions - we only need this in the
struct definition, no need to have explicit error set defined in
user-defined view functions.
2024-02-17 15:35:40 +00:00
Bob Farrell
31927cdb6b Static routes
Generate views defined with `request: *jetzig.http.StaticRequest` as
static content into `static/` directory so that exported JSON and HTML
can be rendered direct from disk, skipping runtime rendering.
2024-02-17 15:28:27 +00:00