4 Commits
Author SHA1 Message Date
Runway 9144c206be Runway 1.2.0 2026-10-30 11:24:46 -06:00
Runway 5fa0c1ef9f Runway 1.1.2 2026-10-29 12:42:22 -06:00
Runway 67d61f339c Runway 1.1.1 2026-10-29 11:41:13 -06:00
Runway 07d5bd7e9a Runway 1.1.0 2026-10-29 09:22:38 -06:00
268 changed files with 24712 additions and 377 deletions

No files matched your search

+404
View File
@@ -2,6 +2,410 @@
All notable changes are recorded here. Versions follow [Semantic Versioning](https://semver.org/). All notable changes are recorded here. Versions follow [Semantic Versioning](https://semver.org/).
## [1.2.0] — 2026-10-30
_A minor release: a site's audit journal records its backups (saved, downloaded, deleted, restored), a restore no
longer erases the site's logs, password settings are never filled in by the browser with your console login, and
the plugin contract gains one method (SPI `1.2.0`: `PluginSettings.savedApp`) that the database plugins 2.0.0 use for
their connection tests. Every plugin that runs on 1.1.2 loads unchanged._
### Upgrading — read this first
**From `1.1.2`: a kernel upgrade, no flag.** From `1.1.1`, `1.1.0`, `1.0.1` or `1.0.0`, read the *Upgrading*
sections of the releases in between first, then install this release directly. Paths are the installer defaults
(`/opt/runway`, `/opt/runway-data`).
**The database plugins.** `database`, `database-postgresql` and `database-mariadb` 1.0.0 keep running on this
release unchanged. Their 2.0.0, released with it, needs it: the server's settings move from the `database` plugin to
the provider plugin, and the connection tests move to the `database` plugin's settings page. Upgrade the kernel
first, then those three plugins together, and move the settings **before** saving the `database` plugin's settings
form (Administration §11.1, *Upgrading from database 1.x*; the plugins' own release notes).
**1. Back up.** Take each site's backup (**Backups**) and copy `/opt/runway-data/external/` somewhere **outside**
`external/plugins/`.
**2. Upgrade the kernel:**
```bash
chmod +x runway-1.2.0.bin
sudo ./runway-1.2.0.bin -y
```
The essential plugin moves with the kernel to `1.2.0` (its two settings pages mark the reCAPTCHA secret as a new
password), so the installer refreshes it; expect these lines, once (a template you edited is backed up instead, and
the line names the copy):
```
refreshing bundled plugin 'protection' from this release (it moves with the kernel; files you edited are backed up)
plugin 'protection': plugin.yml replaced (the previous one kept as plugin.yml.bak, for a rollback)
plugin 'protection': runway-plugin-protection.jar replaced (the previous one kept as runway-plugin-protection.jar.bak, for a rollback)
plugin 'protection': templates/admin-app.html updated (unchanged since it was installed — no backup needed)
plugin 'protection': templates/site-protection.html updated (unchanged since it was installed — no backup needed)
keeping the bundled plugins in the release: /opt/runway-1.2.0/seed/ (the repair copy — Administration §12)
```
**3. Check.**
- **About Runway** shows `1.2.0`.
- On **Plugins**, every row is *Loaded* and none *Blocked*; protection shows `1.2.0`.
- On a site's console, save a backup (**Backups**, *Save a backup on the server*): the site's **Logs** journal
shows `backup.saved` with your name and the backup's.
**4. Rollback**, if needed: `sudo bash runway-1.1.2.bin -y` puts 1.1.2 back, its protection files included. Nothing
this release saves is read differently by 1.1.2. Put the database plugins back to 1.0.0 first if you moved them to
2.0.0 (with the server's settings back in `database.yml`): 2.0.0 needs SPI `1.2.0` and is refused by 1.1.2.
### Added
- **SPI 1.2.0: `PluginSettings.savedApp(key)`.** A plugin can read one of its own app-level settings as it is saved
now, before the restart that applies it (a secret in clear), so it can check a change first. The database plugins
2.0.0 use it for their connection test. Existing plugins load unchanged: the method only adds to the contract. See
`docs/SPI-STABILITY.md`.
- **The site's audit journal records backups.** On the site console, saving a backup on the server (`backup.saved`),
downloading one (`backup.downloaded`: `full`, `transfer`, or `full` and a saved backup's name),
deleting one (`backup.deleted`) and restoring the site (`site.restored`) are now journal lines, with who did it. A
refused act writes nothing. On the application console, downloads join the platform's activity log, which already
had saves, deletes and restores.
- **Journal labels for every recorded action.** User changes (`user.updated`, `user.suspended`, `user.resumed`) and
static-file changes (`static.uploaded`, `static.folder-created`, `static.deleted`) were recorded but shown only by
their key; they now have English and Spanish labels like the others.
### Fixed
- **A restore erased the site's logs.** A restore replaced the whole site folder, and a backup never carries logs
or stats, so the access log and the audit journal started again from nothing (the bandwidth history file too,
until its next periodic save rewrote it from memory). A restore now keeps both folders; if it is interrupted, or
the logs cannot be carried over at once, the next restore of the site or the next start finishes it. Logs or
stats inside an archive are ignored: no backup writes them.
- **A restore could lose the site it replaced.** If a log line was written in the instant between moving the site
folder aside and moving the restored copy in, the site folder came back holding only logs: the restore failed, the
rollback was skipped, and the next start deleted the previous copy. That folder is now set aside and the move
retried, and a folder without a `site.yml` is never taken for the site.
- **A browser could fill a plugin's password setting with your own console login.** On a plugin's settings page, a
text box followed by a password box looks like a login form, and browsers fill it in with the saved console
username and password, ignoring `autocomplete="off"`. A save would then store your console password as the
plugin's credential. Password settings (plugin and widget settings, the protection plugin's CAPTCHA secret, a
master administrator's password reset) are now marked as new passwords, which browsers do not fill in.
## [1.1.2] — 2026-10-29
_A patch release: the access log now records every public request that gets past the protection edge, including the
ones a filter answers on its own: login attempts, refused form posts, a suspended or maintenance site, a slow body's
`408`, an oversized form's `413`, plugin routes such as `robots.txt` and the sitemap._
### Upgrading — read this first
**From `1.1.1`: a kernel upgrade, no flag.** From `1.1.0`, `1.0.1` or `1.0.0`, read `1.1.1`'s and `1.1.0`'s
*Upgrading* first, then install this release directly. Paths are the installer defaults (`/opt/runway`,
`/opt/runway-data`).
**Your access log will carry more lines.** Nothing is removed and the line format is unchanged, but requests that
used to leave no line now leave one: in the `runway.access` stream and in each site's own access log (its **Logs**
screen). Expect, among others, `POST /login -> 302` for a login attempt, `POST /login -> 403` for a form post refused
for its missing token, `-> 503` while a site is suspended, in maintenance or over its quota, `-> 408` for a refused
slow body, `-> 413` for a `PUT`/`PATCH`/`DELETE` form over `runway.endpoints.max-form-bytes`, and `GET /robots.txt`,
`GET /sitemap.xml` and other plugin routes. A tool that reads `runway.access` (a
log shipper, an alert on `4xx`/`5xx` counts, a ban list fed by failed logins) sees these from now on; check any
threshold that assumed they were absent; under a flood of login attempts that gets past the protection edge, the
`runway.access` stream now grows by one line per attempt, which a journal rate limit may also count. Each site's
**Insights** does not count the refusals (it counts only `GET` page views and `404`s), but it now sees plugin routes:
a page a plugin serves counts as a page view, and a plugin route answering `404` (a missing blog post, an icon the
site has not set) appears among the top 404s. Requests the protection edge turns away (`403`/`429`) still go to
`runway.protect` only, throttled, as before.
**1. Back up.** Take each site's backup (**Backups**) and copy `/opt/runway-data/external/` somewhere **outside**
`external/plugins/`.
**2. Upgrade the kernel:**
```bash
chmod +x runway-1.1.2.bin
sudo ./runway-1.1.2.bin -y
```
The essential plugin moves with the kernel to `1.1.2` (its descriptor changes in version only, and its jar is
rebuilt), so the installer refreshes it; expect these lines, once:
```
refreshing bundled plugin 'protection' from this release (it moves with the kernel; files you edited are backed up)
plugin 'protection': plugin.yml replaced (the previous one kept as plugin.yml.bak, for a rollback)
plugin 'protection': runway-plugin-protection.jar replaced (the previous one kept as runway-plugin-protection.jar.bak, for a rollback)
keeping the bundled plugins in the release: /opt/runway-1.1.2/seed/ (the repair copy — Administration §12)
```
**3. Check.**
- **About Runway** shows `1.1.2`.
- On **Plugins**, every row is *Loaded* and none *Blocked*; protection shows `1.1.2`.
- A login form posted without its token appears in the access log:
`curl -s -o /dev/null -w '%{http_code}\n' -H 'Host: <a site host>' -d 'username=x&password=y' http://127.0.0.1:8080/login`
answers `403`, and `journalctl -u runway --since '-5min' | grep 'runway.access' | grep -c 'POST /login -> 403'` is
at least `1`.
**4. Rollback**, if needed: `sudo bash runway-1.1.1.bin -y` puts 1.1.1 back, its protection files included; those
requests then leave no access-log line again. Nothing this release saves is read differently by 1.1.1.
### Fixed
- **The access log records every public request past the protection edge.** It used to be written by the innermost
filter, so any request answered by a filter further out left no line in either the platform log or the site's
own: every attempt at a site's login page, successful or not (Spring Security answers it itself), a form post
refused for its missing token, the `503` of a suspended, maintenance or over-quota site, a request body refused for
arriving too slowly, a `PUT`/`PATCH`/`DELETE` form refused unread for its size, and every plugin route
(`robots.txt`, the sitemap, `llms.txt`, a plugin's form). A password-guessing run against a site's login was
invisible in its access log. The log is now written just inside the protection edge, from where it sees how each
request was answered. A plugin page served by a route now also counts in **Insights** like any other page.
- **Audit lines are kept ahead of access lines when a site's log queue is full.** Both share one queue
(`runway.logs.queue-capacity`); an eighth of it is now held for audit lines, so a flood that fills it drops access
lines first and keeps the `login.failure` records of the very attack that filled it.
### Documentation
- OPERATIONS §3 (what the access log records, and since when), PLUGIN-DEVELOPMENT (which plugin filters' answers are
logged), SITE-MANAGER-GUIDE §3 and §10 (login attempts and refusals on **Logs**; not counted by **Insights**).
## [1.1.1] — 2026-10-29
_A patch release: the slow-request-body limit 1.1.0 introduced now covers form posts and multipart uploads too, and
after a restore the Backups screen shows how the site is reached, for review._
### Upgrading — read this first
**From `1.1.0`: a kernel upgrade, no flag.** From `1.0.1` or `1.0.0`, read `1.1.0`'s *Upgrading* first (behind a
reverse proxy its step 1 matters), then install this release directly: `1.1.0` itself is not needed in between. Paths
are the installer defaults (`/opt/runway`, `/opt/runway-data`).
**1. Back up.** Take each site's backup (**Backups**) and copy `/opt/runway-data/external/` somewhere **outside**
`external/plugins/`.
**2. Upgrade the kernel:**
```bash
chmod +x runway-1.1.1.bin
sudo ./runway-1.1.1.bin -y
```
The essential plugin moves with the kernel to `1.1.1` (its descriptor changes in version only, and its jar is
rebuilt), so the installer refreshes it; expect these lines, once:
```
refreshing bundled plugin 'protection' from this release (it moves with the kernel; files you edited are backed up)
plugin 'protection': plugin.yml replaced (the previous one kept as plugin.yml.bak, for a rollback)
plugin 'protection': runway-plugin-protection.jar replaced (the previous one kept as runway-plugin-protection.jar.bak, for a rollback)
keeping the bundled plugins in the release: /opt/runway-1.1.1/seed/ (the repair copy — Administration §12)
```
**3. Check.**
- **About Runway** shows `1.1.1`.
- On **Plugins**, every row is *Loaded* and none *Blocked*; protection shows `1.1.1`.
- The start log says `request bodies slower than 4096 bytes/s are refused (runway.http.min-request-data-rate)`, with
your value if you changed it.
**4. Rollback**, if needed: `sudo bash runway-1.1.0.bin -y` puts 1.1.0 back, its protection files included; slow form
posts are then held until the idle timeout again. Nothing this release saves is read differently by 1.1.0.
### Fixed
- **Slow request bodies are refused on every path, as 1.1.0 said they would be.** In 1.1.0
`runway.http.min-request-data-rate` was enforced only where a body was read as a stream. Form posts — every login
form, the console's forms, a plugin's form — and multipart uploads were read past it, so a client trickling one in
still held a request thread until the 30-second idle timeout, as in 1.0.1. Runway now checks the rate on every read
of a request body and answers `408 Request Timeout`: within about two seconds for a steady drip (measured: form and
multipart posts at 20 bytes a second, on both login pages and a plugin's form route), and for a client that pauses
between packets when its next packet arrives, within one idle timeout. Only time spent waiting for the client
counts, and a body that has arrived complete is never refused, however late its last packet came. A proxy that
buffers the whole request body before forwarding it kept such clients off Runway already, in 1.1.0 too.
- **Sending part of a body fast no longer buys a long drip.** 1.1.0 averaged over the whole body, so a client that
sent most of a large one at full speed could then drip the rest for the body's size divided by the rate (16 MiB at
4 KiB/s: over an hour). Bytes sent early now earn at most 30 seconds of waiting.
- **A request refused for a slow body is answered `408`.** Depending on how the code above handled the failed read,
1.1.0 could answer it `400` (a form parser's "unable to parse") or an empty `200`.
### Changed
- **After a restore, the Backups screen shows how the site is reached.** On the application console, after a restore
or after creating a site from a backup, the screen shows the site's hosts and base URL as they now are, with the
same editor as **Sites → Edit hosts**: a restore made there brings back the hosts and base URL saved in the backup,
which may not be how this installation reaches the site. On a site's own console the hosts are shown read-only: a
restore made there keeps them. See `docs/ADMINISTRATION.md` §10.
### Documentation
- **Exempting a same-host proxy's health check from the rate limit** (`docs/ADMINISTRATION.md` §12.4): the proxy sends
its check with a fixed `X-Forwarded-For` that no visitor can produce, and that one address is listed in protection's
allowlist, so the check never shares a rate-limit bucket with a local crawl and loopback stays limited.
## [1.1.0] — 2026-10-29
_A minor release: plugins can keep their data in PostgreSQL or MariaDB through the new database plugins, platform
mail can sign in with OAuth2 (Microsoft 365), the client address is read from the right of `X-Forwarded-For`, slow
request bodies are refused, and password-reset links go only to an address an administrator set. The plugin contract
gains one method (SPI `1.1.0`); every plugin that runs on 1.0.1 loads unchanged._
### Upgrading — read this first
**From `1.0.1` or `1.0.0`: a kernel upgrade, no flag. Behind a reverse proxy, check it first (step 1).** Coming from
an older release: read each newer release's *Upgrading* first, oldest first. Paths are the installer defaults
(`/opt/runway`, `/opt/runway-data`).
**1. Behind a reverse proxy: before you upgrade.** This release reads the client address from the right of
`X-Forwarded-For` and no longer reads the `Forwarded` header (see *Security* and *Changed*). Without a proxy, when
visitors reach Runway directly, skip this step.
- **List every proxy of yours in `runway.proxy.trusted-cidrs`:** the reverse proxy and anything in front of it, such
as a CDN, a load balancer or a second proxy (for a CDN, its published address ranges). Runway now walks
`X-Forwarded-For` from the right and stops at the first address that is not listed. An outer hop that is missing
from the list becomes every visitor's address, so all visitors share one set of login lockouts and rate limits.
Until now the leftmost entry was used, so a missing outer hop went unnoticed.
- **A proxy that sends only `Forwarded`** must be set to send `X-Forwarded-For`, `X-Forwarded-Proto` and
`X-Forwarded-Host` instead. Otherwise every visitor appears as the proxy, and the scheme and host as the proxy's
connection.
- **Recommended for every release:** the proxy sets `X-Forwarded-Proto` and `X-Forwarded-Host` and deletes
`X-Forwarded-Port`, `X-Forwarded-Prefix` and `X-Forwarded-Ssl`. `docs/ADMINISTRATION.md` §7 has the HAProxy and
nginx lines.
**2. Password-reset links.** A reset link now points at a site's own address and, on the application console, at a
host listed in `runway.console.hosts` or else at the default site's address (see *Security*). A site's address is
its base URL, or else `https://` and its **first** host name, with no port:
- **A site served over plain `http` or on a port other than 443** must have its **base URL** set (**Sites → Edit
hosts**), or its reset links point at `https://` and port 443. The same goes for the default site when
`runway.console.hosts` is not set, for the console's links.
- Where there is no address, the login page no longer offers **Forgot your password?**: on a site with no host name,
or whose first host is `localhost` (as the setup wizard leaves the default site) and that has no base URL; on the
application console, when `runway.console.hosts` is not set and the default site has no such address. To keep it,
set `runway.console.hosts`, or give the default site its public host name first, or a base URL.
- Without `runway.console.hosts`, the default site's address decides where the platform accounts' reset links go,
so its hosts and base URL can now be edited only by the application master or a wildcard administrator, even where
`MANAGE_SITE_HOSTS` is delegated, and a restore made from a site's own console keeps the site's hosts and base URL
instead of the backup's.
See `docs/ADMINISTRATION.md` §8.3.
**3. Back up.** Take each site's backup (**Backups**) and copy `/opt/runway-data/external/` somewhere **outside**
`external/plugins/`.
**4. Upgrade the kernel:**
```bash
chmod +x runway-1.1.0.bin
sudo ./runway-1.1.0.bin -y
```
The essential plugin moves with the kernel to `1.1.0` (its descriptor changes in version only, and its jar is
rebuilt), so the installer refreshes it; expect these lines, once:
```
refreshing bundled plugin 'protection' from this release (it moves with the kernel; files you edited are backed up)
plugin 'protection': plugin.yml replaced (the previous one kept as plugin.yml.bak, for a rollback)
plugin 'protection': runway-plugin-protection.jar replaced (the previous one kept as runway-plugin-protection.jar.bak, for a rollback)
keeping the bundled plugins in the release: /opt/runway-1.1.0/seed/ (the repair copy — Administration §12)
```
**5. Check.**
- **About Runway** shows `1.1.0`.
- On **Plugins**, every row is *Loaded* and none *Blocked*; protection shows `1.1.0`.
- The start log says `plugins: N registered, 0 blocked`.
- Behind a proxy, **About Runway → This request** shows your own public address as the client address, and the
connection as a trusted proxy.
**What changes without any action.** None of these needs a setting changed, unless it affects you:
- **Slow request bodies are refused.** A request body that arrives at fewer than 4096 bytes per second is answered
`408` (`runway.http.min-request-data-rate`; Settings → Server settings → Request limits; `0` turns the check off).
Lower it only if your users upload large files over very slow links.
- **Sign-in lines in a site's audit log now carry the address in full** (`ip=…`). A site's setting to anonymize
client addresses applies to its access log only.
- **Platform mail can sign in with OAuth2 (Microsoft 365).** This is optional; password accounts work as before.
- **Plugins.** Every plugin that runs on 1.0.1 loads unchanged: SPI `1.1.0` only adds a method. This release also
carries:
- the database plugins (`database`, `database-postgresql`, `database-mariadb`) and the `runway-demo-database`
example, all new and optional; see `docs/ADMINISTRATION.md` §11.1;
- demo `2.1.1`, whose feedback form now asks the site's CAPTCHA.
**6. Rollback**, if needed: `sudo bash runway-1.0.1.bin -y` puts 1.0.1 back, its protection files included.
- The database plugins need 1.1.0 and are *Blocked* on 1.0.1; their data stays in the database.
- 1.0.1 has no OAuth2 sign-in, so an OAuth2 mail account stops sending there. Anything 1.0.1 saves to the platform
settings also drops the OAuth2 fields.
### Added
- **SPI 1.1.0: `PluginSettings.appSecret(key)`.** A plugin can now read its own `secret`-typed app-level setting
(`settings:` in `plugin.yml`) in clear: a credential that belongs to the whole installation, such as a database
password. Until now only per-site secrets could be read in clear; an app-level one reached the plugin only in its
encrypted `ENC(...)` form. The value is the one the running application started with, so a change saved on the
console applies after a restart, like every app-level setting. A plugin that uses it declares
`requiresSpi: ">=1.1.0"`. See `docs/SPI-STABILITY.md`.
- **Database plugins, published with this release:** `database`, `database-postgresql` and `database-mariadb`
`1.0.0`, and the example `runway-demo-database` `1.0.0`. Plugins can keep their own data in PostgreSQL 14+ or
MariaDB 10.11+: one schema per site, per-plugin migrations, per-site backup and restore (also between the two
products), and a **Database** screen in the application console. Runway's own data stays on files, and Runway
starts whether or not the database is reachable. See `docs/ADMINISTRATION.md` §11.1.
- **Testkit: `FakePluginSettings.appSecret(key, clearValue)`**, so a plugin's unit tests can hand it an app-level
secret the way the running application would.
- **About Runway → This request.** The request that loaded the page as Runway saw it: the connection it came from and
whether that is a trusted proxy, the `X-Forwarded-For` list as received, the client address Runway used, and the
scheme and host. A reverse-proxy setup (`runway.proxy.*`) can now be checked from the browser. See
`docs/ADMINISTRATION.md` §7.
- **`runway.http.min-request-data-rate`** (default `4096` bytes per second; Settings → Server settings → Request
limits). A request body that arrives more slowly is answered `408 Request Timeout` and its request thread freed. Until now a client sending a byte now and then could
hold a request thread for as long as it kept sending. `server.jetty.connection-idle-timeout` (`30s`, Jetty's own
default) is now stated in the shipped configuration.
- **Platform mail can sign in with an OAuth2 token (Microsoft 365).** Settings → Platform settings → Platform mail
gains a sign-in method: *OAuth2 token*. Runway obtains an access token from the configured token endpoint with a
client ID and client secret (the client-credentials grant), keeps it until shortly before it expires, and signs in
to the mail server with SASL `XOAUTH2`. This is how Microsoft 365 accepts application mail once password sign-in
to SMTP is retired. The client secret is stored encrypted, like the password; an OAuth2 account requires STARTTLS or
implicit TLS and an `https` token endpoint. **Send test email** says whether the token or the mail server failed.
Existing password accounts are unchanged. See `docs/ADMINISTRATION.md` §8.1.
- **A site's audit log records where a sign-in came from.** `login.success`, `login.failure` and `logout` now carry
the client address (`ip=…`), as the application activity log already did; behind a trusted proxy, the visitor's
address. Until now the field was empty. The address is kept in full: a site's setting to anonymize client
addresses applies to its access log only.
### Security
- **The client address behind a trusted proxy is read from the right of `X-Forwarded-For`.** Runway took the
leftmost entry, which the client can write itself: behind a proxy that appends to the header (HAProxy's
`option forwardfor`, nginx's `$proxy_add_x_forwarded_for`), a client could choose the address that rate limits,
login lockouts, the access log and plugins saw. Runway now skips the addresses in `runway.proxy.trusted-cidrs` from
the right and takes the first one that is not a trusted proxy. An entry that is not an IP address there attributes
the request to the proxy. **Every proxy in front of Runway, a CDN included, must now be listed in
`trusted-cidrs`** (*Upgrading*, step 1).
- **A password-reset email no longer links to the host name the request named.** The link was built from the
request's `Host` (or the `X-Forwarded-Host` of a trusted proxy), so anyone could have the platform mail a real user
a genuine reset link pointing at a site of the sender's choosing, and take over the account if the link was
opened. A site's link now points at the site's own address (its base URL, or its first host name), and the
application console's at a host listed in `runway.console.hosts` (spelled and, if listed with one, numbered as
listed) or else at the default site's address. Where there is no such address, or only `localhost`, "Forgot your
password?" is not offered. See `docs/ADMINISTRATION.md` §8.3.
- **Only a platform administrator can change where the console's reset links go.** Without `runway.console.hosts`
they go to the default site's address, which anyone holding the delegable `MANAGE_SITE_HOSTS` permission could
edit, and a site manager could set through a restore of a backup file they wrote. The default site's hosts and
base URL now need the application master or a wildcard administrator, and a restore made from a site's own
console keeps the site's hosts and base URL.
- **A stored platform-mail secret is no longer sent to a server it was not saved for.** A blank password field kept
the stored password even when the same save changed the mail host, so anyone allowed to edit Platform settings
could point the account at a server of theirs and receive the password at the next send, without knowing it. The
password is now kept only while the host, port and username stay the same, and the OAuth2 client secret only while
the token endpoint, client ID, mail server and scope do (the token minted from it goes to the mail server);
otherwise the password is cleared and must be entered again, and an OAuth2
account is not saved without its secret. The activity log's `platform.settings-changed` line now names the
settings each save changed (never their values). See `docs/ADMINISTRATION.md` §8.1.
### Changed
- **The standard `Forwarded` header (RFC 7239) is no longer read**, even from a trusted proxy; Runway reads the
`X-Forwarded-*` headers only. A client could otherwise send its own `Forwarded` through a proxy that manages only
`X-Forwarded-*` and choose its address, host and scheme. A proxy that sends only `Forwarded` must send
`X-Forwarded-For`, `X-Forwarded-Proto` and `X-Forwarded-Host` instead.
### Fixed
- **`PluginSiteFiles.readText`, `stat` and `list` no longer report a file or folder they cannot reach as absent.**
When a folder cannot be searched (its permissions, a stale network mount), these calls now throw `IOException`, as
their contract said; only a path that is certainly not there answers empty. A plugin that treated "absent" as "start
afresh" could otherwise act on a passing read failure. The testkit's `TempDirSiteFiles` behaves the same way.
- **`Sites.find` no longer answers "no such site" for a site whose folder it cannot read.** It throws instead, so a
plugin cannot take a live site for a deleted one; site lists leave such a site out and log it, as before.
## [1.0.1] — 2026-10-21 ## [1.0.1] — 2026-10-21
_A patch release: every first-party plugin is now published with Runway — blog, carousel-manager, contact and _A patch release: every first-party plugin is now published with Runway — blog, carousel-manager, contact and
+7 -5
View File
@@ -10,7 +10,7 @@ feature delivered as a plugin or a first-class SPI implementation.
| Version | `1.0.0` (plugin contract: SPI `1.0.0`) — the exact version is in the root `pom.xml` and each release in [CHANGELOG.md](CHANGELOG.md) | | Version | `1.0.0` (plugin contract: SPI `1.0.0`) — the exact version is in the root `pom.xml` and each release in [CHANGELOG.md](CHANGELOG.md) |
| Java | 25+ | | Java | 25+ |
| Framework | Spring Boot 4 on embedded Jetty | | Framework | Spring Boot 4 on embedded Jetty |
| Storage | Filesystem / YAML (no database) | | Storage | Filesystem / YAML (no database); plugins may use PostgreSQL or MariaDB through the database plugins |
| Status | **Stable.** Semantic Versioning from `1.0.0`. The kernel, both realms, the setup wizard (with a catch-all default site), the page editor, per-site backups and optional in-app TLS termination run today; open items are in [docs/KNOWN-LIMITATIONS.md](docs/KNOWN-LIMITATIONS.md). | | Status | **Stable.** Semantic Versioning from `1.0.0`. The kernel, both realms, the setup wizard (with a catch-all default site), the page editor, per-site backups and optional in-app TLS termination run today; open items are in [docs/KNOWN-LIMITATIONS.md](docs/KNOWN-LIMITATIONS.md). |
## Modules ## Modules
@@ -23,11 +23,13 @@ runway/ reactor (this pom)
├── runway-plugin-protection/ the essential protection plugin (rate-limit edge guard, login gate, CAPTCHA; ├── runway-plugin-protection/ the essential protection plugin (rate-limit edge guard, login gate, CAPTCHA;
│ shipped inside the installer and seeded on a fresh install) │ shipped inside the installer and seeded on a fresh install)
├── runway-dist/ packaging only: the dist zip, the self-extracting .bin installer, checksums ├── runway-dist/ packaging only: the dist zip, the self-extracting .bin installer, checksums
└── plugins/ the plugins demo, search, search-lucene, lucene-provider (not reactor modules) └── plugins/ every first-party plugin, each a standalone project (not reactor modules)
``` ```
The plugins under `plugins/` are **standalone** projects, each with its own build; one with code is built The plugins under `plugins/` are **standalone** projects, each with its own build; one with code is built
against `runway-spi` alone as a `provided` dependency (with `runway-spi-testkit` for its tests). A plugin that links `runway-app` classes is refused at against `runway-spi` as a `provided` dependency (with `runway-spi-testkit` for its tests), plus another plugin's
published SPI when it implements or uses one (search-lucene uses search's; the database providers and the guestbook
example use database's). A plugin that links `runway-app` classes is refused at
load time — the 1.0 plugin contract is the SPI ([SPI-STABILITY.md](docs/SPI-STABILITY.md)). load time — the 1.0 plugin contract is the SPI ([SPI-STABILITY.md](docs/SPI-STABILITY.md)).
## Quick start ## Quick start
@@ -57,8 +59,8 @@ The installer lays the code under `/opt/runway-<version>`, points `/opt/runway`
keeps editable state (`external/`, `logs/`, `backups/`) in the version-independent keeps editable state (`external/`, `logs/`, `backups/`) in the version-independent
`/opt/runway-data/` so upgrades never clobber it, installs a systemd unit, relabels `/opt/runway-data/` so upgrades never clobber it, installs a systemd unit, relabels
SELinux contexts (required on enforcing RHEL-family hosts), and starts the service. SELinux contexts (required on enforcing RHEL-family hosts), and starts the service.
There is **no database to configure** — Runway is filesystem/YAML-backed; first-run There is **no database to configure** — Runway is filesystem/YAML-backed (plugins that need a database use
configuration happens in the app's own wizard (below). the optional database plugins); first-run configuration happens in the app's own wizard (below).
Confirm it is up: Confirm it is up:
+451 -27
View File
@@ -65,7 +65,7 @@ a listing table's column menu). Day-to-day operational troubleshooting lives in
|---|---| |---|---|
| **OS** | Linux with **systemd** (the installer and unit target it; tested on RHEL-family — Rocky/Fedora/Alma — and Debian-family). macOS/Windows are not covered by the installer. | | **OS** | Linux with **systemd** (the installer and unit target it; tested on RHEL-family — Rocky/Fedora/Alma — and Debian-family). macOS/Windows are not covered by the installer. |
| **Java** | A **JDK or JRE 25+** on the host. A JRE is sufficient — Runway does **not** compile at runtime. The installer auto-detects a 25+ runtime (Zulu, Temurin, generic OpenJDK) or you point it with `--java-home`. | | **Java** | A **JDK or JRE 25+** on the host. A JRE is sufficient — Runway does **not** compile at runtime. The installer auto-detects a 25+ runtime (Zulu, Temurin, generic OpenJDK) or you point it with `--java-home`. |
| **Database** | **None.** The kernel is filesystem/YAML-backed on purpose; there is no SQL server to install or configure, and the first-run wizard never asks for one. A deployment that genuinely needs a database adds it as a plugin. | | **Database** | **None.** The kernel is filesystem/YAML-backed on purpose; there is no SQL server to install or configure, and the first-run wizard never asks for one. Plugins that need one use PostgreSQL or MariaDB through the **database plugins** (§11.1). |
| **CPU / RAM** | Modest. The service runs in one JVM; the shipped heap is `-Xms256m -Xmx1g` (`JAVA_OPTS` in the unit), which suits a small VM. Note the sizing interlock: each Argon2id password verification costs 19–32 MiB, and the hash pool is bounded (`runway.security.max-concurrent-hashes`, default 8) precisely so a login flood cannot exhaust heap — keep `-Xmx` comfortably above `max-concurrent-hashes × memory-cost`. | | **CPU / RAM** | Modest. The service runs in one JVM; the shipped heap is `-Xms256m -Xmx1g` (`JAVA_OPTS` in the unit), which suits a small VM. Note the sizing interlock: each Argon2id password verification costs 19–32 MiB, and the hash pool is bounded (`runway.security.max-concurrent-hashes`, default 8) precisely so a login flood cannot exhaust heap — keep `-Xmx` comfortably above `max-concurrent-hashes × memory-cost`. |
| **Disk** | The code footprint is small (a single fat jar). Plan capacity for **editable state**: `external/` (config + all site folders), `logs/`, and `backups/` (site backup archives can be large — see **§13**). | | **Disk** | The code footprint is small (a single fat jar). Plan capacity for **editable state**: `external/` (config + all site folders), `logs/`, and `backups/` (site backup archives can be large — see **§13**). |
| **Network / ports** | One HTTP listener. By default Runway serves **plain HTTP on port 8080** and expects a reverse proxy (HAProxy/nginx/Caddy) in front to terminate TLS (**§7**). Change the port with `--server.port=` (`RUNWAY_OPTS`). Binding a privileged port (80/443) directly needs `CAP_NET_BIND_SERVICE` — see the unit (**§6**). | | **Network / ports** | One HTTP listener. By default Runway serves **plain HTTP on port 8080** and expects a reverse proxy (HAProxy/nginx/Caddy) in front to terminate TLS (**§7**). Change the port with `--server.port=` (`RUNWAY_OPTS`). Binding a privileged port (80/443) directly needs `CAP_NET_BIND_SERVICE` — see the unit (**§6**). |
@@ -447,7 +447,7 @@ host is bound).
## 7. TLS & reverse-proxy setup ## 7. TLS & reverse-proxy setup
**Trusting forwarded headers (implemented).** Runway honors `X-Forwarded-*`/`Forwarded` headers (client IP, **Trusting forwarded headers (implemented).** Runway honors `X-Forwarded-*` headers (client IP,
host, scheme) **only** from proxy peers you list in `runway.proxy.trusted-cidrs`; from any other peer the host, scheme) **only** from proxy peers you list in `runway.proxy.trusted-cidrs`; from any other peer the
headers are ignored and the raw connection is used, so a directly-reachable instance cannot spoof them. The headers are ignored and the raw connection is used, so a directly-reachable instance cannot spoof them. The
container's own forwarded-header handling is off (`server.forward-headers-strategy: none`) — Runway's gated container's own forwarded-header handling is off (`server.forward-headers-strategy: none`) — Runway's gated
@@ -458,6 +458,48 @@ nothing (every request attributed to its direct peer, logged at startup). A catc
or ranges that add up to one, such as `0.0.0.0/1` with `128.0.0.0/1`) trusts every client to fake its address: or ranges that add up to one, such as `0.0.0.0/1` with `128.0.0.0/1`) trusts every client to fake its address:
Server settings refuses it, and one set in `application.yml` is warned about at startup. Never put a tenant-editable value here — it is an isolation/abuse boundary. Server settings refuses it, and one set in `application.yml` is warned about at startup. Never put a tenant-editable value here — it is an isolation/abuse boundary.
**Which address is the client.** Each proxy *appends* the address it received the request from to
`X-Forwarded-For`, so everything to the left of what your own proxies wrote may have come from the client itself.
Runway therefore reads the list **from the right**: it skips the addresses in `trusted-cidrs` and takes the first
one that is not a proxy you trust. That is the address your nearest trusted proxy saw, and it is what rate limits,
login lockouts, the access log and every plugin see. An entry that is not an IP address where one is needed
(`unknown`, a host name) attributes the request to the proxy instead; Runway never looks names up. So list
**every** proxy of yours in `trusted-cidrs`, a CDN in front of the reverse proxy included, or the client will be
taken to be the outermost one.
**Only the `X-Forwarded-*` headers are read.** The standard `Forwarded` header (RFC 7239) is ignored, even from a
trusted proxy: a client could otherwise send its own `Forwarded` through a proxy that only manages
`X-Forwarded-*` and choose its address, host and scheme. A proxy that sends only `Forwarded` must be set to send
`X-Forwarded-For`, `X-Forwarded-Proto` and `X-Forwarded-Host` instead. From a trusted proxy Runway also applies
`X-Forwarded-Port` and `X-Forwarded-Prefix` (and `X-Forwarded-Ssl`), so whatever of these the proxy does not write
itself comes from the client. The proxy should **set** (replace) `X-Forwarded-Proto` and `X-Forwarded-Host`, and
**delete** the others it does not set:
```
# HAProxy
http-request set-header X-Forwarded-Proto https if { ssl_fc }
http-request set-header X-Forwarded-Proto http if !{ ssl_fc }
http-request set-header X-Forwarded-Host %[req.hdr(host)]
http-request del-header X-Forwarded-Port
http-request del-header X-Forwarded-Prefix
http-request del-header X-Forwarded-Ssl
option forwardfor
```
nginx: `proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;`, `proxy_set_header X-Forwarded-Proto
$scheme;`, `proxy_set_header X-Forwarded-Host $host;`, and `proxy_set_header X-Forwarded-Port "";`,
`proxy_set_header X-Forwarded-Prefix "";`, `proxy_set_header X-Forwarded-Ssl "";` (an empty value removes the
header).
**Check it.** **Settings → About Runway → This request** shows the request that loaded the page as Runway saw it:
the connection it came from and whether that is a trusted proxy, the `X-Forwarded-For` list as received (marked
*ignored* when the peer is not trusted), the client address Runway used, and the scheme and host. Behind a correctly
trusted proxy the client address is your own public address, not the proxy's. To check that a client cannot choose
its address, open the page once with a forged header (a browser extension that adds `X-Forwarded-For: 192.0.2.1`, or
`curl -H 'X-Forwarded-For: 192.0.2.1'` with a signed-in session cookie). Behind a proxy that appends to the header
(`option forwardfor`, `$proxy_add_x_forwarded_for`) the list shows `192.0.2.1` on its left; behind one that replaces
it, `192.0.2.1` does not appear at all. Either way the client address stays yours.
**The host name behind a proxy.** Runway decides which site a request is for, and whether the operator console **The host name behind a proxy.** Runway decides which site a request is for, and whether the operator console
answers (**§8.6**), from the host name it sees: the request's own `Host`, or the forwarded host from a trusted proxy. answers (**§8.6**), from the host name it sees: the request's own `Host`, or the forwarded host from a trusted proxy.
So the proxy must pass the visitor's host name on (`proxy_set_header Host $host;` in nginx, the default in HAProxy So the proxy must pass the visitor's host name on (`proxy_set_header Host $host;` in nginx, the default in HAProxy
@@ -665,9 +707,10 @@ from the configuration metadata shipped in the jar.
| `runway.security.password-strength` | `STANDARD` | Argon2id memory-cost profile for **new** passwords: `STANDARD` (19 MiB) or `HIGH` (32 MiB). The Settings screen can override this (**§8.1**). | | `runway.security.password-strength` | `STANDARD` | Argon2id memory-cost profile for **new** passwords: `STANDARD` (19 MiB) or `HIGH` (32 MiB). The Settings screen can override this (**§8.1**). |
| `runway.security.max-concurrent-hashes` | `8` | Most password hashes computed at once before requests fail "busy" — bounds heap under a login flood. Read once at startup (Settings → Server settings → Capacity, or here); at least `1` — `0` or a negative value stops startup. | | `runway.security.max-concurrent-hashes` | `8` | Most password hashes computed at once before requests fail "busy" — bounds heap under a login flood. Read once at startup (Settings → Server settings → Capacity, or here); at least `1` — `0` or a negative value stops startup. |
| `runway.security.acquire-timeout-millis` | `2000` | How long a request waits for a hashing slot before failing "busy". | | `runway.security.acquire-timeout-millis` | `2000` | How long a request waits for a hashing slot before failing "busy". |
| `runway.security.secret-key` | _(installer-set)_ | Master key for AES-256-GCM encryption of every stored secret (platform SMTP password, per-site CAPTCHA secrets, `secret`-typed plugin settings). The installer generates one on first install and stores it in a root-only systemd drop-in as `RUNWAY_SECURITY_SECRET_KEY` (see `--secret-key`, §3); Spring's relaxed binding maps that env var to this property. **While blank the secret cipher is unavailable and no secret can be saved** — the app console shows a persistent warning on every page until it is set. Holds a real secret — never in the classpath default. | | `runway.security.secret-key` | _(installer-set)_ | Master key for AES-256-GCM encryption of every stored secret (platform SMTP password or OAuth2 client secret, per-site CAPTCHA secrets, `secret`-typed plugin settings). The installer generates one on first install and stores it in a root-only systemd drop-in as `RUNWAY_SECURITY_SECRET_KEY` (see `--secret-key`, §3); Spring's relaxed binding maps that env var to this property. **While blank the secret cipher is unavailable and no secret can be saved** — the app console shows a persistent warning on every page until it is set. Holds a real secret — never in the classpath default. |
| `runway.proxy.forwarded-headers` | `true` | Whether to honor `X-Forwarded-*` / `Forwarded` at all (still only from trusted peers) — see **§7**. | | `runway.proxy.forwarded-headers` | `true` | Whether to honor `X-Forwarded-*` at all (still only from trusted peers; the standard `Forwarded` header is never read) — see **§7**. |
| `runway.proxy.trusted-cidrs` | `127.0.0.1/32`, `::1/128` | Proxy peers whose forwarded headers are trusted. The **bound default is empty** (trust nothing); the shipped file seeds loopback. **§7**. | | `runway.proxy.trusted-cidrs` | `127.0.0.1/32`, `::1/128` | Proxy peers whose forwarded headers are trusted. The **bound default is empty** (trust nothing); the shipped file seeds loopback. **§7**. |
| `runway.http.min-request-data-rate` | `4096` | The slowest a request body may arrive, in **bytes per second**, before Runway answers `408 Request Timeout` and frees the request thread. It applies to every body — login and other forms, multipart uploads, raw bodies alike. Without it a client sending a byte now and then kept a thread for as long as it liked (the idle timeout only limits one stalled read). Only the time spent waiting for the client counts, from the first second of waiting on, so a server slow to start reading is never blamed, and a body that has arrived complete is never refused, however late its last packet came. Sending part of a body fast earns at most 30 seconds of waiting, so a large body cannot buy a long drip; a client pausing between packets is cut when its next packet arrives, within one idle timeout. 4096 (4 KiB/s) is below any real connection; `0` turns the check off. Set on **Settings → Server settings → Request limits**; applies after a restart. |
| `runway.i18n.cache-seconds` | `5` | How often a message lookup **outside** a public page (an error page, a plugin's background text) and the operator console's own bundle re-check their files on disk (`0` = on every lookup). Public pages re-check on every request, so a bundle edited on disk shows on the next page view, under a new ETag. | | `runway.i18n.cache-seconds` | `5` | How often a message lookup **outside** a public page (an error page, a plugin's background text) and the operator console's own bundle re-check their files on disk (`0` = on every lookup). Public pages re-check on every request, so a bundle edited on disk shows on the next page view, under a new ETag. |
| `runway.csp.mode` | `report` | Content-Security-Policy delivery: `report` (report-only — violations are logged, nothing is blocked), `enforce`, or `off`. Upper or lower case; blank means `report`. Any other value (`enforced`, say) stops startup with a message naming it. See **§8.4**. | | `runway.csp.mode` | `report` | Content-Security-Policy delivery: `report` (report-only — violations are logged, nothing is blocked), `enforce`, or `off`. Upper or lower case; blank means `report`. Any other value (`enforced`, say) stops startup with a message naming it. See **§8.4**. |
| `runway.csp.strict-dynamic` | `true` | `'strict-dynamic'` on the nonced pages. `false` rolls the whole estate (console **and** public pages) back to the host allowlist. **§8.4**. | | `runway.csp.strict-dynamic` | `true` | `'strict-dynamic'` on the nonced pages. `false` rolls the whole estate (console **and** public pages) back to the host allowlist. **§8.4**. |
@@ -695,6 +738,7 @@ from the configuration metadata shipped in the jar.
| `spring.thymeleaf.servlet.produce-partial-output-while-processing` | `false` | A page is rendered whole before its first byte is sent. Streamed instead (Boot's default), an error halfway through a render would leave the visitor a blank or cut-off page instead of the error page. Do not turn it on. | | `spring.thymeleaf.servlet.produce-partial-output-while-processing` | `false` | A page is rendered whole before its first byte is sent. Streamed instead (Boot's default), an error halfway through a render would leave the visitor a blank or cut-off page instead of the error page. Do not turn it on. |
| `server.servlet.session.timeout` | `30m` | How long a signed-in session (the operator console and every site console) may sit idle before it signs out. A duration such as `30m`, `2h` or `1d`; a bare number means seconds. Set on **Settings → Server settings → Sessions**; applies after a restart. With clustering on, `runway.cluster.session-ttl` decides instead — keep the two equal (§2). | | `server.servlet.session.timeout` | `30m` | How long a signed-in session (the operator console and every site console) may sit idle before it signs out. A duration such as `30m`, `2h` or `1d`; a bare number means seconds. Set on **Settings → Server settings → Sessions**; applies after a restart. With clustering on, `runway.cluster.session-ttl` decides instead — keep the two equal (§2). |
| `server.jetty.threads.max` / `.min` | `200` / `8` | The request thread pool (§2, *Capacity*). Set on **Settings → Server settings → Capacity**; applies after a restart; the minimum may not exceed the maximum. | | `server.jetty.threads.max` / `.min` | `200` / `8` | The request thread pool (§2, *Capacity*). Set on **Settings → Server settings → Capacity**; applies after a restart; the minimum may not exceed the maximum. |
| `server.jetty.connection-idle-timeout` | `30s` | How long a connection may make no progress before Jetty closes it — a request with nothing more to read, or a response the client has stopped reading. Jetty's own default, stated so it has one home. It is what ends a client that reads a large response too slowly; a request body that keeps trickling in is ended by `runway.http.min-request-data-rate` instead. |
| `server.ssl.*` | from `runway.tls.*` | Filled from `runway.tls.*` (§7.1). Never set these yourself: they would bypass Runway's TLS startup checks. | | `server.ssl.*` | from `runway.tls.*` | Filled from `runway.tls.*` (§7.1). Never set these yourself: they would bypass Runway's TLS startup checks. |
| `management.endpoints.web.exposure.include` | `health, prometheus` | The only actuator endpoints served. Do not add others: everything under `/actuator/` is open to the superadmin and System admins without the console's CSRF protection, and an endpoint such as `heapdump` would hand out what the server holds in memory, secrets included. | | `management.endpoints.web.exposure.include` | `health, prometheus` | The only actuator endpoints served. Do not add others: everything under `/actuator/` is open to the superadmin and System admins without the console's CSRF protection, and an endpoint such as `heapdump` would hand out what the server holds in memory, secrets included. |
| `management.endpoint.health.probes.enabled` | `true` | Adds `/actuator/health/liveness` and `/actuator/health/readiness` for a supervisor or load balancer. | | `management.endpoint.health.probes.enabled` | `true` | Adds `/actuator/health/liveness` and `/actuator/health/readiness` for a supervisor or load balancer. |
@@ -741,14 +785,14 @@ it never travels in a per-site backup:
`RUNWAY_NODE_NAME=web-1` suits that); a value saved in the field wins over it. The name is only displayed; nothing `RUNWAY_NODE_NAME=web-1` suits that); a value saved in the field wins over it. The name is only displayed; nothing
else uses it. else uses it.
- **Platform mail (SMTP)** — the application's own mail account: host, port, From address, and optional - **Platform mail (SMTP)** — the application's own mail account: host, port, From address, and optional
authentication (username + password) with STARTTLS or implicit TLS. With STARTTLS chosen, a relay that does authentication (a username and password, or an OAuth2 token for Microsoft 365) with STARTTLS or implicit TLS. With STARTTLS chosen, a relay that does
not offer it fails the send rather than receiving the password in the clear, and with either TLS mode the not offer it fails the send rather than receiving the password in the clear, and with either TLS mode the
relay's certificate must name its host. A relay that does not accept the connection within 10 seconds, or relay's certificate must name its host. A relay that does not accept the connection within 10 seconds, or
stalls for 30 seconds while sending, fails the send. It is used to send stalls for 30 seconds while sending, fails the send. It is used to send
**password-recovery** links and any future operator notifications, for **both** the application and **password-recovery** links and any future operator notifications, for **both** the application and
site consoles — and is **never** used for mail a site sends itself (a site keeps its own SMTP site consoles — and is **never** used for mail a site sends itself (a site keeps its own SMTP
relay). The password is stored **encrypted** (leave the field blank on a later save to keep the stored relay). The password is stored **encrypted** (leave the field blank on a later save to keep the stored
one), and a **Send test email** button verifies the account. See **§8.3**. The fields in detail: one, as long as the server stays the same: see below), and a **Send test email** button verifies the account. See **§8.3**. The fields in detail:
- Mail counts as configured — the *Forgot your password?* links appear and the test button works — only when - Mail counts as configured — the *Forgot your password?* links appear and the test button works — only when
**both** the host and the From address are set. **both** the host and the From address are set.
- **Port** — blank means `587`; otherwise a number from 1 to 65535. - **Port** — blank means `587`; otherwise a number from 1 to 65535.
@@ -756,9 +800,77 @@ it never travels in a per-site backup:
usually port `465`). If both are ticked, SSL is used and STARTTLS is ignored. With neither, the connection is usually port `465`). If both are ticked, SSL is used and STARTTLS is ignored. With neither, the connection is
not encrypted, and neither is the password when authentication is on. not encrypted, and neither is the password when authentication is on.
- **Authentication** — off by default; while it is off the username and password are not sent. - **Authentication** — off by default; while it is off the username and password are not sent.
- **The password cannot be removed from this form:** a blank field always keeps the stored one, even when you - **Sign-in method** — *Username and password*, or *OAuth2 token (Microsoft 365)*: see *Microsoft 365 and other
empty every other field. To remove it, delete the `smtp:` block (or its `password:` line) from OAuth2 mail servers* below. The fields of the method not chosen are hidden but kept, so switching back does not
`external/platform.yml` and restart (see *Editing platform.yml by hand* below). lose them.
- **A stored secret follows its server.** A blank password field keeps the stored password only while the host,
port and username stay the same; when one of them changes, the password is cleared, the page says so, and it
must be entered again. The OAuth2 client secret is kept only while the token endpoint, the client ID, the mail
server (host and port) and the scope stay the same, because the secret goes to the endpoint and the token minted
from it goes to the mail server; an OAuth2 account where one of them changes is not saved until the secret is
entered again. This way someone who may edit this screen, but does not know the secret, cannot have Runway send
it, or a token made from it, to a server of their choosing. The activity log's `platform.settings-changed` line names the settings each save
changed (never their values) and any secret it cleared.
- **Otherwise the password cannot be removed from this form:** with the same server, a blank field keeps the
stored one. To remove it, delete the `smtp:` block (or its `password:` line) from `external/platform.yml` and
restart (see *Editing platform.yml by hand* below). The same goes for the OAuth2 client secret
(`oauthClientSecret:`).
**Microsoft 365 and other OAuth2 mail servers.** Microsoft is retiring password sign-in to SMTP (SMTP AUTH with
"Basic authentication") in Exchange Online: Microsoft has announced that it is turned off by default from the end
of December 2026 (Message Center MC786329), and it already fails in a tenant whose security defaults or
Conditional Access block legacy sign-in. Runway can sign in the way Microsoft
requires instead: it obtains an **OAuth2 access token** with an application's own credentials (the
*client-credentials* grant) and presents it to the mail server with SASL `XOAUTH2`. In the Microsoft 365 admin
tools, once:
1. In **Microsoft Entra ID → App registrations**, register an application. Note its **Application (client) ID** and
the **Directory (tenant) ID**, and under **Certificates & secrets** create a **client secret** (note its *value*,
and when it expires).
2. Under **API permissions**, add the application permission **Office 365 Exchange Online → SMTP.SendAsApp** and
**grant admin consent**.
3. In Exchange Online PowerShell, register the application's service principal and give it the mailbox Runway sends
as: `New-ServicePrincipal -AppId <client id> -ObjectId <object id of the enterprise application>`, then
`Add-MailboxPermission -Identity <mailbox> -User <service principal id> -AccessRights FullAccess`.
4. Make sure **Authenticated SMTP** is enabled for that mailbox (Microsoft 365 admin center → the user → Mail →
Manage email apps). OAuth2 still goes through SMTP AUTH.
Then on this page: host `smtp.office365.com`, port `587`, **STARTTLS** on, **Authentication** on, sign-in method
**OAuth2 token**, and:
| Field | Microsoft 365 value |
|---|---|
| Username | the mailbox to send as (blank uses the From address) |
| Token endpoint | `https://login.microsoftonline.com/<tenant id>/oauth2/v2.0/token` |
| Client ID | the application (client) ID |
| Client secret | the secret's value (stored encrypted, like the password) |
| Scope | `https://outlook.office365.com/.default` |
Save, then **Send test email**. A failure says which step failed: *"no OAuth2 token"* means the token endpoint
refused or could not be reached, and the message carries Microsoft's reason (an `AADSTS…` code: a wrong secret, a
wrong tenant, missing consent); any other failure came from the mail server after the token was issued (for
Microsoft, a missing `SMTP.SendAsApp` permission or mailbox permission, or Authenticated SMTP turned off).
How it behaves:
- **TLS is required.** An OAuth2 account must use STARTTLS or implicit TLS; the page refuses to save one without it,
because a token, like a password, signs in whoever reads it.
- **The token endpoint must be `https`** (`http` only to this machine's loopback address, for a local identity
provider). Runway does not follow a redirect from it, so the client secret is only ever sent to the address you
entered.
- **Tokens are reused** until five minutes before they expire (Microsoft's last about an hour), so a burst of
recovery mails costs one token request. A mail server that rejects a token makes Runway fetch a new one on the
next send.
- **Only `XOAUTH2` is offered** once OAuth2 is chosen: a server that does not support it fails the sign-in rather
than receiving the token as a password.
- **Remember the secret's expiry.** Microsoft client secrets expire (24 months at most); when it does, recovery mail
stops with an `AADSTS7000222` error. Create a new secret and enter it here before then.
- **Other providers.** Any mail server that accepts `XOAUTH2` tokens issued by a client-credentials grant works the
same way; enter that provider's token endpoint and scope. (Google Workspace issues such tokens to service accounts
through a signed JWT instead, which Runway does not do; use an app password or an SMTP relay there.)
- **Instead of OAuth2**, Microsoft 365 also accepts mail without any sign-in through an **inbound connector** that
trusts the server's fixed public IP address (port 25, Authentication off in Runway). That is set up entirely in
Exchange Online.
Leaving a field blank restores its default (no catch-all site; the `application.yml` password Leaving a field blank restores its default (no catch-all site; the `application.yml` password
strength; the node name from `runway.node.name` or the host name; no platform mail). The three compression strength; the node name from `runway.node.name` or the host name; no platform mail). The three compression
@@ -785,6 +897,11 @@ smtp:
from: runway@example.com from: runway@example.com
starttls: true starttls: true
ssl: false ssl: false
authMethod: password # password | oauth2
oauthTokenUrl: https://login.microsoftonline.com/<tenant id>/oauth2/v2.0/token # oauth2 only
oauthClientId: 00000000-0000-0000-0000-000000000000
oauthClientSecret: ENC(...)
oauthScope: https://outlook.office365.com/.default
``` ```
The same file also keeps `settings:` (Server settings and the policy cards, §8.5), `siteQuotas:` (each site's The same file also keeps `settings:` (Server settings and the policy cards, §8.5), `siteQuotas:` (each site's
@@ -812,7 +929,7 @@ Restricted to the application superadmin or a wildcard admin.
**Settings → About Runway** (`/__app/about`) is a **read-only** view of the running platform — useful **Settings → About Runway** (`/__app/about`) is a **read-only** view of the running platform — useful
when diagnosing an install or filing a report. Unlike Platform settings it changes nothing and exposes when diagnosing an install or filing a report. Unlike Platform settings it changes nothing and exposes
no secret, so it is visible to **any** signed-in operator. It has three parts: no secret, so it is visible to **any** signed-in operator. It has four parts:
- **Version & build** — the running version and, when the build carries it, the build timestamp. - **Version & build** — the running version and, when the build carries it, the build timestamp.
- **Effective configuration** — a curated table of the non-secret settings in force: whether TLS - **Effective configuration** — a curated table of the non-secret settings in force: whether TLS
@@ -825,14 +942,17 @@ no secret, so it is visible to **any** signed-in operator. It has three parts:
heap, data-disk free/total, uptime, start time, PID, host name, time zone and locale — plus the heap, data-disk free/total, uptime, start time, PID, host name, time zone and locale — plus the
versions of the bundled components (Spring Boot, Jetty, Thymeleaf, Jackson, and more). In a versions of the bundled components (Spring Boot, Jetty, Thymeleaf, Jackson, and more). In a
multi-node deployment these describe **whichever node answered you**. multi-node deployment these describe **whichever node answered you**.
- **This request** — the request that loaded the page as Runway saw it: the connection it came from and whether
that is a trusted proxy, the `X-Forwarded-For` list as received, the client address Runway used, and the scheme
and host. It checks a reverse-proxy setup from the browser (§7).
### 8.3 Password recovery ### 8.3 Password recovery
Both sign-in pages — the application login (`/app/login`) and each site's login (`/login`) — offer a Both sign-in pages — the application login (`/app/login`) and each site's login (`/login`) — offer a
**"Forgot your password?"** link that lets a user reset their own password by email, without an operator. **"Forgot your password?"** link that lets a user reset their own password by email, without an operator.
The link appears **only when platform mail is configured** (§8.1); until then, recovery is done manually The link appears **only when platform mail is configured** (§8.1) **and the emailed link has an address to point
(reset an application user from **§9**, a tenant-superadmin from **§10**, or a site sub-user from the at** (below); until then, recovery is done manually (reset an application user from **§9**, a tenant-superadmin
site console). from **§10**, or a site sub-user from the site console).
How it works: How it works:
@@ -855,8 +975,35 @@ How it works:
account, and a site's link works **only on that site's own host**. A tenant-superadmin who manages account, and a site's link works **only on that site's own host**. A tenant-superadmin who manages
several sites has one password; recovering it from any of their sites resets that single account. several sites has one password; recovering it from any of their sites resets that single account.
There is nothing to configure beyond the platform mail account — recovery is on automatically once mail **Where the emailed link points.** Never at the host name the request came in on: anyone can send a request that
works. Verify it with **Send test email** (§8.1), then exercise a full round-trip from a login page. names any host (a made-up `Host`, or `X-Forwarded-Host` through a proxy that passes it on), and a reset mail with a
link to that host would hand the sender the token. The address comes from what Runway was told:
- **A site's sign-in:** the site's own address: its **base URL**, or else `https://` and its **first** host name,
with no port. A site with no host name offers no recovery, and nor does one whose first host is `localhost` (or
`127.0.0.1`, `::1`) and that has no base URL: that is what the setup wizard gives the default site, and
`https://localhost` reaches nobody who reads the mail. **A site served over plain `http` or on a port other than
443 needs its base URL set** (§10, *The site's base URL*), or its links point at `https://` and port 443.
- **The application console:** with `runway.console.hosts` set (§8.6), the listed name the request came in on (as
listed: case and a trailing dot in the request do not count), the request's scheme, and the port listed with the
name if any, else the request's. The request's port is whatever the client wrote in its `Host` header (through a
proxy too: `X-Forwarded-Host` carries it), so list the name with its port (`ops.example.com:443`) to fix it.
Without `runway.console.hosts`, the **default site**'s address as above, on which the console also answers;
without one, the console offers no recovery: set `runway.console.hosts`, or give the default site a public host
name first, or a base URL.
**Who decides the console's link.** Without `runway.console.hosts`, whoever sets the default site's hosts or base URL
decides where the platform accounts' reset links go. So only a platform administrator (the application master or a
wildcard administrator) can edit the default site's hosts, even where `MANAGE_SITE_HOSTS` is delegated, and a
restore made from the site's own console keeps the site's hosts and base URL (§10). Setting `runway.console.hosts`
takes the default site out of it altogether.
The address a link points at is logged at INFO when one is requested (`a link, if mailed, points at …`), and a
request that finds no address is logged at WARN with the reason.
Beyond that there is nothing to configure: recovery is on once mail works. Verify it with **Send test email**
(§8.1), then exercise a full round-trip from a login page and check that the link in the mail points at the
address you expect.
### 8.4 Content-Security-Policy and the public-page nonce secret ### 8.4 Content-Security-Policy and the public-page nonce secret
@@ -1439,9 +1586,14 @@ entries are lowercased, trimmed and de-duplicated, each is validated as a hostna
bound to **another** site is rejected (two sites can never claim the same host). The same rule applies bound to **another** site is rejected (two sites can never claim the same host). The same rule applies
wherever a site gets hosts: creating a site, installing a demo, and creating a site from a backup refuse a wherever a site gets hosts: creating a site, installing a demo, and creating a site from a backup refuse a
malformed host or one another site answers on, before anything is created. Restoring a backup brings back the malformed host or one another site answers on, before anything is created. Restoring a backup brings back the
hosts the site had when the backup was taken; a host given to another site since then is left off, the log hosts and base URL the site had when the backup was taken when it is made from the application console (a host
says which (`restored site '…' without host(s) […]`), and you can add it back with **Edit hosts** once it is given to another site since then is left off, the log says which: `restored site '…' without host(s) […]`, and you
free. A host is a plain DNS name: no scheme, path, can add it back with **Edit hosts** once it is free). After such a restore, and after creating a site from a backup,
the Backups screen shows the site's hosts and base URL **as they now are**, with the same editor as **Edit hosts**:
check them before anything else, because a backup taken on another installation, or before the site moved, brings
back how it was reached then. A restore made from the site's own console keeps the hosts and
base URL the site has: how a site is reached is yours to set, never the site manager's, and a backup file is
theirs to write. A host is a plain DNS name: no scheme, path,
port (`example.com:8080`), wildcard (`*.example.com`) or underscore, and an international name is written in its port (`example.com:8080`), wildcard (`*.example.com`) or underscore, and an international name is written in its
`xn--` form. The port is never part of the match: a site answers on its hosts on whatever port Runway listens on. `xn--` form. The port is never part of the match: a site answers on its hosts on whatever port Runway listens on.
The **first** host is the primary one: the site's links are built on it unless a base URL is set. Leaving the list empty The **first** host is the primary one: the site's links are built on it unless a base URL is set. Leaving the list empty
@@ -1449,7 +1601,9 @@ makes the site reachable only as the catch-all **default** (below). The change t
request — no restart. Unlike the create/suspend/delete lifecycle actions (which are master-only), host request — no restart. Unlike the create/suspend/delete lifecycle actions (which are master-only), host
editing is gated by the **grantable** `MANAGE_SITE_HOSTS` permission, so you can **delegate** it to an editing is gated by the **grantable** `MANAGE_SITE_HOSTS` permission, so you can **delegate** it to an
operator role or user on the **Permissions** screen (**§9.1**) without granting the full tenancy operator role or user on the **Permissions** screen (**§9.1**) without granting the full tenancy
lifecycle. The application superadmin always has it. lifecycle. The application superadmin always has it. The **default site** is the exception: its hosts and base
URL can be edited only by a platform administrator (the application master or a wildcard administrator), because
without `runway.console.hosts` the console's password-reset links go to its address (§8.3).
**The site's base URL.** The same dialog has a **Base URL** field (`baseUrl` in the site's `site.yml`): the origin **The site's base URL.** The same dialog has a **Base URL** field (`baseUrl` in the site's `site.yml`): the origin
every absolute link of the site is built on — canonical and alternate-language links, the sitemap, structured data every absolute link of the site is built on — canonical and alternate-language links, the sitemap, structured data
@@ -1607,7 +1761,8 @@ plugin installed). Delete it afterward to confirm it removes cleanly like any ot
**Where the plugins come from.** Each Runway release on the releases page **Where the plugins come from.** Each Runway release on the releases page
(<https://g.quest.mx/quest/runway/releases>) also carries the public plugins built for it — (<https://g.quest.mx/quest/runway/releases>) also carries the public plugins built for it —
`runway-plugin-<id>-<version>.zip` for `blog`, `carousel-manager`, `contact`, `discoverability`, `runway-demo`, `search`, `runway-plugin-<id>-<version>.zip` for `blog`, `carousel-manager`, `contact`, `discoverability`, `runway-demo`, `search`,
`search-lucene` and `lucene-provider` — listed in `search-lucene`, `lucene-provider` and, from 1.1.0, `database`, `database-postgresql`, `database-mariadb` and
`runway-demo-database` (**§11.1**) — listed in
the same `SHA256SUMS`. Install one by uploading its zip on **Plugins** (below), then restart. the same `SHA256SUMS`. Install one by uploading its zip on **Plugins** (below), then restart.
> ### ⚠️ Never park an old plugin version inside `external/plugins/` > ### ⚠️ Never park an old plugin version inside `external/plugins/`
@@ -1786,6 +1941,245 @@ Authoring plugins is covered in [PLUGIN-DEVELOPMENT.md](PLUGIN-DEVELOPMENT.md).
> other plugin (search and search-lucene, for example) is installed > other plugin (search and search-lucene, for example) is installed
> separately, so `external/plugins/` otherwise starts empty. > separately, so `external/plugins/` otherwise starts empty.
### 11.1 The database plugins (PostgreSQL or MariaDB)
Runway keeps its own data — sites, pages, users, settings — on files, and that does not change. The **database
plugins** let *other plugins* keep their data in a database server: one per installation, PostgreSQL or MariaDB,
chosen in settings. Nothing uses them unless a plugin that needs a database is installed (the first one is the
`runway-demo-database` guestbook example).
| Plugin | What it is |
|---|---|
| `database` | The generic plugin: the connection pool, the provider choice and the limits, one schema per site, migrations, backups, the **Database** screen and the connection tests. Version 2.0.0 requires Runway 1.2.0 or later (1.0.0 ran on 1.1.0). |
| `database-postgresql` | The PostgreSQL provider: bundles the pgjdbc driver and holds the server's settings (host, account, password, TLS). PostgreSQL **14 or later**, database encoding `UTF8`. |
| `database-mariadb` | The MariaDB provider: bundles MariaDB Connector/J (LGPL-2.1; its unmodified sources are published next to the zip) and holds the server's settings, collation included. MariaDB **10.11 or later**; MySQL is not supported. |
Install `database` and the provider for your server, then restart. With one provider installed, it is the one used;
with both, the database plugin's `provider` setting picks one. A plugin that needs the database declares it, so without `database` it shows as **Blocked** with the
reason, and Runway runs normally.
**Setting it up, step by step.** The whole path for one server; each step is explained further down.
1. **Prepare the server**: an account and a UTF-8 database for Runway (*Preparing the server*, below). On PostgreSQL
the account only owns that database; on MariaDB it also needs the grant on the namespace's databases.
2. **Install the plugins.** From the release (the plugin zips are published with each Runway release, §11), download `runway-plugin-database-<version>.zip`, the provider's
zip (`runway-plugin-database-postgresql-…` or `runway-plugin-database-mariadb-…`) and `SHA256SUMS`, check them
(`sha256sum -c --ignore-missing SHA256SUMS`), and upload each zip on **Plugins**. Add the plugins that will use
the database (for a first try, `runway-demo-database`, the guestbook). Do not restart yet.
3. **Enter the settings**: the server, the account, the password and TLS on the provider's page (**Plugins →
Database — PostgreSQL → Settings**, or **Database — MariaDB**), or in its settings file (*Setting it up without the
console*, below). The database plugin's own page (**Plugins → Database → Settings**) needs a change only when both
providers are installed, or for the namespace and the limits. Settings take effect on the next restart.
4. **Test them**: on **Plugins → Database → Settings**, below the form, **Connection tests** → **Test the saved
PostgreSQL settings** (or MariaDB) connects once with what is saved and changes nothing. The answer is one of those
in *When it does not connect*, below.
5. **Restart once.** Runway starts without waiting for the database, then connects on its own thread.
6. **Check**: **Settings → Database** says *Connected* and shows the server's version; the server log has one line
`database: connected to … (postgresql), namespace 'rw'` (or `mariadb`). If it says anything else, see *When it
does not connect*, below.
7. **Try it** (with the guestbook): place `<div id="guestbook" data-widget="guestbook/main"></div>` on a page of a
site, sign the guestbook as a visitor, and the site's schema appears on the server (`rw_s_<site>_<n>`); the entries
are managed under **Guestbook** in that site's console (the site superadmin has it; anyone else needs the
guestbook's *manage* permission, granted on **Permissions**).
**Setting it up without the console.** The server's settings live in the provider's file,
`external/plugin-settings/database-postgresql.yml` (or `database-mariadb.yml`), nested under
`runway.plugin.<provider plugin id>` like every plugin's (§11). `host`, `database` and `username` are required; the
other keys keep their defaults when absent:
```yaml
# external/plugin-settings/database-postgresql.yml (owner: the service account; mode 600 — it holds the password)
runway:
plugin:
database-postgresql: # database-mariadb for MariaDB
host: "127.0.0.1"
port: 5432 # blank or absent: 5432 / 3306
database: "runway"
username: "runway"
password: "…"
tls: disable # same host only; otherwise verify-full (the default) or require
```
The database plugin's own file, `external/plugin-settings/database.yml` (under `runway.plugin.database`), is needed
only to choose the provider when both are installed (`provider: postgresql` or `mariadb`; the default `auto` uses the
one installed), or to change the namespace or a limit.
The password may be written **in clear**: it is used as written and stays in clear in the file. Runway does not
encrypt a hand-written value, and nothing outside the console can produce the encrypted `ENC(...)` form; it is made
only when the password is typed on the settings form, with the platform secret key (§8). So either keep the file
readable by the service account only (`chown runway: …; chmod 600 …`), or type the password once on the form, which
replaces it with `ENC(...)`. Saving the form with the password field left blank keeps whatever is stored, clear or
encrypted, as long as the settings it is bound to do not change (below).
**Upgrading from database 1.x.** Until 2.0.0 the server's settings were in the database plugin's own file. After the
upgrade, a `database.yml` that still holds them gives the status *Not configured: the server settings moved to the
database-postgresql plugin in database 2.0.0: move host, …* and Runway does not connect with them. Move every server
key (`host`, `port`, `database`, `username`, `password`, `tls`, `caCertificate`, and on MariaDB `collation`) into the
provider's file, under `runway.plugin.database-postgresql` (or `database-mariadb`), as above; keep `provider`,
`namespace` and the limits in `database.yml`. An encrypted password (`ENC(...)`) can be moved as it is: it is
encrypted with the platform secret key, not with anything tied to the file. **Move the keys before you save the
Database plugin's settings form**: a save writes only the settings the form has, so it removes the old server keys
from `database.yml`, encrypted password included (if that happens, type the settings on the provider's page). Or retype the settings on the provider's
page and delete the old keys. Install the 2.0.0 versions of all three plugins together; a 1.x provider with
database 2.0.0 gives *No provider: the database-postgresql plugin is older than 2.0.0*. Then test (step 4 above)
and restart.
**What Runway creates.** Every name starts with the **namespace** (setting `namespace`, default `rw`):
- `<ns>_app` — Runway's own registry tables (`rw_…`) and data that belongs to no site;
- `<ns>_s_<site>_<n>` — one per site, created the first time a plugin uses the database for that site. `<n>` is a
generation number that is never reused: a site that is deleted and created again under the same id gets a new
schema, never the old data.
On PostgreSQL these are **schemas** inside the database you name in the settings. On MariaDB, where a schema *is* a
database, they are **databases** next to the one you name, which only serves as the place to connect to and stays
empty. If several Runway installations share a server, give each its own namespace.
**Preparing the server.** The account needs to create and drop what it owns, and nothing more:
```sql
-- PostgreSQL (as a superuser)
CREATE ROLE runway LOGIN PASSWORD '…';
CREATE DATABASE runway OWNER runway ENCODING 'UTF8' TEMPLATE template0;
```
`TEMPLATE template0` lets the database be UTF-8 even on a cluster created with another encoding, whose `template1`
would refuse it; on a UTF-8 cluster it changes nothing. If PostgreSQL then answers that the encoding does not match
the locale, the cluster's locale is not UTF-8 either: add `LOCALE 'C.UTF-8'` (PostgreSQL 14 and later).
Owning the database is all the account needs: Runway creates its schemas inside it. The server must accept the
account over TCP with a password: on PostgreSQL that is a `pg_hba.conf` line for the database, the account and the
address Runway connects from, for example `host runway runway 127.0.0.1/32 scram-sha-256` for a server on the same
host (reload PostgreSQL after editing it), and, for a server on another host, `listen_addresses` covering an
interface Runway can reach. Give the host as `127.0.0.1` rather than `localhost` to avoid depending on which of
`127.0.0.1` and `::1` the name resolves to.
```sql
-- MariaDB (as root). The pattern is the namespace, then an escaped underscore: `rw\_%` for the default `rw`.
CREATE USER 'runway'@'10.0.0.%' IDENTIFIED BY '…';
CREATE DATABASE runway CHARACTER SET utf8mb4;
GRANT ALL PRIVILEGES ON `runway`.* TO 'runway'@'10.0.0.%';
GRANT ALL PRIVILEGES ON `rw\_%`.* TO 'runway'@'10.0.0.%';
```
A MariaDB account without the pattern grant connects but cannot create the namespace's databases: the **Database**
screen stays at *Connecting* with an "Access denied" error until the grant exists.
**Settings** (Runway-wide, applied on **restart**). The server's, on the provider's page (**Plugins → Database —
PostgreSQL → Settings**, or **Database — MariaDB**):
| Setting | Meaning |
|---|---|
| `host`, `port` | One server: a host name or an IP address (no lists, no options). A blank port means 5432 / 3306. |
| `database` | The database to connect to (see above). |
| `username`, `password` | The account. The password is stored encrypted. It is **bound** to host, port, database, username, TLS and the CA certificate: change any of them without typing the password again and the stored password is removed, so it can never be sent to a server someone else chose. |
| `tls` | `verify-full` (default: encrypted, the certificate and the host name checked against the Java trust store or `caCertificate`), `require` (encrypted, the server **not** checked), `disable`. Use `disable` only for a database on the same host or a private network you trust. |
| `caCertificate` | Advanced. The PEM certificate of the CA that signed the server's certificate, when the Java trust store does not know it. |
| `collation` | Advanced, MariaDB's page only: for plugins' tables. Blank means `utf8mb4_uca1400_ai_ci`. Runway's own identifier columns are always binary. |
The rest, on the database plugin's page (**Plugins → Database → Settings**):
| Setting | Meaning |
|---|---|
| `provider` | `auto` (default: the one provider plugin installed), `postgresql` or `mariadb`. Needed only when both providers are installed. |
| `namespace` | Advanced. Default `rw`; lower-case letters and digits, up to 12. Changing it later starts from empty schemas: the old ones stay on the server. |
| `poolMax` | Connections plugins may hold at once (default 10). One site may use at most half, so a busy site cannot starve the others. |
| `statementTimeoutSeconds` | A plugin's statement that runs longer is stopped (default 10). Migrations, backups and restores have their own 30-minute limit. |
| `backupBudgetMiB` | The compressed size a site's database data may reach in its backup (default 128). |
**Connection tests**, below the database plugin's settings form (same permission as the form, and the same as the
Database screen: `CONFIGURE_PLATFORM`): *Running now* shows the status; **Test the running connection** borrows from
the live pool; **Test the saved PostgreSQL settings** (one button per installed provider) opens one throwaway
connection with the settings saved on that provider's page — which the next restart would apply — and changes
nothing. The tests take no typed values: a form with a username and a password box is one a browser fills in with
your own saved console login, which a test would then send to whatever server the form named. Answers are fixed
categories (below); the driver's own message goes only to the server log, never with a password.
**Runway never fails to start because of the database.** Nothing connects while Runway starts; the plugin connects
right after, on its own thread, retrying with back-off. Until it succeeds, plugins that need it say so (for example
the guestbook shows "This example needs the database …"), and everything else works.
**The Database screen** (**Settings → Database**, needs `CONFIGURE_PLATFORM`, which the master and wildcard
administrators hold) shows:
- the status: *Connected*, *Connecting* (with the last error), *Not configured* (with the setting at fault), *No
provider*, or *Server not supported*; the provider, server version, driver, pool use and the number of sites with
data;
- a link to the settings page and its **Connection tests** (above);
- **Plugin tables needing attention**, with recovery actions (below);
- the plugins using the database, the nodes seen in the last five minutes, the largest site backup against the
budget (a warning from 75%), and the last failed restore.
Each site's dashboard shows one line: whether the site keeps data in the database, its size, and the last database
restore.
**Plugin tables needing attention.** Each plugin brings its tables up to date by itself the first time it uses a
schema (its *migrations*). If that cannot happen, only *that plugin* in *that schema* stops — other plugins and other
sites carry on — and the screen lists the case:
| Problem | Meaning | Action |
|---|---|---|
| Script failed | A migration script stopped at a statement (the detail names it). On PostgreSQL nothing of it was kept, nor of the plugin's other scripts that ran with it (the detail lists them); on MariaDB the statements before it were. | Fix the cause (often a permission, or data the script did not expect), then **Retry**. On MariaDB it continues from the failed statement; on PostgreSQL it runs the whole script again, and the scripts rolled back with it, so do not run part of it by hand first. **Mark applied** only if you completed the script by hand, on PostgreSQL every script the detail lists. If the detail says a script *was never applied* although a later one was, apply it by hand and **Mark applied** (**Retry** cannot run it), or restore the schema. |
| Script changed | A script already applied is no longer the one the installed plugin ships. Released scripts must not change: report it to the plugin's author. | **Accept shipped checksum** once you know the change is harmless. |
| Newer than installed | The schema was migrated by a newer version of the plugin (a downgrade, or nodes on different versions), or data a restore kept for the plugin (when it was not installed) is from a newer version. | Install that version or later; kept data then loads on the plugin's first use. |
| Kept data cannot be loaded | A restore kept data for a plugin that was not installed then (in `deferred/<plugin>/` in the site's folder), and it cannot be read now, or the plugin's tables are already past its version. The plugin is refused on that site rather than started empty. | Fix the cause the detail names (often the folder's permissions) and the next use loads it. To go on without that data, remove `deferred/<plugin>/` from the site's folder, or restore the backup again. |
Every recovery action is written to the server log with the operator's name.
**When it does not connect.** The **Database** screen's status, and the server log's `database:` lines, say why;
**Test the saved … settings** checks what is saved before you restart. While the status is *Connecting*,
Runway retries on its own, waiting twice as long each time up to a minute (every 5 minutes for *Server not
supported*); a fixed server is picked up without a restart. A changed setting needs a restart.
| Status / test answer | Usual cause | What to do |
|---|---|---|
| *Not configured: …* (log: `database: not configured: …`; test: *The settings cannot be used: …*) | A setting is missing or invalid; the message names the plugin and the setting (for example *database-postgresql settings: no host is set*), or says *no server is set* on the provider's page, or *both provider plugins are installed* (choose one in `provider`), or *the server settings moved* (*Upgrading from database 1.x*, above). | Set it and restart. |
| *No provider: …* | No provider plugin is installed, `provider` names a product whose plugin is not, two plugins offer the same product, or the provider is older than 2.0.0 (*the database-postgresql plugin is older than 2.0.0*). | Install `database-postgresql` or `database-mariadb` (2.0.0 or later), or change `provider`; restart. |
| *Connecting:* … / *The server could not be reached.* | Wrong host or port, the server is down, it listens on another interface, or a firewall is in between. The connection attempt gives up after 5 seconds. | From the Runway host, check the address and port (`pg_isready -h … -p …`, `nc -vz … 3306`); `listen_addresses` / `bind-address` on the server. |
| *The server refused the username or password.* | Wrong password; on PostgreSQL, no `pg_hba.conf` line matches the database, account and Runway's address; on MariaDB, no account matches the address Runway connects from. | Fix the password (retype it; §11 on bound secrets), the `pg_hba.conf` line (then reload), or the account's host part. |
| *The TLS handshake failed* | `verify-full` against a server whose certificate the Java trust store does not know (a private CA, or a self-signed certificate), or whose name does not match `host`; or TLS asked for from a server that has none (on PostgreSQL the status shows *The server does not support SSL*; database 1.0.0 reported this one as a refused password). | Paste the CA into `caCertificate`, use the name on the certificate as `host`, or, for a server on the same host or a trusted private network only, `tls: disable`. |
| *The database does not exist on the server, or the account has no access to it.* | The `database` setting names a database that is not there, or (MariaDB) the account has no rights on it. On PostgreSQL an account without the `CONNECT` right answers *The test failed; see the server log*. | Create it as shown above, or fix the name. |
| *Connecting:* … *Access denied* (MariaDB) | The account connects but lacks the grant on the namespace's databases. | Add the namespace pattern grant shown above. |
| *Server not supported: …* | PostgreSQL older than 14, MariaDB older than 10.11, MySQL, or a PostgreSQL database whose encoding is not UTF-8 (*the database's encoding is … UTF8 is needed*). | Upgrade the server or use another one; recreate the database as UTF-8 as shown above. |
The test answers are fixed categories. The status and *Last error* on the screen, and the log's `database:` line,
carry the driver's own message (never a password): the exception, its SQL state and the text, which is where the
detail is.
**Clusters.** Every node needs the same `external/plugin-settings/database.yml` and provider file
(`database-postgresql.yml` or `database-mariadb.yml`) and the same platform secret key
(`runway.security.secret-key`), because the password is stored encrypted with it. The database is shared, so a site
deleted on one node has its schema dropped once, by that node. To change the server or the provider, stop **every**
node first.
**Backups and restore.**
- A site's **full backup** carries its database data (every plugin's tables in that site's schema), in a portable
format: a backup taken on PostgreSQL restores on MariaDB and the other way round. If the database is unreachable
when a backup runs, the backup **fails** and names the site — a backup is complete or it is not a backup.
- A **transfer copy** of a site carries **no** database data, and the copy gets its own, empty schema. Plugins are
asked to keep in the database only data that a transfer may leave behind (visitors' entries, caches); content
that must travel stays in files.
- A restore builds the data in a **new** schema next to the live one and switches the site to it only when
everything is loaded; the old schema is dropped later by a cleanup that runs every 15 minutes and waits until it
has been retired for at least 10. If anything fails, the new schema is
dropped, **the previous data stays live**, and the failure shows on the **Database** screen and the site's dashboard
("Last database restore"). The site's files are restored either way.
- A restore is refused when an installed plugin is **older** than the backup's data (upgrade it first). Data of a
plugin that is **not installed** is kept in the site's folder and loaded when that plugin is installed, at the
backup's version or later; an older one is refused with "newer than the installed plugin" and the data waits.
- The backup budget (`backupBudgetMiB`) caps a site's database data in one backup; above it, the backup fails with a
message, and you back that data up with the database's own tools.
- `<ns>_app` (Runway-wide data) is in **no** site backup. Back it up with the database's own tools (`pg_dump -n
rw_app`, `mariadb-dump rw_app`). The **Database** screen names the plugins that keep data there.
**Moving to another server or provider.** Take a full backup of each site, change the settings, restart, then
restore each site. Runway-wide data (`<ns>_app`) does not move this way: copy it with the database's tools if a
plugin keeps data there.
**Removing.** Uninstalling the database plugins leaves the schemas on the server. Drop them there (every name starts
with the namespace) once you no longer need the data.
## 12. Protection & abuse defense ## 12. Protection & abuse defense
**Posture.** The kernel ships the protection *floor* (the request-pipeline seams: the outermost reject point **Posture.** The kernel ships the protection *floor* (the request-pipeline seams: the outermost reject point
@@ -1799,9 +2193,11 @@ upstream at the proxy/edge regardless.
The protection plugin is an **allowlisted-essential** plugin: once its folder is present, it is **fail-closed** The protection plugin is an **allowlisted-essential** plugin: once its folder is present, it is **fail-closed**
— if it is present but fails to load, the kernel serves tenant hosts a `503` (the app realm stays reachable) — if it is present but fails to load, the kernel serves tenant hosts a `503` (the app realm stays reachable)
rather than booting open. **Every upgrade refreshes it** from the new release (§15): it is lockstep with the rather than booting open. **Every upgrade refreshes it** from the new release (§15): it is lockstep with the
kernel — the one plugin allowed to use kernel internals, with a descriptor naming the kernel's own SPI level — so an kernel — the one plugin allowed to use kernel internals; its descriptor's SPI floor is the major line's (`>=1.0.0`,
older copy beside a newer kernel can be refused (Blocked) — and a refused essential plugin is the fail-closed `503` met by every 1.x kernel, raised only when it uses a newer SPI member) — so an older copy beside a newer kernel can
on every site — or load and run code written for the previous kernel. Your settings (`external/plugin-settings/protection.yml` and each site's `plugins/protection.yml`) live fail on a missing internal class, or be refused (Blocked) if its floor is ever above the kernel's — and a refused
or failing essential plugin is the fail-closed `503` on every site — or load and run code written for the previous
kernel. Your settings (`external/plugin-settings/protection.yml` and each site's `plugins/protection.yml`) live
outside the folder and are never touched. There is no supported opt-out: setting `enabled: false` in its outside the folder and are never touched. There is no supported opt-out: setting `enabled: false` in its
`plugin.yml` counts as a broken floor (`503`) and the next upgrade puts the shipped descriptor back, and removing the `plugin.yml` counts as a broken floor (`503`) and the next upgrade puts the shipped descriptor back, and removing the
folder runs the sites without abuse defense until the next installer run seeds it again. folder runs the sites without abuse defense until the next installer run seeds it again.
@@ -2142,6 +2538,24 @@ runway:
- "198.51.100.7" # the audit runner - "198.51.100.7" # the audit runner
``` ```
**A health check from a proxy on the same host.** Behind a same-host reverse proxy, the proxy's own health check
(`GET /actuator/health` or a site's `/__health`) usually reaches Runway from loopback with no `X-Forwarded-For`, so it
shares one rate-limit bucket with everything else run on that host — a local crawl or audit can then earn the check
`429`s and push the proxy towards marking the server down. Exempt the check alone, not loopback: have the proxy send
it with a fixed `X-Forwarded-For` from a documentation range, and list that address here. No visitor can pose as
it: on real traffic the proxy adds the visitor's own address to the right of anything the visitor sent (or replaces
the header), and Runway reads the header from the right. With HAProxy 2.2 or later:
```
backend runway
option httpchk
http-check send meth GET uri /actuator/health ver HTTP/1.1 hdr Host www.example.com hdr X-Forwarded-For 192.0.2.53
```
and `192.0.2.53` in `allowlist`. Loopback must be in `runway.proxy.trusted-cidrs` (it is, for a same-host proxy);
leave the probe's address out of it, which is for real proxies only. Checking
`/actuator/health` from outside the proxy (a monitoring service) needs no header: list that service's own address.
> **If you are blocked, stop — do not keep probing.** Once an address is auto-blocked, requests no longer > **If you are blocked, stop — do not keep probing.** Once an address is auto-blocked, requests no longer
> reach the rate limiter at all; they hit the blocklist. So the `rate-limit` counter freezes while > reach the rate limiter at all; they hit the blocklist. So the `rate-limit` counter freezes while
> `blocklist-auto` keeps climbing, and continued probing simply confirms the block rather than measuring it. > `blocklist-auto` keeps climbing, and continued probing simply confirms the block rather than measuring it.
@@ -2198,6 +2612,14 @@ holder and explains why; the routes answer `403` regardless. A backup the holder
there for an administrator — or the platform operator, on `/__app/backups` — to download or restore. See the there for an administrator — or the platform operator, on `/__app/backups` — to download or restore. See the
*Site Manager & Designer Guide* §12 for the end-user workflow. *Site Manager & Designer Guide* §12 for the end-user workflow.
**Who did it is recorded.** Each backup act on the site console that took effect — saving, downloading (full,
transfer, or a saved backup), deleting and restoring — is a line in that site's own audit journal (`backup.saved`,
`backup.downloaded`, `backup.deleted`, `site.restored`; Site Manager & Designer Guide §3). The same acts on
`/__app/backups` are in the platform's activity log, under the same names, and not in the site's journal. **A
restore keeps the site's logs and traffic history** (on either console): it replaces the content only, so the
journal still holds what happened before it; logs or stats inside an archive are ignored, as no backup writes them.
A site created from a backup starts its own logs.
**Pending editorial work travels with the site.** On a site whose manager has turned on review **Pending editorial work travels with the site.** On a site whose manager has turned on review
(*Site Manager & Designer Guide* §10), changes waiting for approval are kept beside their pages under (*Site Manager & Designer Guide* §10), changes waiting for approval are kept beside their pages under
`sites/<id>/templates/.pending/<slug>/`. They are site content, never served, listed or indexed: a backup `sites/<id>/templates/.pending/<slug>/`. They are site content, never served, listed or indexed: a backup
@@ -2233,7 +2655,7 @@ with:
- `users.yml` and `permissions.yml` **omitted** — accounts, hashes and grants; - `users.yml` and `permissions.yml` **omitted** — accounts, hashes and grants;
- traffic history (`stats/bandwidth.csv`) and logs — absent, as from **every** backup: they are transient - traffic history (`stats/bandwidth.csv`) and logs — absent, as from **every** backup: they are transient
per-site data that no backup carries; per-site data that no backup carries (and a restore keeps the target site's own);
- every per-site plugin value that is **declared** secret, stored `ENC(...)`, or **named** like a credential - every per-site plugin value that is **declared** secret, stored `ENC(...)`, or **named** like a credential
(`secret`, `password`, `passwd`, `token`, `credential`, `apiKey`, `privateKey`) — **blanked** at any depth, (`secret`, `password`, `passwd`, `token`, `credential`, `apiKey`, `privateKey`) — **blanked** at any depth,
including inside nested maps and lists, and kept as an empty key so the recipient sees what to fill in; including inside nested maps and lists, and kept as an empty key so the recipient sees what to fill in;
@@ -2465,7 +2887,8 @@ Each site keeps its own access log (its public traffic) and audit log (its manag
- `runway.logs.queue-capacity` (default `8192`, at least `16`) — log lines wait in a queue between the request and - `runway.logs.queue-capacity` (default `8192`, at least `16`) — log lines wait in a queue between the request and
the disk, so a slow disk never slows a page. When the queue is full, new lines are **dropped**, not waited for: the disk, so a slow disk never slows a page. When the queue is full, new lines are **dropped**, not waited for:
the count is the `runway_logs_dropped` metric (and the Logs screen), and a `WARN` *"site log queue saturated"* is the count is the `runway_logs_dropped` metric (and the Logs screen), and a `WARN` *"site log queue saturated"* is
logged at most once a minute. Raise it if that count grows; each queued line takes a little memory. logged at most once a minute. An eighth of the queue is held for audit lines (sign-ins, changes), so a flood of
public requests drops access lines first. Raise it if that count grows; each queued line takes a little memory.
### Bandwidth metering (`runway.bandwidth.*`) ### Bandwidth metering (`runway.bandwidth.*`)
@@ -2523,8 +2946,9 @@ live outside the folder and are never touched. No flag is needed; `--update-esse
and does nothing. and does nothing.
*Why always.* The essential plugin moves in lockstep with the kernel: it is the one plugin allowed to use kernel *Why always.* The essential plugin moves in lockstep with the kernel: it is the one plugin allowed to use kernel
internals, and its descriptor declares the kernel's own SPI level. An older copy beside a newer kernel can be internals; its descriptor's SPI floor is the major line's (`>=1.0.0`, met by every 1.x kernel, raised only when it
refused (Blocked) or crash on a missing class — and because it is the essential, fail-closed plugin, either way uses a newer SPI member). An older copy beside a newer kernel can crash on a missing internal class, or be refused
(Blocked) if its floor is ever above the kernel's — and because it is the essential, fail-closed plugin, either way
every tenant page answers `503` — or it loads and runs the previous release's code. What makes "always" safe is what the refresh keeps, below. every tenant page answers `503` — or it loads and runs the previous release's code. What makes "always" safe is what the refresh keeps, below.
*What you see.* The installer logs `refreshing bundled plugin 'protection' from this release`, then one line per *What you see.* The installer logs `refreshing bundled plugin 'protection' from this release`, then one line per
+6
View File
@@ -243,6 +243,12 @@ starts normally; the key is ignored.
| `forwarded-headers` | boolean | `true` | | `forwarded-headers` | boolean | `true` |
| `trusted-cidrs` | list of CIDR | empty (trust nothing); the shipped `application.yml` sets `127.0.0.1/32`, `::1/128` | | `trusted-cidrs` | list of CIDR | empty (trust nothing); the shipped `application.yml` sets `127.0.0.1/32`, `::1/128` |
**`runway.http.*`**
| Key | Type | Default |
|---|---|---|
| `min-request-data-rate` | long, bytes per second | `4096` (`0` = off) |
**`runway.reload.*`** — `/__reload/**` **`runway.reload.*`** — `/__reload/**`
| Key | Type | Default | | Key | Type | Default |
+11 -4
View File
@@ -2,7 +2,7 @@
> **What this is:** an honest, current list of what Runway does **not** do, or does only partially, in the > **What this is:** an honest, current list of what Runway does **not** do, or does only partially, in the
> code as it stands (release `1.0.0`; the exact version is in the [CHANGELOG](../CHANGELOG.md)). The plugin > code as it stands (release `1.0.0`; the exact version is in the [CHANGELOG](../CHANGELOG.md)). The plugin
> contract is frozen at SPI `1.0.0` and enforced at load time ([SPI-STABILITY.md](SPI-STABILITY.md)); > contract was frozen at SPI `1.0.0`, changes only additively within `1.x`, and is enforced at load time ([SPI-STABILITY.md](SPI-STABILITY.md));
> configuration, the data folder and backups are governed by > configuration, the data folder and backups are governed by
> [CONFIGURATION-AND-DATA-STABILITY.md](CONFIGURATION-AND-DATA-STABILITY.md), which binds from `1.0.0`. The data > [CONFIGURATION-AND-DATA-STABILITY.md](CONFIGURATION-AND-DATA-STABILITY.md), which binds from `1.0.0`. The data
> folder and backup archives carry the version markers that promise is built on (`external/layout.yml`, a > folder and backup archives carry the version markers that promise is built on (`external/layout.yml`, a
@@ -146,9 +146,16 @@ closes it. Items marked **after 1.0** are decided: they are not part of the `1.0
## By design — not limitations ## By design — not limitations
- **No database.** The kernel is filesystem/YAML-backed on purpose; there is no SQL layer to - **Runway's own data is on files.** The kernel is filesystem/YAML-backed on purpose; there is no SQL
configure. A deployment that genuinely needs one adds it as a **datasource-provider plugin** (the layer to configure, and the first-run wizard provisions the app superadmin and first site, never a
first-run wizard therefore provisions the app superadmin + first site, never a DB). database. Plugins that need one use PostgreSQL or MariaDB through the **database plugins**
(ADMINISTRATION §11.1), with these limits:
- a site's **transfer copy** carries no database data (the copy starts with an empty schema), so
plugins keep there only data a transfer may leave behind;
- the Runway-wide schema (`<ns>_app`) is in no site backup; back it up with the database's own tools;
- a site's database data in one backup is capped by `backupBudgetMiB` (default 128 MiB compressed);
- isolation between sites inside the database is enforced by the plugins' code (one account reaches
every schema), as everywhere else in Runway where plugins are trusted code.
- **Central seed changes do not back-propagate to existing tenants.** Each tenant owns its copy of the - **Central seed changes do not back-propagate to existing tenants.** Each tenant owns its copy of the
seeded master/templates after creation (the self-containment law); improving the seed affects only seeded master/templates after creation (the self-containment law); improving the seed affects only
*new* tenants. This is the deliberate price of complete tenant isolation and portable backups. *new* tenants. This is the deliberate price of complete tenant isolation and portable backups.
+13 -3
View File
@@ -34,7 +34,8 @@ rolling back safely (**§9**).
Runway runs as **one JVM**, filesystem/YAML-backed (there is no database to operate). Everything Runway runs as **one JVM**, filesystem/YAML-backed (there is no database to operate). Everything
it writes lives under the version-independent data dir `/opt/runway-data/` (`external/`, `logs/`, it writes lives under the version-independent data dir `/opt/runway-data/` (`external/`, `logs/`,
`backups/`). Keep that fact in mind — nearly every recovery step below is a file operation there, `backups/`). Keep that fact in mind — nearly every recovery step below is a file operation there,
not a database operation. not a database operation. The one exception is a plugin's data when the optional database plugins are
installed: that lives in your PostgreSQL or MariaDB server (ADMINISTRATION §11.1).
## 2. Health checks & readiness ## 2. Health checks & readiness
@@ -222,7 +223,9 @@ is written **only in detached launcher mode** — the supervisor appends the JVM
usually empty; do not go looking for application logs there when running as a service. usually empty; do not go looking for application logs there when running as a service.
**The public access log.** One line is emitted per **public** request under the logger **The public access log.** One line is emitted per **public** request under the logger
`runway.access`, from the innermost filter (so the status is final): `runway.access`, written once every filter and handler has finished with it, so with the status it was answered
with (the one exception: an error escaping a plugin's own controller is logged with the status set before it,
while the client receives `500`):
``` ```
203.0.113.7 GET /about -> 200 (12ms) 203.0.113.7 GET /about -> 200 (12ms)
@@ -236,6 +239,13 @@ fetch will **not** appear here; that is by design (this is a traffic log, not an
client IP is the gated one (from a trusted forwarded header only — see Administration §7), never a client IP is the gated one (from a trusted forwarded header only — see Administration §7), never a
raw spoofable header. raw spoofable header.
It records **every** public request that gets past the protection edge (§3.1), whoever answers it: a page, a
plugin's route (`robots.txt`, the sitemap, a form), the sign-in form (every login attempt, successful or not, and
a form post refused for its missing token, `403`), an oversized form refused unread (`413`), a suspended, maintenance or over-quota site (`503`), and a
request body refused for arriving too slowly (`408`). Before 1.1.2 every one of these except the page was missing,
because the log was written by the innermost filter and each of them is answered by a filter outside it. Only the
edge's own `403`/`429` stay out: those go to `runway.protect` (§3.1).
**What to grep for** (systemd, hence `journalctl`): **What to grep for** (systemd, hence `journalctl`):
```bash ```bash
@@ -301,7 +311,7 @@ rejections, §3.1); everything else logs under its package, `mx.quest.runway.*`.
### 3.1 Seeing what the edge rejected ### 3.1 Seeing what the edge rejected
A request the protection edge turns away is rejected at `FilterOrder.CORE_PROTECTION` — the outermost slot — A request the protection edge turns away is rejected at `FilterOrder.CORE_PROTECTION` — the outermost slot —
and the chain is never called. The access log lives at the innermost slot. So a `403`/`429` from the edge and the chain is never called. The access log sits just inside that slot, so a `403`/`429` from the edge
**appears in no other log**, and without a log of its own a site manager would have no way to tell that a **appears in no other log**, and without a log of its own a site manager would have no way to tell that a
crawler was being throttled. crawler was being throttled.
+19 -7
View File
@@ -5,7 +5,7 @@
> the contribution seams, settings, permissions, and the rules that keep plugins compatible. > the contribution seams, settings, permissions, and the rules that keep plugins compatible.
> **Doc status.** The plugin contract is **SPI `1.0.0`, frozen** (Runway `1.0.0`): from here it changes only > **Doc status.** The plugin contract is **SPI `1.0.0`, frozen** (Runway `1.0.0`): from here it changes only
> additively within `1.x` — the commitment and the full type list are in [SPI-STABILITY.md](SPI-STABILITY.md); the > additively within `1.x` (SPI `1.1.0` added `PluginSettings.appSecret`, `1.2.0` `PluginSettings.savedApp`) — the commitment and the full type list are in [SPI-STABILITY.md](SPI-STABILITY.md); the
> `plugin.yml` keys and their tolerance rules are covered by > `plugin.yml` keys and their tolerance rules are covered by
> [CONFIGURATION-AND-DATA-STABILITY.md](CONFIGURATION-AND-DATA-STABILITY.md) §4. A plugin is built against > [CONFIGURATION-AND-DATA-STABILITY.md](CONFIGURATION-AND-DATA-STABILITY.md) §4. A plugin is built against
> `runway-spi` **only**; the kernel refuses one that links its internal classes (§3, *The 1.0 contract at a > `runway-spi` **only**; the kernel refuses one that links its internal classes (§3, *The 1.0 contract at a
@@ -104,7 +104,7 @@ boots.
> **Which floor to declare.** The lowest SPI version whose additions you use — the evolution log on > **Which floor to declare.** The lowest SPI version whose additions you use — the evolution log on
> `RunwaySpi.VERSION` lists them per version. `>=0.4.0`, `>=0.5.0` and `>=0.6.0` are all **1.x floors** (the service > `RunwaySpi.VERSION` lists them per version. `>=0.4.0`, `>=0.5.0` and `>=0.6.0` are all **1.x floors** (the service
> tier those versions introduced is the 1.0 contract), so a plugin built against them loads on every `1.x` kernel; > tier those versions introduced is the 1.0 contract), so a plugin built against them loads on every `1.x` kernel;
> declare `>=1.0.0` only if you use `HeadContext.origin()`. The floor is an **SPI level** — the value of > declare `>=1.0.0` only if you use `HeadContext.origin()`, `>=1.1.0` if you call `PluginSettings.appSecret`, and `>=1.2.0` if you call `PluginSettings.savedApp`. The floor is an **SPI level** — the value of
> `RunwaySpi.VERSION` — not the version of the `runway-spi` artifact you compile against, which is the kernel's > `RunwaySpi.VERSION` — not the version of the `runway-spi` artifact you compile against, which is the kernel's
> release version (kernel `1.0.0` carries SPI `1.0.0`; §3). > release version (kernel `1.0.0` carries SPI `1.0.0`; §3).
@@ -216,7 +216,7 @@ Then depend on `mx.quest:runway-spi:<ver>` (`provided`) and `mx.quest:runway-spi
| You need | Use | Never | | You need | Use | Never |
|---|---|---| |---|---|---|
| your per-site settings and secrets (app-level ones: `@ConfigurationProperties("runway.plugin.<id>")`) | `PluginSettings` (+ `SettingsView`) | `SitePluginConfigService`, `SecretCipher`, `@Value("${runway.plugin…}")` on a per-site key | | your per-site settings and secrets (app-level ones: `@ConfigurationProperties("runway.plugin.<id>")`; an app-level secret in clear: `PluginSettings.appSecret`, SPI 1.1.0; an app-level setting as saved, before the restart applies it: `PluginSettings.savedApp`, SPI 1.2.0) | `PluginSettings` (+ `SettingsView`) | `SitePluginConfigService`, `SecretCipher`, `@Value("${runway.plugin…}")` on a per-site key |
| your per-site files | `PluginSiteFiles`; declare personal data in `siteData.personal` | `SiteFileStore`, `StorageLayout`, a path you build | | your per-site files | `PluginSiteFiles`; declare personal data in `siteData.personal` | `SiteFileStore`, `StorageLayout`, a path you build |
| the site, the request's site, a permission check, a message | `Sites`, `RequestContext`, `AccessCheck` (`@authz`), `Messages` | `SiteResolver`, `AuthzExpressions`, `SiteAwareMessageSource` | | the site, the request's site, a permission check, a message | `Sites`, `RequestContext`, `AccessCheck` (`@authz`), `Messages` | `SiteResolver`, `AuthzExpressions`, `SiteAwareMessageSource` |
| a starter page | `SitePages.install` → `InstallResult` | `PageWriteService`, writing templates | | a starter page | `SitePages.install` → `InstallResult` | `PageWriteService`, writing templates |
@@ -226,6 +226,7 @@ Then depend on `mx.quest:runway-spi:<ver>` (`provided`) and `mx.quest:runway-spi
| a start/stop hook | `PluginLifecycle` | `RunwayPlugin`/`PluginContext` (removed at `1.0.0`) | | a start/stop hook | `PluginLifecycle` | `RunwayPlugin`/`PluginContext` (removed at `1.0.0`) |
| a console screen | `@ConsoleScreen` on a `@Controller` under `/__admin/<id>` or `/__app/<id>` | your own `@ControllerAdvice` calling `OperatorShellModel` | | a console screen | `@ConsoleScreen` on a `@Controller` under `/__admin/<id>` or `/__app/<id>` | your own `@ControllerAdvice` calling `OperatorShellModel` |
| an HTTP route on the site | `EndpointContributor` (`Route`, `Route.anonymousPost` for a public form) | a `@Controller` outside the console prefixes, a servlet `Filter` | | an HTTP route on the site | `EndpointContributor` (`Route`, `Route.anonymousPost` for a public form) | a `@Controller` outside the console prefixes, a servlet `Filter` |
| tables in PostgreSQL or MariaDB | the `database` plugin's own SPI (`Databases`, `DatabaseConsumer`, migrations shipped in your jar; `requires: [ "database >= 1.0.0" ]`): `plugins/docs/PLUGIN-AUTHORING-GUIDE.md` §7.14, example `plugins/runway-demo-database/` | a JDBC driver or pool of your own, a connection string in your settings |
| an absolute URL in head markup | `HeadContext.origin()` (1.0.0) | the `Host` header | | an absolute URL in head markup | `HeadContext.origin()` (1.0.0) | the `Host` header |
**How the kernel enforces it** — each is a **Blocked** plugin with the reason in its row on the **Plugins** screen, **How the kernel enforces it** — each is a **Blocked** plugin with the reason in its row on the **Plugins** screen,
@@ -332,7 +333,7 @@ if you use any `0.6.0` type, `">=0.5.0"` for a `0.5.0` service.
| Service | What it gives you | | Service | What it gives you |
|---|---| |---|---|
| `PluginSettings` | `site(siteId)` → a `SettingsView` of **your** per-site settings: the `siteSettings:` defaults overlaid by what the operator saved (`sites/<id>/plugins/<yourId>.yml`), unknown stored keys preserved, secret keys absent. `secret(siteId, key)` → a `type: secret` value in clear (an `ENC(...)` value decrypted; a hand-written plaintext returned as is; empty when unset, undeclared as secret, or undecryptable). | | `PluginSettings` | `site(siteId)` → a `SettingsView` of **your** per-site settings: the `siteSettings:` defaults overlaid by what the operator saved (`sites/<id>/plugins/<yourId>.yml`), unknown stored keys preserved, secret keys absent. `secret(siteId, key)` → a `type: secret` value in clear (an `ENC(...)` value decrypted; a hand-written plaintext returned as is; empty when unset, undeclared as secret, or undecryptable). `appSecret(key)` (SPI 1.1.0) → the same for a secret declared in your app-level `settings:`, as the running application holds it. `savedApp(key)` (SPI 1.2.0) → one of your app-level settings as **saved** now (a secret in clear; a blank non-secret as its declared default), read from your settings file, for checking a change before the restart applies it. |
| `SettingsView` | lenient typed reads: `string(key, fallback)` (blank → fallback), `bool`, `integer` (and a clamped form), `decimal`, `list` (a YAML list or a comma/newline string). A value that does not parse yields the fallback, never an exception. Nested values are frozen; parse structures from `values()` yourself. | | `SettingsView` | lenient typed reads: `string(key, fallback)` (blank → fallback), `bool`, `integer` (and a clamped form), `decimal`, `list` (a YAML list or a comma/newline string). A value that does not parse yields the fallback, never an exception. Nested values are frozen; parse structures from `values()` yourself. |
| `PluginInfo` | your `id`, `version` and install folder. Injectable; also handed to `PluginLifecycle.started`. | | `PluginInfo` | your `id`, `version` and install folder. Injectable; also handed to `PluginLifecycle.started`. |
| `PluginLifecycle` | optional `started(PluginInfo)` after the platform is up (in plugin load order) and `stopping()` at shutdown (reverse order, only if started). Collected by type — no `id()` to keep in sync. | | `PluginLifecycle` | optional `started(PluginInfo)` after the platform is up (in plugin load order) and `stopping()` at shutdown (reverse order, only if started). Collected by type — no `id()` to keep in sync. |
@@ -738,7 +739,9 @@ You declare a **`FilterBand` + a small offset** — never a raw order. The kerne
escape its band to preempt the protection floor or run before security. The bands (outermost → escape its band to preempt the protection floor or run before security. The bands (outermost →
innermost) are `EDGE_INGRESS` (raw request, pre-security), `EDGE_EGRESS` (response rewriting), innermost) are `EDGE_INGRESS` (raw request, pre-security), `EDGE_EGRESS` (response rewriting),
`TENANT` (after the site is resolved, before security), `APPLICATION` (feature filters, inner of `TENANT` (after the site is resolved, before security), `APPLICATION` (feature filters, inner of
security; the default). **`SECURITY` is not contributable** — it belongs to the kernel's realm security; the default). The kernel's access log sits between `EDGE_INGRESS` and the rest: whatever an
`EDGE_EGRESS`, `TENANT` or `APPLICATION` filter answers is logged with its status, while a request an
`EDGE_INGRESS` filter turns away is not (log it yourself, throttled, if you need to). **`SECURITY` is not contributable** — it belongs to the kernel's realm
security chains, and (as above) a non-essential plugin may not declare a `SecurityFilterChain` bean either. security chains, and (as above) a non-essential plugin may not declare a `SecurityFilterChain` bean either.
**Verify:** the boot log prints one line per plugin filter — **Verify:** the boot log prints one line per plugin filter —
@@ -923,7 +926,11 @@ the raw stored map is blocked — it links a kernel class.)
A `secret`-typed value is stored **encrypted** as `ENC(...)` and the file is `chmod 600` whenever it A `secret`-typed value is stored **encrypted** as `ENC(...)` and the file is `chmod 600` whenever it
holds one. Read a per-site secret with `PluginSettings.secret(siteId, key)` — it decrypts for you, and never holds one. Read a per-site secret with `PluginSettings.secret(siteId, key)` — it decrypts for you, and never
appears in `site(siteId)`. Encryption requires `runway.security.secret-key` to be set — until it is, a secret can't be appears in `site(siteId)`. Read an **app-level** secret (declared `type: secret` under `settings:`) with
`PluginSettings.appSecret(key)` (SPI 1.1.0, so declare `requiresSpi: ">=1.1.0"`): your `@ConfigurationProperties`
bind it only in its `ENC(...)` form, which you cannot decrypt. It answers the value the running application started
with, so a saved change applies after the restart, like every app-level setting. To check a saved change before
that restart (a connection test, say), read it with `PluginSettings.savedApp(key)` (SPI 1.2.0). Encryption requires `runway.security.secret-key` to be set — until it is, a secret can't be
saved and the form says so. A **blank secret on resubmit keeps** the stored value (you never retype saved and the form says so. A **blank secret on resubmit keeps** the stored value (you never retype
it), and secrets are never echoed back into the form. it), and secrets are never echoed back into the form.
@@ -996,6 +1003,11 @@ Because the plugin classloader is **shared** and **parent-first** (§10), the ow
to the same `Class` for owner and implementers, so a `List<TheSpi>` injection collects to the same `Class` for owner and implementers, so a `List<TheSpi>` injection collects
implementations across plugins by type. implementations across plugins by type.
The shipped example is the **`database`** plugin: it publishes `mx.quest.database.spi`, which the provider plugins
implement (`DatabaseProvider`) and which plugins that keep data in PostgreSQL or MariaDB use (`Databases`,
`DatabaseConsumer`). How to use it — scopes, transactions, migrations, backups — is in
`plugins/docs/PLUGIN-AUTHORING-GUIDE.md` §7.14; how operators set it up is ADMINISTRATION §11.1.
--- ---
## 8. Static assets, templates & i18n ## 8. Static assets, templates & i18n
@@ -1234,7 +1246,7 @@ id: protection
name: Essential Protection name: Essential Protection
version: 1.0.0 # the kernel's version line version: 1.0.0 # the kernel's version line
essential: true essential: true
requiresSpi: ">=1.0.0" # the kernel's own SPI: the mandatory floor can never block it requiresSpi: ">=1.0.0" # the SPI major's floor, met by every 1.x kernel: the mandatory floor never blocks it
mainClass: mx.quest.protection.ProtectionConfig mainClass: mx.quest.protection.ProtectionConfig
settings: settings:
+2 -1
View File
@@ -47,6 +47,7 @@ How large a request may be. Applies after a restart.
| Setting | Key | What it does | Values | | Setting | Key | What it does | Values |
|---|---|---|---| |---|---|---|---|
| Largest request before sign-in (bytes) | `runway.endpoints.max-form-bytes` | The most a visitor who is not signed in may send in one request, on any path. Default 262144 (256 KiB). | whole number from 1024 to 104857600; default `262144` | | Largest request before sign-in (bytes) | `runway.endpoints.max-form-bytes` | The most a visitor who is not signed in may send in one request, on any path. Default 262144 (256 KiB). | whole number from 1024 to 104857600; default `262144` |
| Slowest request body (bytes per second) *(Advanced)* | `runway.http.min-request-data-rate` | A request body arriving more slowly is answered 408 Request Timeout: login and other forms, uploads and raw bodies alike, so a client sending a byte now and then cannot keep a request thread. Only time spent waiting for the client counts, and a body that has arrived complete is never refused. Sending part of a body fast earns at most 30 seconds of waiting. Default 4096; 0 turns the check off. | whole number from 0 to 1048576; default `4096` |
| Largest request to a plugin (bytes) | `runway.endpoints.max-body-bytes` | The most a signed-in user may send to a plugin's route. Default 10485760 (10 MiB). | whole number from 1024 to 1073741824; default `10485760` | | Largest request to a plugin (bytes) | `runway.endpoints.max-body-bytes` | The most a signed-in user may send to a plugin's route. Default 10485760 (10 MiB). | whole number from 1024 to 1073741824; default `10485760` |
| Largest uploaded file | `spring.servlet.multipart.max-file-size` | For uploads such as a backup to restore. A size like 256MB or 1GB. Default 256MB. | text; default `256MB` | | Largest uploaded file | `spring.servlet.multipart.max-file-size` | For uploads such as a backup to restore. A size like 256MB or 1GB. Default 256MB. | text; default `256MB` |
| Largest upload request | `spring.servlet.multipart.max-request-size` | All the files of one upload together. A size like 256MB. Default 256MB. | text; default `256MB` | | Largest upload request | `spring.servlet.multipart.max-request-size` | All the files of one upload together. A size like 256MB. Default 256MB. | text; default `256MB` |
@@ -132,7 +133,7 @@ Whether to trust X-Forwarded-* headers, and from which addresses. Only from your
| Setting | Key | What it does | Values | | Setting | Key | What it does | Values |
|---|---|---|---| |---|---|---|---|
| Read X-Forwarded-* headers | `runway.proxy.forwarded-headers` | From the trusted addresses below only. | `true` or `false`; default `true` | | Read X-Forwarded-* headers | `runway.proxy.forwarded-headers` | From the trusted addresses below only. | `true` or `false`; default `true` |
| Trusted proxy addresses | `runway.proxy.trusted-cidrs` | The exact address of your reverse proxy, e.g. 10.0.0.5/32. A /0 (0.0.0.0/0, ::/0), or ranges that add up to every address (0.0.0.0/1 with 128.0.0.0/1), would trust every client to fake its address, so it is refused. | comma-separated list; default `127.0.0.1/32,::1/128` | | Trusted proxy addresses | `runway.proxy.trusted-cidrs` | The exact address of your reverse proxy, e.g. 10.0.0.5/32, and of every proxy in front of it (a CDN). Check the result under About Runway → This request. A /0 (0.0.0.0/0, ::/0), or ranges that add up to every address (0.0.0.0/1 with 128.0.0.0/1), would trust every client to fake its address, so it is refused. | comma-separated list; default `127.0.0.1/32,::1/128` |
#### Capacity #### Capacity
+41 -9
View File
@@ -230,10 +230,17 @@ name or the default language. While no field is set and no manifest icon (192, 5
`/manifest.webmanifest` answers 404 and pages do not link to it. `/manifest.webmanifest` answers 404 and pages do not link to it.
The **Logs** screen (`/__admin/logs`) shows your site's own **access log** (public traffic — the most recent The **Logs** screen (`/__admin/logs`) shows your site's own **access log** (public traffic — the most recent
lines) and its **audit journal**: who did what on your site, and when. The journal records sign-ins lines; every sign-in attempt on your site's login page is there too, as a `POST /login`, and so is a request your
(`login.success`, `login.failure`) and sign-outs (`logout`); password recovery through an emailed link site refused, such as a `503` while it is in maintenance) and its **audit journal**: who did what on your site, and when. The journal records sign-ins
(`login.success`, `login.failure`) and sign-outs (`logout`), each with the address it came from (`ip=…`, in full:
the anonymizing setting below applies to the access log only); password recovery through an emailed link
(`recovery.requested`, `recovery.completed`); page changes (`page.saved`, `page.deleted`, `page.published`, (`recovery.requested`, `recovery.completed`); page changes (`page.saved`, `page.deleted`, `page.published`,
`page.unpublished`); user changes (`user.created`, `user.password-reset`, `user.deleted`); role and permission `page.unpublished`); user changes (`user.created`, `user.updated`, `user.suspended`, `user.resumed`,
`user.password-reset`, `user.deleted`); static files (`static.uploaded`, `static.folder-created`, `static.deleted`);
backups made on your console (§12): a backup saved on the server (`backup.saved`) or deleted (`backup.deleted`), a
backup downloaded (`backup.downloaded`: `full` for a fresh full backup, `transfer` for a transfer copy, `full` and the
name for a saved one) and a restore (`site.restored`, naming the backup, or `(upload)` for an uploaded file) — the
platform operator's own backup work is in the platform's log, not here; role and permission
changes on **Permissions** (`permissions.role-assigned`, `permissions.permission-granted`, changes on **Permissions** (`permissions.role-assigned`, `permissions.permission-granted`,
`permissions.role-created` and their counterparts); and settings changes — a plugin's settings `permissions.role-created` and their counterparts); and settings changes — a plugin's settings
(`plugin.settings-changed`, naming the plugin), the site settings (`site-config.changed`, naming which parts — (`plugin.settings-changed`, naming the plugin), the site settings (`site-config.changed`, naming which parts —
@@ -255,7 +262,8 @@ happens when a line is written, so switching it changes only the lines written a
how many **days** of logs to keep, 30 by default, up to the how many **days** of logs to keep, 30 by default, up to the
platform's maximum (90 unless your operator changed it; the field's hint says it). A value above it is refused. If platform's maximum (90 unless your operator changed it; the field's hint says it). A value above it is refused. If
the operator lowers the maximum below what you chose, your choice is kept, the logs are kept only up to the new the operator lowers the maximum below what you chose, your choice is kept, the logs are kept only up to the new
maximum, and the panel says so until you save a value within it. Logs are *transient*: they never travel in a backup, so restoring a site never carries old logs. maximum, and the panel says so until you save a value within it. Logs are *transient*: they never travel in a backup, and a restore keeps the logs your site has now, so the
journal still shows everything before the restore (and, for a restore made on your console, the restore itself).
The **Bandwidth** screen (`/__admin/bandwidth`, site-admin only) charts your site's data transfer — a The **Bandwidth** screen (`/__admin/bandwidth`, site-admin only) charts your site's data transfer — a
30-day daily graph plus 24-hour / 7-day / 30-day totals. Like logs, the underlying stats are transient and 30-day daily graph plus 24-hour / 7-day / 30-day totals. Like logs, the underlying stats are transient and
@@ -834,6 +842,20 @@ index-backed plugin rebuilds its index).
page or master template (described in **§7**); you decide where it appears and — on the **Content page or master template (described in **§7**); you decide where it appears and — on the **Content
widgets** screen below — how each placement behaves. widgets** screen below — how each placement behaves.
**Plugins that keep data in a database.** Most plugins keep your site's data in your site's folder. Some keep it in
a database server the platform operator runs (PostgreSQL or MariaDB) instead: things that pile up, such as visitors'
entries. For you it works the same way: each site has its own part of the database, kept apart from every other site's,
and your **full backups** carry it (**§12**). Your dashboard has a **Database** card saying whether your site keeps
any data there, and how the last restore of that data went. If the database cannot be reached, those plugins say
so on the page (for example *This example needs the database*) and the rest of your site works as usual; the
operator sees why on their own console.
One such plugin is an example, the **guestbook** (`runway-demo-database`), if your operator installed it:
place `<div id="guestbook" data-widget="guestbook/main"></div>` on a page; visitors sign it there, and you read and
delete the entries under **Guestbook** in your console (it needs the *manage* permission of that plugin, which a role
gets on **Permissions**). Its settings, under **Settings → Runway demo — database**, turn it off for your site and cap how many
entries are kept (500 by default; the oldest go first).
### Content widgets — configuring each placement ### Content widgets — configuring each placement
Open **Resources → Content widgets** (`/__admin/widgets`). The screen lists **every widget a Open **Resources → Content widgets** (`/__admin/widgets`). The screen lists **every widget a
@@ -1183,10 +1205,10 @@ two lists, for the **last 7 or 30 days** (never longer than your log retention
with a corrected link, the missing page or file, or a redirect from the old address. with a corrected link, the missing page or file, or a redirect from the old address.
- **Most-visited pages** — your pages by how often they were successfully viewed, with when last. - **Most-visited pages** — your pages by how often they were successfully viewed, with when last.
**What it counts.** Only `GET` requests (a form post or a crawler's `HEAD` is not a visit). A **page view** is a **What it counts.** Only `GET` requests (a form post, a sign-in attempt or a crawler's `HEAD` is not a visit). A **page view** is a
successful (2xx) answer for an address that looks like a page — no file extension in the last part, or `.html` successful (2xx) answer for an address that looks like a page — no file extension in the last part, or `.html`
— so stylesheets, images, downloads, `robots.txt` and the sitemap are left out; a browser re-checking a page it — so stylesheets, images, downloads, `robots.txt` and the sitemap are left out; a browser re-checking a page it
already has (a `304`) is not a new view. A **404** counts for any address, images included, because a missing already has (a `304`) is not a new view, and neither is a refusal (a `403`, or a `503` during maintenance). A **404** counts for any address, images included, because a missing
image is a broken link too. Addresses are shown **without their query string** (`/search?q=…` counts as image is a broken link too. Addresses are shown **without their query string** (`/search?q=…` counts as
`/search`), and very long ones are shortened on screen (hover to see the whole stored address). `/search`), and very long ones are shortened on screen (hover to see the whole stored address).
@@ -1314,17 +1336,27 @@ backup they save stays on the server, where an administrator — or the platform
download or restore it. Why: handing out the permission to keep the site safe should not also hand out download or restore it. Why: handing out the permission to keep the site safe should not also hand out
a copy of everyone's credentials. a copy of everyone's credentials.
**Data in a database.** When plugins keep data for your site in a database (**§8**), a full backup carries it, and
a backup taken while the database cannot be reached **fails** rather than leaving that data out: a backup is
complete or it is not a backup. On restore, that data is loaded beside the live data and switched in only when all
of it loaded; if loading fails, your site's files are still restored, the database data **stays as it was**, and the
dashboard's **Database** card shows the failed restore (tell the operator; the detail is on their console).
**Restoring.** Restore **replaces your entire site** with the contents of a backup — every **Restoring.** Restore **replaces your entire site** with the contents of a backup — every
page, template, user and setting reverts to the moment the backup was taken. Because it is page, template, user and setting reverts to the moment the backup was taken. Because it is
destructive, **only the site's administrators (the site superadmin, or the Administrator tier) may destructive, **only the site's administrators (the site superadmin, or the Administrator tier) may
restore**; the restore controls are hidden for everyone else. You can restore either from a **saved backup** (pick it from the list) or by restore**; the restore controls are hidden for everyone else. You can restore either from a **saved backup** (pick it from the list) or by
**uploading a `.zip`** you downloaded earlier. **uploading a `.zip`** you downloaded earlier. Two things do not revert: the site's **host names and base URL**
(how visitors reach it) stay as the platform operator has set them now, whatever the backup says; and its **logs and
bandwidth history** stay as they are, so the audit journal keeps its record (the backup acts made here are in it,
§3).
Restore is safe by design: the platform first checks the file is a genuine, complete site Restore is safe by design: the platform first checks the file is a genuine, complete site
backup and only then swaps it in, in one step. **A corrupt, empty, or wrong file is rejected backup and only then swaps it in, in one step. **A corrupt, empty, or wrong file is rejected
and your live site is left exactly as it was** — a failed or interrupted restore never leaves and your live site is left exactly as it was** — a failed or interrupted restore never leaves
you with a half-restored or missing site. After a successful restore the site reflects the you with a half-restored or missing site. After a successful restore the site reflects the
backup immediately (no restart). backup immediately (no restart), and the Backups screen shows the site's host names and base URL for you to check: a restore made here keeps them as
they were (how the site is reached is set by the platform operator), so if they look wrong, ask the operator.
A backup made on a **newer** version of the platform than the one your site runs on is refused A backup made on a **newer** version of the platform than the one your site runs on is refused
the same way, with the message *"This backup was made by a newer version of Runway … Ask the the same way, with the message *"This backup was made by a newer version of Runway … Ask the
@@ -1357,7 +1389,7 @@ kind of `.zip`, restorable in the same way, with the parts that are yours alone
| Plugin settings that are **not** secrets | Plugin secrets (blanked, so you can see what to fill in) | | Plugin settings that are **not** secrets | Plugin secrets (blanked, so you can see what to fill in) |
| | Hostnames and base URL (replaced with a placeholder) | | | Hostnames and base URL (replaced with a placeholder) |
| | Traffic figures | | | Traffic figures |
| | Plugin-held data such as form submissions | | | Plugin-held data such as form submissions, and everything plugins keep for your site in a database (§8) |
| | Changes waiting for review — unpublished drafts, who submitted them, reviewers' notes | | | Changes waiting for review — unpublished drafts, who submitted them, reviewers' notes |
The recipient restores it exactly like a backup. Their copy comes up with your content and appearance, no The recipient restores it exactly like a backup. Their copy comes up with your content and appearance, no
+20 -1
View File
@@ -50,7 +50,7 @@ contribution, a host-coupled seam that is not part of the 1.0 contract (see "Wha
| Type | Since | Scope | What it gives a plugin | | Type | Since | Scope | What it gives a plugin |
|---|---|---|---| |---|---|---|---|
| `service.PluginSettings` (+ `model.SettingsView`) | 0.4.0 | plugin-scoped | its per-site settings, defaults applied, and its declared secrets decrypted (app-level settings bind through `@ConfigurationProperties("runway.plugin.<id>")`, not this service) | | `service.PluginSettings` (+ `model.SettingsView`) | 0.4.0 | plugin-scoped | its per-site settings, defaults applied, and its declared secrets decrypted (app-level settings bind through `@ConfigurationProperties("runway.plugin.<id>")`; an app-level `secret` setting in clear through `appSecret(key)`, since 1.1.0; an app-level setting as saved but not yet applied through `savedApp(key)`, since 1.2.0) |
| `model.PluginInfo` | 0.4.0 | plugin-scoped | its own id, version and install facts | | `model.PluginInfo` | 0.4.0 | plugin-scoped | its own id, version and install facts |
| `service.PluginLifecycle` | 0.4.0 | callback | `started(PluginInfo)` / `stopping()`, in load order and reverse | | `service.PluginLifecycle` | 0.4.0 | callback | `started(PluginInfo)` / `stopping()`, in load order and reverse |
| `service.PluginSiteFiles` (+ `model.FileEntry`) | 0.5.0 | plugin-scoped | its own per-site subtree `sites/<id>/plugins/<pluginId>/`: atomic text writes, capped reads, listing, deletes; confined against crafted paths **and** symbolic links | | `service.PluginSiteFiles` (+ `model.FileEntry`) | 0.5.0 | plugin-scoped | its own per-site subtree `sites/<id>/plugins/<pluginId>/`: atomic text writes, capped reads, listing, deletes; confined against crafted paths **and** symbolic links |
@@ -92,6 +92,25 @@ additive rules below apply to them unchanged.
not serve an item's primary locale, x-default is the item's first **available** locale (it used to be the site not serve an item's primary locale, x-default is the item's first **available** locale (it used to be the site
default, an unprefixed path the item may not exist at — which llms.txt then linked). default, an unprefixed path the item may not exist at — which llms.txt then linked).
### What `1.1.0` added
- **`PluginSettings.appSecret(key)`**: the calling plugin's own `secret`-typed **app-level** setting (`settings:` in
`plugin.yml`), in clear. App-level settings bind through `@ConfigurationProperties`, where a secret arrives only in
its stored `ENC(...)` form, and a plugin has no way to decrypt that. The answer is the value the running application
was started with, so a change saved on the console applies after the restart, as every app-level setting does.
It is a `default` method answering empty, so an implementation written against `1.0.0` still compiles. A plugin
that calls it declares `requiresSpi: ">=1.1.0"`.
### What `1.2.0` added
- **`PluginSettings.savedApp(key)`**: the calling plugin's own **app-level** setting as it is **saved now**, which
may differ from the running value until the restart that applies it. It answers the saved value when not blank (a
`secret` in clear, as `appSecret` decrypts it), otherwise the declared default of a non-secret setting, otherwise
empty; only keys the plugin declared in its own `settings:` are read, from its own settings file, on each call. It
lets a plugin check settings before that restart: the database plugin's connection test uses it. It is a `default`
method answering empty, so an implementation written against `1.1.0` still compiles. A plugin that calls it
declares `requiresSpi: ">=1.2.0"`.
## The compatibility rules (in force from `1.0.0`) ## The compatibility rules (in force from `1.0.0`)
The SPI is **binary API**. A plugin compiled against a released `runway-spi` keeps loading on any later version of The SPI is **binary API**. A plugin compiled against a released `runway-spi` keeps loading on any later version of
+13 -6
View File
@@ -2,8 +2,8 @@
This folder holds **Runway plugin projects**. Each plugin is a **standalone project** (its own build) that This folder holds **Runway plugin projects**. Each plugin is a **standalone project** (its own build) that
compiles against the Runway SPI only (`mx.quest:runway-spi`, plus `runway-spi-testkit` for its tests) from the local Maven repository and deploys as a compiles against the Runway SPI only (`mx.quest:runway-spi`, plus `runway-spi-testkit` for its tests) from the local Maven repository and deploys as a
folder under a Runway install's `external/plugins/<id>/`. The contract is **SPI `1.0.0`** (Runway `1.0.0`): the folder under a Runway install's `external/plugins/<id>/`. The contract is **SPI `1.1.0`** (Runway `1.1.0`; every `1.0.0`
kernel blocks a plugin that links its internal classes. The SPI jars are not yet published to a Maven repository — see the authoring plugin still loads): the kernel blocks a plugin that links its internal classes. The SPI jars are not yet published to a Maven repository — see the authoring
guide, §2. guide, §2.
Each Runway release on the releases page (<https://g.quest.mx/quest/runway/releases>) carries the zips of these Each Runway release on the releases page (<https://g.quest.mx/quest/runway/releases>) carries the zips of these
@@ -21,7 +21,11 @@ plugins/
├── discoverability/ # SEO+ & GEO: sitemap.xml, robots.txt, llms.txt and schema.org JSON-LD ├── discoverability/ # SEO+ & GEO: sitemap.xml, robots.txt, llms.txt and schema.org JSON-LD
├── search/ # on-site search: box widget + /search + /search/api + a published SiteSearchEngine SPI ├── search/ # on-site search: box widget + /search + /search/api + a published SiteSearchEngine SPI
├── search-lucene/ # a Lucene engine for `search` (requires: search + lucene-provider; per-locale analyzers, heap or disk) ├── search-lucene/ # a Lucene engine for `search` (requires: search + lucene-provider; per-locale analyzers, heap or disk)
└── lucene-provider/ # CODE-LESS library provider: bundles Apache Lucene under lib/ (no mainClass) ├── lucene-provider/ # CODE-LESS library provider: bundles Apache Lucene under lib/ (no mainClass)
├── database/ # plugins' own data in PostgreSQL or MariaDB: schema per site, migrations, backups
├── database-postgresql/ # the PostgreSQL provider for `database` (bundles pgjdbc)
├── database-mariadb/ # the MariaDB provider for `database` (bundles MariaDB Connector/J)
└── runway-demo-database/ # the worked example of a database consumer: a per-site guestbook
``` ```
The essential **protection** plugin is not here: it is `runway-plugin-protection` at the root of the repository, The essential **protection** plugin is not here: it is `runway-plugin-protection` at the root of the repository,
@@ -29,9 +33,10 @@ and ships inside the Runway installer.
Each plugin carries a `README.md` and a `plugin.yml` (and, when it has code, its unit tests), and versions independently (its Each plugin carries a `README.md` and a `plugin.yml` (and, when it has code, its unit tests), and versions independently (its
version is in its `plugin.yml`). Each also carries a `docs/<NAME>-PLUGIN.md`, and most a version is in its `plugin.yml`). Each also carries a `docs/<NAME>-PLUGIN.md`, and most a
`scripts/verify-against-host.sh` that checks it against the packaged host. One does not have the verify script: `scripts/verify-against-host.sh` that checks it against the packaged host. Three do not have their own verify script:
**`lucene-provider`** has `docs/LUCENE-PROVIDER-PLUGIN.md` but no verify script — it is a code-less library bundle **`lucene-provider`** is a code-less library bundle with no code of its own to verify, and the two database
with no code of its own to verify. providers (**`database-postgresql`**, **`database-mariadb`**) are verified by `database/scripts/verify-against-host.sh`,
which installs both.
## Start here ## Start here
@@ -51,6 +56,8 @@ with no code of its own to verify.
- Server routes and `<head>` markup for a whole site (`EndpointContributor`, `HeadContributor`) → - Server routes and `<head>` markup for a whole site (`EndpointContributor`, `HeadContributor`) →
[`discoverability/`](discoverability/). [`discoverability/`](discoverability/).
- A self-contained content widget with its own static assets → [`carousel-manager/`](carousel-manager/). - A self-contained content widget with its own static assets → [`carousel-manager/`](carousel-manager/).
- Keeping your data in a database (PostgreSQL or MariaDB) → [`runway-demo-database/`](runway-demo-database/), on
[`database/`](database/) (authoring guide §7.14).
## Conventions ## Conventions
+7
View File
@@ -157,6 +157,11 @@
<copy todir="${stage}/lib"> <copy todir="${stage}/lib">
<fileset dir="${project.build.directory}/staged-lib"/> <fileset dir="${project.build.directory}/staged-lib"/>
</copy> </copy>
<!-- Never a plugin zip without its libraries (it would load and fail at its first use). -->
<fail message="no library in ${stage}/lib">
<condition><resourcecount when="equal" count="0">
<fileset dir="${stage}" includes="lib/*.jar"/></resourcecount></condition>
</fail>
<copy todir="${stage}/templates"> <copy todir="${stage}/templates">
<fileset dir="${project.basedir}/templates"/> <fileset dir="${project.basedir}/templates"/>
</copy> </copy>
@@ -169,6 +174,8 @@
<dirset dir="${stage}"/> <dirset dir="${stage}"/>
<dirset dir="${project.build.directory}" includes="blog"/> <dirset dir="${project.build.directory}" includes="blog"/>
</touch> </touch>
<!-- The stamped files predate any earlier zip, so <zip> would skip the rebuild. -->
<delete file="${project.build.directory}/runway-plugin-blog-${project.version}.zip"/>
<zip destfile="${project.build.directory}/runway-plugin-blog-${project.version}.zip"> <zip destfile="${project.build.directory}/runway-plugin-blog-${project.version}.zip">
<zipfileset dir="${project.build.directory}" includes="blog/**"/> <zipfileset dir="${project.build.directory}" includes="blog/**"/>
</zip> </zip>
+2
View File
@@ -125,6 +125,8 @@
entry's DOS time in the local header and again in the central dir. --> entry's DOS time in the local header and again in the central dir. -->
<dirset dir="${project.build.directory}" includes="carousel-manager"/> <dirset dir="${project.build.directory}" includes="carousel-manager"/>
</touch> </touch>
<!-- The stamped files predate any earlier zip, so <zip> would skip the rebuild. -->
<delete file="${project.build.directory}/runway-plugin-carousel-manager-${project.version}.zip"/>
<zip destfile="${project.build.directory}/runway-plugin-carousel-manager-${project.version}.zip"> <zip destfile="${project.build.directory}/runway-plugin-carousel-manager-${project.version}.zip">
<!-- Zip the REAL staged directory rather than synthesising the folder <!-- Zip the REAL staged directory rather than synthesising the folder
with prefix=. Ant stamps a prefix-synthesised directory entry with with prefix=. Ant stamps a prefix-synthesised directory entry with
+2
View File
@@ -129,6 +129,8 @@
<dirset dir="${stage}"/> <dirset dir="${stage}"/>
<dirset dir="${project.build.directory}" includes="contact"/> <dirset dir="${project.build.directory}" includes="contact"/>
</touch> </touch>
<!-- The stamped files predate any earlier zip, so <zip> would skip the rebuild. -->
<delete file="${project.build.directory}/runway-plugin-contact-${project.version}.zip"/>
<zip destfile="${project.build.directory}/runway-plugin-contact-${project.version}.zip"> <zip destfile="${project.build.directory}/runway-plugin-contact-${project.version}.zip">
<zipfileset dir="${project.build.directory}" includes="contact/**"/> <zipfileset dir="${project.build.directory}" includes="contact/**"/>
</zip> </zip>
+26
View File
@@ -0,0 +1,26 @@
# Changelog
All notable changes are recorded here. Versions follow [Semantic Versioning](https://semver.org/).
## [2.0.0] — 2026-10-30
### Upgrade note
- Install it together with `database` 2.0.0, on Runway 1.2.0 or later, and move the MariaDB server's
settings into this plugin as the `database` 2.0.0 *Upgrade note* says. On Runway 1.1.x, keep 1.0.0 of both.
### Changed
- **This plugin holds the MariaDB server's settings**: host, port, database, username, password, TLS and CA
certificate and the collation, on its own settings page (**Plugins → Database — MariaDB → Settings**; file
`external/plugin-settings/database-mariadb.yml`, under `runway.plugin.database-mariadb`). Until 2.0.0 they were the `database` plugin's;
move them as its 2.0.0 *Upgrade note* says.
- Requires `database >= 2.0.0` and Runway SPI 1.2.0 (Runway 1.2.0), whose `PluginSettings.savedApp` hands the saved
settings to the database plugin's connection test.
## [1.0.0] — 2026-10-29
First public release of `database-mariadb`: the MariaDB 10.11+ provider for the `database` plugin, with MariaDB
Connector/J 3.5.8 bundled. Requires SPI `1.1.0` (Runway `1.1.0` or later) and `database` `1.0.0`. Licensed under the
GNU AGPL v3.0 with an additional permission for plugins (`LICENSE`, `LICENSE-EXCEPTION`); Connector/J is under the
GNU LGPL v2.1, and its source is published beside this plugin's zip.
+661
View File
@@ -0,0 +1,661 @@
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
<http://www.gnu.org/licenses/>.
@@ -0,0 +1,44 @@
Runway — additional permission for plugins
(an additional permission under section 7 of the GNU Affero General Public License, version 3)
Copyright (C) 2026 Quest ICT SAS de CV
Runway is free software: you can redistribute it and/or modify it under the terms of the
GNU Affero General Public License as published by the Free Software Foundation, version 3
(the file LICENSE), with the additional permission below. Runway is distributed in the hope
that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public
License for more details.
1. Definitions
"Runway" means the Runway kernel and every Runway plugin whose source carries this file.
"Published SPI" means the public classes and interfaces of the runway-spi artifact
(the package mx.quest.runway.spi and its subpackages), together with the public classes
and interfaces of any package named "spi" that a part of Runway publishes for other
plugins to use (for example mx.quest.search.spi).
"Plugin" means an independent module that Runway loads as a plugin, that interacts with
Runway only through the Published SPI, and that is not based on any part of Runway other
than the Published SPI.
2. Permission
As an additional permission, the copyright holder gives you permission to combine Runway
with Plugins, and to convey and run the resulting combination, without the terms of the
GNU Affero General Public License applying to those Plugins. You may license, convey and
run your Plugins under terms of your choice, provided that you continue to meet the terms
of the GNU Affero General Public License for Runway itself, including offering the
Corresponding Source of Runway, and of any modification you make to it, as that license
requires.
3. Testing
Compiling a Plugin's tests against the runway-spi-testkit artifact, and running them, does
not by itself make the Plugin subject to the GNU Affero General Public License.
4. Modified versions
If you modify Runway, you may extend this additional permission to your version, but you
are not obliged to do so. If you do not wish to, delete this file from your version.
+18
View File
@@ -0,0 +1,18 @@
# Runway Database — MariaDB provider
Lets the [`database`](../database) plugin use **MariaDB 10.11 or later** (MySQL is not supported). It bundles MariaDB
Connector/J and builds a configured, unpooled `DataSource`; every statement Runway runs is written in the database
plugin. Since 2.0.0 it also holds the server's settings, collation included: host, port, database, account, password and TLS,
on its own settings page (**Plugins → Database — MariaDB → Settings**, file `external/plugin-settings/database-mariadb.yml`).
With both providers installed, choose this one with the database plugin's `provider: mariadb` setting; with one
installed, it is used.
- **Plugin id:** `database-mariadb` (v`2.0.0`) — install folder `external/plugins/database-mariadb/`
- **Requires:** `database >= 2.0.0`, Runway SPI `1.2.0` or later (Runway 1.2.0)
- **Bundles:** MariaDB Connector/J `3.5.8` (LGPL-2.1), unmodified, in `lib/`. Its sources are published next to this
plugin's zip in each release (`mariadb-java-client-3.5.8-sources.jar`); the license and how to replace the jar are
in `THIRD-PARTY-NOTICES`.
Setup, grants and settings: the kernel's ADMINISTRATION §11.1 — step by step, the settings file for a setup
without the console, upgrading from 1.x, and a table for when it does not connect. Details: [`docs/DATABASE-MARIADB-PLUGIN.md`](docs/DATABASE-MARIADB-PLUGIN.md),
[`CHANGELOG.md`](CHANGELOG.md).
@@ -0,0 +1,523 @@
Third-party software bundled with the database-mariadb plugin
=============================================================
The plugin's own code is licensed under the GNU Affero General Public License version 3 with an additional
permission for plugins (LICENSE, LICENSE-EXCEPTION). Its zip also carries, unmodified, in lib/:
MariaDB Connector/J 3.5.8 (org.mariadb.jdbc:mariadb-java-client, lib/mariadb-java-client-3.5.8.jar)
https://mariadb.com/kb/en/about-mariadb-connector-j/
Licensed under the GNU Lesser General Public License, version 2.1 or (at your option) any later version; the text
of version 2.1 follows.
Source code: the complete source of this exact version is published beside this plugin's zip, on the same
release page, as mariadb-java-client-3.5.8-sources.jar (also in Maven Central under the same coordinates).
Replacing it: the plugin uses Connector/J only through its public API and loads it from lib/. You may replace
lib/mariadb-java-client-3.5.8.jar with a modified build of the same version; restart Runway to load it.
--------------------------------------------------------------------------------------------------------------------
GNU Lesser General Public License, version 2.1
--------------------------------------------------------------------------------------------------------------------
GNU LESSER GENERAL PUBLIC LICENSE
Version 2.1, February 1999
Copyright (C) 1991, 1999 Free Software Foundation, Inc.
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
[This is the first released version of the Lesser GPL. It also counts
as the successor of the GNU Library Public License, version 2, hence
the version number 2.1.]
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
Licenses are intended to guarantee your freedom to share and change
free software--to make sure the software is free for all its users.
This license, the Lesser General Public License, applies to some
specially designated software packages--typically libraries--of the
Free Software Foundation and other authors who decide to use it. You
can use it too, but we suggest you first think carefully about whether
this license or the ordinary General Public License is the better
strategy to use in any particular case, based on the explanations below.
When we speak of free software, we are referring to freedom of use,
not price. Our General Public Licenses are designed to make sure that
you have the freedom to distribute copies of free software (and charge
for this service if you wish); that you receive source code or can get
it if you want it; that you can change the software and use pieces of
it in new free programs; and that you are informed that you can do
these things.
To protect your rights, we need to make restrictions that forbid
distributors to deny you these rights or to ask you to surrender these
rights. These restrictions translate to certain responsibilities for
you if you distribute copies of the library or if you modify it.
For example, if you distribute copies of the library, whether gratis
or for a fee, you must give the recipients all the rights that we gave
you. You must make sure that they, too, receive or can get the source
code. If you link other code with the library, you must provide
complete object files to the recipients, so that they can relink them
with the library after making changes to the library and recompiling
it. And you must show them these terms so they know their rights.
We protect your rights with a two-step method: (1) we copyright the
library, and (2) we offer you this license, which gives you legal
permission to copy, distribute and/or modify the library.
To protect each distributor, we want to make it very clear that
there is no warranty for the free library. Also, if the library is
modified by someone else and passed on, the recipients should know
that what they have is not the original version, so that the original
author's reputation will not be affected by problems that might be
introduced by others.
Finally, software patents pose a constant threat to the existence of
any free program. We wish to make sure that a company cannot
effectively restrict the users of a free program by obtaining a
restrictive license from a patent holder. Therefore, we insist that
any patent license obtained for a version of the library must be
consistent with the full freedom of use specified in this license.
Most GNU software, including some libraries, is covered by the
ordinary GNU General Public License. This license, the GNU Lesser
General Public License, applies to certain designated libraries, and
is quite different from the ordinary General Public License. We use
this license for certain libraries in order to permit linking those
libraries into non-free programs.
When a program is linked with a library, whether statically or using
a shared library, the combination of the two is legally speaking a
combined work, a derivative of the original library. The ordinary
General Public License therefore permits such linking only if the
entire combination fits its criteria of freedom. The Lesser General
Public License permits more lax criteria for linking other code with
the library.
We call this license the "Lesser" General Public License because it
does Less to protect the user's freedom than the ordinary General
Public License. It also provides other free software developers Less
of an advantage over competing non-free programs. These disadvantages
are the reason we use the ordinary General Public License for many
libraries. However, the Lesser license provides advantages in certain
special circumstances.
For example, on rare occasions, there may be a special need to
encourage the widest possible use of a certain library, so that it becomes
a de-facto standard. To achieve this, non-free programs must be
allowed to use the library. A more frequent case is that a free
library does the same job as widely used non-free libraries. In this
case, there is little to gain by limiting the free library to free
software only, so we use the Lesser General Public License.
In other cases, permission to use a particular library in non-free
programs enables a greater number of people to use a large body of
free software. For example, permission to use the GNU C Library in
non-free programs enables many more people to use the whole GNU
operating system, as well as its variant, the GNU/Linux operating
system.
Although the Lesser General Public License is Less protective of the
users' freedom, it does ensure that the user of a program that is
linked with the Library has the freedom and the wherewithal to run
that program using a modified version of the Library.
The precise terms and conditions for copying, distribution and
modification follow. Pay close attention to the difference between a
"work based on the library" and a "work that uses the library". The
former contains code derived from the library, whereas the latter must
be combined with the library in order to run.
GNU LESSER GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License Agreement applies to any software library or other
program which contains a notice placed by the copyright holder or
other authorized party saying it may be distributed under the terms of
this Lesser General Public License (also called "this License").
Each licensee is addressed as "you".
A "library" means a collection of software functions and/or data
prepared so as to be conveniently linked with application programs
(which use some of those functions and data) to form executables.
The "Library", below, refers to any such software library or work
which has been distributed under these terms. A "work based on the
Library" means either the Library or any derivative work under
copyright law: that is to say, a work containing the Library or a
portion of it, either verbatim or with modifications and/or translated
straightforwardly into another language. (Hereinafter, translation is
included without limitation in the term "modification".)
"Source code" for a work means the preferred form of the work for
making modifications to it. For a library, complete source code means
all the source code for all modules it contains, plus any associated
interface definition files, plus the scripts used to control compilation
and installation of the library.
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running a program using the Library is not restricted, and output from
such a program is covered only if its contents constitute a work based
on the Library (independent of the use of the Library in a tool for
writing it). Whether that is true depends on what the Library does
and what the program that uses the Library does.
1. You may copy and distribute verbatim copies of the Library's
complete source code as you receive it, in any medium, provided that
you conspicuously and appropriately publish on each copy an
appropriate copyright notice and disclaimer of warranty; keep intact
all the notices that refer to this License and to the absence of any
warranty; and distribute a copy of this License along with the
Library.
You may charge a fee for the physical act of transferring a copy,
and you may at your option offer warranty protection in exchange for a
fee.
2. You may modify your copy or copies of the Library or any portion
of it, thus forming a work based on the Library, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) The modified work must itself be a software library.
b) You must cause the files modified to carry prominent notices
stating that you changed the files and the date of any change.
c) You must cause the whole of the work to be licensed at no
charge to all third parties under the terms of this License.
d) If a facility in the modified Library refers to a function or a
table of data to be supplied by an application program that uses
the facility, other than as an argument passed when the facility
is invoked, then you must make a good faith effort to ensure that,
in the event an application does not supply such function or
table, the facility still operates, and performs whatever part of
its purpose remains meaningful.
(For example, a function in a library to compute square roots has
a purpose that is entirely well-defined independent of the
application. Therefore, Subsection 2d requires that any
application-supplied function or table used by this function must
be optional: if the application does not supply it, the square
root function must still compute square roots.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Library,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Library, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote
it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Library.
In addition, mere aggregation of another work not based on the Library
with the Library (or with a work based on the Library) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may opt to apply the terms of the ordinary GNU General Public
License instead of this License to a given copy of the Library. To do
this, you must alter all the notices that refer to this License, so
that they refer to the ordinary GNU General Public License, version 2,
instead of to this License. (If a newer version than version 2 of the
ordinary GNU General Public License has appeared, then you can specify
that version instead if you wish.) Do not make any other change in
these notices.
Once this change is made in a given copy, it is irreversible for
that copy, so the ordinary GNU General Public License applies to all
subsequent copies and derivative works made from that copy.
This option is useful when you wish to copy part of the code of
the Library into a program that is not a library.
4. You may copy and distribute the Library (or a portion or
derivative of it, under Section 2) in object code or executable form
under the terms of Sections 1 and 2 above provided that you accompany
it with the complete corresponding machine-readable source code, which
must be distributed under the terms of Sections 1 and 2 above on a
medium customarily used for software interchange.
If distribution of object code is made by offering access to copy
from a designated place, then offering equivalent access to copy the
source code from the same place satisfies the requirement to
distribute the source code, even though third parties are not
compelled to copy the source along with the object code.
5. A program that contains no derivative of any portion of the
Library, but is designed to work with the Library by being compiled or
linked with it, is called a "work that uses the Library". Such a
work, in isolation, is not a derivative work of the Library, and
therefore falls outside the scope of this License.
However, linking a "work that uses the Library" with the Library
creates an executable that is a derivative of the Library (because it
contains portions of the Library), rather than a "work that uses the
library". The executable is therefore covered by this License.
Section 6 states terms for distribution of such executables.
When a "work that uses the Library" uses material from a header file
that is part of the Library, the object code for the work may be a
derivative work of the Library even though the source code is not.
Whether this is true is especially significant if the work can be
linked without the Library, or if the work is itself a library. The
threshold for this to be true is not precisely defined by law.
If such an object file uses only numerical parameters, data
structure layouts and accessors, and small macros and small inline
functions (ten lines or less in length), then the use of the object
file is unrestricted, regardless of whether it is legally a derivative
work. (Executables containing this object code plus portions of the
Library will still fall under Section 6.)
Otherwise, if the work is a derivative of the Library, you may
distribute the object code for the work under the terms of Section 6.
Any executables containing that work also fall under Section 6,
whether or not they are linked directly with the Library itself.
6. As an exception to the Sections above, you may also combine or
link a "work that uses the Library" with the Library to produce a
work containing portions of the Library, and distribute that work
under terms of your choice, provided that the terms permit
modification of the work for the customer's own use and reverse
engineering for debugging such modifications.
You must give prominent notice with each copy of the work that the
Library is used in it and that the Library and its use are covered by
this License. You must supply a copy of this License. If the work
during execution displays copyright notices, you must include the
copyright notice for the Library among them, as well as a reference
directing the user to the copy of this License. Also, you must do one
of these things:
a) Accompany the work with the complete corresponding
machine-readable source code for the Library including whatever
changes were used in the work (which must be distributed under
Sections 1 and 2 above); and, if the work is an executable linked
with the Library, with the complete machine-readable "work that
uses the Library", as object code and/or source code, so that the
user can modify the Library and then relink to produce a modified
executable containing the modified Library. (It is understood
that the user who changes the contents of definitions files in the
Library will not necessarily be able to recompile the application
to use the modified definitions.)
b) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (1) uses at run time a
copy of the library already present on the user's computer system,
rather than copying library functions into the executable, and (2)
will operate properly with a modified version of the library, if
the user installs one, as long as the modified version is
interface-compatible with the version that the work was made with.
c) Accompany the work with a written offer, valid for at
least three years, to give the same user the materials
specified in Subsection 6a, above, for a charge no more
than the cost of performing this distribution.
d) If distribution of the work is made by offering access to copy
from a designated place, offer equivalent access to copy the above
specified materials from the same place.
e) Verify that the user has already received a copy of these
materials or that you have already sent this user a copy.
For an executable, the required form of the "work that uses the
Library" must include any data and utility programs needed for
reproducing the executable from it. However, as a special exception,
the materials to be distributed need not include anything that is
normally distributed (in either source or binary form) with the major
components (compiler, kernel, and so on) of the operating system on
which the executable runs, unless that component itself accompanies
the executable.
It may happen that this requirement contradicts the license
restrictions of other proprietary libraries that do not normally
accompany the operating system. Such a contradiction means you cannot
use both them and the Library together in an executable that you
distribute.
7. You may place library facilities that are a work based on the
Library side-by-side in a single library together with other library
facilities not covered by this License, and distribute such a combined
library, provided that the separate distribution of the work based on
the Library and of the other library facilities is otherwise
permitted, and provided that you do these two things:
a) Accompany the combined library with a copy of the same work
based on the Library, uncombined with any other library
facilities. This must be distributed under the terms of the
Sections above.
b) Give prominent notice with the combined library of the fact
that part of it is a work based on the Library, and explaining
where to find the accompanying uncombined form of the same work.
8. You may not copy, modify, sublicense, link with, or distribute
the Library except as expressly provided under this License. Any
attempt otherwise to copy, modify, sublicense, link with, or
distribute the Library is void, and will automatically terminate your
rights under this License. However, parties who have received copies,
or rights, from you under this License will not have their licenses
terminated so long as such parties remain in full compliance.
9. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Library or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Library (or any work based on the
Library), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Library or works based on it.
10. Each time you redistribute the Library (or any work based on the
Library), the recipient automatically receives a license from the
original licensor to copy, distribute, link with or modify the Library
subject to these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties with
this License.
11. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Library at all. For example, if a patent
license would not permit royalty-free redistribution of the Library by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Library.
If any portion of this section is held invalid or unenforceable under any
particular circumstance, the balance of the section is intended to apply,
and the section as a whole is intended to apply in other circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
12. If the distribution and/or use of the Library is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Library under this License may add
an explicit geographical distribution limitation excluding those countries,
so that distribution is permitted only in or among countries not thus
excluded. In such case, this License incorporates the limitation as if
written in the body of this License.
13. The Free Software Foundation may publish revised and/or new
versions of the Lesser General Public License from time to time.
Such new versions will be similar in spirit to the present version,
but may differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Library
specifies a version number of this License which applies to it and
"any later version", you have the option of following the terms and
conditions either of that version or of any later version published by
the Free Software Foundation. If the Library does not specify a
license version number, you may choose any version ever published by
the Free Software Foundation.
14. If you wish to incorporate parts of the Library into other free
programs whose distribution conditions are incompatible with these,
write to the author to ask for permission. For software which is
copyrighted by the Free Software Foundation, write to the Free
Software Foundation; we sometimes make exceptions for this. Our
decision will be guided by the two goals of preserving the free status
of all derivatives of our free software and of promoting the sharing
and reuse of software generally.
NO WARRANTY
15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY
KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU
FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Libraries
If you develop a new library, and you want it to be of the greatest
possible use to the public, we recommend making it free software that
everyone can redistribute and change. You can do so by permitting
redistribution under these terms (or, alternatively, under the terms of the
ordinary General Public License).
To apply these terms, attach the following notices to the library. It is
safest to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least the
"copyright" line and a pointer to where the full notice is found.
<one line to give the library's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Also add information on how to contact you by electronic and paper mail.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the library, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the
library `Frob' (a library for tweaking knobs) written by James Random Hacker.
<signature of Ty Coon>, 1 April 1990
Ty Coon, President of Vice
That's all there is to it!
@@ -0,0 +1,46 @@
# The MariaDB provider
`MariaDbProvider` builds a `MariaDbDataSource` whose URL is `jdbc:mariadb://host:port/database` followed only by
properties it pins; the account goes in through the data source's setters, never the URL.
| Property | Value | Why |
|---|---|---|
| `allowLocalInfile` | `false` | the server cannot ask the client for a local file |
| `allowMultiQueries` | `false` | one statement per call |
| `permitRedirect` | `false` | the server cannot send the client to another host |
| `allowPublicKeyRetrieval` | `false` | no key exchange a man in the middle could abuse |
| `connectionTimeZone` | `UTC` | matches the session time zone the database plugin pins |
| `preserveInstants` | not set (off) | a `LocalDateTime` is read and written as it is, whatever the JVM's zone: the database plugin keeps instants as UTC `LocalDateTime` values, and with `preserveInstants` on every value read would be moved into the JVM's zone |
| `tcpKeepAlive` | `true` | |
| `connectTimeout`, `socketTimeout` | from the settings | the socket timeout is longer than any statement timeout |
| TLS `DISABLE` / `REQUIRE` / `VERIFY_FULL` | `sslMode=disable` / `trust` / `verify-full` | `verify-full` checks the chain and the host name, against `serverSslCert` (the CA file) when given, else the JVM trust store |
**Times in plugin code.** The session is UTC, so bind and read an instant as a UTC `LocalDateTime`
(`LocalDateTime.ofInstant(at, ZoneOffset.UTC)`, `rs.getObject(i, LocalDateTime.class)`) or as a `Timestamp` with a
UTC `Calendar` (`setTimestamp(i, ts, utc)`, `getTimestamp(i, utc)`). A bare `setTimestamp`/`getTimestamp`, or an
`OffsetDateTime`, goes through the JVM's own zone and is off by its offset when the JVM is not on UTC.
Values go into the URL as they are: Connector/J decodes nothing, so an encoded value would name another file or
database. A value containing `&`, `?` or `=` (which its parser splits on) is refused. MySQL's `autoDeserialize` has no equivalent in Connector/J 3, so there is nothing to pin.
**Licence.** Connector/J is LGPL-2.1. It is shipped unmodified as its own jar in `lib/`, so it can be replaced with
another build of the same version; the release publishes its sources jar (`mariadb-java-client-3.5.8-sources.jar`)
next to this plugin's zip. The build copies it into `target/release-assets/`, whose files the release scripts attach
beside the zip, and the zip carries the LGPL-2.1 text in `THIRD-PARTY-NOTICES`.
The provider is one bean, `databaseMariadbProvider`, collected by type. Tests: `MariaDbProviderTest` (the URL for
each TLS policy and that it never carries the account, a real connection when `-Ddb.it.mariadb=host:port` and
`-Ddb.it.password-file=…` are set, the bean name, and the linkage scan). End to end:
`../database/scripts/verify-against-host.sh` with `PROVIDER=mariadb`.
## Its settings (since 2.0.0)
The server's settings are this plugin's own app-level settings (`runway.plugin.database-mariadb.*`, the console's **Plugins →
Database — MariaDB → Settings**): `host`, `port`, `database`, `username`, `password` (a `secret`, bound to the
others), `tls`, `caCertificate`, and `collation`. The provider hands them to the database plugin raw; the database
plugin checks every one before use, as before:
- **running** (`runningSettings()`): bound at startup into a `ProviderSettingsProps` bean
(`databaseMariadbSettings`), the password read in clear with `PluginSettings.appSecret("password")`;
- **saved** (`savedSettings()`): read with `PluginSettings.savedApp(key)` (SPI 1.2.0) from the settings file as it is
now, for the database plugin's connection test before a restart applies them.
@@ -0,0 +1,17 @@
# Runway Database — MariaDB provider — English
database-mariadb.group.connection=Server
database-mariadb.group.connection.help=The MariaDB server Runway keeps plugins' data on. Changes apply after a restart; test them first with the connection tests on the Database plugin's settings page. In a cluster every node needs the same values.
database-mariadb.set.host=Host
database-mariadb.set.host.help=A host name or an IP address. One server only.
database-mariadb.set.port=Port
database-mariadb.set.port.help=Leave blank for MariaDB's default, 3306.
database-mariadb.set.database=Database
database-mariadb.set.database.help=An existing database on the server. Runway creates its own databases next to it: one per site and one for the whole installation.
database-mariadb.set.username=Username
database-mariadb.set.password=Password
database-mariadb.set.tls=TLS
database-mariadb.set.tls.help=verify-full checks the server's certificate and name. require encrypts without checking who the server is. Use disable only for a database on the same host or a private network you trust.
database-mariadb.set.caCertificate=CA certificate (PEM)
database-mariadb.set.caCertificate.help=The certificate authority that signed the server's certificate, when the Java trust store does not know it.
database-mariadb.set.collation=Collation
database-mariadb.set.collation.help=For plugins' tables. Blank uses utf8mb4_uca1400_ai_ci (utf8mb4_unicode_ci before MariaDB 10.10).
@@ -0,0 +1,17 @@
# Runway Database — MariaDB provider — español
database-mariadb.group.connection=Servidor
database-mariadb.group.connection.help=El servidor MariaDB donde Runway guarda los datos de los plugins. Los cambios se aplican al reiniciar; pruébelos antes con las pruebas de conexión de la página de ajustes del plugin Base de datos. En un clúster, todos los nodos necesitan los mismos valores.
database-mariadb.set.host=Servidor
database-mariadb.set.host.help=Un nombre de host o una dirección IP. Un solo servidor.
database-mariadb.set.port=Puerto
database-mariadb.set.port.help=Déjelo en blanco para usar el predeterminado de MariaDB, 3306.
database-mariadb.set.database=Base de datos
database-mariadb.set.database.help=Una base de datos existente en el servidor. Runway crea sus propias bases de datos junto a ella: una por sitio y una para toda la instalación.
database-mariadb.set.username=Usuario
database-mariadb.set.password=Contraseña
database-mariadb.set.tls=TLS
database-mariadb.set.tls.help=verify-full comprueba el certificado y el nombre del servidor. require cifra sin comprobar quién es el servidor. Use disable solo para una base de datos en el mismo equipo o en una red privada de confianza.
database-mariadb.set.caCertificate=Certificado de la CA (PEM)
database-mariadb.set.caCertificate.help=La autoridad que firmó el certificado del servidor, cuando el almacén de confianza de Java no la conoce.
database-mariadb.set.collation=Intercalación
database-mariadb.set.collation.help=Para las tablas de los plugins. En blanco se usa utf8mb4_uca1400_ai_ci (utf8mb4_unicode_ci antes de MariaDB 10.10).
+50
View File
@@ -0,0 +1,50 @@
# =============================================================================
# Runway Database — MariaDB provider
# Lets the database plugin use MariaDB 10.11 or later (not MySQL). It brings
# MariaDB Connector/J (LGPL-2.1, unmodified, in lib/; its sources are
# published next to this plugin's release) and builds a configured
# DataSource; every statement Runway runs is written in the database plugin.
#
# The server, the account and TLS are set on THIS plugin's settings page
# (since 2.0.0); the database plugin keeps the provider choice and the
# limits. With both providers installed, choose this one with the database
# plugin's `provider: mariadb` setting.
#
# The install folder name MUST equal this `id`: external/plugins/database-mariadb/.
# =============================================================================
id: database-mariadb
name: Database — MariaDB
version: 2.0.0
mainClass: mx.quest.database.mariadb.MariaDbProviderConfig
# The database plugin publishes the DatabaseProvider interface this plugin implements.
requires: [ "database >= 2.0.0" ]
# SPI 1.2.0: PluginSettings.savedApp, which hands the saved settings to the connection test.
requiresSpi: ">=1.2.0"
settingGroups:
- { id: connection, label: database-mariadb.group.connection, help: database-mariadb.group.connection.help }
# Runway-wide settings, applied on RESTART. In a cluster every node needs the same values and the same platform
# secret key. Test them before restarting: Plugins -> Database -> Settings, "Connection tests".
settings:
- { key: host, type: string, group: connection, label: database-mariadb.set.host, help: database-mariadb.set.host.help }
- { key: port, type: int, range: "1..65535", group: connection, label: database-mariadb.set.port,
help: database-mariadb.set.port.help }
- { key: database, type: string, group: connection, label: database-mariadb.set.database,
help: database-mariadb.set.database.help }
- { key: username, type: string, group: connection, label: database-mariadb.set.username }
# Bound to where it goes: changing any of these without typing the password again removes the stored one.
- key: password
type: secret
group: connection
label: database-mariadb.set.password
secretBoundTo: [host, port, database, username, tls, caCertificate]
- { key: tls, type: enum, range: "verify-full,require,disable", default: verify-full, group: connection,
label: database-mariadb.set.tls, help: database-mariadb.set.tls.help }
- { key: caCertificate, type: text, group: connection, advanced: true, label: database-mariadb.set.caCertificate,
help: database-mariadb.set.caCertificate.help }
- { key: collation, type: string, group: connection, advanced: true, label: database-mariadb.set.collation,
help: database-mariadb.set.collation.help }
+191
View File
@@ -0,0 +1,191 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<!--
The MariaDB provider for the database plugin: MariaDB Connector/J (LGPL-2.1) in lib/, unmodified, and the code that
builds its DataSource. Same managed versions as the Runway kernel (Spring Boot 4.0.6), thin jar, no repackage.
-->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>4.0.6</version>
<relativePath/>
</parent>
<groupId>mx.quest</groupId>
<artifactId>runway-plugin-database-mariadb</artifactId>
<version>2.0.0</version>
<packaging>jar</packaging>
<name>Runway Database — MariaDB</name>
<licenses>
<license>
<name>GNU Affero General Public License v3.0, with the Runway additional permission for plugins</name>
<url>https://www.gnu.org/licenses/agpl-3.0.txt</url>
<distribution>repo</distribution>
<comments>See LICENSE and LICENSE-EXCEPTION.</comments>
</license>
</licenses>
<description>
The MariaDB provider for the Runway database plugin: bundles MariaDB Connector/J and builds a configured, unpooled DataSource (one host, pinned TLS, timeouts and safety properties). Every statement Runway runs is written in the database plugin.
</description>
<properties>
<java.version>25</java.version>
<maven.compiler.release>25</maven.compiler.release>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<!-- Reproducible builds: pins every archive entry's timestamp. Bump at each release. -->
<project.build.outputTimestamp>2026-10-29T00:00:00Z</project.build.outputTimestamp>
<!-- The runway-spi this plugin compiles against: SPI 1.2.0 adds PluginSettings.savedApp. -->
<runway.version>1.2.0</runway.version>
<!-- The database plugin whose SPI this provider implements (provided: the shared plugin class loader
supplies it; install ../database first). -->
<database.version>2.0.0</database.version>
<!-- The driver bundled in lib/. Pinned so the bundle never drifts from what the notices name. -->
<mariadb.version>3.5.8</mariadb.version>
</properties>
<dependencies>
<dependency>
<groupId>mx.quest</groupId>
<artifactId>runway-spi</artifactId>
<version>${runway.version}</version>
</dependency>
<dependency>
<groupId>mx.quest</groupId>
<artifactId>runway-spi-testkit</artifactId>
<version>${runway.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>mx.quest</groupId>
<artifactId>runway-plugin-database</artifactId>
<version>${database.version}</version>
<scope>provided</scope>
</dependency>
<!-- The driver, bundled into lib/ by the assembly below. -->
<dependency>
<groupId>org.mariadb.jdbc</groupId>
<artifactId>mariadb-java-client</artifactId>
<version>${mariadb.version}</version>
</dependency>
<!-- The kernel supplies these at runtime; never bundled. -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>runway-plugin-database-mariadb</finalName>
<plugins>
<!-- 1. The driver into target/staged-lib, with its versioned file name; the assembly copies it into lib/. -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<id>bundle-libs</id>
<phase>package</phase>
<goals>
<goal>copy</goal>
</goals>
<configuration>
<artifactItems>
<artifactItem>
<groupId>org.mariadb.jdbc</groupId>
<artifactId>mariadb-java-client</artifactId>
<version>${mariadb.version}</version>
</artifactItem>
</artifactItems>
<outputDirectory>${project.build.directory}/staged-lib</outputDirectory>
<stripVersion>false</stripVersion>
<overWriteReleases>true</overWriteReleases>
</configuration>
</execution>
<!-- The driver's sources (LGPL-2.1: published beside the zip, see THIRD-PARTY-NOTICES).
publish-plugin-release.sh attaches everything in target/release-assets/. -->
<execution>
<id>driver-sources</id>
<phase>package</phase>
<goals>
<goal>copy</goal>
</goals>
<configuration>
<artifactItems>
<artifactItem>
<groupId>org.mariadb.jdbc</groupId>
<artifactId>mariadb-java-client</artifactId>
<version>${mariadb.version}</version>
<classifier>sources</classifier>
</artifactItem>
</artifactItems>
<outputDirectory>${project.build.directory}/release-assets</outputDirectory>
<stripVersion>false</stripVersion>
<overWriteReleases>true</overWriteReleases>
</configuration>
</execution>
</executions>
</plugin>
<!-- 2. Assemble target/database/ (folder) and the UI zip. -->
<plugin>
<artifactId>maven-antrun-plugin</artifactId>
<executions>
<execution>
<id>assemble-plugin-folder</id>
<phase>package</phase>
<goals>
<goal>run</goal>
</goals>
<configuration>
<target>
<property name="stage" value="${project.build.directory}/database-mariadb"/>
<delete dir="${stage}"/>
<mkdir dir="${stage}"/>
<copy file="${project.basedir}/plugin.yml" todir="${stage}"/>
<copy file="${project.basedir}/LICENSE" todir="${stage}"/>
<copy file="${project.basedir}/LICENSE-EXCEPTION" todir="${stage}"/>
<copy file="${project.basedir}/THIRD-PARTY-NOTICES" todir="${stage}"/>
<copy file="${project.build.directory}/runway-plugin-database-mariadb.jar" todir="${stage}"/>
<copy todir="${stage}/lib">
<fileset dir="${project.build.directory}/staged-lib"/>
</copy>
<copy todir="${stage}/i18n">
<fileset dir="${project.basedir}/i18n"/>
</copy>
<!-- Never a plugin zip without its libraries (it would load and fail at its first use). -->
<fail message="no library in ${stage}/lib">
<condition><resourcecount when="equal" count="0">
<fileset dir="${stage}" includes="lib/*.jar"/></resourcecount></condition>
</fail>
<touch datetime="${project.build.outputTimestamp}"
pattern="yyyy-MM-dd'T'HH:mm:ss'Z'">
<fileset dir="${stage}"/>
<dirset dir="${stage}"/>
<dirset dir="${project.build.directory}" includes="database-mariadb"/>
</touch>
<!-- The stamped files predate any earlier zip, so <zip> would skip the rebuild. -->
<delete file="${project.build.directory}/runway-plugin-database-mariadb-${project.version}.zip"/>
<zip destfile="${project.build.directory}/runway-plugin-database-mariadb-${project.version}.zip">
<zipfileset dir="${project.build.directory}" includes="database-mariadb/**"/>
</zip>
<echo message="Staged install folder (with the driver in lib/): ${stage}"/>
<echo message="UI-uploadable archive: ${project.build.directory}/runway-plugin-database-mariadb-${project.version}.zip"/>
</target>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
@@ -0,0 +1,130 @@
package mx.quest.database.mariadb;
import java.sql.SQLException;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Supplier;
import javax.sql.DataSource;
import mx.quest.database.spi.ConnectionSettings;
import mx.quest.database.spi.DatabaseProvider;
import mx.quest.database.spi.ProviderSettings;
import org.mariadb.jdbc.MariaDbDataSource;
/**
* MariaDB through MariaDB Connector/J. Builds an unpooled {@link MariaDbDataSource} whose URL is
* {@code jdbc:mariadb://host:port/database} plus properties this class pins; the account goes in through the setters,
* never the URL. The database plugin pools it and runs every statement.
*
* <p>Pinned so that no setting and no server can reach outside the connection:
* {@code allowLocalInfile=false} (the server cannot ask for a client file), {@code allowMultiQueries=false},
* {@code permitRedirect=false} (the server cannot send the client to another host),
* {@code allowPublicKeyRetrieval=false}. The connection time zone is UTC, matching the session time zone the
* database plugin pins; {@code preserveInstants} stays off, so a {@code LocalDateTime} is read and written as it is
* (instants as UTC wall-clock values), whatever the JVM's zone. TLS: {@code DISABLE} {@code sslMode=disable}; {@code REQUIRE} {@code sslMode=trust}
* (encrypted, the server not checked); {@code VERIFY_FULL} {@code sslMode=verify-full} against the configured CA file
* ({@code serverSslCert}) or the JVM's trust store.
*/
public final class MariaDbProvider implements DatabaseProvider {
static final int DEFAULT_PORT = 3306;
private final Supplier<ProviderSettings> running;
private final Supplier<ProviderSettings> saved;
/**
* Without settings, as before database 2.0.0: for building data sources only (tests).
*/
public MariaDbProvider() {
this(() -> null, () -> null);
}
/**
* @param running the server settings the application started with, from this plugin's own settings page
* @param saved the server settings saved on that page now, which the next restart applies
*/
public MariaDbProvider(Supplier<ProviderSettings> running, Supplier<ProviderSettings> saved) {
this.running = Objects.requireNonNull(running, "running");
this.saved = Objects.requireNonNull(saved, "saved");
}
@Override
public String id() {
return "mariadb";
}
@Override
public String driverVersion() {
String version = MariaDbDataSource.class.getPackage().getImplementationVersion();
return "MariaDB Connector/J " + (version == null ? "" : version).strip();
}
@Override
public DataSource dataSource(ConnectionSettings settings) {
Objects.requireNonNull(settings, "settings");
try {
MariaDbDataSource ds = new MariaDbDataSource(url(settings));
ds.setUser(settings.username());
ds.setPassword(settings.password());
return ds;
} catch (SQLException e) {
throw new IllegalArgumentException("the MariaDB connection settings are not usable", e);
}
}
/** The URL: the checked host, port and database, then only the properties this class pins. */
static String url(ConnectionSettings settings) {
String host = settings.host().indexOf(':') >= 0 ? "[" + settings.host() + "]" : settings.host();
Map<String, String> p = new LinkedHashMap<>();
p.put("allowLocalInfile", "false");
p.put("allowMultiQueries", "false");
p.put("permitRedirect", "false");
p.put("allowPublicKeyRetrieval", "false");
p.put("connectionTimeZone", "UTC");
// No preserveInstants: with it Connector/J also turns every DATETIME/TIMESTAMP it reads as a LocalDateTime into
// the JVM's zone, and the database plugin reads and writes instants as UTC LocalDateTime values (the session
// is UTC). Without it a LocalDateTime goes both ways as written, whatever the JVM's zone.
p.put("tcpKeepAlive", "true");
p.put("connectTimeout", Long.toString(Math.max(1, settings.connectTimeout().toMillis())));
p.put("socketTimeout", Long.toString(Math.max(1, settings.socketTimeout().toMillis())));
switch (settings.tls()) {
case DISABLE -> p.put("sslMode", "disable");
case REQUIRE -> p.put("sslMode", "trust");
case VERIFY_FULL -> {
p.put("sslMode", "verify-full");
if (settings.caCertificate() != null) {
p.put("serverSslCert", settings.caCertificate().toAbsolutePath().toString());
}
}
default -> throw new IllegalArgumentException("unknown TLS policy " + settings.tls());
}
// Connector/J takes the URL literally (it decodes nothing), so values go in as they are: an encoded CA path
// would name a file that does not exist. The characters its parser splits on are refused instead.
StringBuilder url = new StringBuilder("jdbc:mariadb://").append(host).append(':')
.append(settings.portOr(DEFAULT_PORT)).append('/').append(literal(settings.database()));
char sep = '?';
for (Map.Entry<String, String> e : p.entrySet()) {
url.append(sep).append(e.getKey()).append('=').append(literal(e.getValue()));
sep = '&';
}
return url.toString();
}
private static String literal(String value) {
if (value.indexOf('&') >= 0 || value.indexOf('?') >= 0 || value.indexOf('=') >= 0) {
throw new IllegalArgumentException("a connection value cannot contain '&', '?' or '=': " + value);
}
return value;
}
@Override
public Optional<ProviderSettings> runningSettings() {
return Optional.ofNullable(running.get());
}
@Override
public Optional<ProviderSettings> savedSettings() {
return Optional.ofNullable(saved.get());
}
}
@@ -0,0 +1,33 @@
package mx.quest.database.mariadb;
import mx.quest.database.spi.ProviderSettings;
import mx.quest.database.spi.ProviderSettingsProps;
import mx.quest.runway.spi.service.PluginSettings;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* Registers the MariaDB provider; the database plugin collects it by type. The server's settings are this plugin's
* own app-level settings ({@code runway.plugin.database-mariadb.*}, since database 2.0.0): the running ones as
* bound at startup, the password through {@link PluginSettings#appSecret}, and the saved ones through
* {@link PluginSettings#savedApp} for the connection test. With both providers installed the context holds two
* {@link ProviderSettingsProps} beans, hence the qualifier.
*/
@Configuration(proxyBeanMethods = false)
public class MariaDbProviderConfig {
@Bean
@ConfigurationProperties("runway.plugin.database-mariadb")
public ProviderSettingsProps databaseMariadbSettings() {
return new ProviderSettingsProps();
}
@Bean
public MariaDbProvider databaseMariadbProvider(
@Qualifier("databaseMariadbSettings") ProviderSettingsProps server, PluginSettings settings) {
return new MariaDbProvider(() -> server.toSettings(settings.appSecret(ProviderSettings.PASSWORD)),
() -> ProviderSettings.read(settings::savedApp));
}
}
@@ -0,0 +1,199 @@
package mx.quest.database.mariadb;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.junit.jupiter.api.Assumptions.assumeTrue;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.Timestamp;
import java.time.Duration;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Stream;
import mx.quest.database.spi.ConnectionSettings.Tls;
import mx.quest.database.spi.ConnectionSettings;
import mx.quest.database.spi.ProviderSettings;
import mx.quest.runway.spi.service.PluginSettings;
import mx.quest.runway.spi.testkit.FakePluginSettings;
import org.junit.jupiter.api.Test;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.MapPropertySource;
class MariaDbProviderTest {
static ConnectionSettings settings(String host, int port, String database, String password, Tls tls, Path ca) {
return new ConnectionSettings(host, port, database, "runway", password, tls, ca, Duration.ofSeconds(5),
Duration.ofSeconds(40));
}
@Test
void theUrlCarriesOnlyThePinnedPropertiesAndNeverTheAccount() {
String url = MariaDbProvider.url(settings("db", 0, "runway", "s3cret", Tls.DISABLE, null));
assertThat(url).startsWith("jdbc:mariadb://db:3306/runway?")
.contains("allowLocalInfile=false", "allowMultiQueries=false", "permitRedirect=false",
"allowPublicKeyRetrieval=false", "connectionTimeZone=UTC",
"sslMode=disable",
"connectTimeout=5000", "socketTimeout=40000")
.doesNotContain("preserveInstants").doesNotContain("s3cret").doesNotContain("user=").doesNotContain("password");
assertThat(MariaDbProvider.url(settings("db", 1, "runway", "", Tls.REQUIRE, null))).contains("sslMode=trust");
assertThat(MariaDbProvider.url(settings("db", 1, "runway", "", Tls.VERIFY_FULL, null)))
.contains("sslMode=verify-full").doesNotContain("serverSslCert");
assertThat(MariaDbProvider.url(settings("db", 1, "runway", "", Tls.VERIFY_FULL, Path.of("/a b/ca.pem"))))
.contains("serverSslCert=/a b/ca.pem");
assertThat(MariaDbProvider.url(settings("::1", 1, "run$way", "", Tls.DISABLE, null)))
.startsWith("jdbc:mariadb://[::1]:1/run$way?");
assertThatThrownBy(() -> MariaDbProvider.url(settings("db", 1, "runway", "", Tls.VERIFY_FULL,
Path.of("/x&sslMode=disable/ca.pem")))).isInstanceOf(IllegalArgumentException.class);
}
@Test
void connectorJReadsTheValuesAsWritten() throws Exception {
// The driver decodes nothing: what the URL says is the file it opens and the database it names.
var conf = org.mariadb.jdbc.Configuration.parse(MariaDbProvider.url(settings("db", 1, "run$way", "",
Tls.VERIFY_FULL, Path.of("/opt/run way/ca-abc.pem"))));
assertThat(conf.database()).isEqualTo("run$way");
assertThat(conf.serverSslCert()).isEqualTo("/opt/run way/ca-abc.pem");
assertThat(conf.connectionTimeZone()).isEqualTo("UTC");
assertThat(conf.preserveInstants()).isFalse();
}
@Test
void itConnectsToARealServerAndInstantsGoBothWaysAsUtcWhateverTheJvmZone() throws Exception {
String hostPort = System.getProperty("db.it.mariadb");
String file = System.getProperty("db.it.password-file");
assumeTrue(hostPort != null && file != null, "no MariaDB server configured");
String[] hp = hostPort.split(":");
TimeZone jvm = TimeZone.getDefault();
TimeZone.setDefault(TimeZone.getTimeZone("America/Mexico_City")); // a JVM that is not on UTC
Calendar utc = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
try (Connection c = new MariaDbProvider().dataSource(settings(hp[0], Integer.parseInt(hp[1]), "runway",
Files.readString(Path.of(file)).strip(), Tls.DISABLE, null)).getConnection()) {
try (Statement s = c.createStatement(); ResultSet rs = s.executeQuery("SELECT VERSION()")) {
rs.next();
assertThat(rs.getString(1)).contains("MariaDB");
}
try (Statement s = c.createStatement()) {
s.execute("SET time_zone = '+00:00'"); // what the database plugin pins on every connection
s.execute("CREATE TEMPORARY TABLE rw_times (at DATETIME(6) NOT NULL)");
}
// The way the database plugin's backups and registry write and read (Portable, MariaDbEngine.instant).
Instant now = Instant.now().truncatedTo(ChronoUnit.MICROS); // DATETIME(6)
try (PreparedStatement ps = c.prepareStatement("INSERT INTO rw_times (at) VALUES (?)")) {
ps.setObject(1, LocalDateTime.ofInstant(now, ZoneOffset.UTC));
ps.executeUpdate();
}
try (PreparedStatement ps = c.prepareStatement("SELECT at, UTC_TIMESTAMP(6), "
+ "TIMESTAMPDIFF(SECOND, ?, UTC_TIMESTAMP(6)) FROM rw_times")) {
ps.setTimestamp(1, Timestamp.from(Instant.now()), utc);
try (ResultSet rs = ps.executeQuery()) {
rs.next();
assertThat(rs.getObject(1, LocalDateTime.class).toInstant(ZoneOffset.UTC))
.as("a UTC LocalDateTime read back as written").isEqualTo(now);
assertThat(rs.getObject(2, LocalDateTime.class).toInstant(ZoneOffset.UTC))
.as("the server's UTC clock read as a LocalDateTime")
.isBetween(now.minusSeconds(5), Instant.now().plusSeconds(5));
assertThat(rs.getTimestamp(1, utc).toInstant()).as("read as a Timestamp with a UTC Calendar")
.isEqualTo(now);
assertThat(Math.abs(rs.getLong(3))).as("a Timestamp bound with a UTC Calendar")
.isLessThanOrEqualTo(5);
}
}
} finally {
TimeZone.setDefault(jvm);
}
assertThat(new MariaDbProvider().driverVersion()).startsWith("MariaDB Connector/J");
}
/** Turns on @ConfigurationProperties binding, as the kernel's context does. */
@Configuration(proxyBeanMethods = false)
@EnableConfigurationProperties
static class Binding {
}
@Test
void theConfigurationRegistersOneProviderNamedForThePlugin() {
try (AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext()) {
ctx.registerBean(PluginSettings.class, FakePluginSettings::new);
ctx.register(Binding.class, MariaDbProviderConfig.class);
ctx.refresh();
assertThat(ctx.getBeanNamesForType(mx.quest.database.spi.DatabaseProvider.class))
.containsExactly("databaseMariadbProvider");
for (String name : ctx.getBeanDefinitionNames()) {
if ("mariaDbProviderConfig".equals(ctx.getBeanDefinition(name).getFactoryBeanName())) {
assertThat(name).as("bean names carry the plugin id").startsWith("databaseMariadb");
}
}
}
}
@Test
void theServerSettingsAreThisPluginsOwnRunningAndSaved() {
try (AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext()) {
String prefix = "runway.plugin.database-mariadb.";
ctx.getEnvironment().getPropertySources().addFirst(new MapPropertySource("test", Map.of(
prefix + "host", "db.running", prefix + "port", "6000", prefix + "database", "runway",
prefix + "username", "rw", prefix + "password", "ENC(only-the-stored-form)",
prefix + "tls", "require", prefix + "collation", "utf8mb4_uca1400_ai_ci",
"runway.plugin.database.host", "not-this-plugins")));
ctx.registerBean(PluginSettings.class, () -> new FakePluginSettings().appSecret("password", "running-pw")
.savedApp("host", "db.saved").savedApp("database", "runway").savedApp("username", "rw2")
.savedApp("password", "saved-pw"));
ctx.register(Binding.class, MariaDbProviderConfig.class);
ctx.refresh();
MariaDbProvider provider = ctx.getBean(MariaDbProvider.class);
ProviderSettings running = provider.runningSettings().orElseThrow();
assertThat(running.host()).isEqualTo("db.running");
assertThat(running.port()).isEqualTo("6000");
assertThat(running.username()).isEqualTo("rw");
assertThat(running.tls()).isEqualTo("require");
assertThat(running.password()).as("in clear, from appSecret").isEqualTo("running-pw");
assertThat(running.collation()).isEqualTo("utf8mb4_uca1400_ai_ci");
ProviderSettings saved = provider.savedSettings().orElseThrow();
assertThat(saved.host()).isEqualTo("db.saved");
assertThat(saved.username()).isEqualTo("rw2");
assertThat(saved.password()).isEqualTo("saved-pw");
assertThat(saved.port()).as("unsaved: blank, the product's default").isNull();
}
}
@Test
void withoutSettingsTheProviderSaysNothingAsBeforeTwo() {
assertThat(new MariaDbProvider().runningSettings()).isEmpty();
assertThat(new MariaDbProvider().savedSettings()).isEmpty();
}
@Test
void theCompiledClassesLinkNoHostInternals() throws Exception {
Path classes = Path.of("target", "classes");
Pattern host = Pattern.compile("mx[/.]quest[/.]runway[/.](?!spi[/.])[\\w/.$]*");
List<String> problems = new ArrayList<>();
try (Stream<Path> files = Files.walk(classes)) {
for (Path f : files.filter(x -> x.toString().endsWith(".class")).toList()) {
Matcher m = host.matcher(new String(Files.readAllBytes(f), StandardCharsets.ISO_8859_1));
while (m.find()) {
problems.add(f + " → " + m.group());
}
}
}
assertThat(problems).isEmpty();
}
}
+26
View File
@@ -0,0 +1,26 @@
# Changelog
All notable changes are recorded here. Versions follow [Semantic Versioning](https://semver.org/).
## [2.0.0] — 2026-10-30
### Upgrade note
- Install it together with `database` 2.0.0, on Runway 1.2.0 or later, and move the PostgreSQL server's
settings into this plugin as the `database` 2.0.0 *Upgrade note* says. On Runway 1.1.x, keep 1.0.0 of both.
### Changed
- **This plugin holds the PostgreSQL server's settings**: host, port, database, username, password, TLS and CA
certificate, on its own settings page (**Plugins → Database — PostgreSQL → Settings**; file
`external/plugin-settings/database-postgresql.yml`, under `runway.plugin.database-postgresql`). Until 2.0.0 they were the `database` plugin's;
move them as its 2.0.0 *Upgrade note* says.
- Requires `database >= 2.0.0` and Runway SPI 1.2.0 (Runway 1.2.0), whose `PluginSettings.savedApp` hands the saved
settings to the database plugin's connection test.
## [1.0.0] — 2026-10-29
First public release of `database-postgresql`: the PostgreSQL 14+ provider for the `database` plugin, with the
PostgreSQL JDBC driver (pgjdbc) 42.7.10 bundled. Requires SPI `1.1.0` (Runway `1.1.0` or later) and `database`
`1.0.0`. Licensed under the GNU AGPL v3.0 with an additional permission for plugins (`LICENSE`,
`LICENSE-EXCEPTION`); pgjdbc is under the BSD 2-Clause License.
+661
View File
@@ -0,0 +1,661 @@
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
<http://www.gnu.org/licenses/>.
@@ -0,0 +1,44 @@
Runway — additional permission for plugins
(an additional permission under section 7 of the GNU Affero General Public License, version 3)
Copyright (C) 2026 Quest ICT SAS de CV
Runway is free software: you can redistribute it and/or modify it under the terms of the
GNU Affero General Public License as published by the Free Software Foundation, version 3
(the file LICENSE), with the additional permission below. Runway is distributed in the hope
that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public
License for more details.
1. Definitions
"Runway" means the Runway kernel and every Runway plugin whose source carries this file.
"Published SPI" means the public classes and interfaces of the runway-spi artifact
(the package mx.quest.runway.spi and its subpackages), together with the public classes
and interfaces of any package named "spi" that a part of Runway publishes for other
plugins to use (for example mx.quest.search.spi).
"Plugin" means an independent module that Runway loads as a plugin, that interacts with
Runway only through the Published SPI, and that is not based on any part of Runway other
than the Published SPI.
2. Permission
As an additional permission, the copyright holder gives you permission to combine Runway
with Plugins, and to convey and run the resulting combination, without the terms of the
GNU Affero General Public License applying to those Plugins. You may license, convey and
run your Plugins under terms of your choice, provided that you continue to meet the terms
of the GNU Affero General Public License for Runway itself, including offering the
Corresponding Source of Runway, and of any modification you make to it, as that license
requires.
3. Testing
Compiling a Plugin's tests against the runway-spi-testkit artifact, and running them, does
not by itself make the Plugin subject to the GNU Affero General Public License.
4. Modified versions
If you modify Runway, you may extend this additional permission to your version, but you
are not obliged to do so. If you do not wish to, delete this file from your version.
+16
View File
@@ -0,0 +1,16 @@
# Runway Database — PostgreSQL provider
Lets the [`database`](../database) plugin use **PostgreSQL 14 or later** (database encoding `UTF8`). It bundles the
pgjdbc driver and builds a configured, unpooled `DataSource`; every statement Runway runs is written in the database
plugin. Since 2.0.0 it also holds the server's settings: host, port, database, account, password and TLS,
on its own settings page (**Plugins → Database — PostgreSQL → Settings**, file `external/plugin-settings/database-postgresql.yml`).
With both providers installed, choose this one with the database plugin's `provider: postgresql` setting; with one
installed, it is used.
- **Plugin id:** `database-postgresql` (v`2.0.0`) — install folder `external/plugins/database-postgresql/`
- **Requires:** `database >= 2.0.0`, Runway SPI `1.2.0` or later (Runway 1.2.0)
- **Bundles:** pgjdbc `42.7.10` (BSD-2-Clause) in `lib/`; its license is in `THIRD-PARTY-NOTICES`
Setup, grants and settings: the kernel's ADMINISTRATION §11.1 — step by step, the settings file for a setup
without the console, upgrading from 1.x, and a table for when it does not connect. Details: [`docs/DATABASE-POSTGRESQL-PLUGIN.md`](docs/DATABASE-POSTGRESQL-PLUGIN.md),
[`CHANGELOG.md`](CHANGELOG.md).
@@ -0,0 +1,39 @@
Third-party software bundled with the database-postgresql plugin
=================================================================
The plugin's own code is licensed under the GNU Affero General Public License version 3 with an additional
permission for plugins (LICENSE, LICENSE-EXCEPTION). Its zip also carries, unmodified, in lib/:
PostgreSQL JDBC Driver (pgjdbc) 42.7.10 (org.postgresql:postgresql, lib/postgresql-42.7.10.jar)
https://jdbc.postgresql.org/
Licensed under the BSD 2-Clause License; the text follows. The jar also carries its license and the licenses of
the software it includes in META-INF/LICENSE and META-INF/licenses/.
--------------------------------------------------------------------------------------------------------------------
BSD 2-Clause License (META-INF/LICENSE of the jar, first part)
--------------------------------------------------------------------------------------------------------------------
Copyright (c) 1997, PostgreSQL Global Development Group
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
@@ -0,0 +1,37 @@
# The PostgreSQL provider
`PostgresProvider` builds a `PGSimpleDataSource` from the database plugin's checked `ConnectionSettings`:
| Property | Value |
|---|---|
| server, port, database | the checked host (an IPv6 literal in brackets), the port or 5432, the database |
| user, password | the account, as properties — never in the URL |
| `ApplicationName` | `runway` (visible in `pg_stat_activity`) |
| `connectTimeout`, `loginTimeout` | the connect timeout |
| `socketTimeout` | longer than any statement timeout the database plugin sets |
| `tcpKeepAlive` | on |
| TLS `DISABLE` | `sslmode=disable` |
| TLS `REQUIRE` | `sslmode=require` with `NonValidatingFactory`: encrypted, the server not checked, no client certificate |
| TLS `VERIFY_FULL` | `sslmode=verify-full`; with a CA certificate `LibPQFactory` and `sslrootcert` = the CA file, otherwise `DefaultJavaSSLFactory` (the JVM trust store). The host name is always checked. |
Nothing else is taken from settings: no socket factory, logger file or password callback. `channelBinding` stays at
the driver's default, `prefer`, so a server that offers SCRAM channel binding over TLS gets it.
The provider is one bean, `databasePostgresqlProvider`, collected by type. Tests: `PostgresProviderTest` (the
properties for each TLS policy, a real connection when `-Ddb.it.postgresql=host:port` and
`-Ddb.it.password-file=…` are set, the bean name, and the linkage scan). End to end:
`../database/scripts/verify-against-host.sh` with `PROVIDER=postgresql`.
## Its settings (since 2.0.0)
The server's settings are this plugin's own app-level settings (`runway.plugin.database-postgresql.*`, the console's **Plugins →
Database — PostgreSQL → Settings**): `host`, `port`, `database`, `username`, `password` (a `secret`, bound to the
others), `tls`, `caCertificate`. The provider hands them to the database plugin raw; the database
plugin checks every one before use, as before:
- **running** (`runningSettings()`): bound at startup into a `ProviderSettingsProps` bean
(`databasePostgresqlSettings`), the password read in clear with `PluginSettings.appSecret("password")`;
- **saved** (`savedSettings()`): read with `PluginSettings.savedApp(key)` (SPI 1.2.0) from the settings file as it is
now, for the database plugin's connection test before a restart applies them.
A `collation` written into this plugin's file by hand is never handed over: it is a MariaDB setting.
@@ -0,0 +1,15 @@
# Runway Database — PostgreSQL provider — English
database-postgresql.group.connection=Server
database-postgresql.group.connection.help=The PostgreSQL server Runway keeps plugins' data on. Changes apply after a restart; test them first with the connection tests on the Database plugin's settings page. In a cluster every node needs the same values.
database-postgresql.set.host=Host
database-postgresql.set.host.help=A host name or an IP address. One server only.
database-postgresql.set.port=Port
database-postgresql.set.port.help=Leave blank for PostgreSQL's default, 5432.
database-postgresql.set.database=Database
database-postgresql.set.database.help=An existing database on the server. Runway creates its schemas inside it.
database-postgresql.set.username=Username
database-postgresql.set.password=Password
database-postgresql.set.tls=TLS
database-postgresql.set.tls.help=verify-full checks the server's certificate and name. require encrypts without checking who the server is. Use disable only for a database on the same host or a private network you trust.
database-postgresql.set.caCertificate=CA certificate (PEM)
database-postgresql.set.caCertificate.help=The certificate authority that signed the server's certificate, when the Java trust store does not know it.
@@ -0,0 +1,15 @@
# Runway Database — PostgreSQL provider — español
database-postgresql.group.connection=Servidor
database-postgresql.group.connection.help=El servidor PostgreSQL donde Runway guarda los datos de los plugins. Los cambios se aplican al reiniciar; pruébelos antes con las pruebas de conexión de la página de ajustes del plugin Base de datos. En un clúster, todos los nodos necesitan los mismos valores.
database-postgresql.set.host=Servidor
database-postgresql.set.host.help=Un nombre de host o una dirección IP. Un solo servidor.
database-postgresql.set.port=Puerto
database-postgresql.set.port.help=Déjelo en blanco para usar el predeterminado de PostgreSQL, 5432.
database-postgresql.set.database=Base de datos
database-postgresql.set.database.help=Una base de datos existente en el servidor. Runway crea sus esquemas dentro de ella.
database-postgresql.set.username=Usuario
database-postgresql.set.password=Contraseña
database-postgresql.set.tls=TLS
database-postgresql.set.tls.help=verify-full comprueba el certificado y el nombre del servidor. require cifra sin comprobar quién es el servidor. Use disable solo para una base de datos en el mismo equipo o en una red privada de confianza.
database-postgresql.set.caCertificate=Certificado de la CA (PEM)
database-postgresql.set.caCertificate.help=La autoridad que firmó el certificado del servidor, cuando el almacén de confianza de Java no la conoce.
+47
View File
@@ -0,0 +1,47 @@
# =============================================================================
# Runway Database — PostgreSQL provider
# Lets the database plugin use PostgreSQL 14 or later. It brings the pgjdbc
# driver (BSD-2-Clause, in lib/) and builds a configured DataSource; every
# statement Runway runs is written in the database plugin.
#
# The server, the account and TLS are set on THIS plugin's settings page
# (since 2.0.0); the database plugin keeps the provider choice and the
# limits. With both providers installed, choose this one with the database
# plugin's `provider: postgresql` setting.
#
# The install folder name MUST equal this `id`: external/plugins/database-postgresql/.
# =============================================================================
id: database-postgresql
name: Database — PostgreSQL
version: 2.0.0
mainClass: mx.quest.database.postgresql.PostgresProviderConfig
# The database plugin publishes the DatabaseProvider interface this plugin implements.
requires: [ "database >= 2.0.0" ]
# SPI 1.2.0: PluginSettings.savedApp, which hands the saved settings to the connection test.
requiresSpi: ">=1.2.0"
settingGroups:
- { id: connection, label: database-postgresql.group.connection, help: database-postgresql.group.connection.help }
# Runway-wide settings, applied on RESTART. In a cluster every node needs the same values and the same platform
# secret key. Test them before restarting: Plugins -> Database -> Settings, "Connection tests".
settings:
- { key: host, type: string, group: connection, label: database-postgresql.set.host, help: database-postgresql.set.host.help }
- { key: port, type: int, range: "1..65535", group: connection, label: database-postgresql.set.port,
help: database-postgresql.set.port.help }
- { key: database, type: string, group: connection, label: database-postgresql.set.database,
help: database-postgresql.set.database.help }
- { key: username, type: string, group: connection, label: database-postgresql.set.username }
# Bound to where it goes: changing any of these without typing the password again removes the stored one.
- key: password
type: secret
group: connection
label: database-postgresql.set.password
secretBoundTo: [host, port, database, username, tls, caCertificate]
- { key: tls, type: enum, range: "verify-full,require,disable", default: verify-full, group: connection,
label: database-postgresql.set.tls, help: database-postgresql.set.tls.help }
- { key: caCertificate, type: text, group: connection, advanced: true, label: database-postgresql.set.caCertificate,
help: database-postgresql.set.caCertificate.help }
+169
View File
@@ -0,0 +1,169 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<!--
The PostgreSQL provider for the database plugin: the pgjdbc driver (BSD-2-Clause) in lib/ and the code that
builds its DataSource. Same managed versions as the Runway kernel (Spring Boot 4.0.6), thin jar, no repackage.
-->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>4.0.6</version>
<relativePath/>
</parent>
<groupId>mx.quest</groupId>
<artifactId>runway-plugin-database-postgresql</artifactId>
<version>2.0.0</version>
<packaging>jar</packaging>
<name>Runway Database — PostgreSQL</name>
<licenses>
<license>
<name>GNU Affero General Public License v3.0, with the Runway additional permission for plugins</name>
<url>https://www.gnu.org/licenses/agpl-3.0.txt</url>
<distribution>repo</distribution>
<comments>See LICENSE and LICENSE-EXCEPTION.</comments>
</license>
</licenses>
<description>
The PostgreSQL provider for the Runway database plugin: bundles the pgjdbc driver and builds a configured, unpooled DataSource (one host, pinned TLS and timeouts). Every statement Runway runs is written in the database plugin.
</description>
<properties>
<java.version>25</java.version>
<maven.compiler.release>25</maven.compiler.release>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<!-- Reproducible builds: pins every archive entry's timestamp. Bump at each release. -->
<project.build.outputTimestamp>2026-10-29T00:00:00Z</project.build.outputTimestamp>
<!-- The runway-spi this plugin compiles against: SPI 1.2.0 adds PluginSettings.savedApp. -->
<runway.version>1.2.0</runway.version>
<!-- The database plugin whose SPI this provider implements (provided: the shared plugin class loader
supplies it; install ../database first). -->
<database.version>2.0.0</database.version>
<!-- The driver bundled in lib/. Pinned so the bundle never drifts from what the notices name. -->
<postgresql.version>42.7.10</postgresql.version>
</properties>
<dependencies>
<dependency>
<groupId>mx.quest</groupId>
<artifactId>runway-spi</artifactId>
<version>${runway.version}</version>
</dependency>
<dependency>
<groupId>mx.quest</groupId>
<artifactId>runway-spi-testkit</artifactId>
<version>${runway.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>mx.quest</groupId>
<artifactId>runway-plugin-database</artifactId>
<version>${database.version}</version>
<scope>provided</scope>
</dependency>
<!-- The driver, bundled into lib/ by the assembly below. -->
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>${postgresql.version}</version>
</dependency>
<!-- The kernel supplies these at runtime; never bundled. -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>runway-plugin-database-postgresql</finalName>
<plugins>
<!-- 1. The driver into target/staged-lib, with its versioned file name; the assembly copies it into lib/. -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<id>bundle-libs</id>
<phase>package</phase>
<goals>
<goal>copy</goal>
</goals>
<configuration>
<artifactItems>
<artifactItem>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>${postgresql.version}</version>
</artifactItem>
</artifactItems>
<outputDirectory>${project.build.directory}/staged-lib</outputDirectory>
<stripVersion>false</stripVersion>
<overWriteReleases>true</overWriteReleases>
</configuration>
</execution>
</executions>
</plugin>
<!-- 2. Assemble target/database/ (folder) and the UI zip. -->
<plugin>
<artifactId>maven-antrun-plugin</artifactId>
<executions>
<execution>
<id>assemble-plugin-folder</id>
<phase>package</phase>
<goals>
<goal>run</goal>
</goals>
<configuration>
<target>
<property name="stage" value="${project.build.directory}/database-postgresql"/>
<delete dir="${stage}"/>
<mkdir dir="${stage}"/>
<copy file="${project.basedir}/plugin.yml" todir="${stage}"/>
<copy file="${project.basedir}/LICENSE" todir="${stage}"/>
<copy file="${project.basedir}/LICENSE-EXCEPTION" todir="${stage}"/>
<copy file="${project.basedir}/THIRD-PARTY-NOTICES" todir="${stage}"/>
<copy file="${project.build.directory}/runway-plugin-database-postgresql.jar" todir="${stage}"/>
<copy todir="${stage}/lib">
<fileset dir="${project.build.directory}/staged-lib"/>
</copy>
<copy todir="${stage}/i18n">
<fileset dir="${project.basedir}/i18n"/>
</copy>
<!-- Never a plugin zip without its libraries (it would load and fail at its first use). -->
<fail message="no library in ${stage}/lib">
<condition><resourcecount when="equal" count="0">
<fileset dir="${stage}" includes="lib/*.jar"/></resourcecount></condition>
</fail>
<touch datetime="${project.build.outputTimestamp}"
pattern="yyyy-MM-dd'T'HH:mm:ss'Z'">
<fileset dir="${stage}"/>
<dirset dir="${stage}"/>
<dirset dir="${project.build.directory}" includes="database-postgresql"/>
</touch>
<!-- The stamped files predate any earlier zip, so <zip> would skip the rebuild. -->
<delete file="${project.build.directory}/runway-plugin-database-postgresql-${project.version}.zip"/>
<zip destfile="${project.build.directory}/runway-plugin-database-postgresql-${project.version}.zip">
<zipfileset dir="${project.build.directory}" includes="database-postgresql/**"/>
</zip>
<echo message="Staged install folder (with the driver in lib/): ${stage}"/>
<echo message="UI-uploadable archive: ${project.build.directory}/runway-plugin-database-postgresql-${project.version}.zip"/>
</target>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
@@ -0,0 +1,117 @@
package mx.quest.database.postgresql;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Supplier;
import javax.sql.DataSource;
import mx.quest.database.spi.ConnectionSettings;
import mx.quest.database.spi.DatabaseProvider;
import mx.quest.database.spi.ProviderSettings;
import org.postgresql.ds.PGSimpleDataSource;
import org.postgresql.util.DriverInfo;
/**
* PostgreSQL through pgjdbc. Builds an unpooled {@link PGSimpleDataSource} from the database plugin's checked
* settings: one host, the account as properties, TLS exactly as configured, and nothing taken from free text. The
* database plugin pools it and runs every statement.
*
* <p>TLS:
* <ul>
* <li>{@code DISABLE}: {@code sslmode=disable}.</li>
* <li>{@code REQUIRE}: {@code sslmode=require} with the non-validating factory: encrypted, the server not
* checked, no client certificate (the factory initialises its TLS context with no key manager).</li>
* <li>{@code VERIFY_FULL}: {@code sslmode=verify-full}, checking the chain and the host name, against the
* configured CA file when there is one ({@code sslrootcert}) and the JVM's trust store otherwise.</li>
* </ul>
*/
public final class PostgresProvider implements DatabaseProvider {
static final int DEFAULT_PORT = 5432;
static final String NON_VALIDATING = "org.postgresql.ssl.NonValidatingFactory";
static final String JVM_TRUST = "org.postgresql.ssl.DefaultJavaSSLFactory";
static final String CA_FILE = "org.postgresql.ssl.LibPQFactory";
private final Supplier<ProviderSettings> running;
private final Supplier<ProviderSettings> saved;
/**
* Without settings, as before database 2.0.0: for building data sources only (tests).
*/
public PostgresProvider() {
this(() -> null, () -> null);
}
/**
* @param running the server settings the application started with, from this plugin's own settings page
* @param saved the server settings saved on that page now, which the next restart applies
*/
public PostgresProvider(Supplier<ProviderSettings> running, Supplier<ProviderSettings> saved) {
this.running = Objects.requireNonNull(running, "running");
this.saved = Objects.requireNonNull(saved, "saved");
}
@Override
public String id() {
return "postgresql";
}
@Override
public String driverVersion() {
return "pgjdbc " + DriverInfo.DRIVER_VERSION;
}
@Override
public DataSource dataSource(ConnectionSettings settings) {
Objects.requireNonNull(settings, "settings");
PGSimpleDataSource ds = new PGSimpleDataSource();
String host = settings.host().indexOf(':') >= 0 ? "[" + settings.host() + "]" : settings.host();
ds.setServerNames(new String[] {host});
ds.setPortNumbers(new int[] {settings.portOr(DEFAULT_PORT)});
ds.setDatabaseName(settings.database());
ds.setUser(settings.username());
ds.setPassword(settings.password());
ds.setApplicationName("runway");
ds.setConnectTimeout(seconds(settings.connectTimeout().toSeconds()));
ds.setLoginTimeout(seconds(settings.connectTimeout().toSeconds()));
ds.setSocketTimeout(seconds(settings.socketTimeout().toSeconds()));
ds.setTcpKeepAlive(true);
switch (settings.tls()) {
case DISABLE -> ds.setSslMode("disable");
case REQUIRE -> {
ds.setSslMode("require");
ds.setSslfactory(NON_VALIDATING);
}
case VERIFY_FULL -> {
ds.setSslMode("verify-full");
if (settings.caCertificate() != null) {
ds.setSslfactory(CA_FILE);
ds.setSslRootCert(settings.caCertificate().toAbsolutePath().toString());
} else {
ds.setSslfactory(JVM_TRUST);
}
}
default -> throw new IllegalArgumentException("unknown TLS policy " + settings.tls());
}
return ds;
}
private static int seconds(long value) {
return (int) Math.max(1, Math.min(Integer.MAX_VALUE, value));
}
@Override
public Optional<ProviderSettings> runningSettings() {
return Optional.ofNullable(withoutCollation(running.get()));
}
@Override
public Optional<ProviderSettings> savedSettings() {
return Optional.ofNullable(withoutCollation(saved.get()));
}
/** A collation is a MariaDB setting: never handed over from here, even when written into the file by hand. */
private static ProviderSettings withoutCollation(ProviderSettings s) {
return s == null ? null : new ProviderSettings(s.host(), s.port(), s.database(), s.username(), s.password(),
s.tls(), s.caCertificate(), null);
}
}
@@ -0,0 +1,33 @@
package mx.quest.database.postgresql;
import mx.quest.database.spi.ProviderSettings;
import mx.quest.database.spi.ProviderSettingsProps;
import mx.quest.runway.spi.service.PluginSettings;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* Registers the PostgreSQL provider; the database plugin collects it by type. The server's settings are this plugin's
* own app-level settings ({@code runway.plugin.database-postgresql.*}, since database 2.0.0): the running ones as
* bound at startup, the password through {@link PluginSettings#appSecret}, and the saved ones through
* {@link PluginSettings#savedApp} for the connection test. With both providers installed the context holds two
* {@link ProviderSettingsProps} beans, hence the qualifier.
*/
@Configuration(proxyBeanMethods = false)
public class PostgresProviderConfig {
@Bean
@ConfigurationProperties("runway.plugin.database-postgresql")
public ProviderSettingsProps databasePostgresqlSettings() {
return new ProviderSettingsProps();
}
@Bean
public PostgresProvider databasePostgresqlProvider(
@Qualifier("databasePostgresqlSettings") ProviderSettingsProps server, PluginSettings settings) {
return new PostgresProvider(() -> server.toSettings(settings.appSecret(ProviderSettings.PASSWORD)),
() -> ProviderSettings.read(settings::savedApp));
}
}
@@ -0,0 +1,152 @@
package mx.quest.database.postgresql;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assumptions.assumeTrue;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Stream;
import mx.quest.database.spi.ConnectionSettings.Tls;
import mx.quest.database.spi.ConnectionSettings;
import mx.quest.database.spi.ProviderSettings;
import mx.quest.runway.spi.service.PluginSettings;
import mx.quest.runway.spi.testkit.FakePluginSettings;
import org.junit.jupiter.api.Test;
import org.postgresql.ds.PGSimpleDataSource;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.MapPropertySource;
class PostgresProviderTest {
static ConnectionSettings settings(String host, int port, String password, Tls tls, Path ca) {
return new ConnectionSettings(host, port, "runway", "runway", password, tls, ca, Duration.ofSeconds(5),
Duration.ofSeconds(40));
}
@Test
void tlsIsExactlyAsConfiguredAndTimeoutsArePinned() {
PostgresProvider p = new PostgresProvider();
PGSimpleDataSource off = (PGSimpleDataSource) p.dataSource(settings("db", 0, "pw", Tls.DISABLE, null));
assertThat(off.getSslMode()).isEqualTo("disable");
assertThat(off.getPortNumbers()).containsExactly(5432);
assertThat(off.getConnectTimeout()).isEqualTo(5);
assertThat(off.getSocketTimeout()).isEqualTo(40);
assertThat(off.getTcpKeepAlive()).isTrue();
PGSimpleDataSource req = (PGSimpleDataSource) p.dataSource(settings("db", 1, "pw", Tls.REQUIRE, null));
assertThat(req.getSslMode()).isEqualTo("require");
assertThat(req.getSslfactory()).isEqualTo(PostgresProvider.NON_VALIDATING);
PGSimpleDataSource jvm = (PGSimpleDataSource) p.dataSource(settings("db", 1, "pw", Tls.VERIFY_FULL, null));
assertThat(jvm.getSslMode()).isEqualTo("verify-full");
assertThat(jvm.getSslfactory()).isEqualTo(PostgresProvider.JVM_TRUST);
PGSimpleDataSource ca = (PGSimpleDataSource) p.dataSource(settings("db", 1, "pw", Tls.VERIFY_FULL,
Path.of("/x/ca.pem")));
assertThat(ca.getSslfactory()).isEqualTo(PostgresProvider.CA_FILE);
assertThat(ca.getSslRootCert()).isEqualTo("/x/ca.pem");
assertThat(ca.getUrl()).doesNotContain("pw").doesNotContain("password");
PGSimpleDataSource v6 = (PGSimpleDataSource) p.dataSource(settings("::1", 1, "pw", Tls.DISABLE, null));
assertThat(v6.getServerNames()).containsExactly("[::1]");
}
@Test
void itConnectsToARealServer() throws Exception {
String hostPort = System.getProperty("db.it.postgresql");
String file = System.getProperty("db.it.password-file");
assumeTrue(hostPort != null && file != null, "no PostgreSQL server configured");
String[] hp = hostPort.split(":");
try (Connection c = new PostgresProvider().dataSource(settings(hp[0], Integer.parseInt(hp[1]),
Files.readString(Path.of(file)).strip(), Tls.DISABLE, null)).getConnection();
Statement s = c.createStatement(); ResultSet rs = s.executeQuery("SELECT current_setting('application_name')")) {
rs.next();
assertThat(rs.getString(1)).isEqualTo("runway");
}
assertThat(new PostgresProvider().driverVersion()).isEqualTo("pgjdbc 42.7.10");
}
/** Turns on @ConfigurationProperties binding, as the kernel's context does. */
@Configuration(proxyBeanMethods = false)
@EnableConfigurationProperties
static class Binding {
}
@Test
void theConfigurationRegistersOneProviderNamedForThePlugin() {
try (AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext()) {
ctx.registerBean(PluginSettings.class, FakePluginSettings::new);
ctx.register(Binding.class, PostgresProviderConfig.class);
ctx.refresh();
assertThat(ctx.getBeanNamesForType(mx.quest.database.spi.DatabaseProvider.class))
.containsExactly("databasePostgresqlProvider");
for (String name : ctx.getBeanDefinitionNames()) {
if ("postgresProviderConfig".equals(ctx.getBeanDefinition(name).getFactoryBeanName())) {
assertThat(name).as("bean names carry the plugin id").startsWith("databasePostgresql");
}
}
}
}
@Test
void theServerSettingsAreThisPluginsOwnRunningAndSaved() {
try (AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext()) {
String prefix = "runway.plugin.database-postgresql.";
ctx.getEnvironment().getPropertySources().addFirst(new MapPropertySource("test", Map.of(
prefix + "host", "db.running", prefix + "port", "6000", prefix + "database", "runway",
prefix + "username", "rw", prefix + "password", "ENC(only-the-stored-form)",
prefix + "tls", "require", prefix + "collation", "utf8mb4_uca1400_ai_ci",
"runway.plugin.database.host", "not-this-plugins")));
ctx.registerBean(PluginSettings.class, () -> new FakePluginSettings().appSecret("password", "running-pw")
.savedApp("host", "db.saved").savedApp("database", "runway").savedApp("username", "rw2")
.savedApp("password", "saved-pw"));
ctx.register(Binding.class, PostgresProviderConfig.class);
ctx.refresh();
PostgresProvider provider = ctx.getBean(PostgresProvider.class);
ProviderSettings running = provider.runningSettings().orElseThrow();
assertThat(running.host()).isEqualTo("db.running");
assertThat(running.port()).isEqualTo("6000");
assertThat(running.username()).isEqualTo("rw");
assertThat(running.tls()).isEqualTo("require");
assertThat(running.password()).as("in clear, from appSecret").isEqualTo("running-pw");
assertThat(running.collation()).as("a MariaDB setting, never handed over").isNull();
ProviderSettings saved = provider.savedSettings().orElseThrow();
assertThat(saved.host()).isEqualTo("db.saved");
assertThat(saved.username()).isEqualTo("rw2");
assertThat(saved.password()).isEqualTo("saved-pw");
assertThat(saved.port()).as("unsaved: blank, the product's default").isNull();
}
}
@Test
void withoutSettingsTheProviderSaysNothingAsBeforeTwo() {
assertThat(new PostgresProvider().runningSettings()).isEmpty();
assertThat(new PostgresProvider().savedSettings()).isEmpty();
}
@Test
void theCompiledClassesLinkNoHostInternals() throws Exception {
Path classes = Path.of("target", "classes");
Pattern host = Pattern.compile("mx[/.]quest[/.]runway[/.](?!spi[/.])[\\w/.$]*");
List<String> problems = new ArrayList<>();
try (Stream<Path> files = Files.walk(classes)) {
for (Path f : files.filter(x -> x.toString().endsWith(".class")).toList()) {
Matcher m = host.matcher(new String(Files.readAllBytes(f), StandardCharsets.ISO_8859_1));
while (m.find()) {
problems.add(f + " → " + m.group());
}
}
}
assertThat(problems).isEmpty();
}
}
+60
View File
@@ -0,0 +1,60 @@
# Changelog
All notable changes are recorded here. Versions follow [Semantic Versioning](https://semver.org/).
## [2.0.0] — 2026-10-30
The server's settings move to the provider plugins, and the connection tests move to this plugin's settings page.
**A breaking change for the settings**: read the *Upgrade note* first.
### Upgrade note
- Install `database`, and the provider you use, **2.0.0 together**, on Runway **1.2.0** or later (SPI 1.2.0). A 1.x
provider with database 2.0.0 gives *No provider: the database-postgresql plugin is older than 2.0.0*.
- Move the server's keys — `host`, `port`, `database`, `username`, `password`, `tls`, `caCertificate`, and on
MariaDB `collation` — from `external/plugin-settings/database.yml` (under `runway.plugin.database`) to the
provider's file, `external/plugin-settings/database-postgresql.yml` under `runway.plugin.database-postgresql` (or
`database-mariadb`). An encrypted password (`ENC(...)`) moves as it is. Keep `provider`, `namespace` and the limits
in `database.yml`. Or retype the settings on the provider's settings page and delete the old keys. Move them
**before** saving this plugin's settings form: a save keeps only the settings the form has, so it removes the old
keys, encrypted password included.
- Until they are moved, the status is *Not configured: the server settings moved to the database-postgresql plugin
…*, naming the keys to move; Runway never connects with the old keys.
- Then test them (below) and restart.
- On Runway 1.1.x, keep `database` 1.0.0 and its provider 1.0.0.
### Changed
- **The server's settings are the provider's.** Host, port, database, account, password, TLS and CA certificate are
set on the provider plugin's own settings page; MariaDB's collation is on MariaDB's page only. This plugin keeps
the provider choice, the namespace and the limits (pool size, statement time limit, backup budget).
- **The `provider` setting defaults to `auto`**: with one provider plugin installed, it is used; a choice is needed
only when both are installed.
- **The connection tests are below this plugin's settings form** (**Plugins → Database → Settings**), no longer on
the **Database** screen, which now links to them. They test the running connection and **each installed
provider's saved settings**, the ones the next restart would apply, and take no typed values. 1.0.0's test of
typed values is removed: a form with a username and a password box is one a browser fills in with the operator's
own saved console login, which a test would then send to whatever server the form named.
- The password is bound to host, port, database, username, TLS and CA certificate (no longer to the provider, which
now has a password of its own).
### Added
- Provider SPI: `ProviderSettings` (a provider's server settings, raw), `ProviderSettingsProps` (to bind them), and
`DatabaseProvider.runningSettings()` / `savedSettings()` (`default` methods; empty means a provider older than
2.0.0).
### Fixed
- On PostgreSQL, asking for TLS from a server that has TLS off was reported as a refused username or password; it is
now reported as a TLS failure.
## [1.0.0] — 2026-10-29
First public release of `database`: plugins can keep their own data in PostgreSQL 14+ or MariaDB 10.11+, through a
provider plugin (`database-postgresql` or `database-mariadb`). One schema per site, per-plugin migrations with
recovery actions, per-site backup and restore (also between the two products), and a **Database** screen in the
application console; Runway's own data stays on files, and Runway starts whether or not the database is reachable.
Plugins use it through the consumer SPI `mx.quest.database.spi`. Requires SPI `1.1.0` (Runway `1.1.0` or later).
Licensed under the GNU AGPL v3.0 with an additional permission for plugins (`LICENSE`, `LICENSE-EXCEPTION`); bundles
HikariCP (Apache License 2.0).
+661
View File
@@ -0,0 +1,661 @@
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
<http://www.gnu.org/licenses/>.
+44
View File
@@ -0,0 +1,44 @@
Runway — additional permission for plugins
(an additional permission under section 7 of the GNU Affero General Public License, version 3)
Copyright (C) 2026 Quest ICT SAS de CV
Runway is free software: you can redistribute it and/or modify it under the terms of the
GNU Affero General Public License as published by the Free Software Foundation, version 3
(the file LICENSE), with the additional permission below. Runway is distributed in the hope
that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public
License for more details.
1. Definitions
"Runway" means the Runway kernel and every Runway plugin whose source carries this file.
"Published SPI" means the public classes and interfaces of the runway-spi artifact
(the package mx.quest.runway.spi and its subpackages), together with the public classes
and interfaces of any package named "spi" that a part of Runway publishes for other
plugins to use (for example mx.quest.search.spi).
"Plugin" means an independent module that Runway loads as a plugin, that interacts with
Runway only through the Published SPI, and that is not based on any part of Runway other
than the Published SPI.
2. Permission
As an additional permission, the copyright holder gives you permission to combine Runway
with Plugins, and to convey and run the resulting combination, without the terms of the
GNU Affero General Public License applying to those Plugins. You may license, convey and
run your Plugins under terms of your choice, provided that you continue to meet the terms
of the GNU Affero General Public License for Runway itself, including offering the
Corresponding Source of Runway, and of any modification you make to it, as that license
requires.
3. Testing
Compiling a Plugin's tests against the runway-spi-testkit artifact, and running them, does
not by itself make the Plugin subject to the GNU Affero General Public License.
4. Modified versions
If you modify Runway, you may extend this additional permission to your version, but you
are not obliged to do so. If you do not wish to, delete this file from your version.
+59
View File
@@ -0,0 +1,59 @@
# Runway Database
Lets Runway plugins keep their own data in **PostgreSQL** or **MariaDB**. Runway's own data — sites, pages, users,
settings — stays on files; this plugin is for plugins.
- **One schema per site** (a database per site on MariaDB), created the first time a plugin uses the database for that
site, plus one installation-wide schema. Generations are never reused, so a site deleted and created again never
sees the old data.
- **Per-plugin migrations** read only from the plugin's own jar, with **ownership checks**: every object a plugin
creates carries its prefix. PostgreSQL runs a plugin's scripts in one transaction; MariaDB statement by statement,
resuming after a failure.
- **Backups**: a site's full backup carries its database data in a portable format (PostgreSQL ↔ MariaDB); a restore
builds a new generation and switches only when everything loaded.
- **A health screen** in the application console (**Settings → Database**) with recovery actions; **connection
tests** below this plugin's settings form, which try the running connection and each provider's saved settings
before a restart applies them; one line on each site's dashboard.
- **Runway never fails to start because of the database**: the plugin connects after startup, on its own thread.
The product comes from a provider plugin — [`database-postgresql`](../database-postgresql) or
[`database-mariadb`](../database-mariadb) — which brings the driver and, since 2.0.0, holds the server's settings
(host, account, password, TLS) on its own settings page; every statement Runway runs is written here. This plugin's
settings are the provider choice (`auto`: the one installed), the namespace and the limits.
- **Plugin id:** `database` (v`2.0.0`) — install folder `external/plugins/database/`
- **Requires:** Runway with SPI `1.2.0` or later (Runway 1.2.0; `requiresSpi: ">=1.2.0"`) and one provider plugin
2.0.0 or later
- **Bundles:** HikariCP `7.0.2` (Apache-2.0) in `lib/`; its license is in `THIRD-PARTY-NOTICES`
- **Publishes:** `mx.quest.database.spi` — the consumer interface (`DatabaseConsumer`, `Databases`, `PluginDatabase`,
`Scope`, `Dialect`) and the provider interface (`DatabaseProvider`, `ConnectionSettings`, `ProviderSettings`,
`ProviderSettingsProps`)
## For operators
Installation, the server's grants, every setting, TLS, clusters, backups and recovery are in the kernel's
**ADMINISTRATION §11.1**: *Setting it up, step by step*, *Setting it up without the console* (the provider's
`external/plugin-settings/database-postgresql.yml` or `database-mariadb.yml` file and its password), *Upgrading from
database 1.x* and *When it does not connect*. What site managers
see (the dashboard card, backups, the guestbook) is in the **SITE-MANAGER-GUIDE**, §8 and §12.
## For plugin authors
Read the authoring guide's **§7.14 "Using the database"** ([`../docs/PLUGIN-AUTHORING-GUIDE.md`](../docs/PLUGIN-AUTHORING-GUIDE.md)),
then the worked example [`runway-demo-database`](../runway-demo-database). How the plugin works inside, and why, is in
[`docs/DATABASE-PLUGIN.md`](docs/DATABASE-PLUGIN.md).
## Build and verify
```bash
mvn -o install # unit tests; the real-server tests skip without servers
# against throwaway servers (podman run … postgres:17 / mariadb:11.4), both products:
mvn -o test -Ddb.it.postgresql=127.0.0.1:55432 -Ddb.it.mariadb=127.0.0.1:53306 -Ddb.it.password-file=/path/pw
# inside a real Runway, with both providers installed:
PROVIDER=postgresql DB_HOST=127.0.0.1 DB_PORT=55432 DB_PASSWORD_FILE=/path/pw scripts/verify-against-host.sh
```
The real-server tests expect an account `runway` with a database `runway`; on MariaDB the account needs
`ALL PRIVILEGES` on `` `it%`.* `` for the tests' namespaces (and on `` `hv%`.* `` for the verify script's).
See [`CHANGELOG.md`](CHANGELOG.md).
+216
View File
@@ -0,0 +1,216 @@
Third-party software bundled with the database plugin
======================================================
The database plugin's own code is licensed under the GNU Affero General Public License version 3 with an additional
permission for plugins (LICENSE, LICENSE-EXCEPTION). Its zip also carries, unmodified, in lib/:
HikariCP 7.0.2 (com.zaxxer:HikariCP, lib/HikariCP-7.0.2.jar)
The JDBC connection pool. https://github.com/brettwooldridge/HikariCP
Licensed under the Apache License, Version 2.0; the full text follows. The jar carries no NOTICE file.
--------------------------------------------------------------------------------------------------------------------
Apache License, Version 2.0
--------------------------------------------------------------------------------------------------------------------
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
+235
View File
@@ -0,0 +1,235 @@
# The database plugin — how it works and why
> **Audience:** whoever maintains the `database` plugin or a provider, and plugin authors who want to know what
> happens behind `Scope.transaction`. Operators want the kernel's ADMINISTRATION §11.1; plugin authors start with the
> authoring guide's §7.14.
## 1. What it is for, and what it is not
Runway keeps its own data on files: a site is a folder, a backup is a zip of it, and nothing needs a database to
run. Some plugins are better served by one — many small records, queries, concurrent writers. This plugin gives them
PostgreSQL or MariaDB **without** making Runway depend on it:
- one database server per installation, chosen in settings;
- one schema per site, so a site's data is separate, travels in its backups and disappears with it;
- each plugin's objects carry its prefix, so plugins sharing a schema cannot collide;
- Runway starts, serves and administers sites whether or not the database is there.
Not covered: Runway's own data (it stays on files); a database per plugin; read replicas or several servers;
a plugin choosing its own server. Plugins are trusted code in the same JVM, as everywhere in Runway: the
separation between sites is enforced by this plugin's API, not by database permissions, because one account
reaches every schema.
## 2. The parts
| Part | Where | Job |
|---|---|---|
| Settings | `DatabaseProps`, `ProviderChoice` → `DatabaseConfig` | This plugin's own settings (provider choice, namespace, limits) bound from `runway.plugin.database.*`; `ProviderChoice` picks the provider (`auto`: the one installed) and takes the server's settings from it (`DatabaseProvider.runningSettings()`, since 2.0.0); `DatabaseConfig` checks every value before any use. 1.x server keys still in `database.yml` are bound only to report that they moved. |
| Runtime | `DatabaseRuntime` | Connects after startup on the plugin's executor, with back-off; checks the server; owns the pools. |
| Engines | `PostgresEngine`, `MariaDbEngine` | **All** the SQL Runway runs, per product. |
| Registry | `Registry` | Runway's own `rw_` tables in `<ns>_app`. |
| Site schemas | `SiteSchemas` | Which schema holds a site's data; allocation, retirement, removal, the sweep. |
| Locks | `Locks` | Per-site and install-wide locks across nodes. |
| Migrations | `Migrator` | Brings a plugin's tables in a schema to the shipped version. |
| Scopes | `ScopeImpl`, `PluginDatabaseImpl`, `DatabasesImpl` | What consumers call. |
| Backups | `DatabaseBackup`, `Archive`, `Portable` | Export, staged restore, parked data. |
| Console | `DatabaseConsoleController`, `DatabaseScreens`, `ConnectionTester` | The health screen, the dashboard line, and the connection tests (panel `templates/admin-app.html`, below this plugin's settings form): the running connection, and each installed provider's **saved** settings (`DatabaseProvider.savedSettings()`, read by the provider through the kernel's `PluginSettings.savedApp`). |
**Providers bring the driver, not the SQL.** A provider builds an unpooled `DataSource` from its own driver
classes with the checked settings and pinned properties; nothing goes through `DriverManager`. Every statement —
schema creation, locks, ownership checks, migrations, backup, restore — is in this plugin's engines, so the checks
that keep sites and plugins apart are written and reviewed in one place and a provider cannot weaken them. The
price: a new product needs a new engine here, not only a provider.
## 3. Connections
Three ways to a connection, for three jobs:
- **The main pool** (`poolMax`) lends connections to consumers: a 2-second borrow timeout so an outage fails fast,
the consumer statement timeout, and a per-site in-flight cap of half the pool so one busy site cannot starve the
others. A borrow that times out because every connection is in use fails that call only ("too many database calls
in flight"); only a failure to reach the server (SQLState class `08`, a connection-class exception) marks an
outage, which is re-checked after 2 seconds and then by the minute's heartbeat. The heartbeat opens a connection
of its own, so a setup pool that is only busy (a long restore, a migration) is never taken for an outage.
- **The setup pool** (two connections, 30-minute timeout) runs schema creation, registry writes, migrations, backup
and restore — never on a consumer's connection, because MariaDB's DDL commits whatever transaction it is in.
- **Lock connections** are opened unpooled for each database lock and closed after it, so a lock is never held on a
pooled connection and lock holders cannot exhaust a pool.
Every new connection is pinned: UTC time zone; on MariaDB a strict `sql_mode`, `InnoDB` by default,
`explicit_defaults_for_timestamp = 1` (a server can still be configured with it off, and then a table's first
`TIMESTAMP NOT NULL` column silently gains `DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP`, so a `created_at` would change on every
update), and a statement and lock-wait limit. Every borrow **binds** the connection in the same round trip that checks the registry still maps
the site to that schema (PostgreSQL: `set_config('search_path', …)` selected from `rw_sites`; MariaDB: the check, then
an explicit `USE`, never `setCatalog`, which the driver may skip). A connection whose bind or reset fails is thrown
away. On return PostgreSQL runs `DISCARD TEMP` (never `DISCARD ALL`, which would drop the driver's prepared
statements).
The server is checked before anything is created: PostgreSQL 14+ with a `UTF8` database; MariaDB 10.11+ and not MySQL (a
session cannot set `explicit_defaults_for_timestamp` before 10.10, so an older server is refused by its version rather
than failing every connection).
A failed check counts as unreachable, with the reason on the health screen.
## 4. Names and the life of a site's schema
Every name starts with the **namespace** (`rw`): `<ns>_app` and `<ns>_s_<base>_<gen>`, where `<base>` is the site id
lower-cased with everything else mapped to `_`, cut to fit 63/64 bytes, and `<gen>` comes from a sequence. The
mapping from site ids loses information (`Acme`/`acme`, `a.b`/`a_b`), so the generation — never reused — is what makes
names unique. Every name is checked against `^<ns>_(app|s_[a-z0-9_]+)$` and the length limit before any DDL, and
quoted. The namespace has no underscore, so one installation's names are never the start of another's.
**The incarnation token.** Allocation records the mapping with a random token, then writes the same token, and the
site id it was issued for, to the site's own folder (`schema.yml`, declared personal so transfer copies leave it out);
every resolution compares the two. What the folder says decides:
- **the same token**: the mapping is the site's;
- **a token issued for another site id** (copied in with another site's full backup), or the **`fresh: new site`**
marker: the data the registry has for this id is not this site's; that mapping is retired and a new generation
allocated. A new site gets the marker when it is created while the database is unreachable; with the database
reachable, creating a site retires at once any data an earlier site with the same id left behind;
- **another token of this site, or the `adopt: live` marker**: a restore put back a folder from another moment of the
same site (a full backup carries the token of the generation live when it was taken). The registry is the
authority: the live mapping's token is written back and its data stays;
- **no token file** while the registry has live data for the id: either a restore whose first step has not run yet,
or a site deleted and created again while the plugin was off. Neither binding (it could be an earlier site's data)
nor a fresh start (it could be a restored site's live data) is safe, so the site's data is "being prepared" until
the restore writes the token back, or the sweep finds the folder still without one on two passes in a row and
retires the data;
- **a folder that cannot be read** (permissions, a stale network mount): nothing is decided or changed. The call fails
as "database unavailable", the sweep skips the site, and a backup of it fails rather than record "no data".
The registry is written first and the token after, so a failure between the two leaves a folder that does not name
the new mapping: allocation retires it on the next use (and a late call for a deleted site leaves only that, which the
sweep drops); a restore's switch is adopted on the next use.
**Registry tables** (`<ns>_app`, identifier columns binary so ids never match by case): `rw_sites` (the live mapping),
`rw_schemas` (every generation and its state: `creating`, `live`, `staging`, `retired`, `dropping`), `rw_plugins`
(prefixes), `rw_nodes` (heartbeats; a node not seen for a day is removed at the next heartbeat), `rw_issues` (migration problems, visible to every node), `rw_install`.
**Locks.** Allocation, restore and removal take the per-site lock: an in-JVM lock, then `pg_advisory_lock` /
`GET_LOCK` on a lock connection, both with a bounded wait; a request that cannot get it fails fast with
"site data is being prepared" while holding no pooled connection.
**Removal.** The site-deleted event only enqueues, and only on the node that deleted the site (the database is
shared). The job re-reads the mapping under the lock, retires it and drops exactly that schema. The **reconcile
sweep** (after connecting and every 15 minutes) retires mappings whose site is gone (their data is dropped after
the grace period, never at once: a site that reads as gone may only be unreadable for a moment), whose folder names
another site or is marked new, or whose folder has had no token on two passes in a row; it re-adopts those whose folder
names another generation of the same site; it drops retired generations once they have been retired for 10
minutes, staging generations no restore is building, and creations a crash interrupted. Every retire or drop is
decided again under the site lock from fresh reads, so a restore or an allocation that finishes while the sweep waits
for the lock is never undone, and a schema a site maps to is never dropped. A site folder that cannot be read, or a
site the kernel cannot read, is skipped and the sweep goes on with the others. A schema in the namespace that the registry never recorded is reported, never dropped.
## 5. Migrations
Scripts come only from the jar the consumer's `DatabaseConsumer` bean was loaded from (its `CodeSource`, whose folder
must be named after the plugin id): every plugin shares one class loader, so "the first resource with that name"
could be another plugin's. Each folder has an `index`; the plugin never lists a folder through the class loader.
The checksum is the SHA-256 of the script with the BOM stripped, line endings normalized and trailing blanks trimmed;
comments stay (MariaDB executes `/*! … */`). Statements are split on a line holding only `-- runway:next`; a statement
that would move the connection is refused before anything runs, and after every statement the binding is checked
again.
- **PostgreSQL**: all of a plugin's pending scripts in one transaction under `pg_advisory_xact_lock`; the ownership
check compares the schema's objects before and after; a failure or a foreign object rolls everything back. Every
script of the rolled-back batch gets a `failed` row (the failing one with its statement), so Retry runs them all
again and Mark applied covers them all. A shipped script below the highest applied one that has no row at all is
refused as a failure, never skipped.
- **MariaDB**: per statement under `GET_LOCK`. The script's row is written `failed` first and `last_ok_statement`
advances after each statement; the ownership check runs after **each** statement and drops exactly what that
statement created outside the prefix (or a table not on InnoDB). Retry resumes after the last good statement.
The ownership check covers, on PostgreSQL, relations (so every index, including those constraints create),
functions, procedures and types other than row and array types, minus extension members; on MariaDB tables, views,
sequences, triggers, routines, events and foreign-key names. Index and CHECK names on MariaDB and trigger names on
PostgreSQL are scoped to their table and exempt.
**The lazy check is the authority.** The first call per (schema, plugin) in a JVM runs it, single-flight, waiting at
most 10 seconds (then "being prepared", while the migration continues). The startup sweep only warms it up.
**Failure is per (schema, plugin)**: a failed script, a changed checksum or a schema newer than the shipped scripts
stops that plugin in that schema with a `ScopeNotReadyException`, recorded in `rw_issues` for the health screen,
until an operator acts; the outcome is remembered for 30 seconds so a failing plugin does not hammer the server.
**Prefixes** are recorded in `rw_plugins` at a plugin's first migration. A prefix equal to, starting or started by a
recorded one is refused (`a-b`/`a_b`, `Blog`/`blog`), and `rw_` is reserved.
## 6. Scopes
`transaction` and `read` borrow one connection per outer call. A call on the same scope from inside the work joins
(same connection, no commit of its own, a throw rolls back the outer call); `transaction` inside `read` throws; a call
on another scope throws, so a consumer never holds two connections. There is no Spring transaction manager over a
per-site binding; the helper gives the same one-connection guarantee explicitly, which is what makes `lastValue`
after an insert reliable. `read` sets read-only and `REPEATABLE READ`; MariaDB also starts `START TRANSACTION WITH
CONSISTENT SNAPSHOT, READ ONLY` explicitly, because its driver ignores `setReadOnly` on a single host.
## 7. Backups
**Export** (only in full backups — the kernel gives transfer copies no participants): a site without a token writes
`state.json {"schema":"none"}`. Otherwise one read-only snapshot reads the tables (streamed with a fetch size), the
applied versions and, last, the sequences (as the next value to issue and the increment), into
`tables/<t>/part-NNNNN.jsonl.gz` (at most 4 MiB compressed, under the kernel's per-file write cap so the same parts
can be parked in the site folder), one `index.json` per table with row counts and SHA-256s, and `manifest.json`
**last** — a backup cut short has no manifest and never restores. Unreachable database with a token present: the
backup fails. The parts are read into a private spool folder under the plugin's work folder and handed to the kernel
only after the read transaction has ended: a download streams to the browser, and a slow browser must not hold a
setup-pool connection and an open snapshot. The spool holds at most the backup budget and is deleted afterwards.
**The format is typed** (`Portable`): `BIGINT, INTEGER, SMALLINT, DECIMAL(p,s), DOUBLE, BOOLEAN, VARCHAR(n), TEXT,
DATE, TIME, TIMESTAMP, TIMESTAMPTZ, BYTES, JSON`. Each column is read with the getter its type names and restored by
the **target** column's type; types of the same family restore into each other, which is what lets a PostgreSQL backup
load into MariaDB.
**Restore** treats the archive as untrusted (a site administrator can upload one). The kernel has already put the
archive's site folder in place when the plugin's turn comes, token included (or none, for a backup taken before the
site used the database). So the first step, under the site lock, makes the folder name the **live** generation again:
whatever happens next — success, failure, an archive without database data — the site keeps its data until a restore
actually replaces it. With the database unreachable, a folder left without a token gets the `adopt: live` marker,
which the next resolution honours. An archive whose state is `none` (the site had no database data) retires the live
data, as before (with the database unreachable, the folder is marked `fresh: new site` instead). A restore does not
make other nodes drop their cached mapping: every borrow re-checks it against the registry, and a restore that
replaces the data changes the registry. If the switch to the restored data reports an error after it committed, the
restore counts as done; a staging generation is dropped only while no site maps to it.
1. The whole archive is checked first — names, counts, checksums, line lengths, the budget, and text with NUL on
PostgreSQL.
2. Per plugin: installed at or above the backup's version → restored; installed but older → the restore is refused;
absent → its data is parked in the site folder and loaded, exactly like a restore, when the plugin first migrates
at the data's version or later (an older plugin is refused as `NEWER_THAN_INSTALLED`, shown on the Database
screen, and the data waits). The parked manifest is removed only once the data is in, so a load that fails part
way runs again on the next use. Parked data that cannot be read, or that is older than the plugin's tables already
in the schema, refuses the plugin on that site (`PLUGIN_REFUSED`, a "PARKED" problem on the screen); it is never
taken for "no data" and the tables are never started empty over it.
3. Under the site lock a **new generation** is created; each plugin is migrated to the backup's version, its tables
emptied (seed rows), every archived table and column matched **by lookup** against the new generation's catalog
(no archive string ever becomes an identifier), loaded with user triggers and foreign keys out of the way
(PostgreSQL: `DISABLE TRIGGER USER` and dropped foreign keys re-added afterwards, which re-checks them; MariaDB:
triggers captured and recreated, `FOREIGN_KEY_CHECKS = 0`), given its sequences, and migrated forward.
4. One transaction switches `rw_sites` to the new generation with a fresh token, then the token is written to the
site folder; the old generation is retired and dropped by the sweep.
5. On any failure the new generation is dropped, the old one stays live, and the restore throws; the failure is kept
for the health screen and the site's dashboard, because the kernel reports the site files as restored either way.
## 8. Security notes
- Host, port and database are checked against strict grammars (one host, no lists, options or credentials); the
URL is built from them and nothing else; the account goes in as properties. MariaDB pins `allowLocalInfile=false`,
`allowMultiQueries=false`, `permitRedirect=false`, `allowPublicKeyRetrieval=false`.
- TLS defaults to `verify-full`. The CA certificate is written to an owner-only file in the plugin's folder.
- The password is bound (`secretBoundTo`, on the provider's page) to everything that decides where it goes. The
connection test takes no typed values, only what is saved: a form with a username and a password box is one a
browser fills with the operator's own console login, which a typed test (1.0.0's) would then send to whatever host
was typed.
- No log line carries the password or a credentialed URL (checked by the tests and the verify script).
- The health screen needs `CONFIGURE_PLATFORM`; its recovery actions are logged with the operator's name.
## 9. Known gaps
- A transfer copy carries no database data; a kernel hook telling participants a backup's purpose would let plugins
mark which tables travel.
- The backup budget exists because the kernel holds a participant's restored entries in memory.
- A widget cannot read the database and stay cache-correct; it renders a shell and loads rows from a `no-store`
endpoint.
- `<ns>_app` has no export of its own.
- MariaDB keeps a lent connection's temporary tables; consumers drop them in `finally`.
+100
View File
@@ -0,0 +1,100 @@
# Runway Database — English
database.menu=Database
database.group.provider=Database product
database.group.provider.help=Which provider plugin Runway uses, and the names it gives its schemas. Changes apply after a restart; in a cluster every node needs the same values. The connection tests are below the form.
database.group.limits=Limits
database.group.limits.help=How much of the server Runway may use, and how large a site's database backup may be.
database.set.provider=Provider
database.set.provider.help=auto uses the one provider plugin installed. Choose a product only when both database-postgresql and database-mariadb are installed. The server, the account and TLS are set on the provider plugin's own settings page.
database.set.namespace=Namespace
database.set.namespace.help=The start of every schema name Runway creates. Give each installation that shares a server its own. Lower-case letters and digits, starting with a letter, up to 12.
database.set.poolMax=Connections
database.set.poolMax.help=The most connections plugins may hold at once. One site may use at most half.
database.set.statementTimeoutSeconds=Statement time limit (seconds)
database.set.statementTimeoutSeconds.help=A plugin's statement that runs longer is stopped. Migrations, backups and restores have their own, longer limit.
database.set.backupBudgetMiB=Backup budget (MiB)
database.set.backupBudgetMiB.help=The compressed size a site's database data may reach in its backup. Larger data needs the database's own backup tools.
database.console.title=Database
database.console.pretitle=Application
database.console.heading=Database
database.console.status=Status
database.console.available=Available
database.console.unavailable=Not available
database.console.provider=Provider
database.console.server=Server
database.console.driver=Driver
database.console.target=Database
database.console.tls=TLS
database.console.namespace=Namespace
database.console.pool=Connections in use
database.console.schemas=Sites with data
database.console.lastError=Last error
database.console.settings=Settings and tests
database.console.settings.text=The provider choice and the limits are on the Database plugin's settings page, together with the connection tests. The server, the account and TLS are on the provider plugin's settings page.
database.console.settings.link=Settings and connection tests
database.console.issues=Plugin tables needing attention
database.console.none=None.
database.console.schema=Schema
database.console.plugin=Plugin
database.console.problem=Problem
database.console.detail=Detail
database.console.actions=Actions
database.console.consumers=Plugins using it
database.console.appWarning=These plugins keep Runway-wide data, which does not move with a change of database:
database.console.nodes=Nodes seen recently
database.console.nodes.help=More than one node is normal in a cluster. Nodes you do not recognise may mean another installation shares this namespace.
database.console.backups=Backups
database.console.largest=Largest site backup
database.console.budgetWarning=Close to the backup budget: raise it, or back the database up with its own tools.
database.console.restoreFailure=Last failed restore
database.status.NOT_CONFIGURED=Not configured: {0}
database.status.NO_PROVIDER=No provider: {0}
database.status.CONNECTING=Connecting: {0}
database.status.UNSUPPORTED=Server not supported: {0}
database.status.AVAILABLE=Connected.
database.status.STOPPED=Stopped.
database.issue.FAILED=Script failed
database.issue.CHECKSUM=Script changed
database.issue.NEWER=Newer than installed
database.issue.PARKED=Kept data cannot be loaded
database.recover.retry=Retry
database.recover.markApplied=Mark applied
database.recover.acceptChecksum=Accept shipped checksum
database.recover.unknown=Unknown action.
database.recover.unavailable=The database is not available.
database.recover.none=There is no such problem to act on (it may have been resolved).
database.recover.failed=The action failed; see the server log.
database.recover.done=Done. The plugin checks its tables again on its next database call.
database.test.ok=Connected: {0}.
database.test.invalid_settings=The settings cannot be used: {0}
database.test.no_provider=The provider plugin {0} is not installed.
database.test.unreachable=The server could not be reached.
database.test.tls=The TLS handshake failed (certificate or TLS settings).
database.test.authentication=The server refused the username or password.
database.test.database_missing=The database does not exist on the server, or the account has no access to it.
database.test.unsupported_server=The server is not supported: {0}
database.test.not_available=The database is not in use: {0}
database.test.other=The test failed; see the server log.
database.panel.title=Connection tests
database.panel.intro=Settings saved here and on a provider's page apply at the next restart. Test them first: the test connects once with the saved values and changes nothing.
database.panel.now=Running now:
database.panel.testRunning=Test the running connection
database.panel.testSaved=Test the saved {0} settings
database.panel.edit=Edit the {0} settings
database.panel.none=No provider plugin is installed: install database-postgresql or database-mariadb.
database.product.postgresql=PostgreSQL
database.product.mariadb=MariaDB
database.dashboard.title=Database
database.dashboard.has=This site keeps plugin data in the database.
database.dashboard.none=This site keeps no data in the database.
database.dashboard.restore=Last database restore
@@ -0,0 +1,100 @@
# Runway Database — español
database.menu=Base de datos
database.group.provider=Producto de base de datos
database.group.provider.help=Qué plugin proveedor usa Runway y los nombres que da a sus esquemas. Los cambios se aplican al reiniciar; en un clúster, todos los nodos necesitan los mismos valores. Las pruebas de conexión están debajo del formulario.
database.group.limits=Límites
database.group.limits.help=Cuánto del servidor puede usar Runway y qué tamaño puede alcanzar el respaldo de la base de datos de un sitio.
database.set.provider=Proveedor
database.set.provider.help=auto usa el único plugin proveedor instalado. Elija un producto solo cuando estén instalados database-postgresql y database-mariadb. El servidor, el usuario y TLS se configuran en la página de ajustes del propio plugin proveedor.
database.set.namespace=Espacio de nombres
database.set.namespace.help=El inicio de cada nombre de esquema que crea Runway. Dé uno distinto a cada instalación que comparta un servidor. Minúsculas y dígitos, empezando por una letra, hasta 12.
database.set.poolMax=Conexiones
database.set.poolMax.help=El máximo de conexiones que los plugins pueden usar a la vez. Un sitio puede usar como mucho la mitad.
database.set.statementTimeoutSeconds=Límite por sentencia (segundos)
database.set.statementTimeoutSeconds.help=Se detiene la sentencia de un plugin que tarde más. Las migraciones, los respaldos y las restauraciones tienen su propio límite, más largo.
database.set.backupBudgetMiB=Presupuesto de respaldo (MiB)
database.set.backupBudgetMiB.help=El tamaño comprimido que pueden alcanzar los datos de base de datos de un sitio en su respaldo. Para datos mayores, use las herramientas de respaldo de la propia base de datos.
database.console.title=Base de datos
database.console.pretitle=Aplicación
database.console.heading=Base de datos
database.console.status=Estado
database.console.available=Disponible
database.console.unavailable=No disponible
database.console.provider=Proveedor
database.console.server=Servidor
database.console.driver=Controlador
database.console.target=Base de datos
database.console.tls=TLS
database.console.namespace=Espacio de nombres
database.console.pool=Conexiones en uso
database.console.schemas=Sitios con datos
database.console.lastError=Último error
database.console.settings=Ajustes y pruebas
database.console.settings.text=La elección del proveedor y los límites están en la página de ajustes del plugin Base de datos, junto con las pruebas de conexión. El servidor, el usuario y TLS están en la página de ajustes del plugin proveedor.
database.console.settings.link=Ajustes y pruebas de conexión
database.console.issues=Tablas de plugins que requieren atención
database.console.none=Ninguno.
database.console.schema=Esquema
database.console.plugin=Plugin
database.console.problem=Problema
database.console.detail=Detalle
database.console.actions=Acciones
database.console.consumers=Plugins que la usan
database.console.appWarning=Estos plugins guardan datos de toda la instalación, que no se trasladan al cambiar de base de datos:
database.console.nodes=Nodos vistos recientemente
database.console.nodes.help=Más de un nodo es normal en un clúster. Nodos que no reconozca pueden indicar que otra instalación comparte este espacio de nombres.
database.console.backups=Respaldos
database.console.largest=Respaldo de sitio más grande
database.console.budgetWarning=Cerca del presupuesto de respaldo: auméntelo o respalde la base de datos con sus propias herramientas.
database.console.restoreFailure=Última restauración fallida
database.status.NOT_CONFIGURED=Sin configurar: {0}
database.status.NO_PROVIDER=Sin proveedor: {0}
database.status.CONNECTING=Conectando: {0}
database.status.UNSUPPORTED=Servidor no compatible: {0}
database.status.AVAILABLE=Conectada.
database.status.STOPPED=Detenida.
database.issue.FAILED=Script fallido
database.issue.CHECKSUM=Script modificado
database.issue.NEWER=Más nueva que la instalada
database.issue.PARKED=No se pueden cargar los datos conservados
database.recover.retry=Reintentar
database.recover.markApplied=Marcar como aplicado
database.recover.acceptChecksum=Aceptar la suma de control incluida
database.recover.unknown=Acción desconocida.
database.recover.unavailable=La base de datos no está disponible.
database.recover.none=No hay tal problema sobre el que actuar (puede que ya se haya resuelto).
database.recover.failed=La acción falló; consulte el registro del servidor.
database.recover.done=Hecho. El plugin vuelve a comprobar sus tablas en su próxima llamada a la base de datos.
database.test.ok=Conectado: {0}.
database.test.invalid_settings=Los ajustes no se pueden usar: {0}
database.test.no_provider=El plugin proveedor {0} no está instalado.
database.test.unreachable=No se pudo alcanzar el servidor.
database.test.tls=Falló el intercambio TLS (certificado o ajustes de TLS).
database.test.authentication=El servidor rechazó el usuario o la contraseña.
database.test.database_missing=La base de datos no existe en el servidor o el usuario no tiene acceso a ella.
database.test.unsupported_server=El servidor no es compatible: {0}
database.test.not_available=La base de datos no está en uso: {0}
database.test.other=La prueba falló; consulte el registro del servidor.
database.panel.title=Pruebas de conexión
database.panel.intro=Los ajustes guardados aquí y en la página de un proveedor se aplican en el próximo reinicio. Pruébelos antes: la prueba se conecta una vez con los valores guardados y no cambia nada.
database.panel.now=En uso ahora:
database.panel.testRunning=Probar la conexión en uso
database.panel.testSaved=Probar los ajustes guardados de {0}
database.panel.edit=Editar los ajustes de {0}
database.panel.none=No hay ningún plugin proveedor instalado: instale database-postgresql o database-mariadb.
database.product.postgresql=PostgreSQL
database.product.mariadb=MariaDB
database.dashboard.title=Base de datos
database.dashboard.has=Este sitio guarda datos de plugins en la base de datos.
database.dashboard.none=Este sitio no guarda datos en la base de datos.
database.dashboard.restore=Última restauración de la base de datos
+62
View File
@@ -0,0 +1,62 @@
# =============================================================================
# Runway Database
# Lets plugins keep their own data in PostgreSQL or MariaDB. Runway's own data
# (pages, users, settings) stays on files.
#
# - One schema per site (a database per site on MariaDB), created by Runway the
# first time a site uses it, plus one installation-wide schema.
# - Each consumer plugin's objects carry its prefix; its migration scripts are
# read only from its own jar and checked for ownership.
# - A site's database data travels in its full backups (not in transfer copies).
# - The product comes from a provider plugin: database-postgresql or
# database-mariadb. This plugin holds no driver, and since 2.0.0 no server
# settings either: host, account, password and TLS are set on the
# provider plugin's own settings page.
#
# The install folder name MUST equal this `id`: external/plugins/database/.
# =============================================================================
id: database
name: Database
version: 2.0.0
mainClass: mx.quest.database.DatabasePluginConfig
# SPI 1.2.0: PluginSettings.savedApp, which the providers use to hand over their saved settings for the
# connection test (the database plugin itself reads no secret).
requiresSpi: ">=1.2.0"
# In each site's folder (sites/<id>/plugins/database/): the token that ties the site to its schema, and data kept
# for plugins that were not installed when a backup was restored. Both stay out of transfer copies: a copy of a site
# gets a fresh schema rather than sharing the original's.
siteData:
personal:
- schema.yml
- deferred/
settingGroups:
- { id: provider, label: database.group.provider, help: database.group.provider.help }
- { id: limits, label: database.group.limits, help: database.group.limits.help }
# Runway-wide settings, applied on RESTART. In a cluster every node needs the same values and the same platform
# secret key. The server's settings are on the provider plugin's page. Changing the server or the provider does not
# move data: move sites with backup and restore. The connection tests sit below this form (templates/admin-app.html).
settings:
- { key: provider, type: enum, range: "auto,postgresql,mariadb", default: auto, group: provider,
label: database.set.provider, help: database.set.provider.help }
- { key: namespace, type: string, default: rw, group: provider, advanced: true, label: database.set.namespace,
help: database.set.namespace.help }
- { key: poolMax, type: int, default: 10, range: "2..200", group: limits, label: database.set.poolMax,
help: database.set.poolMax.help }
- { key: statementTimeoutSeconds, type: int, default: 10, range: "1..3600", group: limits,
label: database.set.statementTimeoutSeconds, help: database.set.statementTimeoutSeconds.help }
- { key: backupBudgetMiB, type: int, default: 128, range: "1..4096", group: limits,
label: database.set.backupBudgetMiB, help: database.set.backupBudgetMiB.help }
# The health screen, under the application console's Settings menu. The controller enforces the same permission.
menu:
- { realm: application, region: settings, order: 80, label: database.menu, path: "/__app/database",
permission: "CONFIGURE_PLATFORM" }
# One line on each site's dashboard: whether the site has database data, its size, the last restore.
dashboardCards:
- { realm: tenant, order: 95, fragment: dashboard }
+210
View File
@@ -0,0 +1,210 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<!--
The generic database plugin: the pool, the settings, schema allocation and removal, migrations, backup and
restore, and the health screen. It publishes mx.quest.database.spi (the consumer and provider interfaces) and
bundles HikariCP in lib/. It holds no JDBC driver: a provider plugin (database-postgresql, database-mariadb)
brings one. Same managed versions as the Runway kernel (Spring Boot 4.0.6), thin jar, no repackage.
-->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>4.0.6</version>
<relativePath/>
</parent>
<groupId>mx.quest</groupId>
<artifactId>runway-plugin-database</artifactId>
<version>2.0.0</version>
<packaging>jar</packaging>
<name>Runway Database</name>
<licenses>
<license>
<name>GNU Affero General Public License v3.0, with the Runway additional permission for plugins</name>
<url>https://www.gnu.org/licenses/agpl-3.0.txt</url>
<distribution>repo</distribution>
<comments>See LICENSE and LICENSE-EXCEPTION.</comments>
</license>
</licenses>
<description>
Lets Runway plugins keep their own data in PostgreSQL or MariaDB: one schema per site plus one for the whole
installation, created by Runway; per-plugin migrations with ownership checks; per-site backup and restore;
a health screen in the application console. The database product comes from a provider plugin.
</description>
<properties>
<java.version>25</java.version>
<maven.compiler.release>25</maven.compiler.release>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<!-- Reproducible builds: pins every archive entry's timestamp. Bump at each release. -->
<project.build.outputTimestamp>2026-10-29T00:00:00Z</project.build.outputTimestamp>
<!-- The runway-spi this plugin compiles against: SPI 1.2.0 adds PluginSettings.savedApp. -->
<runway.version>1.2.0</runway.version>
<!-- Bundled in lib/ (Apache-2.0). Managed by Boot 4.0.6; pinned here so the bundle never drifts. -->
<hikaricp.version>7.0.2</hikaricp.version>
<!-- Test only: the drivers the provider plugins bundle, for the tests against real servers. -->
<postgresql.version>42.7.10</postgresql.version>
<mariadb.version>3.5.8</mariadb.version>
</properties>
<dependencies>
<dependency>
<groupId>mx.quest</groupId>
<artifactId>runway-spi</artifactId>
<version>${runway.version}</version>
</dependency>
<dependency>
<groupId>mx.quest</groupId>
<artifactId>runway-spi-testkit</artifactId>
<version>${runway.version}</version>
<scope>test</scope>
</dependency>
<!-- The pool, bundled into lib/ by the assembly below. slf4j comes from the kernel. -->
<dependency>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
<version>${hikaricp.version}</version>
<exclusions>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- The kernel supplies these at runtime; never bundled. -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
<scope>provided</scope>
</dependency>
<!-- Jackson 3 (tools.jackson): the backup format's JSON. -->
<dependency>
<groupId>tools.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>jakarta.servlet</groupId>
<artifactId>jakarta.servlet-api</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>${postgresql.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mariadb.jdbc</groupId>
<artifactId>mariadb-java-client</artifactId>
<version>${mariadb.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>runway-plugin-database</finalName>
<plugins>
<!-- 1. HikariCP into target/staged-lib, with its versioned file name; the assembly copies it into lib/. -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<id>bundle-libs</id>
<phase>package</phase>
<goals>
<goal>copy</goal>
</goals>
<configuration>
<artifactItems>
<artifactItem>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
<version>${hikaricp.version}</version>
</artifactItem>
</artifactItems>
<outputDirectory>${project.build.directory}/staged-lib</outputDirectory>
<stripVersion>false</stripVersion>
<overWriteReleases>true</overWriteReleases>
</configuration>
</execution>
</executions>
</plugin>
<!-- 2. Assemble target/database/ (folder) and the UI zip. -->
<plugin>
<artifactId>maven-antrun-plugin</artifactId>
<executions>
<execution>
<id>assemble-plugin-folder</id>
<phase>package</phase>
<goals>
<goal>run</goal>
</goals>
<configuration>
<target>
<property name="stage" value="${project.build.directory}/database"/>
<delete dir="${stage}"/>
<mkdir dir="${stage}"/>
<copy file="${project.basedir}/plugin.yml" todir="${stage}"/>
<copy file="${project.basedir}/LICENSE" todir="${stage}"/>
<copy file="${project.basedir}/LICENSE-EXCEPTION" todir="${stage}"/>
<copy file="${project.basedir}/THIRD-PARTY-NOTICES" todir="${stage}"/>
<copy file="${project.build.directory}/runway-plugin-database.jar" todir="${stage}"/>
<copy todir="${stage}/lib">
<fileset dir="${project.build.directory}/staged-lib"/>
</copy>
<!-- Never a plugin zip without its libraries (it would load and fail at its first use). -->
<fail message="no library in ${stage}/lib">
<condition><resourcecount when="equal" count="0">
<fileset dir="${stage}" includes="lib/*.jar"/></resourcecount></condition>
</fail>
<copy todir="${stage}/templates">
<fileset dir="${project.basedir}/templates"/>
</copy>
<copy todir="${stage}/i18n">
<fileset dir="${project.basedir}/i18n"/>
</copy>
<touch datetime="${project.build.outputTimestamp}"
pattern="yyyy-MM-dd'T'HH:mm:ss'Z'">
<fileset dir="${stage}"/>
<dirset dir="${stage}"/>
<dirset dir="${project.build.directory}" includes="database"/>
</touch>
<!-- The stamped files predate any earlier zip, so <zip> would skip the rebuild. -->
<delete file="${project.build.directory}/runway-plugin-database-${project.version}.zip"/>
<zip destfile="${project.build.directory}/runway-plugin-database-${project.version}.zip">
<zipfileset dir="${project.build.directory}" includes="database/**"/>
</zip>
<echo message="Staged install folder (with lib/HikariCP): ${stage}"/>
<echo message="UI-uploadable archive: ${project.build.directory}/runway-plugin-database-${project.version}.zip"/>
</target>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
+222
View File
@@ -0,0 +1,222 @@
#!/usr/bin/env bash
# =============================================================================
# Verify the database plugin and both providers inside a real Runway.
#
# Boots a throwaway Runway (wizard, then ACTIVE) with database, database-postgresql and database-mariadb installed
# and the chosen provider pointed at a server you name, then checks:
# - a 1.x database.yml (server keys in the database plugin's file) is reported as moved, and never used;
# - all three plugins load: none blocked or quarantined, no linkage or surface findings;
# - the runtime connects (on its own thread, after startup) and the password appears in no log line;
# - the application console's database screen answers only after login and points to the settings page;
# - the settings pages: the provider's holds the server, the database plugin's holds the connection tests, which
# take no typed values; the running test passes, and the saved test reads the provider's file as saved now
# (a wrong password saved after startup is refused while the running connection stays up);
# - a site's dashboard shows the database card.
#
# Usage:
# PROVIDER=postgresql DB_HOST=127.0.0.1 DB_PORT=55432 DB_PASSWORD_FILE=/path/pw scripts/verify-against-host.sh
# Needs JAVA_HOME (a JDK 25). Optional: MVN (default mvn on the PATH), DB_NAME (default runway), DB_USER (default
# runway), HOST_TARGET (default the Runway this folder sits in, else ../runway), HOST_JAR (default that build's
# runway-app-<version>-exec.jar), --keep (keep the scratch folder), --port N.
#
# The server needs an account that may create schemas (PostgreSQL) or databases named <namespace>_… (MariaDB).
# Each run uses a fresh namespace (printed); its schemas stay on the server, so point it at a throwaway one.
# =============================================================================
set -u
HERE="$(cd "$(dirname "$0")/.." && pwd)"
REPO="$(cd "$HERE/.." && pwd)"
# The kernel build: the Runway this plugin folder sits in (the public layout, plugins/ inside the kernel), else a
# runway checkout beside this repository.
if [ -z "${HOST_TARGET:-}" ]; then
if [ -f "$REPO/../runway-app/pom.xml" ]; then HOST_TARGET="$REPO/../runway-app/target"
else HOST_TARGET="$REPO/../runway/runway-app/target"; fi
fi
MVN="${MVN:-mvn}"
if [ -z "${JAVA_HOME:-}" ] || [ ! -x "$JAVA_HOME/bin/java" ]; then echo "set JAVA_HOME to a JDK 25"; exit 2; fi
export JAVA_HOME
JAVA="$JAVA_HOME/bin/java"
: "${PROVIDER:?set PROVIDER=postgresql or mariadb}"
: "${DB_HOST:?set DB_HOST}"
: "${DB_PORT:?set DB_PORT}"
: "${DB_PASSWORD_FILE:?set DB_PASSWORD_FILE}"
DB_NAME="${DB_NAME:-runway}"; DB_USER="${DB_USER:-runway}"
DB_PASSWORD="$(cat "$DB_PASSWORD_FILE")"
KEEP="no"; PORT=""
while [ $# -gt 0 ]; do
case "$1" in
--keep) KEEP="yes"; shift ;;
--port) PORT="${2:?}"; shift 2 ;;
*) echo "unknown argument $1"; exit 2 ;;
esac
done
free_port() { python3 -I -c 'import socket;s=socket.socket();s.bind(("127.0.0.1",0));print(s.getsockname()[1]);s.close()'; }
[ -n "$PORT" ] || PORT="$(free_port)"
BASE="http://localhost:$PORT"
APP_USER=root; APP_PW=Database-Admin-2026; SITE_USER=owner; SITE_PW=Database-Site-2026
NS="hv$(date +%s | tail -c 9)"
echo "[verify] packaging database, database-postgresql, database-mariadb ..."
( cd "$HERE" && "$MVN" -o -q -DskipTests install ) || { echo "database build failed"; exit 1; }
( cd "$REPO/database-postgresql" && "$MVN" -o -q -DskipTests package ) || { echo "postgresql build failed"; exit 1; }
( cd "$REPO/database-mariadb" && "$MVN" -o -q -DskipTests package ) || { echo "mariadb build failed"; exit 1; }
if [ -n "${HOST_JAR:-}" ]; then
JAR="$HOST_JAR"
else
HOST_VERSION="$(sed -n 's:.*<version>\(.*\)</version>.*:\1:p' "$HOST_TARGET/../pom.xml" | head -1)"
JAR="$HOST_TARGET/runway-app-$HOST_VERSION-exec.jar"
fi
[ -f "$JAR" ] || { echo "no host exec jar $JAR — build the host (mvn -pl runway-app -am package) or set HOST_JAR"; exit 1; }
echo "[verify] host jar: $JAR; provider $PROVIDER at $DB_HOST:$DB_PORT/$DB_NAME; namespace $NS"
mkdir -p "$HERE/target"
SCRATCH="$(mktemp -d "$HERE/target/database-verify.XXXXXX")"
PID=""
stop_host() { [ -z "$PID" ] || { kill "$PID" 2>/dev/null; wait "$PID" 2>/dev/null; PID=""; }; }
cleanup() { stop_host; [ "$KEEP" = "yes" ] && echo "[verify] kept $SCRATCH" || rm -rf "$SCRATCH"; }
trap cleanup EXIT
wait_for() { for _ in $(seq 1 "$3"); do grep -q "$2" "$1" 2>/dev/null && return 0; sleep 1; done; return 1; }
PASS=0; FAIL=0
ck() { if eval "$2" >/dev/null 2>&1; then echo " PASS $1"; PASS=$((PASS+1)); else echo " FAIL $1"; FAIL=$((FAIL+1)); fi; }
code() { curl -s -o /dev/null -w '%{http_code}' "$@"; }
token() { grep -o 'name="_csrf" value="[^"]*"' | head -1 | sed 's/.*value="//; s/"$//'; }
EXT="$SCRATCH/external"; LOG="$SCRATCH/active.log"
mkdir -p "$EXT/plugins" "$EXT/plugin-settings"
cp -r "$HERE/target/database" "$EXT/plugins/database"
cp -r "$REPO/database-postgresql/target/database-postgresql" "$EXT/plugins/database-postgresql"
cp -r "$REPO/database-mariadb/target/database-mariadb" "$EXT/plugins/database-mariadb"
boot() { ( cd "$SCRATCH" && exec "$JAVA" -jar "$JAR" --server.port="$PORT" --runway.storage.external="$EXT" ) >"$1" 2>&1 & PID=$!; }
echo "[verify] booting host (wizard) on :$PORT ..."
boot "$SCRATCH/wizard.log"
wait_for "$SCRATCH/wizard.log" "Started RunwayApplication" 90 || { echo "wizard did not start"; tail -20 "$SCRATCH/wizard.log"; exit 1; }
curl -s -o /dev/null -X POST "$BASE/setup" --data-urlencode "username=$APP_USER" --data-urlencode "password=$APP_PW" \
--data-urlencode "displayName=Root" --data-urlencode "siteAdminUsername=$SITE_USER" \
--data-urlencode "siteAdminPassword=$SITE_PW"
for _ in $(seq 1 30); do kill -0 "$PID" 2>/dev/null || break; sleep 1; done
stop_host
# 1.x layout first: the server keys in the database plugin's own file. 2.0.0 must say they moved, and not connect.
umask 077
cat > "$EXT/plugin-settings/database.yml" <<EOF
runway:
plugin:
database:
provider: $PROVIDER
namespace: $NS
host: "$DB_HOST"
port: $DB_PORT
database: "$DB_NAME"
username: "$DB_USER"
password: "$DB_PASSWORD"
tls: disable
EOF
umask 022
echo "[verify] booting host (ACTIVE, 1.x settings) ..."
boot "$SCRATCH/legacy.log"
wait_for "$SCRATCH/legacy.log" "Started RunwayApplication" 90 || { echo "ACTIVE did not start"; tail -20 "$SCRATCH/legacy.log"; exit 1; }
wait_for "$SCRATCH/legacy.log" "database: not configured" 30
stop_host
echo "== 1.x settings =="
ck "reported as moved to the provider plugin" "grep -q 'not configured: the server settings moved to the database-$PROVIDER plugin' '$SCRATCH/legacy.log'"
ck "never used to connect" "! grep -q 'database: connected to' '$SCRATCH/legacy.log'"
# 2.0.0 layout. Both providers are installed, so the database plugin names one (auto would ask which). A hand-written
# plaintext password works like an encrypted one; these files are deleted with the scratch folder.
if [ "$PROVIDER" = postgresql ]; then PRODUCT=PostgreSQL; else PRODUCT=MariaDB; fi
umask 077
cat > "$EXT/plugin-settings/database.yml" <<EOF
runway:
plugin:
database:
provider: $PROVIDER
namespace: $NS
EOF
cat > "$EXT/plugin-settings/database-$PROVIDER.yml" <<EOF
runway:
plugin:
database-$PROVIDER:
host: "$DB_HOST"
port: $DB_PORT
database: "$DB_NAME"
username: "$DB_USER"
password: "$DB_PASSWORD"
tls: disable
EOF
umask 022
echo "[verify] booting host (ACTIVE) ..."
boot "$LOG"
wait_for "$LOG" "Started RunwayApplication" 90 || { echo "ACTIVE did not start"; tail -20 "$LOG"; exit 1; }
wait_for "$LOG" "database: connected to" 30
echo "== plugin load =="
ck "3 plugins registered, 0 blocked" "grep -qE 'plugins: 3 registered, 0 blocked' '$LOG'"
ck "none blocked or quarantined" "! grep -qE \"plugin 'database[a-z-]*' is blocked|plugin-quarantine\" '$LOG'"
ck "ZERO host-linkage findings" "! grep -qE \"plugin 'database[a-z-]*' linkage scan\" '$LOG'"
ck "ZERO bean-name/surface findings" "! grep -qE \"plugin 'database[a-z-]*'.*(bean name|may not contribute)\" '$LOG'"
ck "no missing class" "! grep -qiE 'NoClassDefFound|ClassNotFound' '$LOG'"
ck "HikariCP and the drivers are in lib/" "ls '$EXT/plugins/database/lib/'HikariCP-*.jar '$EXT/plugins/database-postgresql/lib/'postgresql-*.jar '$EXT/plugins/database-mariadb/lib/'mariadb-java-client-*.jar"
echo "== connection =="
ck "connected after startup, on its own thread" "grep -E 'database: connected to' '$LOG' | grep -qv '\\[main\\]'"
ck "the password appears in no log line" "! grep -qF -- '$DB_PASSWORD' '$LOG' '$SCRATCH/wizard.log' '$SCRATCH/legacy.log'"
echo "== application console =="
ck "the screen needs a login" "[ \"\$(code '$BASE/__app/database')\" = 302 ]"
ac() { curl -s -H 'Accept-Language: en' -c "$SCRATCH/app.jar" -b "$SCRATCH/app.jar" "$@"; }
ac -o /dev/null -X POST "$BASE/app/login" --data-urlencode "username=$APP_USER" --data-urlencode "password=$APP_PW" \
--data-urlencode "_csrf=$(ac "$BASE/app/login" | token)"
ac "$BASE/__app/database" > "$SCRATCH/screen.html"
ck "the screen renders for the master" "grep -q 'Connected.' '$SCRATCH/screen.html' && grep -q '$NS' '$SCRATCH/screen.html'"
ck "the screen holds no password" "! grep -qF -- '$DB_PASSWORD' '$SCRATCH/screen.html'"
ck "the screen points to the settings page" "grep -q '/__app/plugins/database/settings#db-tests' '$SCRATCH/screen.html'"
ck "the screen has no test form any more" "! grep -qE 'test-new|type=\"password\"' '$SCRATCH/screen.html'"
ck "the 1.x typed test is gone" "[ \"\$(ac -o /dev/null -w '%{http_code}' -X POST '$BASE/__app/database/test-new' --data-urlencode '_csrf=$(token < "$SCRATCH/screen.html")')\" != 302 ]"
echo "== settings pages =="
ac "$BASE/__app/plugins/database/settings" > "$SCRATCH/settings.html"
ck "the database page has the provider choice" "grep -q 'name=\"provider\"' '$SCRATCH/settings.html'"
ck "the database page has no server fields" "! grep -qE 'name=\"(host|username|password)\"' '$SCRATCH/settings.html'"
ck "the connection tests are below its form" "grep -q 'id=\"db-tests\"' '$SCRATCH/settings.html' && grep -q 'Test the saved $PRODUCT settings' '$SCRATCH/settings.html'"
ck "the panel shows the running status" "grep -q 'Running now:' '$SCRATCH/settings.html' && grep -q 'Connected\\.' '$SCRATCH/settings.html'"
ac "$BASE/__app/plugins/database-$PROVIDER/settings" > "$SCRATCH/provider.html"
ck "the provider page holds the server" "grep -q 'value=\"$DB_HOST\"' '$SCRATCH/provider.html' && grep -q 'name=\"username\"' '$SCRATCH/provider.html'"
ck "its password box is never autofilled" "grep -q 'autocomplete=\"new-password\"' '$SCRATCH/provider.html' && ! grep -q 'type=\"password\"[^>]*autocomplete=\"off\"' '$SCRATCH/provider.html'"
ck "the pages hold no password" "! grep -qF -- '$DB_PASSWORD' '$SCRATCH/provider.html' '$SCRATCH/settings.html'"
if [ "$PROVIDER" = mariadb ]; then
ck "collation is on the MariaDB page only" "grep -q 'name=\"collation\"' '$SCRATCH/provider.html' && ! grep -q 'name=\"collation\"' '$SCRATCH/settings.html'"
fi
CSRF="$(token < "$SCRATCH/settings.html")"
ac -L "$BASE/__app/database/test-running" --data-urlencode "_csrf=$CSRF" > "$SCRATCH/tested.html"
ck "Test the running connection: connected" "grep -qE 'Connected: (PostgreSQL|MariaDB)' '$SCRATCH/tested.html' && grep -q 'id=\"db-tests\"' '$SCRATCH/tested.html'"
ac -L "$BASE/__app/database/test-saved" --data-urlencode "_csrf=$CSRF" --data-urlencode "provider=$PROVIDER" > "$SCRATCH/saved.html"
ck "Test the saved settings: connected" "grep -qE 'Connected: $PRODUCT' '$SCRATCH/saved.html'"
# Save a wrong password after startup, as the provider's form would (only a restart would apply it): the saved test
# reads the file as it is now, and the running connection is untouched.
sed -i 's/^ password: .*/ password: "not-the-password"/' "$EXT/plugin-settings/database-$PROVIDER.yml"
ac -L "$BASE/__app/database/test-saved" --data-urlencode "_csrf=$CSRF" --data-urlencode "provider=$PROVIDER" > "$SCRATCH/saved2.html"
ck "a wrong saved password is refused" "grep -q 'The server refused the username or password.' '$SCRATCH/saved2.html'"
ck "the running connection is untouched" "grep -q 'Connected\\.' '$SCRATCH/saved2.html'"
ac -L "$BASE/__app/database/test-saved" --data-urlencode "_csrf=$CSRF" --data-urlencode "provider=oracle" > "$SCRATCH/saved3.html"
ck "an unknown provider is answered, not tested" "grep -q 'is not installed' '$SCRATCH/saved3.html'"
ck "a POST without the CSRF token is refused" "[ \"\$(code -b '$SCRATCH/app.jar' -X POST '$BASE/__app/database/test-saved')\" = 403 ]"
echo "== site console =="
sc() { curl -s -H 'Accept-Language: en' -c "$SCRATCH/site.jar" -b "$SCRATCH/site.jar" "$@"; }
sc -o /dev/null -X POST "$BASE/login" --data-urlencode "username=$SITE_USER" --data-urlencode "password=$SITE_PW" \
--data-urlencode "_csrf=$(sc "$BASE/login" | token)"
ck "the site dashboard shows the database card" "sc '$BASE/__admin' | grep -q 'keeps no data in the database'"
ck "a site admin cannot open the application screen" "[ \"\$(code -b '$SCRATCH/site.jar' '$BASE/__app/database')\" != 200 ]"
# With the site session's own CSRF token, so a refusal comes from the permission gate, not from a missing token.
SITE_CSRF="$(sc "$BASE/__admin" | token)"
ck "nor test the saved settings" "[ \"\$(code -b '$SCRATCH/site.jar' -X POST --data-urlencode '_csrf=$SITE_CSRF' --data-urlencode 'provider=$PROVIDER' '$BASE/__app/database/test-saved')\" != 302 ]"
ck "no ERROR line names the database plugin" "! grep -E ' ERROR ' '$LOG' | grep -qiE 'mx\\.quest\\.database|database:'"
echo "[verify] $PASS passed, $FAIL failed (namespace $NS left on the server)"
[ "$FAIL" = 0 ]
@@ -0,0 +1,141 @@
package mx.quest.database;
import java.nio.file.Path;
import java.util.List;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Supplier;
import mx.quest.database.console.DatabaseConsoleController;
import mx.quest.database.console.DatabaseScreens;
import mx.quest.database.internal.ConnectionTester;
import mx.quest.database.internal.DatabaseBackup;
import mx.quest.database.internal.DatabaseCore;
import mx.quest.database.internal.DatabaseLifecycle;
import mx.quest.database.internal.DatabaseProps;
import mx.quest.database.internal.DatabaseRuntime;
import mx.quest.database.internal.DatabaseSiteEvents;
import mx.quest.database.internal.DatabasesImpl;
import mx.quest.database.internal.Migrator;
import mx.quest.database.internal.ProviderChoice;
import mx.quest.database.internal.SiteSchemas;
import mx.quest.database.spi.DatabaseConsumer;
import mx.quest.database.spi.DatabaseProvider;
import mx.quest.runway.spi.model.PluginInfo;
import mx.quest.runway.spi.service.Messages;
import mx.quest.runway.spi.service.PluginSiteFiles;
import mx.quest.runway.spi.service.RequestContext;
import mx.quest.runway.spi.service.Sites;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* The database plugin's beans, every one registered explicitly and named {@code database…}. Nothing here connects:
* the runtime connects on the plugin's executor after the platform has started ({@link DatabaseLifecycle}).
*
* <p>Consumers inject {@link mx.quest.database.spi.Databases} (the {@code databaseDatabases} bean) by type;
* providers and consumer declarations are collected by type from the other plugins, lazily, once everything is
* registered.
*/
@Configuration(proxyBeanMethods = false)
public class DatabasePluginConfig {
@Bean
@ConfigurationProperties("runway.plugin.database")
public DatabaseProps databaseProps() {
return new DatabaseProps();
}
@Bean(destroyMethod = "shutdownNow")
public ScheduledExecutorService databaseExecutor() {
AtomicInteger count = new AtomicInteger();
ThreadFactory threads = r -> {
Thread t = new Thread(r, "runway-database-" + count.incrementAndGet());
t.setDaemon(true);
return t;
};
ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(4, threads);
executor.setRemoveOnCancelPolicy(true);
return executor;
}
@Bean
public DatabaseRuntime databaseRuntime(DatabaseProps databaseProps, ObjectProvider<DatabaseProvider> providers,
PluginInfo self, ScheduledExecutorService databaseExecutor) {
Supplier<List<DatabaseProvider>> found = () -> providers.orderedStream().toList();
return new DatabaseRuntime(() -> ProviderChoice.running(databaseProps, found.get()), workDir(self),
databaseExecutor);
}
@Bean
public SiteSchemas databaseSiteSchemas(DatabaseRuntime databaseRuntime, PluginSiteFiles files, Sites sites) {
return new SiteSchemas(databaseRuntime, files, sites);
}
@Bean
public Migrator databaseMigrator(DatabaseRuntime databaseRuntime) {
return new Migrator(databaseRuntime);
}
@Bean
public DatabaseCore databaseCore(DatabaseRuntime databaseRuntime, SiteSchemas databaseSiteSchemas,
Migrator databaseMigrator, Sites sites, RequestContext requestContext) {
return new DatabaseCore(databaseRuntime, databaseSiteSchemas, databaseMigrator, sites, requestContext);
}
@Bean
public DatabasesImpl databaseDatabases(DatabaseCore databaseCore) {
return new DatabasesImpl(databaseCore);
}
@Bean
public DatabaseBackup databaseBackup(DatabaseCore databaseCore, DatabasesImpl databaseDatabases,
PluginSiteFiles files) {
DatabaseBackup backup = new DatabaseBackup(databaseCore, databaseDatabases, files);
databaseCore.migrator().parked(backup);
return backup;
}
@Bean
public DatabaseSiteEvents databaseSiteEvents(DatabaseCore databaseCore, ScheduledExecutorService databaseExecutor) {
return new DatabaseSiteEvents(databaseCore, databaseExecutor);
}
@Bean
public DatabaseLifecycle databaseLifecycle(DatabaseCore databaseCore, DatabasesImpl databaseDatabases,
ObjectProvider<DatabaseConsumer> consumers,
ScheduledExecutorService databaseExecutor) {
return new DatabaseLifecycle(databaseCore, databaseDatabases, () -> consumers.orderedStream().toList(),
databaseExecutor);
}
@Bean
public ConnectionTester databaseConnectionTester(DatabaseRuntime databaseRuntime, DatabaseProps databaseProps,
ObjectProvider<DatabaseProvider> providers, PluginInfo self) {
return new ConnectionTester(databaseRuntime, databaseProps, () -> providers.orderedStream().toList(),
workDir(self));
}
@Bean
public DatabaseScreens databaseScreens(DatabaseCore databaseCore, DatabasesImpl databaseDatabases,
DatabaseBackup databaseBackup) {
return new DatabaseScreens(databaseCore, databaseDatabases, databaseBackup);
}
@Bean
public DatabaseConsoleController databaseConsoleController(DatabaseScreens databaseScreens,
ConnectionTester databaseConnectionTester,
DatabaseCore databaseCore,
DatabasesImpl databaseDatabases, Messages messages) {
return new DatabaseConsoleController(databaseScreens, databaseConnectionTester, databaseCore,
databaseDatabases, messages);
}
/** The plugin's own folder for the CA file it hands the driver. */
static Path workDir(PluginInfo self) {
return self.installDir().resolve("run");
}
}
@@ -0,0 +1,172 @@
package mx.quest.database.console;
import java.sql.SQLException;
import java.util.Locale;
import java.util.Optional;
import mx.quest.database.internal.ConnectionTester;
import mx.quest.database.internal.Consumer;
import mx.quest.database.internal.DatabaseCore;
import mx.quest.database.internal.DatabaseRuntime;
import mx.quest.database.internal.DatabasesImpl;
import mx.quest.database.internal.Migrator;
import mx.quest.database.internal.ProviderChoice;
import mx.quest.database.internal.Registry;
import mx.quest.database.spi.Scope;
import mx.quest.runway.spi.service.ConsoleScreen;
import mx.quest.runway.spi.service.Messages;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
/**
* The database screen in the application console ({@code /__app/database}): health and the migration recovery
* actions; and the connection tests, whose panel is on the plugin's settings page and whose result goes back there.
* Every handler needs {@code CONFIGURE_PLATFORM}, which the master and wildcard
* administrators hold; a delegable plugin permission does not open it. Every state change is a CSRF-checked POST,
* and every recovery action is logged with the operator's name.
*/
@Controller
@ConsoleScreen
@RequestMapping(DatabaseConsoleController.BASE)
public class DatabaseConsoleController {
static final String BASE = "/__app/database";
static final String GATE = "@authz.may('CONFIGURE_PLATFORM')";
static final String CONTENT = "__plugin__/database/health";
static final String TITLE_KEY = "database.console.title";
static final String FLASH = "databaseFlash";
static final String FLASH_ERROR = "databaseError";
/** The connection tests' result, shown on their panel on the plugin's settings page. */
static final String TEST_FLASH = "databaseTest";
static final String TEST_FLASH_ERROR = "databaseTestError";
/** Where the connection tests are: the panel below the plugin's settings form (templates/admin-app.html). */
static final String SETTINGS_PAGE = "/__app/plugins/database/settings#db-tests";
private static final Logger log = LoggerFactory.getLogger(DatabaseConsoleController.class);
private final DatabaseScreens screens;
private final ConnectionTester tester;
private final DatabaseCore core;
private final DatabasesImpl databases;
private final Messages messages;
public DatabaseConsoleController(DatabaseScreens screens, ConnectionTester tester, DatabaseCore core,
DatabasesImpl databases, Messages messages) {
this.screens = screens;
this.tester = tester;
this.core = core;
this.databases = databases;
this.messages = messages;
}
@GetMapping
@PreAuthorize(GATE)
public String health(Model model) {
model.addAttribute("db", screens.health());
model.addAttribute(ConsoleScreen.CONTENT_TEMPLATE, CONTENT);
model.addAttribute(ConsoleScreen.PAGE_TITLE_KEY, TITLE_KEY);
return ConsoleScreen.LAYOUT_VIEW;
}
@PostMapping("/test-running")
@PreAuthorize(GATE)
public String testRunning(RedirectAttributes flash) {
return result(flash, tester.running());
}
/** Tests the settings saved on one provider plugin's page; the result shows on the settings page's panel. */
@PostMapping("/test-saved")
@PreAuthorize(GATE)
public String testSaved(@RequestParam(name = "provider", defaultValue = "") String provider,
RedirectAttributes flash) {
if (!tester.testable().contains(provider)) {
return result(flash, new ConnectionTester.Result(ConnectionTester.Category.NO_PROVIDER,
ProviderChoice.plugin(provider.isBlank() ? "?" : provider)));
}
return result(flash, tester.saved(provider));
}
@PostMapping("/recover")
@PreAuthorize(GATE)
public String recover(@RequestParam(name = "schema") String schema,
@RequestParam(name = "plugin") String plugin,
@RequestParam(name = "action") String action,
RedirectAttributes flash) {
Migrator.Recovery recovery;
try {
recovery = Migrator.Recovery.valueOf(action.toUpperCase(Locale.ROOT));
} catch (IllegalArgumentException e) {
return back(flash, FLASH_ERROR, console("database.recover.unknown", "Unknown action."));
}
DatabaseRuntime runtime = core.runtime();
if (!runtime.available()) {
return back(flash, FLASH_ERROR, console("database.recover.unavailable",
"The database is not available."));
}
try {
// Act only on a problem the registry recorded: the form's values are never trusted as names.
Optional<Registry.Issue> issue = runtime.registry().issues().stream()
.filter(i -> i.schema().equals(schema) && i.pluginId().equals(plugin)).findFirst();
Optional<Consumer> consumer = databases.consumers().stream().filter(c -> c.pluginId().equals(plugin))
.findFirst();
if (issue.isEmpty() || consumer.isEmpty()) {
return back(flash, FLASH_ERROR, console("database.recover.none",
"There is no such problem to act on (it may have been resolved)."));
}
Registry.Issue i = issue.get();
Scope.Kind kind = i.schema().equals(runtime.registry().appSchema()) ? Scope.Kind.APP : Scope.Kind.SITE;
core.migrator().recover(consumer.get(), kind, i.schema(), recovery);
log.warn("database: operator '{}' ran {} for plugin '{}' in schema '{}' (was {} at version {})",
operator(), recovery, plugin, i.schema(), i.state(), i.version());
} catch (SQLException | RuntimeException e) {
log.warn("database: recovery {} for plugin '{}' in schema '{}' failed: {}", recovery, plugin, schema,
DatabaseRuntime.describe(e));
return back(flash, FLASH_ERROR, console("database.recover.failed", "The action failed; see the log."));
}
return back(flash, FLASH, console("database.recover.done",
"Done. The plugin checks its tables again on its next database call."));
}
private String result(RedirectAttributes flash, ConnectionTester.Result result) {
String key = "database.test." + result.category().name().toLowerCase(Locale.ROOT);
String text = switch (result.category()) {
case OK -> console(key, "Connected: {0}.", result.detail());
case INVALID_SETTINGS -> console(key, "The settings cannot be used: {0}", result.detail());
case NO_PROVIDER -> console(key, "The provider plugin {0} is not installed.", result.detail());
case UNREACHABLE -> console(key, "The server could not be reached.");
case TLS -> console(key, "The TLS handshake failed (certificate or TLS settings).");
case AUTHENTICATION -> console(key, "The server refused the username or password.");
case DATABASE_MISSING -> console(key, "The database does not exist on the server, or the account has no "
+ "access to it.");
case UNSUPPORTED_SERVER -> console(key, "The server is not supported: {0}", result.detail());
case NOT_AVAILABLE -> console(key, "The database is not in use: {0}", result.detail());
default -> console("database.test.other", "The test failed; see the server log.");
};
flash.addFlashAttribute(result.category() == ConnectionTester.Category.OK ? TEST_FLASH : TEST_FLASH_ERROR,
text);
return "redirect:" + SETTINGS_PAGE;
}
private static String operator() {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
return auth == null ? "unknown" : auth.getName();
}
private String console(String code, String fallback, Object... args) {
return messages.console(code, fallback, args);
}
private static String back(RedirectAttributes flash, String kind, String text) {
flash.addFlashAttribute(kind, text);
return "redirect:" + BASE;
}
}
@@ -0,0 +1,124 @@
package mx.quest.database.console;
import java.sql.SQLException;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.TreeSet;
import mx.quest.database.internal.DatabaseBackup;
import mx.quest.database.internal.DatabaseConfig;
import mx.quest.database.internal.DatabaseCore;
import mx.quest.database.internal.DatabaseRuntime;
import mx.quest.database.internal.DatabasesImpl;
import mx.quest.database.internal.Registry;
import mx.quest.database.internal.ScreenQueries;
/**
* What the database screens show, built per request: the application console's health screen and the one line on
* a site's dashboard. Every database read here is bounded and failure-tolerant: a screen about an unreachable
* database must still render.
*/
public final class DatabaseScreens {
/** The health screen. Never holds a credential. */
public record Health(DatabaseRuntime.Health runtime, String provider, String namespace, String target,
String tls, int liveSchemas, List<Registry.Node> nodes, List<Registry.Issue> issues,
List<String> consumers, List<String> appSchemaPlugins, String largestBackup,
boolean backupBudgetWarning, String lastRestoreFailure, String problem) {
/** Whether the database is in use now. */
public boolean available() {
return runtime.status() == DatabaseRuntime.Status.AVAILABLE && !runtime.outage();
}
}
/** A site's dashboard line. */
public record SiteLine(boolean hasData, String size, String lastRestore, boolean lastRestoreOk) {
}
static final Duration NODE_WINDOW = Duration.ofMinutes(5);
private final DatabaseCore core;
private final DatabasesImpl databases;
private final DatabaseBackup backup;
public DatabaseScreens(DatabaseCore core, DatabasesImpl databases, DatabaseBackup backup) {
this.core = core;
this.databases = databases;
this.backup = backup;
}
/** The application console's health screen. */
public Health health() {
DatabaseRuntime runtime = core.runtime();
DatabaseConfig c = runtime.config();
int live = 0;
List<Registry.Node> nodes = List.of();
List<Registry.Issue> issues = List.of();
List<String> appPlugins = List.of();
String problem = null;
if (runtime.available()) {
try {
Registry registry = runtime.registry();
live = registry.liveSchemaCount();
nodes = registry.nodes(NODE_WINDOW);
issues = registry.issues();
appPlugins = ScreenQueries.appSchemaPlugins(runtime);
} catch (SQLException | RuntimeException e) {
problem = DatabaseRuntime.describe(e);
}
}
List<String> consumers = new ArrayList<>(new TreeSet<>(databases.consumers().stream()
.map(x -> x.pluginId()).toList()));
String largest = null;
boolean warn = false;
Optional<Map.Entry<String, Long>> big = backup.largestBackup();
if (big.isPresent() && c != null) {
largest = big.get().getKey() + ": " + mib(big.get().getValue()) + " / " + mib(c.backupBudgetBytes());
warn = big.get().getValue() * 4 >= c.backupBudgetBytes() * 3;
}
String restoreFailure = backup.lastFailure().map(e -> e.getKey() + " — " + e.getValue().at() + ": "
+ e.getValue().message()).orElse(null);
return new Health(runtime.health(), c == null ? "" : c.provider(), c == null ? "" : c.namespace(),
c == null ? "" : c.host() + (c.port() == 0 ? "" : ":" + c.port()) + "/" + c.database(),
c == null ? "" : c.tls().name().toLowerCase().replace('_', '-'), live, nodes, issues, consumers,
appPlugins, largest, warn, restoreFailure, problem);
}
/** A site's dashboard line. */
public SiteLine site(String siteId) {
if (siteId == null) {
return new SiteLine(false, "", "", true);
}
boolean has;
try {
has = core.schemas().hasToken(siteId);
} catch (java.io.IOException unreadable) {
has = true; // the folder cannot be read: show the line, never "no data"
}
String size = "";
DatabaseRuntime runtime = core.runtime();
if (has && runtime.available()) {
try {
java.util.OptionalLong bytes = ScreenQueries.siteSize(runtime, siteId);
size = bytes.isPresent() ? mib(bytes.getAsLong()) : "";
} catch (SQLException | RuntimeException e) {
size = "";
}
}
Optional<DatabaseBackup.Outcome> outcome = backup.outcome(siteId);
return new SiteLine(has, size, outcome.map(o -> o.at().toString() + " — " + o.message()).orElse(""),
outcome.map(DatabaseBackup.Outcome::ok).orElse(true));
}
static String mib(long bytes) {
return String.format("%.1f MiB", bytes / (1024.0 * 1024.0));
}
static String at(Instant at) {
return at == null ? "" : at.toString();
}
}
@@ -0,0 +1,316 @@
package mx.quest.database.internal;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.regex.Pattern;
import java.util.zip.GZIPInputStream;
import tools.jackson.core.JacksonException;
import tools.jackson.databind.JsonNode;
import tools.jackson.databind.json.JsonMapper;
/**
* A site's database backup as read back: the manifest, each table's index and the parts, all checked before
* anything live is touched. <b>The archive is untrusted</b> (a site's administrator can upload one), so every name is
* checked against a strict grammar, every part against its recorded SHA-256 and row count, every line against a
* length cap, and the whole against the backup budget; nothing in it ever becomes an identifier — the restore looks
* names up in the new generation's own catalog.
*/
final class Archive {
static final String STATE = "state.json";
static final String MANIFEST = "manifest.json";
static final int FORMAT = 1;
static final int LINE_MAX = 16 * 1024 * 1024;
static final int SMALL_ENTRY_MAX = 4 * 1024 * 1024;
private static final Pattern NAME = Pattern.compile("[a-z0-9_]{1,64}");
private static final Pattern PLUGIN = Pattern.compile("[A-Za-z0-9][A-Za-z0-9._-]{0,254}");
private static final Pattern PART = Pattern.compile("part-[0-9]{5}\\.jsonl\\.gz");
private static final JsonMapper JSON = JsonMapper.builder().build();
/** Where the entries come from: the backup being restored, or data parked in the site folder. */
interface Entries {
boolean has(String entry) throws IOException;
byte[] read(String entry) throws IOException;
}
record Column(String name, String type) {
}
record Part(String entry, long rows, String sha256) {
}
record Table(String name, String plugin, List<Column> columns, long rows, List<Part> parts) {
}
record Sequence(String name, String plugin, long next, long increment) {
}
final String dialect;
final Map<String, Integer> plugins;
final List<Table> tables;
final List<Sequence> sequences;
private Archive(String dialect, Map<String, Integer> plugins, List<Table> tables, List<Sequence> sequences) {
this.dialect = dialect;
this.plugins = plugins;
this.tables = tables;
this.sequences = sequences;
}
/** The tables of one plugin. */
List<Table> tables(String pluginId) {
return tables.stream().filter(t -> t.plugin().equals(pluginId)).toList();
}
/** The sequences of one plugin. */
List<Sequence> sequences(String pluginId) {
return sequences.stream().filter(s -> s.plugin().equals(pluginId)).toList();
}
/** The state entry: {@code none}, {@code present}, or empty when the backup has none. */
static Optional<String> state(Entries in) throws IOException {
if (!in.has(STATE)) {
return Optional.empty();
}
JsonNode node = parse(in.read(STATE), STATE);
JsonNode schema = node.get("schema");
if (schema == null || !schema.isString()) {
throw new IOException("the database state entry is malformed");
}
return Optional.of(schema.stringValue());
}
/**
* Reads and checks the whole archive: names, counts, checksums, line lengths, budgets, and on PostgreSQL text
* holding U+0000, which it cannot store.
*/
static Archive read(Entries in, long budget, boolean postgres) throws IOException {
if (!in.has(MANIFEST)) {
throw new IOException("the database backup has no manifest");
}
JsonNode manifest = parse(in.read(MANIFEST), MANIFEST);
if (manifest.get("format") == null || manifest.get("format").asLong() != FORMAT) {
throw new IOException("the database backup's format is not one this plugin reads");
}
String dialect = text(manifest, "dialect");
Map<String, Integer> plugins = new LinkedHashMap<>();
JsonNode pluginNode = manifest.get("plugins");
if (pluginNode == null || !pluginNode.isObject()) {
throw new IOException("the database backup's manifest lists no plugins");
}
for (Map.Entry<String, JsonNode> e : pluginNode.properties()) {
requireMatch(PLUGIN, e.getKey(), "plugin id");
JsonNode v = e.getValue().get("version");
if (v == null || !v.isIntegralNumber() || v.asLong() < 0 || v.asLong() > 1_000_000) {
throw new IOException("the version of plugin " + e.getKey() + " is malformed");
}
plugins.put(e.getKey(), (int) v.asLong());
}
long[] spent = {0};
long decompressedBudget = Math.max(budget, 1) * 20;
long[] decompressed = {0};
List<Table> tables = new ArrayList<>();
JsonNode tableList = manifest.get("tables");
if (tableList == null || !tableList.isArray()) {
throw new IOException("the database backup's manifest lists no tables");
}
for (JsonNode t : tableList) {
String name = requireMatch(NAME, text(t, "name"), "table name");
String plugin = requireMatch(PLUGIN, text(t, "plugin"), "plugin id");
if (!plugins.containsKey(plugin)) {
throw new IOException("table " + name + " belongs to a plugin the manifest does not list");
}
tables.add(readTable(in, name, plugin, budget, spent, decompressedBudget, decompressed, postgres));
}
List<Sequence> sequences = new ArrayList<>();
JsonNode seqList = manifest.get("sequences");
if (seqList != null && seqList.isArray()) {
for (JsonNode s : seqList) {
String plugin = requireMatch(PLUGIN, text(s, "plugin"), "plugin id");
sequences.add(new Sequence(requireMatch(NAME, text(s, "name"), "sequence name"), plugin,
Long.parseLong(text(s, "next")), Long.parseLong(text(s, "increment"))));
}
}
return new Archive(dialect, Map.copyOf(plugins), List.copyOf(tables), List.copyOf(sequences));
}
private static Table readTable(Entries in, String name, String plugin, long budget, long[] spent,
long decompressedBudget, long[] decompressed, boolean postgres)
throws IOException {
String folder = "tables/" + name + "/";
JsonNode index = parse(in.read(folder + "index.json"), folder + "index.json");
List<Column> columns = columns(index.get("columns"), name);
List<Part> parts = new ArrayList<>();
long total = 0;
JsonNode partList = index.get("parts");
if (partList == null || !partList.isArray()) {
throw new IOException("table " + name + " lists no parts");
}
for (JsonNode p : partList) {
String file = requireMatch(PART, text(p, "name"), "part name");
long rows = p.get("rows") == null ? -1 : p.get("rows").asLong();
String sha = text(p, "sha256");
byte[] bytes = in.read(folder + file);
spent[0] += bytes.length;
if (spent[0] > budget) {
throw new IOException("the database backup is larger than the backup budget");
}
if (!Names.sha256Hex(bytes).equals(sha)) {
throw new IOException("part " + file + " of table " + name + " does not match its checksum");
}
long counted = forEachRow(bytes, name, columns, decompressedBudget, decompressed, row -> {
if (postgres) {
for (Object v : row) {
if (v instanceof String s && s.indexOf('\0') >= 0) {
throw new IOException("table " + name + " holds text with a NUL character, which "
+ "PostgreSQL cannot store");
}
}
}
});
if (counted != rows) {
throw new IOException("part " + file + " of table " + name + " holds " + counted + " rows, not "
+ rows);
}
total += rows;
parts.add(new Part(folder + file, rows, sha));
}
if (index.get("rows") == null || index.get("rows").asLong() != total) {
throw new IOException("table " + name + " row count does not add up");
}
return new Table(name, plugin, columns, total, List.copyOf(parts));
}
private static List<Column> columns(JsonNode node, String table) throws IOException {
if (node == null || !node.isArray() || node.isEmpty()) {
throw new IOException("table " + table + " has no column list");
}
List<Column> columns = new ArrayList<>();
for (JsonNode c : node) {
String type = text(c, "type");
if (type.length() > 64 || !type.matches("[A-Z]+(\\([0-9]{1,5}(,[0-9]{1,5})?\\))?")) {
throw new IOException("table " + table + " has a malformed column type");
}
columns.add(new Column(requireMatch(NAME, text(c, "name"), "column name"), type));
}
return List.copyOf(columns);
}
/** Receives one decoded row. */
@FunctionalInterface
interface RowSink {
void row(Object[] values) throws IOException;
}
/** Decodes every row of a part, checking the header against the table's columns; returns the row count. */
static long forEachRow(byte[] part, String table, List<Column> columns, long decompressedBudget,
long[] decompressed, RowSink sink) throws IOException {
long rows = 0;
try (InputStream in = new BufferedInputStream(new GZIPInputStream(new ByteArrayInputStream(part)))) {
byte[] headerLine = readLine(in, decompressed, decompressedBudget);
if (headerLine == null) {
throw new IOException("a part of table " + table + " is empty");
}
List<Column> header = columns(parse(headerLine, "part header").get("columns"), table);
if (!header.equals(columns)) {
throw new IOException("a part of table " + table + " has a header unlike the table's");
}
byte[] line;
while ((line = readLine(in, decompressed, decompressedBudget)) != null) {
JsonNode row = parse(line, "row");
if (!row.isArray() || row.size() != columns.size()) {
throw new IOException("a row of table " + table + " has the wrong number of values");
}
Object[] values = new Object[columns.size()];
for (int i = 0; i < values.length; i++) {
values[i] = value(row.get(i));
}
sink.row(values);
rows++;
}
}
return rows;
}
private static Object value(JsonNode n) throws IOException {
if (n == null || n.isNull()) {
return null;
}
if (n.isString()) {
return n.stringValue();
}
if (n.isBoolean()) {
return n.booleanValue();
}
if (n.isIntegralNumber()) {
BigInteger big = n.bigIntegerValue();
return big.bitLength() < 64 ? (Object) big.longValue() : big;
}
if (n.isNumber()) {
return n.doubleValue();
}
throw new IOException("a value in the backup is not a scalar");
}
private static byte[] readLine(InputStream in, long[] decompressed, long budget) throws IOException {
ByteArrayOutputStream line = new ByteArrayOutputStream();
int b;
boolean any = false;
while ((b = in.read()) >= 0) {
any = true;
if (++decompressed[0] > budget) {
throw new IOException("the database backup expands beyond its budget");
}
if (b == '\n') {
return line.toByteArray();
}
if (line.size() >= LINE_MAX) {
throw new IOException("a line in the database backup is longer than " + LINE_MAX + " bytes");
}
line.write(b);
}
return any && line.size() > 0 ? line.toByteArray() : null;
}
static JsonNode parse(byte[] bytes, String what) throws IOException {
if (bytes.length > LINE_MAX) {
throw new IOException(what + " is too large");
}
try {
return JSON.readTree(bytes);
} catch (JacksonException e) {
throw new IOException(what + " is not valid JSON");
}
}
private static String text(JsonNode node, String field) throws IOException {
JsonNode v = node == null ? null : node.get(field);
if (v == null || !v.isString()) {
throw new IOException("the database backup is missing '" + field + "'");
}
return v.stringValue();
}
private static String requireMatch(Pattern p, String value, String what) throws IOException {
if (!p.matcher(value).matches()) {
throw new IOException("the database backup holds a malformed " + what);
}
return value;
}
/** The mapper the participant writes with. */
static JsonMapper json() {
return JSON;
}
}
@@ -0,0 +1,127 @@
package mx.quest.database.internal;
import java.nio.file.Path;
import java.sql.Connection;
import java.sql.SQLException;
import java.time.Duration;
import java.util.List;
import java.util.function.Supplier;
import javax.sql.DataSource;
import mx.quest.database.spi.ConnectionSettings;
import mx.quest.database.spi.DatabaseProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* The connection tests on the database plugin's settings page. Each answers with a fixed category (and, for success,
* the server version); the driver's own message goes only to the server log, never with a credential.
*
* <ul>
* <li><b>Running</b>: borrows from the live pool and asks the server what it is.</li>
* <li><b>Saved</b>: opens one throwaway connection with short timeouts from the settings saved on one provider
* plugin's page, which the next restart would apply, and changes nothing. The test takes no typed values: a
* form with a username and a password box is one a browser fills in with the operator's own saved login,
* which a test would then send to whatever server the form named (the 1.x test did exactly that).</li>
* </ul>
*/
public final class ConnectionTester {
private static final Logger log = LoggerFactory.getLogger(ConnectionTester.class);
static final Duration TEST_CONNECT = Duration.ofSeconds(5);
static final Duration TEST_SOCKET = Duration.ofSeconds(15);
/** The categories the console shows. */
public enum Category {
OK, INVALID_SETTINGS, NO_PROVIDER, UNREACHABLE, TLS, AUTHENTICATION, DATABASE_MISSING, UNSUPPORTED_SERVER,
NOT_AVAILABLE, OTHER
}
/** A test's answer: the category and a detail safe to show (a server version or a settings problem). */
public record Result(Category category, String detail) {
}
private final DatabaseRuntime runtime;
private final DatabaseProps props;
private final Supplier<List<DatabaseProvider>> providers;
private final Path workDir;
public ConnectionTester(DatabaseRuntime runtime, DatabaseProps props, Supplier<List<DatabaseProvider>> providers,
Path workDir) {
this.runtime = runtime;
this.props = props;
this.providers = providers;
this.workDir = workDir;
}
/** The products whose provider plugin is installed, each once, in the order found: what "Saved" can test. */
public List<String> testable() {
return ProviderChoice.supported(providers.get()).stream().map(DatabaseProvider::id).distinct().toList();
}
/** Tests the live pool. */
public Result running() {
if (!runtime.available()) {
return new Result(Category.NOT_AVAILABLE, runtime.health().detail());
}
try (Connection c = runtime.borrow()) {
return new Result(Category.OK, runtime.engine().inspectServer(c));
} catch (SQLException | RuntimeException e) {
log.warn("database: running-connection test failed: {}", DatabaseRuntime.describe(e));
return new Result(e instanceof SQLException sql ? category(runtime.engine().classify(sql))
: Category.UNREACHABLE, "");
}
}
/**
* Tests the settings saved on one provider plugin's page.
*
* @param product {@code postgresql} or {@code mariadb}
*/
public Result saved(String product) {
List<DatabaseProvider> matching = ProviderChoice.supported(providers.get()).stream()
.filter(p -> p.id().equals(product)).toList();
if (matching.size() != 1) {
return new Result(Category.NO_PROVIDER, ProviderChoice.plugin(String.valueOf(product)));
}
DatabaseConfig config;
try {
config = ProviderChoice.saved(props, matching.get(0)).config();
} catch (IllegalArgumentException e) {
return new Result(Category.INVALID_SETTINGS, e.getMessage());
} catch (RuntimeException e) {
// A provider whose saved settings cannot be read; its message is not trusted to be free of a secret.
log.warn("database: the saved settings of {} could not be read ({})", ProviderChoice.plugin(product),
e.getClass().getSimpleName());
return new Result(Category.OTHER, "");
}
Engine engine = DatabaseRuntime.engineFor(config.provider());
try {
Path ca = DatabaseRuntime.writeCa(workDir, config.caCertificate());
DataSource source = matching.get(0).dataSource(new ConnectionSettings(config.host(), config.port(),
config.database(), config.username(), config.password(), config.tls(), ca, TEST_CONNECT,
TEST_SOCKET));
try (Connection c = source.getConnection()) {
return new Result(Category.OK, engine.inspectServer(c));
}
} catch (SQLException e) {
log.warn("database: saved-settings test against {} failed: {}", config, DatabaseRuntime.describe(e));
return new Result(category(engine.classify(e)), e instanceof UnsupportedServerException ? e.getMessage()
: "");
} catch (Exception e) {
log.warn("database: saved-settings test against {} failed: {}", config, DatabaseRuntime.describe(e));
return new Result(Category.OTHER, "");
}
}
private static Category category(Engine.ConnectFailure failure) {
return switch (failure) {
case UNREACHABLE -> Category.UNREACHABLE;
case TLS -> Category.TLS;
case AUTHENTICATION -> Category.AUTHENTICATION;
case DATABASE_MISSING -> Category.DATABASE_MISSING;
case UNSUPPORTED_SERVER -> Category.UNSUPPORTED_SERVER;
default -> Category.OTHER;
};
}
}
@@ -0,0 +1,27 @@
package mx.quest.database.internal;
import java.util.Objects;
import java.util.Set;
import mx.quest.database.spi.Scope;
/**
* A consumer plugin as the database plugin knows it: the id its jar proved, its prefix, the scopes it declared and
* where its scripts are.
*/
public record Consumer(String pluginId, String prefix, Set<Scope.Kind> scopes, ScriptSource scripts) {
public Consumer {
Objects.requireNonNull(pluginId, "pluginId");
Objects.requireNonNull(prefix, "prefix");
scopes = Set.copyOf(scopes);
Objects.requireNonNull(scripts, "scripts");
if (scopes.isEmpty()) {
throw new IllegalArgumentException("plugin '" + pluginId + "' declares no database scope");
}
}
/** A consumer whose prefix follows from its id. */
public static Consumer of(String pluginId, Set<Scope.Kind> scopes, ScriptSource scripts) {
return new Consumer(pluginId, Names.pluginPrefix(pluginId), scopes, scripts);
}
}
@@ -0,0 +1,80 @@
package mx.quest.database.internal;
import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.CodeSource;
import java.util.Optional;
import java.util.jar.JarFile;
import java.util.zip.ZipEntry;
/**
* Where a consumer's migration scripts come from: <b>only</b> the jar its {@code DatabaseConsumer} bean was loaded
* from, never "the first hit" on the class loader every plugin shares. The jar also proves the plugin id: the
* loader requires a plugin's install folder to be named after its id, and the jar sits directly in it.
*/
public final class ConsumerJar implements ScriptSource {
private final String pluginId;
private final Path jar;
private ConsumerJar(String pluginId, Path jar) {
this.pluginId = pluginId;
this.jar = jar;
}
/**
* The jar a bean's class was loaded from, checked against the plugin id it claims.
*
* @throws IllegalArgumentException when the class does not come from a jar directly inside a folder named
* {@code pluginId} (a library in {@code lib/}, a class folder, another plugin)
*/
public static ConsumerJar of(Class<?> beanClass, String pluginId) {
CodeSource source = beanClass.getProtectionDomain().getCodeSource();
if (source == null || source.getLocation() == null) {
throw new IllegalArgumentException("cannot tell which jar " + beanClass.getName() + " comes from");
}
Path path;
try {
path = Path.of(source.getLocation().toURI());
} catch (URISyntaxException | IllegalArgumentException e) {
throw new IllegalArgumentException("cannot tell which jar " + beanClass.getName() + " comes from");
}
Path folder = path.getParent();
if (!Files.isRegularFile(path) || !path.getFileName().toString().endsWith(".jar") || folder == null
|| folder.getFileName() == null || !folder.getFileName().toString().equals(pluginId)) {
throw new IllegalArgumentException("the DatabaseConsumer bean " + beanClass.getName()
+ " is not in the jar of plugin '" + pluginId + "' (it comes from " + path + ")");
}
return new ConsumerJar(pluginId, path);
}
@Override
public String pluginId() {
return pluginId;
}
@Override
public Optional<byte[]> read(String entry) throws IOException {
try (JarFile file = new JarFile(jar.toFile())) {
ZipEntry e = file.getEntry(entry);
if (e == null || e.isDirectory()) {
return Optional.empty();
}
try (InputStream in = file.getInputStream(e)) {
byte[] bytes = in.readNBytes(Scripts.MAX_SCRIPT_BYTES + 1);
if (bytes.length > Scripts.MAX_SCRIPT_BYTES) {
throw new IOException(entry + " is larger than " + Scripts.MAX_SCRIPT_BYTES + " bytes");
}
return Optional.of(bytes);
}
}
}
@Override
public String toString() {
return jar.toString();
}
}
@@ -0,0 +1,794 @@
package mx.quest.database.internal;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.nio.file.attribute.PosixFilePermissions;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Base64;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.zip.GZIPOutputStream;
import mx.quest.database.spi.Scope;
import mx.quest.runway.spi.BackupParticipant;
import mx.quest.runway.spi.model.BackupReader;
import mx.quest.runway.spi.model.BackupWriter;
import mx.quest.runway.spi.model.SiteRef;
import mx.quest.runway.spi.service.PluginSiteFiles;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A site's database data in its backups ({@code plugin-data/database/} inside the archive).
*
* <h2>Export</h2>
* A site whose folder has no database token has no data: {@code state.json} says {@code none} and the backup goes
* on. Otherwise every table of every plugin is read in one consistent snapshot — tables streamed with a fetch size,
* sequences last — into typed, versioned JSON-lines parts (gzip, at most {@value #PART_MAX} bytes each), one
* {@code index.json} per table, and {@code manifest.json} last. If the database cannot be reached the backup fails,
* naming the site: a backup is complete or it is not a backup. The whole is capped by {@code backupBudgetMiB}.
*
* <h2>Restore</h2>
* <ol>
* <li>The archive is checked whole before anything live is touched ({@link Archive}).</li>
* <li>Per plugin: installed and at or above the backup's version, restore it; installed but older, refuse the
* restore; not installed, park its data in the site folder until it arrives.</li>
* <li>A new generation is built under the site lock: each plugin is migrated to the backup's version, its tables
* emptied, checked against the archive, loaded with user triggers and foreign keys out of the way, given its
* sequences, and migrated forward.</li>
* <li>One transaction switches the site to the new generation; the old one is dropped later. On failure the new
* generation is dropped, the old one stays live, and the restore throws; the failure is kept for the health
* screen and the site's dashboard.</li>
* </ol>
*/
public final class DatabaseBackup implements BackupParticipant, Migrator.Parked {
private static final Logger log = LoggerFactory.getLogger(DatabaseBackup.class);
public static final String KEY = "database";
static final int PART_MAX = 4 * 1024 * 1024;
static final int FETCH = 500;
static final int BATCH = 500;
static final String PARKED = "deferred/";
static final Duration RESTORE_LOCK_WAIT = Duration.ofMinutes(5);
/** The last restore of a site, for the health screen and the site's dashboard. */
public record Outcome(Instant at, boolean ok, String message) {
}
private final DatabaseCore core;
private final DatabasesImpl databases;
private final PluginSiteFiles files;
private final Map<String, Outcome> outcomes = new ConcurrentHashMap<>();
private final Map<String, Long> exportBytes = new ConcurrentHashMap<>();
public DatabaseBackup(DatabaseCore core, DatabasesImpl databases, PluginSiteFiles files) {
this.core = core;
this.databases = databases;
this.files = files;
}
@Override
public String key() {
return KEY;
}
/** The last restore outcome of a site. */
public Optional<Outcome> outcome(String siteId) {
return Optional.ofNullable(outcomes.get(siteId));
}
/** The largest compressed size a site's last backup reached on this node, with the site, if any backup ran. */
public Optional<Map.Entry<String, Long>> largestBackup() {
return exportBytes.entrySet().stream().max(Map.Entry.comparingByValue());
}
/** The most recent failed restore of any site, for the health screen. */
public Optional<Map.Entry<String, Outcome>> lastFailure() {
return outcomes.entrySet().stream().filter(e -> !e.getValue().ok())
.max(Map.Entry.comparingByValue((a, b) -> a.at().compareTo(b.at())));
}
// =============================================================================================== export ==
@Override
public void export(BackupWriter out, SiteRef site) throws IOException {
String siteId = site.id();
if (!core.schemas().hasToken(siteId)) {
writeJson(out, Archive.STATE, Map.of("schema", "none"));
return;
}
DatabaseRuntime runtime = core.runtime();
if (!runtime.available()) {
throw new IOException("the database is not reachable, so the database data of site '" + siteId
+ "' cannot be backed up");
}
String schema;
try {
schema = core.schemas().resolve(siteId);
} catch (RuntimeException e) {
throw new IOException("the database schema of site '" + siteId + "' cannot be resolved: "
+ e.getMessage(), e);
}
Engine engine = runtime.engine();
long[] spent = {0};
long budget = runtime.config().backupBudgetBytes();
List<Map<String, Object>> tableEntries = new ArrayList<>();
List<Map<String, Object>> sequenceEntries = new ArrayList<>();
Map<String, Integer> versions;
// The tables are read into a spool on disk and handed to the kernel only after the read transaction has ended
// and its connection is back: the kernel streams a download straight to the browser, and writing to it from
// inside the transaction held one of the setup pool's two connections (and an open snapshot) for as long as
// the slowest browser took. The spool holds at most the backup budget.
try (Spool spool = new Spool(runtime.workDir().resolve("spool"))) {
try (Connection c = runtime.setupConnection()) {
Map<String, String> prefixes;
c.setAutoCommit(true);
prefixes = runtime.registry().prefixes(c);
c.setAutoCommit(false);
c.setReadOnly(true);
c.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
try {
engine.bind(c, schema, DatabaseRuntime.LONG_TIMEOUT);
engine.beginRead(c);
Map<String, List<Engine.Column>> tables = engine.tables(c, schema);
versions = appliedVersions(c, engine, schema);
for (Map.Entry<String, List<Engine.Column>> t : new TreeMap<>(tables).entrySet()) {
String table = t.getKey();
if (table.startsWith(Names.RESERVED_PREFIX)) {
continue;
}
String plugin = owner(table, prefixes);
if (plugin == null) {
log.warn("database: table '{}' of site '{}' carries no known plugin prefix; it is not "
+ "in the backup", table, siteId);
continue;
}
versions.putIfAbsent(plugin, 0);
tableEntries.add(Map.of("name", table, "plugin", plugin));
writeTable(spool, c, engine, table, t.getValue(), budget, spent);
}
for (Engine.Sequence s : engine.sequences(c, schema)) {
String plugin = owner(s.name(), prefixes);
if (plugin != null) {
versions.putIfAbsent(plugin, 0);
sequenceEntries.add(Map.of("name", s.name(), "plugin", plugin,
"next", Long.toString(s.next()), "increment", Long.toString(s.increment())));
}
}
c.commit();
} finally {
try {
c.rollback();
} catch (SQLException ignored) {
// committed already
}
c.setReadOnly(false);
c.setAutoCommit(true);
}
} catch (SQLException e) {
throw new IOException("reading the database data of site '" + siteId + "' failed: "
+ DatabaseRuntime.describe(e), e);
}
spool.drainTo(out);
}
Map<String, Object> plugins = new TreeMap<>();
versions.forEach((id, v) -> plugins.put(id, Map.of("version", v)));
Map<String, Object> manifest = new LinkedHashMap<>();
manifest.put("format", Archive.FORMAT);
manifest.put("dialect", engine.id());
manifest.put("plugins", plugins);
manifest.put("tables", tableEntries);
manifest.put("sequences", sequenceEntries);
writeJson(out, Archive.STATE, Map.of("schema", "present"));
writeJson(out, Archive.MANIFEST, manifest); // last: a backup cut short has no manifest and never restores
exportBytes.put(siteId, spent[0]);
}
/** The plugin whose prefix a name starts with (prefixes never start one another, so at most one). */
static String owner(String name, Map<String, String> prefixes) {
for (Map.Entry<String, String> e : prefixes.entrySet()) {
if (name.startsWith(e.getValue())) {
return e.getKey();
}
}
return null;
}
private static Map<String, Integer> appliedVersions(Connection c, Engine engine, String schema)
throws SQLException {
Map<String, Integer> versions = new HashMap<>();
try (PreparedStatement ps = c.prepareStatement("SELECT plugin_id, MAX(version) FROM " + engine.quote(schema)
+ ".rw_migrations WHERE state = 'applied' GROUP BY plugin_id")) {
try (ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
versions.put(rs.getString(1), rs.getInt(2));
}
}
}
return versions;
}
private void writeTable(BackupWriter out, Connection c, Engine engine, String table, List<Engine.Column> columns,
long budget, long[] spent) throws IOException, SQLException {
List<Map<String, Object>> header = new ArrayList<>();
StringBuilder select = new StringBuilder("SELECT ");
for (int i = 0; i < columns.size(); i++) {
Engine.Column col = columns.get(i);
if (col.type().startsWith(Portable.UNSUPPORTED)) {
throw new IOException("column " + table + "." + col.name() + " has a type the backup cannot carry ("
+ col.type().substring(Portable.UNSUPPORTED.length()) + ")");
}
header.add(Map.of("name", col.name(), "type", col.type()));
select.append(i == 0 ? "" : ", ").append(engine.quote(col.name()));
}
select.append(" FROM ").append(engine.quote(table));
byte[] headerLine = line(Map.of("columns", header));
List<Map<String, Object>> parts = new ArrayList<>();
long total = 0;
try (PreparedStatement ps = c.prepareStatement(select.toString(), ResultSet.TYPE_FORWARD_ONLY,
ResultSet.CONCUR_READ_ONLY)) {
ps.setFetchSize(FETCH);
try (ResultSet rs = ps.executeQuery()) {
PartBuffer part = new PartBuffer(headerLine);
Object[] row = new Object[columns.size()];
while (rs.next()) {
for (int i = 0; i < row.length; i++) {
row[i] = engine.readValue(rs, i + 1, columns.get(i).type());
}
part.add(line(row));
total++;
if (part.size() >= PART_MAX) {
parts.add(flush(out, table, parts.size() + 1, part, budget, spent));
part = new PartBuffer(headerLine);
}
}
if (part.rows() > 0 || parts.isEmpty()) {
parts.add(flush(out, table, parts.size() + 1, part, budget, spent));
}
}
}
Map<String, Object> index = new LinkedHashMap<>();
index.put("table", table);
index.put("columns", header);
index.put("rows", total);
index.put("parts", parts);
writeJson(out, "tables/" + table + "/index.json", index);
}
private Map<String, Object> flush(BackupWriter out, String table, int number, PartBuffer part, long budget,
long[] spent) throws IOException {
byte[] bytes = part.finish();
spent[0] += bytes.length;
if (spent[0] > budget) {
throw new IOException("the database data is larger than the backup budget (" + (budget / (1024 * 1024))
+ " MiB compressed); raise backupBudgetMiB or back the database up with its own dump tools");
}
String name = String.format("part-%05d.jsonl.gz", number);
try (OutputStream o = out.put("tables/" + table + "/" + name)) {
o.write(bytes);
}
Map<String, Object> entry = new LinkedHashMap<>();
entry.put("name", name);
entry.put("rows", part.rows());
entry.put("sha256", Names.sha256Hex(bytes));
return entry;
}
/**
* Entries written while the read transaction is open, kept in files in a private folder and handed to the real
* writer, in the same order, once the transaction is over. Deleted on close; a spool left by a crash is deleted by
* the next export.
*/
static final class Spool implements BackupWriter, AutoCloseable {
private final Path dir;
private final List<String> entries = new ArrayList<>();
Spool(Path parent) throws IOException {
Files.createDirectories(parent);
try (DirectoryStream<Path> old = Files.newDirectoryStream(parent, "export-*")) {
for (Path p : old) {
if (Files.getLastModifiedTime(p).toInstant().isBefore(Instant.now().minus(Duration.ofDays(1)))) {
deleteQuietly(p);
}
}
}
Path made;
try {
made = Files.createTempDirectory(parent, "export-",
PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("rwx------")));
} catch (UnsupportedOperationException noPosix) {
made = Files.createTempDirectory(parent, "export-");
}
dir = made;
}
@Override
public OutputStream put(String entry) throws IOException {
Path file = dir.resolve(String.format("%06d", entries.size()));
entries.add(entry);
return Files.newOutputStream(file, StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE);
}
/** Copies every entry to {@code out}, in the order written. */
void drainTo(BackupWriter out) throws IOException {
for (int i = 0; i < entries.size(); i++) {
try (OutputStream o = out.put(entries.get(i));
InputStream in = Files.newInputStream(dir.resolve(String.format("%06d", i)))) {
in.transferTo(o);
}
}
}
@Override
public void close() {
deleteQuietly(dir);
}
private static void deleteQuietly(Path folder) {
try (DirectoryStream<Path> files = Files.newDirectoryStream(folder)) {
for (Path f : files) {
Files.deleteIfExists(f);
}
Files.deleteIfExists(folder);
} catch (IOException e) {
log.warn("database: could not delete the export spool {}: {}", folder, e.getMessage());
}
}
}
/** One part being written: gzip in memory, the header line first. */
private static final class PartBuffer {
private final ByteArrayOutputStream bytes = new ByteArrayOutputStream();
private final GZIPOutputStream gzip;
private long rows;
PartBuffer(byte[] header) throws IOException {
gzip = new GZIPOutputStream(bytes, 64 * 1024);
gzip.write(header);
}
void add(byte[] line) throws IOException {
gzip.write(line);
rows++;
}
long rows() {
return rows;
}
int size() {
return bytes.size();
}
byte[] finish() throws IOException {
gzip.finish();
return bytes.toByteArray();
}
}
private static byte[] line(Object value) {
byte[] json = Archive.json().writeValueAsBytes(value);
byte[] withNewline = new byte[json.length + 1];
System.arraycopy(json, 0, withNewline, 0, json.length);
withNewline[json.length] = '\n';
return withNewline;
}
private static void writeJson(BackupWriter out, String entry, Object value) throws IOException {
try (OutputStream o = out.put(entry)) {
o.write(Archive.json().writeValueAsBytes(value));
}
}
// ============================================================================================== restore ==
@Override
public void importInto(BackupReader in, SiteRef site) throws IOException {
String siteId = site.id();
try {
restore(entries(in), siteId);
} catch (IOException | RuntimeException e) {
String why = e.getMessage() == null ? e.getClass().getSimpleName() : e.getMessage();
outcomes.put(siteId, new Outcome(Instant.now(), false, why));
log.error("database: restoring the database data of site '{}' failed: {}; its previous data is still "
+ "live", siteId, why);
throw e instanceof IOException io ? io : new IOException(why, e);
}
}
private static Archive.Entries entries(BackupReader in) {
return new Archive.Entries() {
@Override
public boolean has(String entry) {
return in.has(entry);
}
@Override
public byte[] read(String entry) throws IOException {
try (var stream = in.open(entry)) {
byte[] bytes = stream.readNBytes(Archive.LINE_MAX + 1);
if (bytes.length > Archive.LINE_MAX) {
throw new IOException(entry + " is too large");
}
return bytes;
}
}
};
}
private void restore(Archive.Entries in, String siteId) throws IOException {
DatabaseRuntime runtime = core.runtime();
Optional<String> state;
try {
state = Archive.state(in);
} catch (IOException | RuntimeException e) {
core.schemas().keepLiveDataAcrossRestore(siteId, RESTORE_LOCK_WAIT); // the live data stays the site's
throw e;
}
if (state.isPresent() && "none".equals(state.get())) {
retireIfAny(siteId);
outcomes.put(siteId, new Outcome(Instant.now(), true, "the backup held no database data"));
return;
}
// The kernel has already put the archive's folder in place, with the token of whatever generation was live
// when the backup was taken (or none). Until this restore actually switches generations, the live data stays
// the site's, also if a step below fails.
core.schemas().keepLiveDataAcrossRestore(siteId, RESTORE_LOCK_WAIT);
if (state.isEmpty()) {
log.warn("database: the backup of site '{}' has no database state (taken without the database plugin); "
+ "its database data is left as it is", siteId);
return;
}
if (!"present".equals(state.get())) {
throw new IOException("the backup's database state is unknown: " + state.get());
}
if (!runtime.available()) {
throw new IOException("the database is not reachable; the site's files were restored but not its "
+ "database data");
}
Engine engine = runtime.engine();
Archive archive = Archive.read(in, runtime.config().backupBudgetBytes(), engine instanceof PostgresEngine);
Map<String, Consumer> installed = new HashMap<>();
for (Consumer c : databases.consumers()) {
installed.put(c.pluginId(), c);
}
List<Consumer> restore = new ArrayList<>();
List<String> park = new ArrayList<>();
for (Map.Entry<String, Integer> p : new TreeMap<>(archive.plugins).entrySet()) {
Consumer consumer = installed.get(p.getKey());
if (consumer == null || !consumer.scopes().contains(Scope.Kind.SITE)) {
park.add(p.getKey());
continue;
}
int shipped = core.migrator().shipped(consumer, Scope.Kind.SITE).size();
if (shipped < p.getValue()) {
throw new IOException("plugin '" + p.getKey() + "' is older than the backup (its data is at version "
+ p.getValue() + ", the installed plugin ships " + shipped + "); upgrade it first");
}
restore.add(consumer);
}
try {
runtime.locks().site(siteId, RESTORE_LOCK_WAIT, () -> {
String staging = core.schemas().createStaging(siteId);
try {
for (Consumer consumer : restore) {
core.migrator().migrateWithData(consumer, Scope.Kind.SITE, staging,
archive.plugins.get(consumer.pluginId()),
schema -> load(in, archive, consumer, schema));
}
core.schemas().switchTo(siteId, staging);
} catch (SQLException | RuntimeException e) {
if (switchCommitted(siteId, staging)) {
log.warn("database: switching site '{}' to its restored data reported an error after it was "
+ "made: {}", siteId, DatabaseRuntime.describe(e));
core.schemas().evict(siteId);
return null;
}
core.schemas().abandonStaging(staging);
throw e;
}
return null;
});
} catch (Locks.LockTimeoutException e) {
throw new IOException("the site's data is busy (another restore or a removal); try again later");
} catch (SQLException e) {
throw new IOException("the database restore failed: " + DatabaseRuntime.describe(e), e);
}
for (String plugin : park) {
park(in, archive, siteId, plugin);
}
outcomes.put(siteId, new Outcome(Instant.now(), true, "restored " + restore.size() + " plugin(s)"
+ (park.isEmpty() ? "" : ", kept data of " + String.join(", ", park) + " until installed")));
log.info("database: restored the database data of site '{}'", siteId);
}
/** Whether a switch that reported an error had committed: the registry already maps the site to the staging data. */
private boolean switchCommitted(String siteId, String staging) {
try {
return core.schemas().isLive(siteId, staging);
} catch (SQLException | RuntimeException e) {
return false; // abandonStaging then leaves a schema that turns out to be mapped alone
}
}
private void retireIfAny(String siteId) {
DatabaseRuntime runtime = core.runtime();
if (!runtime.available()) {
core.schemas().markFresh(siteId); // the old mapping is retired on its next use
return;
}
try {
runtime.locks().site(siteId, RESTORE_LOCK_WAIT, () -> {
try (Connection c = runtime.setupConnection()) {
c.setAutoCommit(true);
Optional<Registry.SiteRow> row = runtime.registry().site(c, siteId);
if (row.isPresent()) {
core.schemas().retire(c, siteId, row.get().schema());
}
}
return null;
});
} catch (SQLException | RuntimeException e) {
log.warn("database: could not retire the old data of site '{}' now; the sweep will: {}", siteId,
DatabaseRuntime.describe(e));
core.schemas().markFresh(siteId);
}
}
/**
* Loads one plugin's archived tables into a schema migrated to the archive's version: checks every archived
* table and column against the schema's own catalog, empties the plugin's tables (seed rows), loads with user
* triggers and foreign keys out of the way, then sets the plugin's sequences.
*/
void load(Archive.Entries in, Archive archive, Consumer consumer, String schema) throws SQLException,
IOException {
DatabaseRuntime runtime = core.runtime();
Engine engine = runtime.engine();
boolean postgres = engine instanceof PostgresEngine;
try (Connection c = runtime.setupConnection()) {
c.setAutoCommit(true);
engine.bind(c, schema, DatabaseRuntime.LONG_TIMEOUT);
c.setAutoCommit(false);
boolean done = false;
try {
Map<String, List<Engine.Column>> catalog = engine.tables(c, schema);
List<String> own = catalog.keySet().stream().filter(t -> t.startsWith(consumer.prefix())).sorted()
.toList();
Map<Archive.Table, Plan> plans = new LinkedHashMap<>();
for (Archive.Table table : archive.tables(consumer.pluginId())) {
plans.put(table, plan(table, catalog, consumer));
}
List<String> putBack = engine.suspendForLoad(c, schema, own);
for (String table : own) {
Jdbc.execute(c, "DELETE FROM " + engine.quote(table));
}
long[] decompressed = {0};
long cap = runtime.config().backupBudgetBytes() * 20;
for (Map.Entry<Archive.Table, Plan> e : plans.entrySet()) {
Plan plan = e.getValue();
try (PreparedStatement ps = c.prepareStatement(plan.insert(engine, postgres))) {
int[] pending = {0};
for (Archive.Part part : e.getKey().parts()) {
Archive.forEachRow(in.read(part.entry()), e.getKey().name(), e.getKey().columns(), cap,
decompressed, values -> {
try {
for (int i = 0; i < values.length; i++) {
engine.bindValue(ps, i + 1, plan.types().get(i), values[i]);
}
ps.addBatch();
if (++pending[0] >= BATCH) {
ps.executeBatch();
pending[0] = 0;
}
} catch (SQLException | IllegalArgumentException | java.time.DateTimeException
| ArithmeticException ex) {
throw new IOException("a value of table " + e.getKey().name()
+ " does not fit its column: " + ex.getMessage(), ex);
}
});
}
if (pending[0] > 0) {
ps.executeBatch();
}
}
}
for (String statement : putBack) {
Jdbc.execute(c, statement);
}
List<String> sequences = engine.sequences(c, schema).stream().map(Engine.Sequence::name).toList();
for (Archive.Sequence s : archive.sequences(consumer.pluginId())) {
if (sequences.contains(s.name()) && s.name().startsWith(consumer.prefix())) {
engine.setSequence(c, schema, s.name(), s.next());
}
}
c.commit();
done = true;
} finally {
if (done) {
c.setAutoCommit(true);
} else {
try {
c.rollback();
} catch (SQLException ignored) {
// the generation is dropped anyway
}
// The load may have left session state behind (on MariaDB, FOREIGN_KEY_CHECKS = 0): the next
// migration on this connection would run without referential checks. Never lend it again.
runtime.evictSetup(c);
}
}
}
}
/** How one archived table loads: the target's own table and column names, and the target types. */
private record Plan(String table, List<String> columns, List<String> types) {
String insert(Engine engine, boolean postgres) {
StringBuilder sql = new StringBuilder("INSERT INTO ").append(engine.quote(table)).append(" (");
for (int i = 0; i < columns.size(); i++) {
sql.append(i == 0 ? "" : ", ").append(engine.quote(columns.get(i)));
}
sql.append(")").append(postgres ? " OVERRIDING SYSTEM VALUE" : "").append(" VALUES (");
for (int i = 0; i < columns.size(); i++) {
sql.append(i == 0 ? "?" : ", ?");
}
return sql.append(")").toString();
}
}
/** Matches an archived table to the catalog by lookup; refuses what does not fit. */
private static Plan plan(Archive.Table table, Map<String, List<Engine.Column>> catalog, Consumer consumer)
throws IOException {
if (!table.name().startsWith(consumer.prefix())) {
throw new IOException("table " + table.name() + " is outside the prefix of plugin '"
+ consumer.pluginId() + "'");
}
String target = null;
for (String name : catalog.keySet()) {
if (name.equals(table.name())) {
target = name; // the catalog's own string, never the archive's
}
}
if (target == null) {
throw new IOException("plugin '" + consumer.pluginId() + "' has no table " + table.name()
+ " at the backup's version");
}
Map<String, Engine.Column> targetColumns = new LinkedHashMap<>();
for (Engine.Column col : catalog.get(target)) {
targetColumns.put(col.name(), col);
}
List<String> names = new ArrayList<>();
List<String> types = new ArrayList<>();
for (Archive.Column col : table.columns()) {
Engine.Column t = targetColumns.remove(col.name());
if (t == null) {
throw new IOException("table " + table.name() + " has no column " + col.name());
}
if (!Portable.compatible(col.type(), t.type())) {
throw new IOException("column " + table.name() + "." + col.name() + " is " + t.type()
+ " here but " + col.type() + " in the backup");
}
names.add(t.name());
types.add(t.type());
}
for (Engine.Column rest : targetColumns.values()) {
if (!rest.nullable() && !rest.hasDefault()) {
throw new IOException("column " + table.name() + "." + rest.name() + " is required but not in the "
+ "backup");
}
}
return new Plan(target, List.copyOf(names), List.copyOf(types));
}
// =============================================================================================== parked ==
/** Keeps an absent plugin's data in the site folder (base64 of the archived bytes), best effort. */
private void park(Archive.Entries in, Archive archive, String siteId, String plugin) {
String folder = PARKED + plugin + "/";
try {
files.deleteTree(siteId, PARKED + plugin);
Map<String, Object> manifest = new LinkedHashMap<>();
manifest.put("format", Archive.FORMAT);
manifest.put("dialect", archive.dialect);
manifest.put("plugins", Map.of(plugin, Map.of("version", archive.plugins.get(plugin))));
List<Map<String, Object>> tables = new ArrayList<>();
for (Archive.Table t : archive.tables(plugin)) {
tables.add(Map.of("name", t.name(), "plugin", plugin));
files.writeText(siteId, folder + "tables/" + t.name() + "/index.json.b64",
Base64.getEncoder().encodeToString(in.read("tables/" + t.name() + "/index.json")));
for (Archive.Part p : t.parts()) {
files.writeText(siteId, folder + p.entry() + ".b64",
Base64.getEncoder().encodeToString(in.read(p.entry())));
}
}
manifest.put("tables", tables);
List<Map<String, Object>> sequences = new ArrayList<>();
for (Archive.Sequence s : archive.sequences(plugin)) {
sequences.add(Map.of("name", s.name(), "plugin", plugin, "next", Long.toString(s.next()),
"increment", Long.toString(s.increment())));
}
manifest.put("sequences", sequences);
files.writeText(siteId, folder + Archive.MANIFEST + ".b64",
Base64.getEncoder().encodeToString(Archive.json().writeValueAsBytes(manifest)));
log.info("database: kept the data of plugin '{}' for site '{}' until that plugin is installed", plugin,
siteId);
} catch (IOException | RuntimeException e) {
log.warn("database: could not keep the data of absent plugin '{}' for site '{}': {}", plugin, siteId,
e.getMessage());
}
}
private Archive.Entries parkedEntries(String siteId, String plugin) {
String folder = PARKED + plugin + "/";
return new Archive.Entries() {
@Override
public boolean has(String entry) throws IOException {
return files.stat(siteId, folder + entry + ".b64").isPresent();
}
@Override
public byte[] read(String entry) throws IOException {
String text = files.readText(siteId, folder + entry + ".b64")
.orElseThrow(() -> new IOException("parked entry missing: " + entry));
try {
return Base64.getDecoder().decode(text.strip().getBytes(StandardCharsets.US_ASCII));
} catch (IllegalArgumentException e) {
throw new IOException("parked entry is damaged: " + entry);
}
}
};
}
@Override
public Optional<Integer> version(String siteId, Consumer consumer) throws IOException {
Archive.Entries in = parkedEntries(siteId, consumer.pluginId());
if (!in.has(Archive.MANIFEST)) { // a folder that cannot be searched throws: never "none"
return Optional.empty();
}
// Read whole, as the load will: what cannot be loaded is refused now, before any table is created.
Integer version = Archive.read(in, core.runtime().config().backupBudgetBytes(),
core.runtime().engine() instanceof PostgresEngine).plugins.get(consumer.pluginId());
if (version == null) {
throw new IOException("the kept data does not name plugin '" + consumer.pluginId() + "'");
}
return Optional.of(version);
}
@Override
public void load(String siteId, Consumer consumer, String schema) throws SQLException, IOException {
Archive.Entries in = parkedEntries(siteId, consumer.pluginId());
Archive archive = Archive.read(in, core.runtime().config().backupBudgetBytes(),
core.runtime().engine() instanceof PostgresEngine);
load(in, archive, consumer, schema);
// The manifest is the mark that data waits: it goes first, and only once the data is in. If this fails the
// load runs again on the next use (it empties the tables first).
files.delete(siteId, PARKED + consumer.pluginId() + "/" + Archive.MANIFEST + ".b64");
log.info("database: loaded the kept data of plugin '{}' into site '{}'", consumer.pluginId(), siteId);
try {
files.deleteTree(siteId, PARKED + consumer.pluginId());
} catch (IOException | RuntimeException e) {
log.warn("database: the rest of the kept data of plugin '{}' in site '{}' could not be removed: {}",
consumer.pluginId(), siteId, DatabaseRuntime.describe(e));
}
}
}
@@ -0,0 +1,254 @@
package mx.quest.database.internal;
import java.io.ByteArrayInputStream;
import java.nio.charset.StandardCharsets;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.time.Duration;
import java.util.Locale;
import java.util.Optional;
import java.util.Set;
import java.util.regex.Pattern;
import mx.quest.database.spi.ConnectionSettings.Tls;
import mx.quest.database.spi.ProviderSettings;
/**
* The database plugin's settings after checking: what the pool, the names and the console screen use. Built once at
* startup from {@link DatabaseProps} and the chosen provider's running settings, and by the connection test from a
* provider's saved settings. A
* value the plugin cannot use safely is refused with a reason rather than repaired, except the tuning numbers, which
* are clamped to a working range.
*
* @param provider {@code postgresql} or {@code mariadb}
* @param namespace the install's namespace ({@link Names#NAMESPACE})
* @param host the checked host: an RFC-1123 name, an IPv4 address or an IPv6 literal without brackets
* @param port 1–65535, or 0 for the default
* @param database the database name
* @param username the account
* @param password the account's password in clear, possibly empty; never logged
* @param tls the TLS policy
* @param caCertificate a PEM certificate to verify the server against, or {@code null}
* @param poolMax the main pool's size
* @param statementTimeout a consumer statement's limit
* @param backupBudgetBytes the compressed size a site's database backup may reach
* @param collation MariaDB's collation for consumer tables, or {@code null} for the server's best
*/
public record DatabaseConfig(String provider, String namespace, String host, int port, String database,
String username, String password, Tls tls, String caCertificate, int poolMax,
Duration statementTimeout, long backupBudgetBytes, String collation) {
/** The providers this database plugin has SQL for. */
public static final Set<String> PROVIDERS = Set.of("postgresql", "mariadb");
private static final Pattern LABEL = Pattern.compile("[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?");
private static final Pattern IPV4 = Pattern.compile(
"(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])(\\.(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3}");
private static final Pattern IPV6_CHARS = Pattern.compile("[0-9A-Fa-f:.]{2,45}");
private static final Pattern DATABASE = Pattern.compile("[A-Za-z0-9_$-]{1,63}");
private static final Pattern COLLATION = Pattern.compile("[a-z0-9_]{1,64}");
private static final int USERNAME_MAX = 128;
private static final int PASSWORD_MAX = 1024;
private static final int PEM_MAX = 64 * 1024;
/** Clamped tuning ranges. */
static final int POOL_MIN = 2;
static final int POOL_MAX = 200;
static final int TIMEOUT_MIN_S = 1;
static final int TIMEOUT_MAX_S = 3600;
static final int BUDGET_MIN_MIB = 1;
static final int BUDGET_MAX_MIB = 4096;
/** The secret is never part of the text. */
@Override
public String toString() {
return "DatabaseConfig[provider=" + provider + ", namespace=" + namespace + ", host=" + host + ", port="
+ port + ", database=" + database + ", username=" + username + ", tls=" + tls + "]";
}
/**
* Checks raw settings.
*
* @param props the database plugin's own settings: namespace and limits (its provider choice is resolved by
* the caller, {@link ProviderChoice})
* @param provider the chosen provider's id
* @param server the chosen provider's server settings, the password in clear
* @return the checked settings
* @throws IllegalArgumentException naming the first setting that is missing or unusable; the message never
* holds the password
*/
public static DatabaseConfig from(DatabaseProps props, String provider, ProviderSettings server) {
String product = trimToNull(provider);
if (product == null) {
throw new IllegalArgumentException("no provider is chosen");
}
product = product.toLowerCase(Locale.ROOT);
if (!PROVIDERS.contains(product)) {
throw new IllegalArgumentException("unknown provider: " + product);
}
String namespace = Names.namespace(Optional.ofNullable(trimToNull(props.getNamespace())).orElse("rw"));
String host = checkHost(server.host());
int port = port(server.port());
String database = trimToNull(server.database());
if (database == null || !DATABASE.matcher(database).matches()) {
throw new IllegalArgumentException("the database name must be 1 to 63 letters, digits, '_', '$' or '-'");
}
String username = trimToNull(server.username());
if (username == null || username.length() > USERNAME_MAX || hasControl(username)) {
throw new IllegalArgumentException("the username must be 1 to " + USERNAME_MAX
+ " characters, without control characters");
}
String secret = server.password() == null ? "" : server.password();
if (secret.length() > PASSWORD_MAX || hasControl(secret)) {
throw new IllegalArgumentException("the password is too long or holds control characters");
}
Tls tls = tls(server.tls());
String ca = trimToNull(server.caCertificate());
if (ca != null) {
ca = checkPem(ca);
}
String collation = trimToNull(server.collation());
if (collation != null && !COLLATION.matcher(collation).matches()) {
throw new IllegalArgumentException("the collation must be a MariaDB collation name such as "
+ "utf8mb4_uca1400_ai_ci");
}
int poolMax = clamp(props.getPoolMax(), 10, POOL_MIN, POOL_MAX);
int timeout = clamp(props.getStatementTimeoutSeconds(), 10, TIMEOUT_MIN_S, TIMEOUT_MAX_S);
int budget = clamp(props.getBackupBudgetMiB(), 128, BUDGET_MIN_MIB, BUDGET_MAX_MIB);
return new DatabaseConfig(product, namespace, host, port, database, username, secret, tls, ca, poolMax,
Duration.ofSeconds(timeout), budget * 1024L * 1024L, collation);
}
/** The port: blank for the product's default (0), else 1–65535. */
static int port(String value) {
String v = trimToNull(value);
if (v == null) {
return 0;
}
try {
int port = Integer.parseInt(v);
if (port >= 1 && port <= 65535) {
return port;
}
} catch (NumberFormatException e) {
// reported below
}
throw new IllegalArgumentException("the port must be between 1 and 65535, or blank for the default");
}
/** The TLS setting: {@code disable}, {@code require} or {@code verify-full} (the default). */
static Tls tls(String value) {
String v = trimToNull(value);
if (v == null) {
return Tls.VERIFY_FULL;
}
return switch (v.toLowerCase(Locale.ROOT)) {
case "disable" -> Tls.DISABLE;
case "require" -> Tls.REQUIRE;
case "verify-full" -> Tls.VERIFY_FULL;
default -> throw new IllegalArgumentException("tls must be disable, require or verify-full");
};
}
/**
* An RFC-1123 host name, an IPv4 address or an IPv6 literal (brackets allowed and removed). Anything that could
* smuggle driver syntax — a list, a query, credentials, an address block, whitespace — is refused.
*/
static String checkHost(String value) {
String host = trimToNull(value);
if (host == null) {
throw new IllegalArgumentException("no host is set");
}
if (host.startsWith("[") && host.endsWith("]")) {
host = host.substring(1, host.length() - 1);
}
if (host.indexOf(':') >= 0) {
if (IPV6_CHARS.matcher(host).matches() && isIpv6(host)) {
return host.toLowerCase(Locale.ROOT);
}
throw new IllegalArgumentException("the host is not a valid IPv6 address");
}
if (IPV4.matcher(host).matches()) {
return host;
}
if (host.length() > 253 || host.endsWith(".")) {
throw new IllegalArgumentException("the host is not a valid host name");
}
for (String label : host.split("\\.", -1)) {
if (!LABEL.matcher(label).matches()) {
throw new IllegalArgumentException("the host is not a valid host name");
}
}
if (host.chars().allMatch(c -> Character.isDigit(c) || c == '.')) {
throw new IllegalArgumentException("the host is not a valid IPv4 address");
}
return host.toLowerCase(Locale.ROOT);
}
/** An IPv6 literal: at most one {@code ::}, up to eight 1–4 digit groups, an optional trailing IPv4. */
private static boolean isIpv6(String s) {
int doubleColon = s.indexOf("::");
if (doubleColon >= 0 && s.indexOf("::", doubleColon + 1) >= 0) {
return false;
}
String[] parts = s.split(":", -1);
int groups = 0;
for (int i = 0; i < parts.length; i++) {
String p = parts[i];
if (p.isEmpty()) {
continue; // part of a "::" or a leading/trailing colon next to it
}
if (i == parts.length - 1 && p.indexOf('.') >= 0) {
if (!IPV4.matcher(p).matches()) {
return false;
}
groups += 2;
} else if (p.length() > 4 || !p.chars().allMatch(c -> Character.digit(c, 16) >= 0)) {
return false;
} else {
groups++;
}
}
if (doubleColon < 0) {
return groups == 8 && !s.startsWith(":") && !s.endsWith(":");
}
return groups < 8;
}
/** One or more PEM certificates and nothing else. */
static String checkPem(String pem) {
if (pem.length() > PEM_MAX) {
throw new IllegalArgumentException("the CA certificate is too large");
}
String body = pem.replace("\r\n", "\n").strip();
if (!body.startsWith("-----BEGIN CERTIFICATE-----") || !body.endsWith("-----END CERTIFICATE-----")) {
throw new IllegalArgumentException("the CA certificate must be in PEM form (-----BEGIN CERTIFICATE-----)");
}
try {
CertificateFactory factory = CertificateFactory.getInstance("X.509");
if (factory.generateCertificates(new ByteArrayInputStream(body.getBytes(StandardCharsets.US_ASCII)))
.isEmpty()) {
throw new IllegalArgumentException("the CA certificate holds no certificate");
}
} catch (CertificateException e) {
throw new IllegalArgumentException("the CA certificate cannot be read as an X.509 certificate");
}
return body + "\n";
}
private static int clamp(Integer value, int fallback, int min, int max) {
int v = value == null ? fallback : value;
return Math.max(min, Math.min(max, v));
}
private static boolean hasControl(String s) {
return s.chars().anyMatch(Character::isISOControl);
}
static String trimToNull(String s) {
if (s == null) {
return null;
}
String t = s.strip();
return t.isEmpty() ? null : t;
}
}
@@ -0,0 +1,69 @@
package mx.quest.database.internal;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Semaphore;
import mx.quest.runway.spi.service.RequestContext;
import mx.quest.runway.spi.service.Sites;
/**
* The parts every consumer handle shares: the runtime, the site schemas, the migrator, the kernel services, and the
* per-site in-flight caps that keep one busy site from taking the whole pool.
*/
public final class DatabaseCore {
private final DatabaseRuntime runtime;
private final SiteSchemas schemas;
private final Migrator migrator;
private final Sites sites;
private final RequestContext requestContext;
private final Map<String, Semaphore> perSite = new ConcurrentHashMap<>();
private final Semaphore app = new Semaphore(Integer.MAX_VALUE);
public DatabaseCore(DatabaseRuntime runtime, SiteSchemas schemas, Migrator migrator, Sites sites,
RequestContext requestContext) {
this.runtime = Objects.requireNonNull(runtime, "runtime");
this.schemas = Objects.requireNonNull(schemas, "schemas");
this.migrator = Objects.requireNonNull(migrator, "migrator");
this.sites = Objects.requireNonNull(sites, "sites");
this.requestContext = Objects.requireNonNull(requestContext, "requestContext");
}
public DatabaseRuntime runtime() {
return runtime;
}
public SiteSchemas schemas() {
return schemas;
}
public Migrator migrator() {
return migrator;
}
public Sites sites() {
return sites;
}
public RequestContext requestContext() {
return requestContext;
}
/** The in-flight cap for a site: half the pool (at least one). */
Semaphore siteSlots(String siteId) {
DatabaseConfig c = runtime.config();
int permits = c == null ? 1 : Math.max(1, c.poolMax() / 2);
return perSite.computeIfAbsent(siteId, id -> new Semaphore(permits, true));
}
/** The app scope is not capped beyond the pool itself. */
Semaphore appSlots() {
return app;
}
/** Forgets a deleted site's cap. */
void forgetSite(String siteId) {
perSite.remove(siteId);
}
}
@@ -0,0 +1,92 @@
package mx.quest.database.internal;
import java.sql.Connection;
import java.sql.SQLException;
import java.time.Duration;
import java.util.List;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;
import mx.quest.database.spi.DatabaseConsumer;
import mx.quest.database.spi.Scope;
import mx.quest.runway.spi.model.PluginInfo;
import mx.quest.runway.spi.service.PluginLifecycle;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Starts and stops the database plugin. {@link #started} only hands work to the executor — the first connection,
* then (each time the database becomes available) the reconcile sweep and the migration warm-up — so Runway's
* start never waits on the database. {@link #stopping} closes the pools and stops the executor.
*/
public final class DatabaseLifecycle implements PluginLifecycle {
private static final Logger log = LoggerFactory.getLogger(DatabaseLifecycle.class);
static final Duration SWEEP_EVERY = Duration.ofMinutes(15);
private final DatabaseCore core;
private final DatabasesImpl databases;
private final Supplier<List<DatabaseConsumer>> consumers;
private final ScheduledExecutorService executor;
public DatabaseLifecycle(DatabaseCore core, DatabasesImpl databases, Supplier<List<DatabaseConsumer>> consumers,
ScheduledExecutorService executor) {
this.core = core;
this.databases = databases;
this.consumers = consumers;
this.executor = executor;
}
@Override
public void started(PluginInfo self) {
DatabaseRuntime runtime = core.runtime();
runtime.onAvailable(() -> {
databases.registerAll(consumers.get(), refused -> log.warn("database: a consumer was refused: {}",
refused));
core.schemas().reconcile();
warmUp();
});
runtime.start();
executor.scheduleWithFixedDelay(core.schemas()::reconcile, SWEEP_EVERY.toMinutes(), SWEEP_EVERY.toMinutes(),
TimeUnit.MINUTES);
}
/**
* Brings every consumer's tables up to date ahead of the first call, one schema at a time. Only a warm-up: the
* check each first call makes is the authority, so a failure here is logged and nothing more.
*/
void warmUp() {
DatabaseRuntime runtime = core.runtime();
List<Consumer> all = databases.consumers();
if (all.isEmpty() || !runtime.available()) {
return;
}
String app = Names.appSchema(runtime.config().namespace());
List<Registry.SiteRow> sites;
try (Connection c = runtime.setupConnection()) {
sites = runtime.registry().sites(c);
} catch (SQLException e) {
log.warn("database: the warm-up could not list the sites: {}", DatabaseRuntime.describe(e));
return;
}
for (Consumer consumer : all) {
if (consumer.scopes().contains(Scope.Kind.APP)) {
core.migrator().warm(consumer, Scope.Kind.APP, null, app);
}
if (consumer.scopes().contains(Scope.Kind.SITE)) {
for (Registry.SiteRow site : sites) {
if (SiteSchemas.LIVE.equals(site.state()) && core.sites().find(site.siteId()).isPresent()) {
core.migrator().warm(consumer, Scope.Kind.SITE, site.siteId(), site.schema());
}
}
}
}
}
@Override
public void stopping() {
core.runtime().stop();
executor.shutdownNow();
}
}
@@ -0,0 +1,155 @@
package mx.quest.database.internal;
import java.util.ArrayList;
import java.util.List;
/**
* The database plugin's app-level settings as bound from {@code runway.plugin.database.*} at startup
* ({@code external/plugin-settings/database.yml}): the provider choice, the namespace and the limits. Raw values:
* {@link DatabaseConfig#from} checks them. The server's own settings (host, account, password, TLS) belong to the
* provider plugin since 2.0.0 ({@link mx.quest.database.spi.ProviderSettings}).
*
* <p>The 1.x connection keys are still bound, only so that a {@code database.yml} that still holds them can be
* reported as moved ({@link #legacyKeys()}) rather than read as "nothing is set". They are never used to connect.
*/
public class DatabaseProps {
private String provider = "auto";
private String namespace = "rw";
private Integer poolMax = 10;
private Integer statementTimeoutSeconds = 10;
private Integer backupBudgetMiB = 128;
// 1.x keys, bound only to report that they moved (never used to connect).
private String host;
private String port;
private String database;
private String username;
private String password;
private String tls;
private String caCertificate;
private String collation;
/** The 1.x connection keys still set in {@code database.yml}, in declaration order; empty when none is. */
public List<String> legacyKeys() {
List<String> keys = new ArrayList<>();
add(keys, "host", host);
add(keys, "port", port);
add(keys, "database", database);
add(keys, "username", username);
add(keys, "password", password);
add(keys, "tls", tls);
add(keys, "caCertificate", caCertificate);
add(keys, "collation", collation);
return keys;
}
private static void add(List<String> keys, String key, String value) {
if (value != null && !value.isBlank()) {
keys.add(key);
}
}
public String getProvider() {
return provider;
}
public void setProvider(String provider) {
this.provider = provider;
}
public String getNamespace() {
return namespace;
}
public void setNamespace(String namespace) {
this.namespace = namespace;
}
public Integer getPoolMax() {
return poolMax;
}
public void setPoolMax(Integer poolMax) {
this.poolMax = poolMax;
}
public Integer getStatementTimeoutSeconds() {
return statementTimeoutSeconds;
}
public void setStatementTimeoutSeconds(Integer statementTimeoutSeconds) {
this.statementTimeoutSeconds = statementTimeoutSeconds;
}
public Integer getBackupBudgetMiB() {
return backupBudgetMiB;
}
public void setBackupBudgetMiB(Integer backupBudgetMiB) {
this.backupBudgetMiB = backupBudgetMiB;
}
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public String getPort() {
return port;
}
public void setPort(String port) {
this.port = port;
}
public String getDatabase() {
return database;
}
public void setDatabase(String database) {
this.database = database;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getTls() {
return tls;
}
public void setTls(String tls) {
this.tls = tls;
}
public String getCaCertificate() {
return caCertificate;
}
public void setCaCertificate(String caCertificate) {
this.caCertificate = caCertificate;
}
public String getCollation() {
return collation;
}
public void setCollation(String collation) {
this.collation = collation;
}
}
@@ -0,0 +1,556 @@
package mx.quest.database.internal;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.nio.file.attribute.PosixFilePermissions;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.SQLNonTransientConnectionException;
import java.sql.SQLRecoverableException;
import java.sql.SQLTransientConnectionException;
import java.time.Duration;
import java.time.Instant;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;
import javax.sql.DataSource;
import mx.quest.database.spi.ConnectionSettings;
import mx.quest.database.spi.DatabaseProvider;
import mx.quest.database.spi.DatabaseUnavailableException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* The connection to the configured database: the settings, the engine, the pools and whether the database can be
* used right now. <b>Runway never fails to start because of it</b>: nothing here connects on the caller's thread;
* {@link #start()} hands a connect-with-back-off task to the plugin's executor, and {@link #available()} turns true
* once the server has passed its checks and the registry exists.
*
* <p>Three ways to a connection, for three jobs:
* <ul>
* <li>the <b>main pool</b> ({@code poolMax}) lends connections to consumers, with a 2-second borrow timeout and the
* consumer statement timeout;</li>
* <li>the <b>setup pool</b> (two connections, a long timeout) runs schema creation, registry writes, migrations,
* backup and restore, so none of that ever happens on a consumer's connection;</li>
* <li><b>lock connections</b> are opened unpooled from the provider's data source and closed after use, so a
* database lock is never held on a pooled connection and lock holders cannot starve either pool.</li>
* </ul>
*/
public final class DatabaseRuntime {
private static final Logger log = LoggerFactory.getLogger(DatabaseRuntime.class);
/** Where the runtime stands, for {@link #available()} and the health screen. */
public enum Status {
/** The settings are missing or unusable; fixed by saving the settings and restarting. */
NOT_CONFIGURED,
/** The chosen provider plugin is not installed, two offer the same product, or it predates 2.0.0. */
NO_PROVIDER,
/** Trying to reach the server. */
CONNECTING,
/** The server answered but is not supported. */
UNSUPPORTED,
/** Ready. */
AVAILABLE,
/** Shut down. */
STOPPED
}
/** A snapshot for the health screen. Never holds a credential. */
public record Health(Status status, String detail, String server, String driver, boolean outage,
Instant lastErrorAt, String lastError, int poolActive, int poolIdle, int poolMax) {
}
static final Duration BORROW_TIMEOUT = Duration.ofSeconds(2);
static final Duration CONNECT_TIMEOUT = Duration.ofSeconds(5);
static final Duration LONG_TIMEOUT = Duration.ofMinutes(30);
static final Duration HEARTBEAT = Duration.ofSeconds(60);
static final Duration MAX_BACKOFF = Duration.ofSeconds(60);
static final Duration UNSUPPORTED_RETRY = Duration.ofMinutes(5);
private static final int LOCK_CONNECTIONS = 4;
private final Supplier<ProviderChoice.Chosen> source;
private final Path workDir;
private final ScheduledExecutorService executor;
private final Semaphore lockConnections = new Semaphore(LOCK_CONNECTIONS, true);
private final List<Runnable> onAvailable = new CopyOnWriteArrayList<>();
private final Locks locks = new Locks(this);
private volatile Status status = Status.CONNECTING;
private volatile String detail = "starting";
private volatile String server;
private volatile String driver;
private volatile boolean outage;
private volatile Instant lastErrorAt;
private volatile String lastError;
private volatile DatabaseConfig config;
private volatile Engine engine;
private volatile DataSource rawMain;
private volatile DataSource rawSetup;
private volatile HikariDataSource main;
private volatile HikariDataSource setup;
private volatile Registry registry;
private long backoffMillis = 1000;
/**
* @param source chooses the provider and checks the settings ({@link ProviderChoice#running}); throws
* {@link ProviderChoice.NoProviderException} or {@link IllegalArgumentException} with a reason
* @param workDir the plugin's own folder for the CA file
* @param executor the plugin's executor
*/
public DatabaseRuntime(Supplier<ProviderChoice.Chosen> source, Path workDir, ScheduledExecutorService executor) {
this.source = Objects.requireNonNull(source, "source");
this.workDir = Objects.requireNonNull(workDir, "workDir");
this.executor = Objects.requireNonNull(executor, "executor");
}
/** Hands the first connection attempt to the executor; never connects on the caller's thread. */
public void start() {
executor.execute(this::connect);
}
/** Runs {@code hook} on the executor each time the database becomes available (first time and after an outage). */
public void onAvailable(Runnable hook) {
onAvailable.add(hook);
}
/** Whether consumers can use the database now. */
public boolean available() {
return status == Status.AVAILABLE && !outage;
}
/** The current status. */
public Status status() {
return status;
}
/** The checked settings, or {@code null} when not configured. */
public DatabaseConfig config() {
return config;
}
/** The engine for the configured provider, or {@code null} when not configured. */
public Engine engine() {
return engine;
}
/** The registry, once available. */
public Registry registry() {
return registry;
}
/** The per-site and install-wide locks. */
Locks locks() {
return locks;
}
/** The plugin's own folder (the CA file, export spools). */
Path workDir() {
return workDir;
}
/** The executor. */
ScheduledExecutorService executor() {
return executor;
}
/** The health snapshot. */
public Health health() {
HikariDataSource pool = main;
int active = 0;
int idle = 0;
if (pool != null && pool.getHikariPoolMXBean() != null) {
active = pool.getHikariPoolMXBean().getActiveConnections();
idle = pool.getHikariPoolMXBean().getIdleConnections();
}
DatabaseConfig c = config;
return new Health(status, detail, server, driver, outage, lastErrorAt, lastError, active, idle,
c == null ? 0 : c.poolMax());
}
// --- connecting ---------------------------------------------------------------------------------------------
private void connect() {
if (status == Status.STOPPED) {
return;
}
if (config == null && !prepare()) {
return; // settings or provider problem: fixed only by a restart
}
try (Connection c = rawSetup.getConnection()) {
server = engine.inspectServer(c);
} catch (UnsupportedServerException e) {
fail(Status.UNSUPPORTED, e.getMessage(), null);
schedule(UNSUPPORTED_RETRY);
return;
} catch (SQLException | RuntimeException e) {
fail(Status.CONNECTING, describe(e), e);
schedule(nextBackoff());
return;
}
try {
openPools();
Registry r = new Registry(this);
r.ensure();
registry = r;
} catch (SQLException | RuntimeException e) {
fail(Status.CONNECTING, "the registry could not be prepared: " + describe(e), e);
schedule(nextBackoff());
return;
}
status = Status.AVAILABLE;
detail = "available";
outage = false;
backoffMillis = 1000;
log.info("database: connected to {} ({}), namespace '{}'", server, config.provider(), config.namespace());
executor.scheduleWithFixedDelay(this::heartbeat, HEARTBEAT.toMillis(), HEARTBEAT.toMillis(),
TimeUnit.MILLISECONDS);
fireAvailable();
}
/** Chooses the provider and reads its settings; false (with the status set) when that cannot work. */
private boolean prepare() {
DatabaseConfig c;
DatabaseProvider provider;
try {
ProviderChoice.Chosen chosen = source.get();
c = chosen.config();
provider = chosen.provider();
} catch (ProviderChoice.NoProviderException e) {
status = Status.NO_PROVIDER;
detail = e.getMessage();
log.warn("database: {}", detail);
return false;
} catch (IllegalArgumentException e) {
status = Status.NOT_CONFIGURED;
detail = e.getMessage();
log.info("database: not configured: {}", e.getMessage());
return false;
}
Engine e = engineFor(c.provider());
Path ca;
try {
ca = writeCa(workDir, c.caCertificate());
} catch (IOException ex) {
status = Status.NOT_CONFIGURED;
detail = "the CA certificate could not be written to the plugin folder: " + ex.getClass().getSimpleName();
log.warn("database: {}", detail);
return false;
}
driver = provider.driverVersion();
engine = e;
rawMain = provider.dataSource(settings(c, ca, c.statementTimeout().plusSeconds(30)));
rawSetup = provider.dataSource(settings(c, ca, LONG_TIMEOUT.plusSeconds(60)));
config = c;
return true;
}
/** The engine that has SQL for a provider id. */
public static Engine engineFor(String provider) {
return switch (provider) {
case "postgresql" -> new PostgresEngine();
case "mariadb" -> new MariaDbEngine();
default -> throw new IllegalArgumentException("unknown provider: " + provider);
};
}
/** Connection settings for one pool. */
static ConnectionSettings settings(DatabaseConfig c, Path ca, Duration socketTimeout) {
return new ConnectionSettings(c.host(), c.port(), c.database(), c.username(), c.password(), c.tls(), ca,
CONNECT_TIMEOUT, socketTimeout);
}
/** Writes the CA certificate to an owner-only file named by its hash; {@code null} when there is none. */
static Path writeCa(Path workDir, String pem) throws IOException {
if (pem == null) {
return null;
}
Files.createDirectories(workDir);
Path target = workDir.resolve("ca-" + Names.sha256Hex(pem).substring(0, 16) + ".pem");
if (Files.isRegularFile(target)) {
return target;
}
Path tmp = Files.createTempFile(workDir, "ca-", ".tmp");
try {
if (FileSystems.getDefault().supportedFileAttributeViews().contains("posix")) {
Files.setPosixFilePermissions(tmp, PosixFilePermissions.fromString("rw-------"));
}
Files.writeString(tmp, pem, StandardCharsets.US_ASCII);
Files.move(tmp, target, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
} finally {
Files.deleteIfExists(tmp);
}
return target;
}
private void openPools() {
if (main != null) {
return;
}
DatabaseConfig c = config;
HikariConfig m = new HikariConfig();
m.setPoolName("runway-database");
m.setDataSource(rawMain);
m.setMaximumPoolSize(c.poolMax());
m.setMinimumIdle(Math.min(2, c.poolMax()));
m.setConnectionTimeout(BORROW_TIMEOUT.toMillis());
m.setValidationTimeout(1000);
m.setInitializationFailTimeout(-1);
m.setKeepaliveTime(Duration.ofMinutes(5).toMillis());
m.setIdleTimeout(Duration.ofMinutes(10).toMillis());
m.setMaxLifetime(Duration.ofMinutes(30).toMillis());
m.setConnectionInitSql(engine.connectionInitSql(c.statementTimeout(), c.collation()));
HikariConfig s = new HikariConfig();
s.setPoolName("runway-database-setup");
s.setDataSource(rawSetup);
s.setMaximumPoolSize(2);
s.setMinimumIdle(0);
s.setConnectionTimeout(Duration.ofSeconds(30).toMillis());
s.setValidationTimeout(1000);
s.setInitializationFailTimeout(-1);
s.setIdleTimeout(Duration.ofMinutes(2).toMillis());
s.setMaxLifetime(Duration.ofMinutes(30).toMillis());
s.setConnectionInitSql(engine.connectionInitSql(LONG_TIMEOUT, c.collation()));
main = new HikariDataSource(m);
setup = new HikariDataSource(s);
}
/** How soon after an outage is marked the server is tried again, once, before the regular heartbeat. */
static final Duration OUTAGE_RECHECK = Duration.ofSeconds(2);
/**
* One heartbeat: records this node and ends an outage once the server answers. It uses a connection of its own,
* not the setup pool, so a pool that is only busy (a long restore, a migration) is never taken for an outage.
* Package-visible for tests.
*/
void heartbeat() {
Registry r = registry;
DataSource raw = rawSetup;
if (r == null || raw == null || status != Status.AVAILABLE) {
return;
}
Connection c;
try {
c = raw.getConnection();
} catch (SQLException | RuntimeException e) {
markOutage(e);
return;
}
try (c) {
c.setAutoCommit(true);
r.heartbeat(c);
} catch (SQLException e) {
if (isConnectionFailure(e)) {
markOutage(e);
return;
}
log.warn("database: could not record this node's heartbeat: {}", describe(e));
} catch (RuntimeException e) {
log.warn("database: could not record this node's heartbeat: {}", describe(e));
}
if (outage) {
outage = false;
log.info("database: reachable again");
fireAvailable();
}
}
private void fireAvailable() {
for (Runnable hook : onAvailable) {
executor.execute(() -> {
try {
hook.run();
} catch (RuntimeException e) {
log.warn("database: a task after connecting failed: {}", describe(e));
}
});
}
}
private void fail(Status s, String why, Throwable cause) {
status = s;
detail = why;
lastError = why;
lastErrorAt = Instant.now();
log.warn("database: {}{}", why, cause == null ? "" : " (retrying)");
}
private void schedule(Duration delay) {
if (status != Status.STOPPED) {
executor.schedule(this::connect, delay.toMillis(), TimeUnit.MILLISECONDS);
}
}
private Duration nextBackoff() {
long now = backoffMillis;
backoffMillis = Math.min(MAX_BACKOFF.toMillis(), backoffMillis * 2);
return Duration.ofMillis(now);
}
/** Records a failure to reach the server after it was available. */
void markOutage(Exception e) {
if (!outage) {
log.warn("database: unreachable: {}", describe(e));
try {
// One early re-check, so a blip ends in seconds rather than at the next minute's heartbeat.
executor.schedule(this::heartbeat, OUTAGE_RECHECK.toMillis(), TimeUnit.MILLISECONDS);
} catch (java.util.concurrent.RejectedExecutionException stopping) {
// shutting down
}
}
outage = true;
lastError = describe(e);
lastErrorAt = Instant.now();
}
/** A one-line description without credentials: the exception type, the SQL state and the driver message. */
public static String describe(Throwable e) {
StringBuilder b = new StringBuilder(e.getClass().getSimpleName());
if (e instanceof SQLException sql && sql.getSQLState() != null) {
b.append(" [").append(sql.getSQLState()).append(']');
}
if (e.getMessage() != null) {
String msg = e.getMessage().replaceAll("[\\r\\n]+", " ");
b.append(": ").append(msg.length() > 300 ? msg.substring(0, 300) + "…" : msg);
}
return b.toString();
}
// --- connections ----------------------------------------------------------------------------------------------
private void requireAvailable() {
if (status != Status.AVAILABLE) {
throw new DatabaseUnavailableException("the database is not available: " + detail);
}
}
/**
* A consumer connection from the main pool. A failure to reach the server marks an outage; a pool that is merely
* full (every connection in use for the whole borrow timeout) does not: it fails this call only, since marking an
* outage would refuse every consumer on every site until the next heartbeat.
*/
Connection borrow() {
requireAvailable();
try {
return main.getConnection();
} catch (SQLTransientConnectionException e) {
if (e.getCause() == null) {
// HikariCP attaches the last failed connection attempt as the cause; none means the pool is full.
lastError = describe(e);
lastErrorAt = Instant.now();
throw new DatabaseUnavailableException("too many database calls in flight; try again shortly", e);
}
markOutage(e);
throw new DatabaseUnavailableException("the database is not reachable", e);
} catch (SQLException e) {
markOutage(e);
throw new DatabaseUnavailableException("the database is not reachable", e);
}
}
/**
* Whether a failure says the server cannot be reached (SQLState class {@code 08}, a connection-class exception, or
* a pool timeout caused by a failed connection attempt), as opposed to a statement the server refused.
*/
static boolean isConnectionFailure(SQLException e) {
String state = e.getSQLState();
return (state != null && state.startsWith("08")) || e instanceof SQLNonTransientConnectionException
|| e instanceof SQLRecoverableException
|| (e instanceof SQLTransientConnectionException && e.getCause() != null);
}
/** A connection from the setup pool. */
Connection setupConnection() throws SQLException {
HikariDataSource s = setup;
if (s == null) {
throw new SQLException("the database is not connected yet");
}
return s.getConnection();
}
/** Throws a consumer connection away instead of returning it to its pool (a failed bind or reset). */
void evict(Connection c) {
try {
main.evictConnection(c);
} catch (RuntimeException e) {
try {
c.close();
} catch (SQLException ignored) {
// already broken
}
}
}
/** Throws a setup connection away. */
void evictSetup(Connection c) {
try {
setup.evictConnection(c);
} catch (RuntimeException e) {
try {
c.close();
} catch (SQLException ignored) {
// already broken
}
}
}
/**
* An unpooled connection for a database lock, waiting at most {@code wait} for one of the few lock slots. Hand it
* back with {@link #closeLockConnection}, which frees the slot.
*
* @return {@code null} when no slot came free in time
*/
Connection openLockConnection(Duration wait) throws SQLException {
try {
if (!lockConnections.tryAcquire(wait.toMillis(), TimeUnit.MILLISECONDS)) {
return null;
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return null;
}
try {
Connection c = rawSetup.getConnection();
c.setAutoCommit(true);
return c;
} catch (SQLException | RuntimeException e) {
lockConnections.release();
throw e;
}
}
/** Closes a lock connection (which releases any lock still on it) and frees its slot. */
void closeLockConnection(Connection c) {
try {
c.close();
} catch (SQLException ignored) {
// the server releases session locks when the connection goes away
} finally {
lockConnections.release();
}
}
/** Stops the runtime and closes the pools. */
public void stop() {
status = Status.STOPPED;
detail = "stopped";
HikariDataSource m = main;
HikariDataSource s = setup;
if (m != null) {
m.close();
}
if (s != null) {
s.close();
}
}
}
@@ -0,0 +1,46 @@
package mx.quest.database.internal;
import java.util.concurrent.Executor;
import mx.quest.runway.spi.model.SiteLifecycleEvent;
import mx.quest.runway.spi.service.SiteEventListener;
/**
* Site creations and deletions. The listener only evicts and enqueues: the work runs on the plugin's executor, and
* only on the node where the change happened ({@code local}), because every node shares the database. A restore's
* database work happens in {@link DatabaseBackup#importInto}; nothing is done here for it.
*/
public final class DatabaseSiteEvents implements SiteEventListener {
private final DatabaseCore core;
private final Executor executor;
public DatabaseSiteEvents(DatabaseCore core, Executor executor) {
this.core = core;
this.executor = executor;
}
@Override
public void onSiteLifecycle(SiteLifecycleEvent event) {
switch (event.kind()) {
case DELETED -> {
core.schemas().evict(event.siteId());
core.forgetSite(event.siteId());
if (event.local()) {
String siteId = event.siteId();
executor.execute(() -> core.schemas().dropDeleted(siteId));
}
}
case CREATED -> {
if (event.local()) {
String siteId = event.siteId();
executor.execute(() -> core.schemas().retireEarlierSite(siteId));
}
}
default -> {
// RESTORED included: the cached mapping stays, since every borrow re-checks it against the registry
// and a restore that replaces the data changes the registry. Evicting here would make the next
// request on every node resolve again while the restored folder may not name the data yet.
}
}
}
}
@@ -0,0 +1,72 @@
package mx.quest.database.internal;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.BiFunction;
import mx.quest.database.spi.DatabaseConsumer;
import mx.quest.database.spi.Databases;
import mx.quest.database.spi.PluginDatabase;
/**
* Hands each consumer plugin its handle, after proving which plugin the {@link DatabaseConsumer} bean belongs to:
* the jar its class was loaded from must sit in a folder named after the id it claims, and a plugin gets one bean.
*/
public final class DatabasesImpl implements Databases {
private final DatabaseCore core;
private final BiFunction<Class<?>, String, ScriptSource> locator;
private final Map<String, DatabaseConsumer> beans = new ConcurrentHashMap<>();
private final Map<String, PluginDatabaseImpl> handles = new ConcurrentHashMap<>();
/** With the real check: scripts come from the bean's own jar. */
public DatabasesImpl(DatabaseCore core) {
this(core, ConsumerJar::of);
}
/**
* @param locator finds (and proves) a bean's script source from its class and claimed plugin id; throws
* {@link IllegalArgumentException} when the class does not belong to that plugin
*/
public DatabasesImpl(DatabaseCore core, BiFunction<Class<?>, String, ScriptSource> locator) {
this.core = Objects.requireNonNull(core, "core");
this.locator = Objects.requireNonNull(locator, "locator");
}
@Override
public synchronized PluginDatabase of(DatabaseConsumer me) {
Objects.requireNonNull(me, "me");
String pluginId = Objects.requireNonNull(me.pluginId(), "pluginId");
PluginDatabaseImpl handle = handles.get(pluginId);
if (handle != null) {
if (beans.get(pluginId) != me) {
throw new IllegalArgumentException("plugin '" + pluginId + "' already has a DatabaseConsumer bean");
}
return handle;
}
ScriptSource source = locator.apply(me.getClass(), pluginId);
Consumer consumer = Consumer.of(pluginId, me.scopes(), source);
handle = new PluginDatabaseImpl(core, consumer);
beans.put(pluginId, me);
handles.put(pluginId, handle);
return handle;
}
/** The consumers registered so far. */
public List<Consumer> consumers() {
return handles.values().stream().map(PluginDatabaseImpl::consumer).toList();
}
/** Registers every collected consumer bean, logging (not throwing) the ones refused. */
public void registerAll(Collection<DatabaseConsumer> collected, java.util.function.Consumer<String> refused) {
for (DatabaseConsumer bean : collected) {
try {
of(bean);
} catch (RuntimeException e) {
refused.accept(bean.getClass().getName() + ": " + e.getMessage());
}
}
}
}
@@ -0,0 +1,183 @@
package mx.quest.database.internal;
import java.sql.Connection;
import java.sql.SQLException;
import java.time.Duration;
import java.util.List;
import java.util.Set;
import mx.quest.database.spi.Dialect;
/**
* Every statement the database plugin runs, for one product. Providers bring the driver; the SQL lives here, so the
* checks that keep installs, sites and plugins apart are written once per product and reviewed in one place.
*
* <p>Schema and object names reaching these methods have already passed {@link Names}; they are still quoted
* through {@link #quote}, never concatenated raw.
*/
public interface Engine {
/** {@code postgresql} or {@code mariadb}. */
String id();
/** The consumer-facing helpers. */
Dialect dialect();
/** The longest identifier the product accepts, in bytes (all our names are ASCII). */
int identifierMax();
/** The product's default port. */
int defaultPort();
/** A quoted identifier. */
String quote(String name);
/** The SQL for the current instant, stored as UTC. */
String nowSql();
/** Reads an instant written with {@link #nowSql()}; {@code null} for SQL NULL. */
java.time.Instant instant(java.sql.ResultSet rs, int column) throws SQLException;
/** The SQL pinned on every new connection: time zone, strict modes, the session statement timeout. */
String connectionInitSql(Duration statementTimeout, String collation);
/**
* Checks the server and fails closed.
*
* @return the product and version for the health screen
* @throws UnsupportedServerException when the product, version or encoding is not supported
*/
String inspectServer(Connection c) throws SQLException;
// --- binding --------------------------------------------------------------------------------------------
/**
* Binds a borrowed connection to a site's schema and sets the statement timeout, checking in the same step
* that the registry still maps the site to that schema.
*
* @return false when the mapping changed (the caller re-resolves); the connection is then unbound
*/
boolean bindSite(Connection c, String appSchema, String siteId, String schema, Duration timeout)
throws SQLException;
/** Binds a connection to a schema and sets the statement timeout, without a registry check (the app schema,
* or a setup connection about to migrate or restore a schema it already resolved). */
void bind(Connection c, String schema, Duration timeout) throws SQLException;
/** Makes a connection fit for the next borrower: drops temporary objects where the product can. */
void reset(Connection c) throws SQLException;
/** Starts a read-only transaction with a consistent snapshot (autocommit is already off). */
void beginRead(Connection c) throws SQLException;
/** Whether the connection is still bound exactly as {@link #bindSite} or {@link #bindApp} left it, to detect a
* script that moved it. */
boolean stillBound(Connection c, String schema) throws SQLException;
// --- schemas --------------------------------------------------------------------------------------------
/** Creates a schema (a database, in MariaDB) if it does not exist. */
void createSchema(Connection c, String schema, String collation) throws SQLException;
/** Drops a schema and everything in it, if it exists. */
void dropSchema(Connection c, String schema) throws SQLException;
/** The schemas whose names start with {@code <namespace>_}. */
List<String> listSchemas(Connection c, String namespace) throws SQLException;
/** The registry tables in the app schema, created if missing; idempotent. */
List<String> registryDdl(String appSchema);
/** The {@code rw_migrations} table in a schema, created if missing; idempotent. */
String migrationsDdl(String schema);
/** The next value of the install-wide generation sequence. */
long nextGeneration(Connection c, String appSchema) throws SQLException;
// --- locks ------------------------------------------------------------------------------------------------
/**
* Takes a session-level lock on a dedicated connection, waiting at most {@code wait}.
*
* @return false on timeout
*/
boolean lock(Connection c, String key, Duration wait) throws SQLException;
/** Releases a lock taken with {@link #lock}; a failure means the caller must discard the connection. */
void unlock(Connection c, String key) throws SQLException;
/** Takes the migration lock for (schema, plugin) on the migration connection, inside its transaction where the
* product has one. */
boolean migrationLock(Connection c, String key, Duration wait) throws SQLException;
/** Releases the migration lock where it is not released by the transaction's end. */
void migrationUnlock(Connection c, String key) throws SQLException;
/** Whether DDL is transactional, so a whole plugin's scripts run in one transaction. */
boolean transactionalDdl();
/** Sets the timeout for long work (migrations, backup, restore) on a setup connection. */
void setLongTimeout(Connection c, Duration timeout) throws SQLException;
// --- ownership --------------------------------------------------------------------------------------------
/** The objects in a schema whose names must carry a plugin prefix (see the design's ownership table). */
Set<DbObject> ownedObjects(Connection c, String schema) throws SQLException;
/** Base tables in a schema not using the required storage engine; empty where the product has one. */
List<String> tablesWithWrongEngine(Connection c, String schema) throws SQLException;
/** Drops one object found by {@link #ownedObjects}; used to undo what a refused statement created. */
void dropObject(Connection c, String schema, DbObject object) throws SQLException;
// --- backup and restore ------------------------------------------------------------------------------------
/**
* The base tables of a schema with their columns in order, each column's type in the backup's portable form
* ({@link Portable}); a type outside it is reported as {@code UNSUPPORTED:<native type>}.
*/
java.util.Map<String, List<Column>> tables(Connection c, String schema) throws SQLException;
/** The schema's sequences, each with the next value it will issue and its increment. */
List<Sequence> sequences(Connection c, String schema) throws SQLException;
/** Makes a sequence issue {@code next} next. */
void setSequence(Connection c, String schema, String name, long next) throws SQLException;
/**
* Gets user triggers and foreign keys out of the way before rows are loaded into {@code tables} (and into any
* table whose foreign keys point at them), and returns the statements that put them back. The connection is
* bound to {@code schema}.
*/
List<String> suspendForLoad(Connection c, String schema, java.util.Collection<String> tables) throws SQLException;
/** Binds a value read from a backup to an insert parameter, by the target column's portable type. */
void bindValue(java.sql.PreparedStatement ps, int index, String portableType, Object value) throws SQLException;
/** Reads a column for a backup, by its portable type: {@code null}, or the value's text or JSON form. */
Object readValue(java.sql.ResultSet rs, int index, String portableType) throws SQLException;
/** The bytes a schema's tables and indexes take on disk, as the server reports them. */
long schemaSize(Connection c, String schema) throws SQLException;
/** One column of a base table. */
record Column(String name, String type, boolean nullable, boolean hasDefault) {
}
/** One sequence: the next value it issues and its increment. */
record Sequence(String name, long next, long increment) {
}
// --- failure categories (console tests) -------------------------------------------------------------------
/** Sorts a connection failure into a fixed category the console shows. */
ConnectFailure classify(SQLException failure);
/** The fixed failure categories of a connection test. */
enum ConnectFailure {
UNREACHABLE, TLS, AUTHENTICATION, DATABASE_MISSING, UNSUPPORTED_SERVER, OTHER
}
/** One named object in a schema. {@code table} is set for objects scoped to a table (MariaDB foreign keys). */
record DbObject(String kind, String name, String table) {
}
}
@@ -0,0 +1,49 @@
package mx.quest.database.internal;
import java.net.ConnectException;
import java.net.NoRouteToHostException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.util.regex.Pattern;
import javax.net.ssl.SSLException;
/** Small shared checks: failure causes and simple SQL names. */
final class Failures {
private static final Pattern SIMPLE_NAME = Pattern.compile("[a-z_][a-z0-9_]{0,62}");
private Failures() {
}
/** Whether a TLS failure is anywhere in the cause chain. */
static boolean hasTlsCause(Throwable failure) {
for (Throwable t = failure; t != null; t = t.getCause()) {
if (t instanceof SSLException) {
return true;
}
}
return false;
}
/** Whether a network failure (refused, unknown host, timeout, no route) is anywhere in the cause chain. */
static boolean hasNetworkCause(Throwable failure) {
for (Throwable t = failure; t != null; t = t.getCause()) {
if (t instanceof ConnectException || t instanceof UnknownHostException
|| t instanceof SocketTimeoutException || t instanceof NoRouteToHostException) {
return true;
}
}
return false;
}
/**
* A lower-case, unquoted SQL name (the convention for consumer objects), checked before it goes into a
* statement's text.
*/
static String requireSimpleName(String name) {
if (name == null || !SIMPLE_NAME.matcher(name).matches()) {
throw new IllegalArgumentException("not a lower-case SQL name: " + name);
}
return name;
}
}
@@ -0,0 +1,19 @@
package mx.quest.database.internal;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
/** Plain JDBC helpers. */
final class Jdbc {
private Jdbc() {
}
/** Runs one statement that returns no rows the caller needs. */
static void execute(Connection c, String sql) throws SQLException {
try (Statement s = c.createStatement()) {
s.execute(sql);
}
}
}
@@ -0,0 +1,95 @@
package mx.quest.database.internal;
import java.sql.Connection;
import java.sql.SQLException;
import java.time.Duration;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;
/**
* The per-site lock (allocation, restore and removal take it) and the install-wide named locks. Each is an in-JVM
* lock first, then a database lock on a dedicated unpooled connection, so a waiter holds no pooled connection and
* the lock covers every node. A waiter gives up after a bounded time.
*/
final class Locks {
/** Work run while holding a lock. */
@FunctionalInterface
interface Locked<T> {
T run() throws SQLException;
}
/** The lock was not obtained in time. */
static final class LockTimeoutException extends RuntimeException {
private static final long serialVersionUID = 1L;
LockTimeoutException(String what) {
super("timed out waiting for " + what);
}
}
private static final int STRIPES = 64;
private final DatabaseRuntime runtime;
private final ReentrantLock[] stripes = new ReentrantLock[STRIPES];
Locks(DatabaseRuntime runtime) {
this.runtime = runtime;
for (int i = 0; i < STRIPES; i++) {
stripes[i] = new ReentrantLock(true);
}
}
/** Runs {@code work} holding the site's lock. */
<T> T site(String siteId, Duration wait, Locked<T> work) throws SQLException {
return hold("site:" + siteId, wait, work);
}
/** Runs {@code work} holding an install-wide lock ({@code registry}, {@code plugins}). */
<T> T global(String name, Duration wait, Locked<T> work) throws SQLException {
return hold("global:" + name, wait, work);
}
private <T> T hold(String name, Duration wait, Locked<T> work) throws SQLException {
long deadline = System.nanoTime() + wait.toNanos();
ReentrantLock local = stripes[Math.floorMod(name.hashCode(), STRIPES)];
try {
if (!local.tryLock(wait.toNanos(), TimeUnit.NANOSECONDS)) {
throw new LockTimeoutException(name);
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new LockTimeoutException(name);
}
try {
String key = runtime.config().namespace() + ":" + name;
Connection c = runtime.openLockConnection(remaining(deadline));
if (c == null) {
throw new LockTimeoutException(name);
}
try {
if (!runtime.engine().lock(c, key, remaining(deadline))) {
throw new LockTimeoutException(name);
}
try {
return work.run();
} finally {
try {
runtime.engine().unlock(c, key);
} catch (SQLException ignored) {
// closing the connection below releases it
}
}
} finally {
runtime.closeLockConnection(c);
}
} finally {
local.unlock();
}
}
private static Duration remaining(long deadline) {
return Duration.ofNanos(Math.max(TimeUnit.MILLISECONDS.toNanos(1), deadline - System.nanoTime()));
}
}
@@ -0,0 +1,591 @@
package mx.quest.database.internal;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.time.Duration;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import mx.quest.database.spi.Dialect;
/**
* MariaDB 10.11 or later (never MySQL): a database per schema, DDL that commits on its own, {@code GET_LOCK}. Runway's
* own identifier columns are {@code ascii_bin}, so a site id never matches another by case.
*/
public final class MariaDbEngine implements Engine {
static final int MIN_MAJOR = 10;
static final int MIN_MINOR = 11;
static final String SQL_MODE = "STRICT_ALL_TABLES,NO_ZERO_DATE,NO_ZERO_IN_DATE,ERROR_FOR_DIVISION_BY_ZERO,"
+ "NO_ENGINE_SUBSTITUTION";
private static final Pattern VERSION = Pattern.compile("^(\\d+)\\.(\\d+)\\.(\\d+)");
private static final String ID = "VARCHAR(255) CHARACTER SET ascii COLLATE ascii_bin";
private static final String SCHEMA_NAME = "VARCHAR(64) CHARACTER SET ascii COLLATE ascii_bin";
private final Dialect dialect = new MariaDbDialect();
/** The collation used when none is configured: on every supported server (10.10 brought it). */
private static final String DEFAULT_COLLATION = "utf8mb4_uca1400_ai_ci";
@Override
public String id() {
return "mariadb";
}
@Override
public Dialect dialect() {
return dialect;
}
@Override
public int identifierMax() {
return 64;
}
@Override
public int defaultPort() {
return 3306;
}
@Override
public String quote(String name) {
return quoteIdent(name);
}
@Override
public String nowSql() {
return "UTC_TIMESTAMP(6)";
}
@Override
public java.time.Instant instant(ResultSet rs, int column) throws SQLException {
java.time.LocalDateTime t = rs.getObject(column, java.time.LocalDateTime.class);
return t == null ? null : t.toInstant(java.time.ZoneOffset.UTC); // the session time zone is pinned to UTC
}
static String quoteIdent(String name) {
return "`" + name.replace("`", "``") + "`";
}
private static String seconds(Duration d) {
return Long.toString(Math.max(1, d.toSeconds()));
}
@Override
public String connectionInitSql(Duration statementTimeout, String collation) {
// explicit_defaults_for_timestamp: on by default since MariaDB 10.10, but a server can still be configured
// off, and then the first TIMESTAMP NOT NULL column of a table a plugin creates silently gains DEFAULT
// CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, so a created_at column would change on every UPDATE. Set
// here, a script means the same on every supported server (a session can set it from 10.10, hence 10.11).
return "SET time_zone = '+00:00', sql_mode = '" + SQL_MODE + "', default_storage_engine = InnoDB, "
+ "explicit_defaults_for_timestamp = 1, "
+ "max_statement_time = " + seconds(statementTimeout) + ", innodb_lock_wait_timeout = "
+ seconds(statementTimeout);
}
@Override
public String inspectServer(Connection c) throws SQLException {
String product = c.getMetaData().getDatabaseProductName();
try (Statement s = c.createStatement();
ResultSet rs = s.executeQuery("SELECT VERSION(), @@version_comment")) {
rs.next();
return checkServer(product, rs.getString(1), rs.getString(2));
}
}
/**
* MariaDB 10.11 or later, and not MySQL. 10.11 is the floor because before 10.10 a session cannot set
* {@code explicit_defaults_for_timestamp}, which {@link #connectionInitSql} sets on every connection: on an older
* server every connection would fail with a message about a read-only variable, not about the version.
*/
static String checkServer(String product, String version, String comment) throws UnsupportedServerException {
String note = comment == null ? "" : comment;
if (!"MariaDB".equalsIgnoreCase(product) || version == null || !version.contains("MariaDB")
|| note.toLowerCase(Locale.ROOT).contains("mysql")) {
throw new UnsupportedServerException("the server is not MariaDB (" + version + ", " + note
+ "): MySQL is not supported");
}
Matcher m = VERSION.matcher(version);
if (!m.find()) {
throw new UnsupportedServerException("cannot read the MariaDB version: " + version);
}
int major = Integer.parseInt(m.group(1));
int minor = Integer.parseInt(m.group(2));
if (major < MIN_MAJOR || (major == MIN_MAJOR && minor < MIN_MINOR)) {
throw new UnsupportedServerException("MariaDB " + version + " is too old: 10.11 or later is needed");
}
return "MariaDB " + m.group();
}
// --- binding --------------------------------------------------------------------------------------------
@Override
public boolean bindSite(Connection c, String appSchema, String siteId, String schema, Duration timeout)
throws SQLException {
try (PreparedStatement ps = c.prepareStatement("SELECT 1 FROM " + quoteIdent(appSchema)
+ ".rw_sites WHERE site_id = ? AND schema_name = ? AND state = 'live'")) {
ps.setString(1, siteId);
ps.setString(2, schema);
try (ResultSet rs = ps.executeQuery()) {
if (!rs.next()) {
return false;
}
}
}
use(c, schema, timeout);
return true;
}
@Override
public void bind(Connection c, String schema, Duration timeout) throws SQLException {
use(c, schema, timeout);
}
/** An explicit USE, never setCatalog: the driver skips that when it believes it is already there. */
private static void use(Connection c, String schema, Duration timeout) throws SQLException {
try (Statement s = c.createStatement()) {
s.execute("USE " + quoteIdent(schema));
s.execute("SET max_statement_time = " + seconds(timeout) + ", innodb_lock_wait_timeout = "
+ seconds(timeout));
}
}
@Override
public void reset(Connection c) {
// MariaDB has no DISCARD: a consumer drops its temporary tables in finally (the authoring guide says so).
}
@Override
public void beginRead(Connection c) throws SQLException {
// setReadOnly does nothing on a single-host URL, so start the read-only snapshot explicitly.
execute(c, "START TRANSACTION WITH CONSISTENT SNAPSHOT, READ ONLY");
}
@Override
public boolean stillBound(Connection c, String schema) throws SQLException {
try (Statement s = c.createStatement(); ResultSet rs = s.executeQuery("SELECT DATABASE()")) {
rs.next();
return schema.equals(rs.getString(1));
}
}
// --- schemas --------------------------------------------------------------------------------------------
/** The collation for consumer tables: the configured one, else the server's best. */
String collationOr(String configured) {
return configured == null ? DEFAULT_COLLATION : configured;
}
@Override
public void createSchema(Connection c, String schema, String collation) throws SQLException {
execute(c, "CREATE DATABASE IF NOT EXISTS " + quoteIdent(schema) + " CHARACTER SET utf8mb4 COLLATE "
+ Failures.requireSimpleName(collationOr(collation)));
}
@Override
public void dropSchema(Connection c, String schema) throws SQLException {
execute(c, "DROP DATABASE IF EXISTS " + quoteIdent(schema));
}
@Override
public List<String> listSchemas(Connection c, String namespace) throws SQLException {
List<String> names = new ArrayList<>();
try (PreparedStatement ps = c.prepareStatement("SELECT SCHEMA_NAME FROM information_schema.SCHEMATA "
+ "WHERE SCHEMA_NAME LIKE ? ORDER BY SCHEMA_NAME")) {
ps.setString(1, namespace + "\\_%");
try (ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
names.add(rs.getString(1));
}
}
}
return names;
}
@Override
public List<String> registryDdl(String appSchema) {
String a = quoteIdent(appSchema);
String table = " ENGINE=InnoDB";
return List.of(
"CREATE TABLE IF NOT EXISTS " + a + ".rw_install (`key` VARCHAR(64) CHARACTER SET ascii COLLATE "
+ "ascii_bin PRIMARY KEY, value VARCHAR(255) NOT NULL)" + table,
"CREATE SEQUENCE IF NOT EXISTS " + a + ".rw_generation",
"CREATE TABLE IF NOT EXISTS " + a + ".rw_sites (site_id " + ID + " PRIMARY KEY, schema_name "
+ SCHEMA_NAME + " NOT NULL UNIQUE, token CHAR(32) CHARACTER SET ascii COLLATE ascii_bin "
+ "NOT NULL, generation BIGINT NOT NULL, state VARCHAR(16) CHARACTER SET ascii COLLATE "
+ "ascii_bin NOT NULL, created_at DATETIME(6) NOT NULL)" + table,
"CREATE TABLE IF NOT EXISTS " + a + ".rw_schemas (schema_name " + SCHEMA_NAME + " PRIMARY KEY, "
+ "site_id " + ID + " NOT NULL, generation BIGINT NOT NULL, state VARCHAR(16) CHARACTER SET "
+ "ascii COLLATE ascii_bin NOT NULL, changed_at DATETIME(6) NOT NULL)" + table,
"CREATE TABLE IF NOT EXISTS " + a + ".rw_plugins (plugin_id " + ID + " PRIMARY KEY, prefix "
+ "VARCHAR(24) CHARACTER SET ascii COLLATE ascii_bin NOT NULL UNIQUE, "
+ "first_seen DATETIME(6) NOT NULL)" + table,
"CREATE TABLE IF NOT EXISTS " + a + ".rw_nodes (node_id VARCHAR(64) CHARACTER SET ascii COLLATE "
+ "ascii_bin PRIMARY KEY, host VARCHAR(255) NOT NULL, version VARCHAR(32) NOT NULL, "
+ "started_at DATETIME(6) NOT NULL, seen_at DATETIME(6) NOT NULL)" + table,
"CREATE TABLE IF NOT EXISTS " + a + ".rw_issues (schema_name " + SCHEMA_NAME + " NOT NULL, "
+ "plugin_id " + ID + " NOT NULL, state VARCHAR(16) NOT NULL, version INT NOT NULL, "
+ "statement INT NOT NULL, detail VARCHAR(1000) NOT NULL, at DATETIME(6) NOT NULL, "
+ "PRIMARY KEY (schema_name, plugin_id))" + table);
}
@Override
public String migrationsDdl(String schema) {
return "CREATE TABLE IF NOT EXISTS " + quoteIdent(schema) + ".rw_migrations (plugin_id " + ID + " NOT NULL, "
+ "version INT NOT NULL, name VARCHAR(128) CHARACTER SET ascii COLLATE ascii_bin NOT NULL, "
+ "checksum CHAR(64) CHARACTER SET ascii COLLATE ascii_bin NOT NULL, state VARCHAR(16) CHARACTER "
+ "SET ascii COLLATE ascii_bin NOT NULL, last_ok_statement INT NOT NULL, applied_at DATETIME(6), "
+ "PRIMARY KEY (plugin_id, version)) ENGINE=InnoDB";
}
@Override
public long nextGeneration(Connection c, String appSchema) throws SQLException {
try (Statement s = c.createStatement();
ResultSet rs = s.executeQuery("SELECT NEXTVAL(" + quoteIdent(appSchema) + ".rw_generation)")) {
rs.next();
return rs.getLong(1);
}
}
// --- locks ------------------------------------------------------------------------------------------------
/** GET_LOCK names are at most 64 characters: the namespace part stays readable, the rest is hashed. */
static String lockName(String key) {
int colon = key.indexOf(':');
String head = colon < 0 ? "" : key.substring(0, Math.min(colon, 12)) + ":";
return head + Names.sha256Hex(key).substring(0, 40);
}
@Override
public boolean lock(Connection c, String key, Duration wait) throws SQLException {
try (PreparedStatement ps = c.prepareStatement("SELECT GET_LOCK(?, ?)")) {
ps.setString(1, lockName(key));
ps.setDouble(2, Math.max(0.001, wait.toMillis() / 1000.0));
try (ResultSet rs = ps.executeQuery()) {
rs.next();
int got = rs.getInt(1);
if (rs.wasNull()) {
throw new SQLException("GET_LOCK failed for " + key);
}
return got == 1;
}
}
}
@Override
public void unlock(Connection c, String key) throws SQLException {
try (PreparedStatement ps = c.prepareStatement("SELECT RELEASE_LOCK(?)")) {
ps.setString(1, lockName(key));
try (ResultSet rs = ps.executeQuery()) {
if (!rs.next() || rs.getInt(1) != 1) {
throw new SQLException("lock was not held: " + key);
}
}
}
}
@Override
public boolean migrationLock(Connection c, String key, Duration wait) throws SQLException {
return lock(c, key, wait);
}
@Override
public void migrationUnlock(Connection c, String key) throws SQLException {
unlock(c, key);
}
@Override
public boolean transactionalDdl() {
return false;
}
@Override
public void setLongTimeout(Connection c, Duration timeout) throws SQLException {
execute(c, "SET max_statement_time = " + seconds(timeout) + ", innodb_lock_wait_timeout = "
+ seconds(timeout));
}
// --- ownership --------------------------------------------------------------------------------------------
@Override
public Set<DbObject> ownedObjects(Connection c, String schema) throws SQLException {
Set<DbObject> objects = new LinkedHashSet<>();
// Tables, views and sequences share one name space; the type decides how to drop one.
try (PreparedStatement ps = c.prepareStatement(
"SELECT TABLE_NAME, TABLE_TYPE FROM information_schema.TABLES WHERE TABLE_SCHEMA = ?")) {
ps.setString(1, schema);
try (ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
String type = rs.getString(2);
String kind = "VIEW".equals(type) ? "view" : "SEQUENCE".equals(type) ? "sequence" : "table";
objects.add(new DbObject(kind, rs.getString(1), null));
}
}
}
collect(c, objects, "SELECT 'trigger', TRIGGER_NAME, NULL FROM information_schema.TRIGGERS "
+ "WHERE TRIGGER_SCHEMA = ?", schema);
collect(c, objects, "SELECT LOWER(ROUTINE_TYPE), ROUTINE_NAME, NULL FROM information_schema.ROUTINES "
+ "WHERE ROUTINE_SCHEMA = ?", schema);
collect(c, objects, "SELECT 'event', EVENT_NAME, NULL FROM information_schema.EVENTS "
+ "WHERE EVENT_SCHEMA = ?", schema);
collect(c, objects, "SELECT 'fk', CONSTRAINT_NAME, TABLE_NAME FROM information_schema.REFERENTIAL_CONSTRAINTS "
+ "WHERE CONSTRAINT_SCHEMA = ?", schema);
return objects;
}
private static void collect(Connection c, Set<DbObject> into, String sql, String schema) throws SQLException {
try (PreparedStatement ps = c.prepareStatement(sql)) {
ps.setString(1, schema);
try (ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
into.add(new DbObject(rs.getString(1), rs.getString(2), rs.getString(3)));
}
}
}
}
@Override
public List<String> tablesWithWrongEngine(Connection c, String schema) throws SQLException {
List<String> tables = new ArrayList<>();
try (PreparedStatement ps = c.prepareStatement("SELECT TABLE_NAME FROM information_schema.TABLES "
+ "WHERE TABLE_SCHEMA = ? AND TABLE_TYPE = 'BASE TABLE' AND (ENGINE IS NULL OR ENGINE <> 'InnoDB')")) {
ps.setString(1, schema);
try (ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
tables.add(rs.getString(1));
}
}
}
return tables;
}
@Override
public void dropObject(Connection c, String schema, DbObject object) throws SQLException {
String s = quoteIdent(schema) + ".";
String n = quoteIdent(object.name());
String sql = switch (object.kind()) {
case "table" -> "DROP TABLE IF EXISTS " + s + n;
case "view" -> "DROP VIEW IF EXISTS " + s + n;
case "sequence" -> "DROP SEQUENCE IF EXISTS " + s + n;
case "trigger" -> "DROP TRIGGER IF EXISTS " + s + n;
case "procedure" -> "DROP PROCEDURE IF EXISTS " + s + n;
case "function" -> "DROP FUNCTION IF EXISTS " + s + n;
case "event" -> "DROP EVENT IF EXISTS " + s + n;
case "fk" -> "ALTER TABLE " + s + quoteIdent(object.table()) + " DROP FOREIGN KEY " + n;
default -> throw new SQLException("cannot drop an object of kind " + object.kind());
};
execute(c, sql);
}
// --- backup and restore ------------------------------------------------------------------------------------
@Override
public java.util.Map<String, List<Column>> tables(Connection c, String schema) throws SQLException {
java.util.Map<String, List<Column>> tables = new java.util.LinkedHashMap<>();
try (PreparedStatement ps = c.prepareStatement("SELECT c.TABLE_NAME, c.COLUMN_NAME, c.DATA_TYPE, "
+ "c.COLUMN_TYPE, c.CHARACTER_MAXIMUM_LENGTH, c.NUMERIC_PRECISION, c.NUMERIC_SCALE, c.IS_NULLABLE, "
+ "c.COLUMN_DEFAULT, c.EXTRA FROM information_schema.COLUMNS c JOIN information_schema.TABLES t "
+ "ON t.TABLE_SCHEMA = c.TABLE_SCHEMA AND t.TABLE_NAME = c.TABLE_NAME "
+ "WHERE c.TABLE_SCHEMA = ? AND t.TABLE_TYPE = 'BASE TABLE' "
+ "ORDER BY c.TABLE_NAME, c.ORDINAL_POSITION")) {
ps.setString(1, schema);
try (ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
String extra = rs.getString(10) == null ? "" : rs.getString(10).toLowerCase(Locale.ROOT);
if (extra.contains("generated")) {
continue; // a generated column is derived: never backed up, never loaded
}
Long length = toLong(rs.getObject(5));
Long precision = toLong(rs.getObject(6));
Long scale = toLong(rs.getObject(7));
String type = portableType(rs.getString(3), rs.getString(4), length, precision, scale);
String def = rs.getString(9);
boolean hasDefault = (def != null && !def.equalsIgnoreCase("NULL"))
|| extra.contains("auto_increment");
tables.computeIfAbsent(rs.getString(1), k -> new ArrayList<>()).add(new Column(rs.getString(2),
type, "YES".equals(rs.getString(8)), hasDefault));
}
}
}
return tables;
}
private static Long toLong(Object value) {
return value instanceof Number n ? n.longValue() : null;
}
static String portableType(String dataType, String columnType, Long length, Long precision, Long scale) {
String type = dataType.toLowerCase(Locale.ROOT);
String column = columnType == null ? "" : columnType.toLowerCase(Locale.ROOT);
return switch (type) {
case "bigint" -> "BIGINT";
case "int", "mediumint" -> "INTEGER";
case "smallint" -> "SMALLINT";
case "tinyint" -> column.startsWith("tinyint(1)") ? "BOOLEAN" : "SMALLINT";
case "decimal" -> "DECIMAL(" + precision + "," + (scale == null ? 0 : scale) + ")";
case "double", "float" -> "DOUBLE";
case "varchar", "char" -> "VARCHAR(" + length + ")";
case "text", "tinytext", "mediumtext", "longtext" -> "TEXT";
case "date" -> "DATE";
case "time" -> "TIME";
case "datetime" -> "TIMESTAMP";
case "timestamp" -> "TIMESTAMPTZ";
case "blob", "tinyblob", "mediumblob", "longblob", "varbinary", "binary" -> "BYTES";
default -> Portable.UNSUPPORTED + type;
};
}
@Override
public List<Sequence> sequences(Connection c, String schema) throws SQLException {
List<String> names = new ArrayList<>();
try (PreparedStatement ps = c.prepareStatement("SELECT TABLE_NAME FROM information_schema.TABLES "
+ "WHERE TABLE_SCHEMA = ? AND TABLE_TYPE = 'SEQUENCE' ORDER BY TABLE_NAME")) {
ps.setString(1, schema);
try (ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
names.add(rs.getString(1));
}
}
}
List<Sequence> out = new ArrayList<>();
for (String name : names) {
try (Statement s = c.createStatement();
ResultSet rs = s.executeQuery("SELECT next_not_cached_value, increment FROM " + quoteIdent(schema)
+ "." + quoteIdent(name))) {
rs.next();
out.add(new Sequence(name, rs.getLong(1), rs.getLong(2)));
}
}
return out;
}
@Override
public void setSequence(Connection c, String schema, String name, long next) throws SQLException {
execute(c, "ALTER SEQUENCE " + quoteIdent(schema) + "." + quoteIdent(name) + " RESTART WITH " + next);
}
@Override
public List<String> suspendForLoad(Connection c, String schema, java.util.Collection<String> tables)
throws SQLException {
List<String> restore = new ArrayList<>();
restore.add("SET FOREIGN_KEY_CHECKS = 1");
if (!tables.isEmpty()) {
String marks = String.join(", ", java.util.Collections.nCopies(tables.size(), "?"));
List<String> triggers = new ArrayList<>();
try (PreparedStatement ps = c.prepareStatement("SELECT TRIGGER_NAME FROM information_schema.TRIGGERS "
+ "WHERE TRIGGER_SCHEMA = ? AND EVENT_OBJECT_TABLE IN (" + marks + ") ORDER BY TRIGGER_NAME")) {
ps.setString(1, schema);
int i = 2;
for (String t : tables) {
ps.setString(i++, t);
}
try (ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
triggers.add(rs.getString(1));
}
}
}
for (String trigger : triggers) {
String qualified = quoteIdent(schema) + "." + quoteIdent(trigger);
try (Statement s = c.createStatement();
ResultSet rs = s.executeQuery("SHOW CREATE TRIGGER " + qualified)) {
rs.next();
restore.add(rs.getString("SQL Original Statement"));
}
execute(c, "DROP TRIGGER " + qualified);
}
}
execute(c, "SET FOREIGN_KEY_CHECKS = 0");
return restore;
}
@Override
public void bindValue(PreparedStatement ps, int index, String portableType, Object value) throws SQLException {
Portable.bind(ps, index, portableType, value, false);
}
@Override
public Object readValue(ResultSet rs, int index, String portableType) throws SQLException {
return Portable.read(rs, index, portableType, false);
}
@Override
public long schemaSize(Connection c, String schema) throws SQLException {
try (PreparedStatement ps = c.prepareStatement(
"SELECT COALESCE(SUM(DATA_LENGTH + INDEX_LENGTH), 0) FROM information_schema.TABLES "
+ "WHERE TABLE_SCHEMA = ?")) {
ps.setString(1, schema);
try (ResultSet rs = ps.executeQuery()) {
rs.next();
return rs.getLong(1);
}
}
}
// --- failure categories -----------------------------------------------------------------------------------
@Override
public ConnectFailure classify(SQLException failure) {
if (failure instanceof UnsupportedServerException) {
return ConnectFailure.UNSUPPORTED_SERVER;
}
if (Failures.hasTlsCause(failure)) {
return ConnectFailure.TLS;
}
int code = failure.getErrorCode();
String state = failure.getSQLState() == null ? "" : failure.getSQLState();
if (code == 1045 || state.equals("28000")) {
return ConnectFailure.AUTHENTICATION;
}
// 1049 unknown database; 1044 no access to it, which is also what a missing one looks like to an account
// without global rights.
if (code == 1049 || code == 1044) {
return ConnectFailure.DATABASE_MISSING;
}
if (state.startsWith("08") || Failures.hasNetworkCause(failure)) {
return ConnectFailure.UNREACHABLE;
}
return ConnectFailure.OTHER;
}
static void execute(Connection c, String sql) throws SQLException {
try (Statement s = c.createStatement()) {
s.execute(sql);
}
}
/** {@code NEXTVAL}/{@code LASTVAL} on a sequence in the bound database. */
static final class MariaDbDialect implements Dialect {
@Override
public String id() {
return "mariadb";
}
@Override
public String nextValue(String sequence) {
return "NEXTVAL(" + Failures.requireSimpleName(sequence) + ")";
}
@Override
public long lastValue(Connection connection, String sequence) throws SQLException {
try (Statement s = connection.createStatement();
ResultSet rs = s.executeQuery("SELECT LASTVAL(" + Failures.requireSimpleName(sequence) + ")")) {
rs.next();
return rs.getLong(1);
}
}
@Override
public String quote(String name) {
return quoteIdent(name);
}
}
}
@@ -0,0 +1,843 @@
package mx.quest.database.internal;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.Duration;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import mx.quest.database.spi.DatabaseException;
import mx.quest.database.spi.DatabaseUnavailableException;
import mx.quest.database.spi.Scope;
import mx.quest.database.spi.ScopeNotReadyException;
import mx.quest.database.spi.ScopeNotReadyException.Reason;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Brings one consumer plugin's tables in one schema to the version the installed plugin ships.
*
* <p><b>The lazy check is the authority.</b> The first call per (schema, plugin) in a JVM runs it, single-flight, on
* the setup pool; later calls skip it. The startup sweep only warms it up.
*
* <ul>
* <li><b>PostgreSQL</b> runs all of a plugin's pending scripts in one transaction under a transaction-level
* advisory lock: a failure, or an object outside the plugin's prefix, rolls everything back.</li>
* <li><b>MariaDB</b> commits each DDL statement on its own, so it runs statement by statement under
* {@code GET_LOCK}: the script's row is written {@code failed} first and {@code last_ok_statement} moves after
* each statement; the ownership check runs after each statement, and an object a statement created outside
* the prefix is dropped at once. Nothing reruns a failed script from statement 1.</li>
* </ul>
*
* A failure, a changed checksum or a schema newer than the shipped scripts stops <b>that plugin in that schema</b>
* with a {@link ScopeNotReadyException}, recorded in {@code rw_issues} for the health screen, where an operator can
* retry, mark the script applied, or accept the shipped checksum.
*/
public final class Migrator {
private static final Logger log = LoggerFactory.getLogger(Migrator.class);
static final String APPLIED = "applied";
static final String FAILED = "failed";
static final String RETRY = "retry";
/** Issue states shown on the health screen. */
public static final String ISSUE_FAILED = "FAILED";
public static final String ISSUE_CHECKSUM = "CHECKSUM";
public static final String ISSUE_NEWER = "NEWER";
/** Data a restore kept for the plugin cannot be loaded; the plugin is refused on that site until it can. */
public static final String ISSUE_PARKED = "PARKED";
static final Duration WAIT = Duration.ofSeconds(10);
static final Duration LOCK_WAIT = Duration.ofSeconds(60);
static final Duration FAILURE_MEMORY = Duration.ofSeconds(30);
/** A script the installed plugin ships. */
public record Shipped(int version, String name, String checksum, List<String> statements) {
}
/** A row of {@code rw_migrations}. */
record Applied(int version, String name, String checksum, String state, int lastOk) {
}
private record Failure(Reason reason, String message, long untilNanos) {
}
private final DatabaseRuntime runtime;
private final Map<String, List<Shipped>> shipped = new ConcurrentHashMap<>();
private final Set<String> verified = ConcurrentHashMap.newKeySet();
private final Set<String> prefixesChecked = ConcurrentHashMap.newKeySet();
private final Map<String, CompletableFuture<Void>> inflight = new ConcurrentHashMap<>();
private final Map<String, Failure> failures = new ConcurrentHashMap<>();
private volatile Parked parked;
/** Loads rows into a schema whose plugin tables were just migrated to the data's version. */
@FunctionalInterface
public interface Loader {
void load(String schema) throws SQLException, IOException;
}
/**
* Data a restore parked in a site's folder because its plugin was not installed then. When that plugin first
* migrates in the site's schema, the data is loaded exactly as a restore would: migrate to its version, load,
* migrate forward.
*/
public interface Parked {
/**
* The version of the plugin's parked data for a site, or empty when there is none.
*
* @throws IOException when there is parked data that cannot be read (never answered as "none")
*/
Optional<Integer> version(String siteId, Consumer consumer) throws IOException;
/**
* Loads the parked data into a schema, then removes its manifest (the mark that it waits) and the rest of it
* from the site folder.
*/
void load(String siteId, Consumer consumer, String schema) throws SQLException, IOException;
}
public Migrator(DatabaseRuntime runtime) {
this.runtime = runtime;
}
/** Sets where parked data comes from. */
public void parked(Parked source) {
this.parked = source;
}
private static String key(String schema, String pluginId) {
return schema + "|" + pluginId;
}
/**
* Makes sure the plugin's tables in the schema are at the shipped version, migrating if needed. Waits a bounded
* time; a migration that takes longer carries on in the background.
*
* @throws ScopeNotReadyException when the plugin cannot use this schema yet, or until an operator acts
* @throws DatabaseUnavailableException when the database cannot be reached
*/
public void ensure(Consumer consumer, Scope.Kind kind, String siteId, String schema) {
String key = key(schema, consumer.pluginId());
if (verified.contains(key)) {
return;
}
Failure remembered = failures.get(key);
if (remembered != null && System.nanoTime() < remembered.untilNanos()) {
throw new ScopeNotReadyException(remembered.reason(), remembered.message());
}
CompletableFuture<Void> future = inflight.computeIfAbsent(key, k -> CompletableFuture.runAsync(
() -> run(consumer, kind, siteId, schema, k), runtime.executor()));
try {
future.get(WAIT.toMillis(), TimeUnit.MILLISECONDS);
} catch (TimeoutException e) {
throw new ScopeNotReadyException(Reason.PREPARING, "the plugin's tables are being prepared; try again "
+ "shortly");
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new ScopeNotReadyException(Reason.PREPARING, "interrupted while the tables were being prepared");
} catch (ExecutionException e) {
Throwable cause = e.getCause() instanceof CompletionException ce && ce.getCause() != null
? ce.getCause() : e.getCause();
if (cause instanceof DatabaseException de) {
throw de;
}
throw new DatabaseException("the plugin's tables could not be prepared", cause);
}
}
/**
* The startup warm-up for one (schema, plugin): the same single-flight check, waited for without a time limit
* and with every failure kept to the log, since the first call's check stays the authority.
*/
public void warm(Consumer consumer, Scope.Kind kind, String siteId, String schema) {
String key = key(schema, consumer.pluginId());
if (verified.contains(key)) {
return;
}
try {
inflight.computeIfAbsent(key, k -> CompletableFuture.runAsync(
() -> run(consumer, kind, siteId, schema, k), runtime.executor())).get();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} catch (ExecutionException e) {
log.debug("database: warm-up of plugin '{}' in schema '{}' did not finish: {}", consumer.pluginId(),
schema, e.getCause() == null ? e.toString() : e.getCause().getMessage());
}
}
/** Runs the check on the executor; never on a request thread. */
void run(Consumer consumer, Scope.Kind kind, String siteId, String schema, String key) {
try {
migrate(consumer, kind, siteId, schema);
verified.add(key);
failures.remove(key);
} catch (ScopeNotReadyException e) {
if (e.reason() != Reason.PREPARING) {
failures.put(key, new Failure(e.reason(), e.getMessage(),
System.nanoTime() + FAILURE_MEMORY.toNanos()));
}
throw e;
} catch (SQLException e) {
if (DatabaseRuntime.isConnectionFailure(e)) {
runtime.markOutage(e);
}
throw new DatabaseUnavailableException("the database failed while preparing the plugin's tables: "
+ DatabaseRuntime.describe(e), e);
} finally {
inflight.remove(key);
}
}
/** Forgets what is known about a schema (dropped, replaced, or after an operator action). */
public void forget(String schema) {
verified.removeIf(k -> k.startsWith(schema + "|"));
failures.keySet().removeIf(k -> k.startsWith(schema + "|"));
}
// --- the shipped scripts -------------------------------------------------------------------------------------
/** The scripts a plugin ships for the configured product and a scope, read once from its jar. */
public List<Shipped> shipped(Consumer consumer, Scope.Kind kind) {
String folder = "db/" + consumer.pluginId() + "/" + runtime.engine().id() + "/"
+ kind.name().toLowerCase(Locale.ROOT) + "/";
return shipped.computeIfAbsent(consumer.pluginId() + "|" + folder, k -> load(consumer.scripts(), folder));
}
static List<Shipped> load(ScriptSource source, String folder) {
try {
Optional<byte[]> index = source.read(folder + "index");
if (index.isEmpty()) {
return List.of();
}
List<Shipped> scripts = new ArrayList<>();
for (Scripts.Entry entry : Scripts.parseIndex(Scripts.normalize(index.get()))) {
byte[] bytes = source.read(folder + entry.fileName()).orElseThrow(() -> new IllegalArgumentException(
"the index lists " + entry.fileName() + " but the jar does not hold it"));
String text = Scripts.normalize(bytes);
scripts.add(new Shipped(entry.version(), entry.fileName(), Scripts.checksum(text),
Scripts.split(text)));
}
return List.copyOf(scripts);
} catch (IOException | IllegalArgumentException e) {
throw new ScopeNotReadyException(Reason.PLUGIN_REFUSED, "plugin '" + source.pluginId()
+ "' ships unusable migration scripts in " + folder + ": " + e.getMessage());
}
}
// --- the prefix ----------------------------------------------------------------------------------------------
/** Records the plugin's prefix the first time, refusing one that clashes with another plugin's. */
void checkPrefix(Consumer consumer) throws SQLException {
if (prefixesChecked.contains(consumer.pluginId())) {
return;
}
String prefix = consumer.prefix();
if (Names.isReservedPrefix(prefix)) {
throw refused(consumer, "its prefix '" + prefix + "' starts with the reserved 'rw_'");
}
String problem = runtime.locks().global("plugins", Registry.GLOBAL_LOCK_WAIT, () -> {
try (Connection c = runtime.setupConnection()) {
c.setAutoCommit(true);
Map<String, String> recorded = runtime.registry().prefixes(c);
String own = recorded.get(consumer.pluginId());
if (own != null) {
return own.equals(prefix) ? null : "the registry records the prefix '" + own + "', not '"
+ prefix + "'";
}
for (Map.Entry<String, String> other : recorded.entrySet()) {
if (Names.prefixesClash(prefix, other.getValue())) {
return "its prefix '" + prefix + "' clashes with '" + other.getValue() + "' of plugin '"
+ other.getKey() + "'";
}
}
runtime.registry().insertPrefix(c, consumer.pluginId(), prefix);
return null;
}
});
if (problem != null) {
throw refused(consumer, problem);
}
prefixesChecked.add(consumer.pluginId());
}
private static ScopeNotReadyException refused(Consumer consumer, String why) {
return new ScopeNotReadyException(Reason.PLUGIN_REFUSED, "plugin '" + consumer.pluginId()
+ "' cannot use the database: " + why);
}
// --- migrating -------------------------------------------------------------------------------------------
/** Migrates, loading parked data first when the plugin is new to a site's schema and data waits for it. */
void migrate(Consumer consumer, Scope.Kind kind, String siteId, String schema) throws SQLException {
checkPrefix(consumer);
List<Shipped> scripts = shipped(consumer, kind);
Parked source = parked;
if (kind == Scope.Kind.SITE && siteId != null && source != null) {
Optional<Integer> version;
try {
version = source.version(siteId, consumer);
} catch (IOException | RuntimeException e) {
// Never "no parked data": migrating the tables empty would make the schema "migrated", and the kept
// data would never be read again.
throw recordIssue(schema, consumer, ISSUE_PARKED, 0, Reason.PLUGIN_REFUSED, "the data kept for "
+ "plugin '" + consumer.pluginId() + "' from a restore (" + DatabaseBackup.PARKED
+ consumer.pluginId() + "/ in the site's folder) cannot be read: " + DatabaseRuntime.describe(e)
+ "; the plugin is refused on this site until it can");
}
if (version.isPresent()) {
if (version.get() > scripts.size()) {
// Not skipped either: the folder stays until a plugin that can read it arrives.
throw recordIssue(schema, consumer, ISSUE_NEWER, version.get(), Reason.NEWER_THAN_INSTALLED,
"data kept for plugin '" + consumer.pluginId() + "' from a restore is at version "
+ version.get() + ", newer than the " + scripts.size() + " scripts the installed "
+ "plugin ships; install that version or later (the data is kept until then)");
}
int recorded = highestRecorded(consumer, schema);
if (recorded > version.get()) {
throw recordIssue(schema, consumer, ISSUE_PARKED, version.get(), Reason.PLUGIN_REFUSED,
"data kept for plugin '" + consumer.pluginId() + "' from a restore is at version "
+ version.get() + ", but its tables in this schema are already at version "
+ recorded + "; restore the site's backup again, or remove " + DatabaseBackup.PARKED
+ consumer.pluginId() + "/ from the site's folder to go on without that data");
}
// First use, or a load that failed part way (the manifest goes only once the data is in): the loader
// empties the plugin's tables before it loads.
migrateWithData(consumer, kind, schema, version.get(), s -> source.load(siteId, consumer, s));
return;
}
}
migrateScripts(consumer, schema, scripts);
}
/**
* Migrates a plugin to {@code version}, runs the loader, then migrates to the shipped version: what a restore
* does in a new generation, and what parked data gets when its plugin arrives.
*/
public void migrateWithData(Consumer consumer, Scope.Kind kind, String schema, int version, Loader loader)
throws SQLException {
checkPrefix(consumer);
List<Shipped> scripts = shipped(consumer, kind);
if (version > scripts.size()) {
throw new ScopeNotReadyException(Reason.NEWER_THAN_INSTALLED, "the data is at version " + version
+ " of plugin '" + consumer.pluginId() + "', newer than the installed plugin's " + scripts.size()
+ "; install that version or later (the data is kept until then)");
}
migrateScripts(consumer, schema, scripts.subList(0, version));
try {
loader.load(schema);
} catch (IOException e) {
throw new SQLException("loading the data failed: " + e.getMessage(), e);
}
migrateScripts(consumer, schema, scripts);
verified.add(key(schema, consumer.pluginId()));
}
/** The highest script version a plugin has a row for in a schema, in any state; 0 for none. */
private int highestRecorded(Consumer consumer, String schema) throws SQLException {
try (Connection c = runtime.setupConnection()) {
c.setAutoCommit(true);
return readApplied(c, schema, consumer.pluginId()).keySet().stream().mapToInt(Integer::intValue).max()
.orElse(0);
}
}
/** Records a problem on the database screen, logs it, and returns the refusal to throw. */
private ScopeNotReadyException recordIssue(String schema, Consumer consumer, String state, int version,
Reason reason, String message) throws SQLException {
log.warn("database: plugin '{}' in schema '{}': {}", consumer.pluginId(), schema, message);
try (Connection c = runtime.setupConnection()) {
c.setAutoCommit(true);
return issue(c, schema, consumer, state, version, 0, reason, message);
}
}
private void migrateScripts(Consumer consumer, String schema, List<Shipped> scripts) throws SQLException {
String lockKey = "migrate:" + schema + ":" + consumer.pluginId();
try (Connection c = runtime.setupConnection()) {
try {
if (runtime.engine().transactionalDdl()) {
migrateInTransaction(c, consumer, schema, scripts, lockKey);
} else {
migrateStepwise(c, consumer, schema, scripts, lockKey);
}
} finally {
c.setAutoCommit(true);
}
} catch (Locks.LockTimeoutException e) {
throw new ScopeNotReadyException(Reason.PREPARING, "another node is migrating; try again shortly");
}
}
/** PostgreSQL: everything in one transaction. */
private void migrateInTransaction(Connection c, Consumer consumer, String schema, List<Shipped> scripts,
String lockKey) throws SQLException {
Engine engine = runtime.engine();
c.setAutoCommit(false);
boolean committed = false;
try {
if (!engine.migrationLock(c, lockKey, LOCK_WAIT)) {
throw new Locks.LockTimeoutException(lockKey);
}
engine.bind(c, schema, DatabaseRuntime.LONG_TIMEOUT);
Map<Integer, Applied> applied = readApplied(c, schema, consumer.pluginId());
List<Shipped> pending = pending(c, consumer, schema, scripts, applied);
if (pending.isEmpty()) {
c.commit();
committed = true;
clearIssue(schema, consumer);
return;
}
Set<Engine.DbObject> before = engine.ownedObjects(c, schema);
for (int k = 0; k < pending.size(); k++) {
Shipped script = pending.get(k);
if (applied.containsKey(script.version())) {
deleteRow(c, schema, consumer.pluginId(), script.version()); // a RETRY: run it again whole
}
for (int i = 0; i < script.statements().size(); i++) {
try {
Jdbc.execute(c, script.statements().get(i));
} catch (SQLException e) {
c.rollback();
markRolledBack(c, schema, consumer, pending.subList(0, k));
throw fail(c, schema, consumer, script, i, "statement " + (i + 1) + " failed: "
+ DatabaseRuntime.describe(e) + rolledBackNote(pending.subList(0, k)));
}
if (!engine.stillBound(c, schema)) {
c.rollback();
markRolledBack(c, schema, consumer, pending.subList(0, k));
throw fail(c, schema, consumer, script, i, "statement " + (i + 1)
+ " moved the connection to another schema" + rolledBackNote(pending.subList(0, k)));
}
}
insertRow(c, schema, consumer.pluginId(), script, APPLIED, script.statements().size());
}
List<String> foreign = foreign(before, engine.ownedObjects(c, schema), consumer.prefix());
if (!foreign.isEmpty()) {
c.rollback();
Shipped last = pending.get(pending.size() - 1);
markRolledBack(c, schema, consumer, pending.subList(0, pending.size() - 1));
throw fail(c, schema, consumer, last, 0, "the scripts touch objects outside the prefix '"
+ consumer.prefix() + "': " + String.join(", ", foreign)
+ rolledBackNote(pending.subList(0, pending.size() - 1)));
}
c.commit();
committed = true;
log.info("database: plugin '{}' in schema '{}' is at version {}", consumer.pluginId(), schema,
scripts.size());
clearIssue(schema, consumer);
} finally {
if (!committed) {
try {
c.rollback();
} catch (SQLException ignored) {
// the connection is closed next
}
}
}
}
/** MariaDB: statement by statement, the script row written first. */
private void migrateStepwise(Connection c, Consumer consumer, String schema, List<Shipped> scripts,
String lockKey) throws SQLException {
Engine engine = runtime.engine();
c.setAutoCommit(true);
engine.bind(c, schema, DatabaseRuntime.LONG_TIMEOUT);
if (!engine.migrationLock(c, lockKey, LOCK_WAIT)) {
throw new Locks.LockTimeoutException(lockKey);
}
try {
Map<Integer, Applied> applied = readApplied(c, schema, consumer.pluginId());
List<Shipped> pending = pending(c, consumer, schema, scripts, applied);
if (pending.isEmpty()) {
clearIssue(schema, consumer);
return;
}
Set<Engine.DbObject> current = engine.ownedObjects(c, schema);
Set<String> wrongEngine = new LinkedHashSet<>(engine.tablesWithWrongEngine(c, schema));
for (Shipped script : pending) {
Applied row = applied.get(script.version());
int start = row != null && RETRY.equals(row.state()) ? row.lastOk() : 0;
if (row == null) {
insertRow(c, schema, consumer.pluginId(), script, FAILED, 0);
} else {
setState(c, schema, consumer.pluginId(), script.version(), FAILED);
}
for (int i = start; i < script.statements().size(); i++) {
try {
Jdbc.execute(c, script.statements().get(i));
} catch (SQLException e) {
throw fail(c, schema, consumer, script, i, "statement " + (i + 1) + " failed: "
+ DatabaseRuntime.describe(e));
}
if (!engine.stillBound(c, schema)) {
engine.bind(c, schema, DatabaseRuntime.LONG_TIMEOUT);
throw fail(c, schema, consumer, script, i, "statement " + (i + 1)
+ " moved the connection to another database");
}
Set<Engine.DbObject> after = engine.ownedObjects(c, schema);
List<Engine.DbObject> added = new ArrayList<>();
for (Engine.DbObject o : after) {
if (!current.contains(o) && !o.name().startsWith(consumer.prefix())) {
added.add(o);
}
}
List<String> removed = new ArrayList<>();
for (Engine.DbObject o : current) {
if (!after.contains(o) && !o.name().startsWith(consumer.prefix())) {
removed.add(o.kind() + " " + o.name());
}
}
List<String> newWrongEngine = new ArrayList<>();
for (String t : engine.tablesWithWrongEngine(c, schema)) {
if (!wrongEngine.contains(t)) {
newWrongEngine.add(t);
}
}
if (!added.isEmpty() || !removed.isEmpty() || !newWrongEngine.isEmpty()) {
for (Engine.DbObject o : added) {
engine.dropObject(c, schema, o);
}
for (String t : newWrongEngine) {
engine.dropObject(c, schema, new Engine.DbObject("table", t, null));
}
StringBuilder why = new StringBuilder("statement " + (i + 1));
if (!added.isEmpty()) {
why.append(" created objects outside the prefix '").append(consumer.prefix())
.append("' (dropped again): ").append(names(added));
}
if (!removed.isEmpty()) {
why.append(" removed objects outside the prefix: ").append(String.join(", ", removed));
}
if (!newWrongEngine.isEmpty()) {
why.append(" created tables that are not InnoDB (dropped again): ")
.append(String.join(", ", newWrongEngine));
}
throw fail(c, schema, consumer, script, i, why.toString());
}
current = after;
setLastOk(c, schema, consumer.pluginId(), script.version(), i + 1);
}
setState(c, schema, consumer.pluginId(), script.version(), APPLIED);
}
log.info("database: plugin '{}' in schema '{}' is at version {}", consumer.pluginId(), schema,
scripts.size());
clearIssue(schema, consumer);
} finally {
try {
engine.migrationUnlock(c, lockKey);
} catch (SQLException e) {
runtime.evictSetup(c);
}
}
}
/** What the applied rows allow: the scripts still to run, or a refusal. */
private List<Shipped> pending(Connection c, Consumer consumer, String schema, List<Shipped> scripts,
Map<Integer, Applied> applied) throws SQLException {
int highest = 0;
// A downgrade first: a schema ahead of the installed plugin explains any checksum difference too.
for (Applied a : applied.values()) {
if (a.version() > scripts.size()) {
throw issue(c, schema, consumer, ISSUE_NEWER, a.version(), 0, Reason.NEWER_THAN_INSTALLED,
"the schema is at version " + a.version() + " of plugin '" + consumer.pluginId()
+ "', newer than the " + scripts.size() + " scripts the installed plugin ships; "
+ "install that version or later");
}
}
List<Applied> failed = applied.values().stream().filter(a -> FAILED.equals(a.state()))
.sorted(java.util.Comparator.comparingInt(Applied::version)).toList();
if (!failed.isEmpty()) {
// The highest failed script is the one that failed: on PostgreSQL the scripts of its batch below it were
// rolled back with it and are recorded failed at statement 0, to run again.
Applied worst = failed.get(failed.size() - 1);
Optional<Registry.Issue> recorded = runtime.registry().issue(c, schema, consumer.pluginId());
if (recorded.isPresent() && ISSUE_FAILED.equals(recorded.get().state())
&& recorded.get().version() == worst.version()) {
// Recorded when it failed, with the server's error: kept, not replaced by a vaguer one.
throw new ScopeNotReadyException(Reason.MIGRATION_FAILED, recorded.get().detail());
}
List<Shipped> undone = failed.subList(0, failed.size() - 1).stream()
.map(a -> scripts.get(a.version() - 1)).toList();
throw issue(c, schema, consumer, ISSUE_FAILED, worst.version(), worst.lastOk() + 1,
Reason.MIGRATION_FAILED, "script " + scripts.get(worst.version() - 1).name() + " of plugin '"
+ consumer.pluginId() + "' failed at statement " + (worst.lastOk() + 1)
+ rolledBackNote(undone) + "; retry it or mark it applied on the database screen");
}
for (Applied a : applied.values()) {
Shipped s = scripts.get(a.version() - 1);
if (APPLIED.equals(a.state()) && !a.checksum().equals(s.checksum())) {
throw issue(c, schema, consumer, ISSUE_CHECKSUM, a.version(), 0, Reason.CHECKSUM_MISMATCH,
"script " + s.name() + " of plugin '" + consumer.pluginId() + "' changed after it was "
+ "applied; released scripts must not change. Accept the shipped checksum on the "
+ "database screen once the change is understood");
}
if (APPLIED.equals(a.state())) {
highest = Math.max(highest, a.version());
}
}
for (Shipped s : scripts) {
if (s.version() < highest && !applied.containsKey(s.version())) {
// A script below the highest applied one that never ran: running later scripts on top of the gap
// would build on something that is not there.
throw issue(c, schema, consumer, ISSUE_FAILED, s.version(), 0, Reason.MIGRATION_FAILED,
"script " + s.name() + " of plugin '" + consumer.pluginId() + "' was never applied, but a "
+ "later one was; apply it by hand and then use Mark applied (Retry cannot run it), "
+ "or restore the schema");
}
}
List<Shipped> pending = new ArrayList<>();
for (Shipped s : scripts) {
Applied a = applied.get(s.version());
if (s.version() > highest && (a == null || RETRY.equals(a.state()))) {
pending.add(s);
}
}
return pending;
}
private static String names(List<Engine.DbObject> objects) {
List<String> out = new ArrayList<>();
for (Engine.DbObject o : objects) {
out.add(o.kind() + " " + o.name());
}
return String.join(", ", out);
}
/** Objects added or removed between two snapshots whose names lack the prefix. */
static List<String> foreign(Set<Engine.DbObject> before, Set<Engine.DbObject> after, String prefix) {
List<String> out = new ArrayList<>();
for (Engine.DbObject o : after) {
if (!before.contains(o) && !o.name().startsWith(prefix)) {
out.add("created " + o.kind() + " " + o.name());
}
}
for (Engine.DbObject o : before) {
if (!after.contains(o) && !o.name().startsWith(prefix)) {
out.add("removed " + o.kind() + " " + o.name());
}
}
return out;
}
// --- failure records -------------------------------------------------------------------------------------
/**
* On the transactional engine one failure rolls back the whole batch: the scripts that ran before the failing
* one are undone too. Each gets a {@code failed} row (no statement kept), so <b>Retry</b> runs them all again and
* <b>Mark applied</b> covers them all, instead of the batch's earlier scripts being skipped for ever once the
* failing one is marked.
*/
private void markRolledBack(Connection c, String schema, Consumer consumer, List<Shipped> undone)
throws SQLException {
if (undone.isEmpty()) {
return;
}
boolean auto = c.getAutoCommit();
c.setAutoCommit(true);
Map<Integer, Applied> rows = readApplied(c, schema, consumer.pluginId());
for (Shipped s : undone) {
if (rows.containsKey(s.version())) {
setState(c, schema, consumer.pluginId(), s.version(), FAILED);
setLastOk(c, schema, consumer.pluginId(), s.version(), 0);
} else {
insertRow(c, schema, consumer.pluginId(), s, FAILED, 0);
}
}
c.setAutoCommit(auto);
}
private static String rolledBackNote(List<Shipped> undone) {
return undone.isEmpty() ? "" : "; rolled back with it, and to run again: "
+ undone.stream().map(Shipped::name).collect(java.util.stream.Collectors.joining(", "));
}
private ScopeNotReadyException fail(Connection c, String schema, Consumer consumer, Shipped script, int statement,
String why) throws SQLException {
boolean auto = c.getAutoCommit();
c.setAutoCommit(true);
if (readApplied(c, schema, consumer.pluginId()).containsKey(script.version())) {
setState(c, schema, consumer.pluginId(), script.version(), FAILED);
setLastOk(c, schema, consumer.pluginId(), script.version(), statement);
} else {
insertRow(c, schema, consumer.pluginId(), script, FAILED, statement);
}
c.setAutoCommit(auto);
log.warn("database: plugin '{}' in schema '{}': script {} {}", consumer.pluginId(), schema, script.name(), why);
return issue(c, schema, consumer, ISSUE_FAILED, script.version(), statement + 1, Reason.MIGRATION_FAILED,
"script " + script.name() + " of plugin '" + consumer.pluginId() + "' failed: " + why);
}
private ScopeNotReadyException issue(Connection c, String schema, Consumer consumer, String state, int version,
int statement, Reason reason, String message) throws SQLException {
boolean auto = c.getAutoCommit();
if (!auto) {
c.rollback();
c.setAutoCommit(true);
}
runtime.registry().putIssue(c, schema, consumer.pluginId(), state, version, statement, message);
c.setAutoCommit(auto);
return new ScopeNotReadyException(reason, message);
}
private void clearIssue(String schema, Consumer consumer) throws SQLException {
try (Connection c = runtime.setupConnection()) {
c.setAutoCommit(true);
runtime.registry().clearIssue(c, schema, consumer.pluginId());
}
}
// --- rw_migrations ---------------------------------------------------------------------------------------
private String table(String schema) {
return runtime.engine().quote(schema) + ".rw_migrations";
}
Map<Integer, Applied> readApplied(Connection c, String schema, String pluginId) throws SQLException {
Map<Integer, Applied> rows = new LinkedHashMap<>();
try (PreparedStatement ps = c.prepareStatement("SELECT version, name, checksum, state, last_ok_statement FROM "
+ table(schema) + " WHERE plugin_id = ? ORDER BY version")) {
ps.setString(1, pluginId);
try (ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
rows.put(rs.getInt(1), new Applied(rs.getInt(1), rs.getString(2), rs.getString(3), rs.getString(4),
rs.getInt(5)));
}
}
}
return rows;
}
private void insertRow(Connection c, String schema, String pluginId, Shipped script, String state, int lastOk)
throws SQLException {
try (PreparedStatement ps = c.prepareStatement("INSERT INTO " + table(schema) + " (plugin_id, version, name, "
+ "checksum, state, last_ok_statement, applied_at) VALUES (?, ?, ?, ?, ?, ?, "
+ (APPLIED.equals(state) ? runtime.engine().nowSql() : "NULL") + ")")) {
ps.setString(1, pluginId);
ps.setInt(2, script.version());
ps.setString(3, script.name());
ps.setString(4, script.checksum());
ps.setString(5, state);
ps.setInt(6, lastOk);
ps.executeUpdate();
}
}
private void setState(Connection c, String schema, String pluginId, int version, String state)
throws SQLException {
try (PreparedStatement ps = c.prepareStatement("UPDATE " + table(schema) + " SET state = ?, applied_at = "
+ (APPLIED.equals(state) ? runtime.engine().nowSql() : "applied_at")
+ " WHERE plugin_id = ? AND version = ?")) {
ps.setString(1, state);
ps.setString(2, pluginId);
ps.setInt(3, version);
ps.executeUpdate();
}
}
private void setLastOk(Connection c, String schema, String pluginId, int version, int lastOk) throws SQLException {
try (PreparedStatement ps = c.prepareStatement("UPDATE " + table(schema) + " SET last_ok_statement = ? "
+ "WHERE plugin_id = ? AND version = ?")) {
ps.setInt(1, lastOk);
ps.setString(2, pluginId);
ps.setInt(3, version);
ps.executeUpdate();
}
}
private void deleteRow(Connection c, String schema, String pluginId, int version) throws SQLException {
try (PreparedStatement ps = c.prepareStatement("DELETE FROM " + table(schema)
+ " WHERE plugin_id = ? AND version = ?")) {
ps.setString(1, pluginId);
ps.setInt(2, version);
ps.executeUpdate();
}
}
/** The highest applied version of a plugin in a schema (0 when none), read on a bound or unbound connection. */
int appliedVersion(Connection c, String schema, String pluginId) throws SQLException {
int highest = 0;
for (Applied a : readApplied(c, schema, pluginId).values()) {
if (APPLIED.equals(a.state())) {
highest = Math.max(highest, a.version());
}
}
return highest;
}
// --- operator recovery (audited by the caller) -----------------------------------------------------------
/** The recovery actions on the health screen. */
public enum Recovery {
/** Run the failed script again from the statement after the last one that succeeded. */
RETRY,
/** Record the failed script as applied (the operator finished it by hand). */
MARK_APPLIED,
/** Record the shipped checksum for every applied script whose checksum changed. */
ACCEPT_CHECKSUM
}
/** Applies a recovery action to one plugin in one schema. */
public void recover(Consumer consumer, Scope.Kind kind, String schema, Recovery action) throws SQLException {
List<Shipped> scripts = shipped(consumer, kind);
try (Connection c = runtime.setupConnection()) {
c.setAutoCommit(true);
Map<Integer, Applied> applied = readApplied(c, schema, consumer.pluginId());
for (Applied a : applied.values()) {
switch (action) {
case RETRY -> {
if (FAILED.equals(a.state())) {
setState(c, schema, consumer.pluginId(), a.version(), RETRY);
}
}
case MARK_APPLIED -> {
if (FAILED.equals(a.state()) || RETRY.equals(a.state())) {
setState(c, schema, consumer.pluginId(), a.version(), APPLIED);
}
}
case ACCEPT_CHECKSUM -> {
if (APPLIED.equals(a.state()) && a.version() <= scripts.size()) {
try (PreparedStatement ps = c.prepareStatement("UPDATE " + table(schema)
+ " SET checksum = ? WHERE plugin_id = ? AND version = ?")) {
ps.setString(1, scripts.get(a.version() - 1).checksum());
ps.setString(2, consumer.pluginId());
ps.setInt(3, a.version());
ps.executeUpdate();
}
}
}
default -> throw new IllegalArgumentException("unknown action " + action);
}
}
if (action == Recovery.MARK_APPLIED) {
// A script below the highest applied one that never ran (the gap refusal): the operator applied it.
Map<Integer, Applied> now = readApplied(c, schema, consumer.pluginId());
int highest = now.values().stream().filter(a -> APPLIED.equals(a.state()))
.mapToInt(Applied::version).max().orElse(0);
for (Shipped s : scripts) {
if (s.version() < highest && !now.containsKey(s.version())) {
insertRow(c, schema, consumer.pluginId(), s, APPLIED, s.statements().size());
}
}
}
runtime.registry().clearIssue(c, schema, consumer.pluginId());
}
String key = key(schema, consumer.pluginId());
failures.remove(key);
verified.remove(key);
}
}
@@ -0,0 +1,164 @@
package mx.quest.database.internal;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HexFormat;
import java.util.Locale;
import java.util.Objects;
import java.util.regex.Pattern;
/**
* Every name the database plugin creates or checks: the namespace, the schema names and the plugin prefixes. Pure
* functions, so the rules that keep installs, sites and plugins apart are tested without a database.
*
* <ul>
* <li>The Runway-wide schema is {@code <ns>_app}; a site's schema is {@code <ns>_s_<base>_<gen>}, where
* {@code <base>} is the site id lower-cased with everything outside {@code [a-z0-9]} mapped to {@code _}, and
* {@code <gen>} comes from an install-wide sequence, so a name is never reused even when two site ids map to
* the same base.</li>
* <li>A plugin's prefix is its id mapped the same way, ending in a double underscore, at most
* {@value #PREFIX_MAX} characters (a longer one is cut and given a short hash).</li>
* </ul>
*/
public final class Names {
/** The namespace grammar: no underscore, so one install's names never start another's. */
public static final Pattern NAMESPACE = Pattern.compile("[a-z][a-z0-9]{0,11}");
/** The longest plugin prefix, double underscore included. */
public static final int PREFIX_MAX = 24;
/** Database's own objects; no plugin prefix may start with it. */
public static final String RESERVED_PREFIX = "rw_";
private static final Pattern SITE_SCHEMA_TAIL = Pattern.compile("s_[a-z0-9_]+");
private Names() {
}
/** The namespace, checked: refuses anything outside {@link #NAMESPACE}. */
public static String namespace(String value) {
if (value == null || !NAMESPACE.matcher(value).matches()) {
throw new IllegalArgumentException("the namespace must be a lower-case letter followed by up to 11 "
+ "lower-case letters or digits: " + value);
}
return value;
}
/** {@code <ns>_app}. */
public static String appSchema(String namespace) {
return namespace(namespace) + "_app";
}
/**
* {@code <ns>_s_<base>_<gen>}, with the base cut so that the whole name is at most {@code maxLength} bytes.
*
* @param maxLength the engine's identifier limit (63 for PostgreSQL, 64 for MariaDB)
*/
public static String siteSchema(String namespace, String siteId, long generation, int maxLength) {
Objects.requireNonNull(siteId, "siteId");
if (siteId.isEmpty()) {
throw new IllegalArgumentException("empty site id");
}
if (generation < 1) {
throw new IllegalArgumentException("generation must be positive: " + generation);
}
String head = namespace(namespace) + "_s_";
String tail = "_" + generation;
int room = maxLength - head.length() - tail.length();
if (room < 1) {
throw new IllegalArgumentException("no room for a site name within " + maxLength + " characters");
}
String base = fold(siteId);
if (base.length() > room) {
base = base.substring(0, room);
}
return head + base + tail;
}
/**
* Whether {@code name} is one this install may create or drop: {@code <ns>_app} or {@code <ns>_s_…}, only
* {@code [a-z0-9_]}, and within the engine limit. Checked before any DDL.
*/
public static boolean isOwnSchema(String namespace, String name, int maxLength) {
if (name == null || name.length() > maxLength) {
return false;
}
String head = namespace(namespace) + "_";
if (!name.startsWith(head)) {
return false;
}
String rest = name.substring(head.length());
return rest.equals("app") || SITE_SCHEMA_TAIL.matcher(rest).matches();
}
/** Whether {@code name} is a site schema of this install (not the app schema). */
public static boolean isSiteSchema(String namespace, String name, int maxLength) {
return isOwnSchema(namespace, name, maxLength) && !name.equals(appSchema(namespace));
}
/** Throws unless {@link #isOwnSchema}: the guard in front of every CREATE, DROP and binding. */
public static String requireOwnSchema(String namespace, String name, int maxLength) {
if (!isOwnSchema(namespace, name, maxLength)) {
throw new IllegalStateException("refusing a schema name outside this install's namespace: " + name);
}
return name;
}
/**
* A plugin's object prefix: the id lower-cased, everything outside {@code [a-z0-9]} mapped to {@code _}, then
* {@code __}; capped at {@value #PREFIX_MAX} characters by cutting and appending a hash of the full id.
*/
public static String pluginPrefix(String pluginId) {
Objects.requireNonNull(pluginId, "pluginId");
if (pluginId.isEmpty()) {
throw new IllegalArgumentException("empty plugin id");
}
String folded = fold(pluginId);
String prefix = folded + "__";
if (prefix.length() <= PREFIX_MAX) {
return prefix;
}
String hash = sha256Hex(pluginId).substring(0, 6);
return folded.substring(0, PREFIX_MAX - 2 - 1 - hash.length()) + "_" + hash + "__";
}
/**
* Whether two prefixes cannot both be recorded: equal, or one the start of the other, so an object name could
* belong to either. Also true when either starts with the reserved {@code rw_}.
*/
public static boolean prefixesClash(String a, String b) {
return a.startsWith(b) || b.startsWith(a);
}
/** Whether a plugin prefix is refused outright because it starts with the reserved {@code rw_}. */
public static boolean isReservedPrefix(String prefix) {
return prefix.startsWith(RESERVED_PREFIX);
}
/** Lower-cased, with every character outside {@code [a-z0-9]} mapped to {@code _}. */
static String fold(String value) {
String lower = value.toLowerCase(Locale.ROOT);
StringBuilder out = new StringBuilder(lower.length());
for (int i = 0; i < lower.length(); i++) {
char c = lower.charAt(i);
out.append((c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') ? c : '_');
}
return out.toString();
}
/** The SHA-256 of a string's UTF-8 bytes, in lower-case hex. */
public static String sha256Hex(String value) {
return sha256Hex(value.getBytes(StandardCharsets.UTF_8));
}
/** The SHA-256 of some bytes, in lower-case hex. */
public static String sha256Hex(byte[] bytes) {
try {
return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes));
} catch (NoSuchAlgorithmException impossible) {
throw new IllegalStateException("SHA-256 is missing from this JVM", impossible);
}
}
}
@@ -0,0 +1,71 @@
package mx.quest.database.internal;
import java.util.Objects;
import mx.quest.database.spi.DatabaseUnavailableException;
import mx.quest.database.spi.Dialect;
import mx.quest.database.spi.PluginDatabase;
import mx.quest.database.spi.Scope;
import mx.quest.runway.spi.model.SiteRef;
import mx.quest.runway.spi.model.SiteView;
/** One consumer plugin's handle, handed out by {@link DatabasesImpl}. */
final class PluginDatabaseImpl implements PluginDatabase {
private final DatabaseCore core;
private final Consumer consumer;
PluginDatabaseImpl(DatabaseCore core, Consumer consumer) {
this.core = core;
this.consumer = consumer;
}
Consumer consumer() {
return consumer;
}
@Override
public boolean available() {
return core.runtime().available();
}
@Override
public Dialect dialect() {
Engine engine = core.runtime().engine();
if (engine == null || !available()) {
throw new DatabaseUnavailableException("the database is not available");
}
return engine.dialect();
}
@Override
public String prefix() {
return consumer.prefix();
}
@Override
public Scope currentSite() {
SiteView site = core.requestContext().site().orElseThrow(() -> new IllegalStateException(
"there is no site in this request (an application-console request or a background thread)"));
return new ScopeImpl(core, consumer, Scope.Kind.SITE, site.id());
}
@Override
public Scope site(SiteRef site) {
Objects.requireNonNull(site, "site");
return siteInBackground(site.id());
}
@Override
public Scope siteInBackground(String siteId) {
Objects.requireNonNull(siteId, "siteId");
if (core.sites().find(siteId).isEmpty()) {
throw new IllegalArgumentException("no site with id " + siteId);
}
return new ScopeImpl(core, consumer, Scope.Kind.SITE, siteId);
}
@Override
public Scope app() {
return new ScopeImpl(core, consumer, Scope.Kind.APP, null);
}
}
@@ -0,0 +1,226 @@
package mx.quest.database.internal;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Base64;
/**
* The backup's portable column types and their encoding, the same for both products, so a backup taken on one
* restores on the other.
*
* <ul>
* <li>Types: {@code BIGINT, INTEGER, SMALLINT, DECIMAL(p,s), DOUBLE, BOOLEAN, VARCHAR(n), TEXT, DATE, TIME,
* TIMESTAMP} (a wall-clock time), {@code TIMESTAMPTZ} (an instant), {@code BYTES, JSON}.</li>
* <li>Encoding in JSON: {@code BIGINT} and {@code DECIMAL} as strings; {@code INTEGER} and {@code SMALLINT} as
* numbers; {@code DOUBLE} as a number (a string for NaN and the infinities); {@code TIMESTAMPTZ} as ISO-8601
* UTC with {@code Z} and six fractional digits; {@code TIMESTAMP}, {@code DATE}, {@code TIME} in ISO-8601
* without an offset; {@code BYTES} in base64; {@code JSON} as a string holding the document; SQL NULL as
* {@code null} only.</li>
* <li>A column is read with the getter its type names, never {@code getObject} without a type, and a restored
* value is bound by the <b>target</b> column's type: types in the same family restore into each other
* (the integers; {@code VARCHAR}, {@code TEXT} and {@code JSON}; {@code TIMESTAMP} and {@code TIMESTAMPTZ},
* taking a wall-clock time as UTC, which is the zone both products' sessions are pinned to).</li>
* </ul>
*/
final class Portable {
static final String UNSUPPORTED = "UNSUPPORTED:";
private static final DateTimeFormatter INSTANT = DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss.SSSSSS'Z'")
.withZone(ZoneOffset.UTC);
private Portable() {
}
/** The type's family: what it may restore into. */
static String family(String type) {
String base = base(type);
return switch (base) {
case "BIGINT", "INTEGER", "SMALLINT" -> "INTEGER";
case "VARCHAR", "TEXT", "JSON" -> "TEXT";
case "TIMESTAMP", "TIMESTAMPTZ" -> "TIMESTAMP";
default -> base;
};
}
/** The type without its parameters: {@code DECIMAL(10,2)} gives {@code DECIMAL}. */
static String base(String type) {
int paren = type.indexOf('(');
return paren < 0 ? type : type.substring(0, paren);
}
/** Whether a backed-up column restores into a target column. */
static boolean compatible(String archived, String target) {
return !archived.startsWith(UNSUPPORTED) && !target.startsWith(UNSUPPORTED)
&& family(archived).equals(family(target));
}
static String instant(Instant value) {
return INSTANT.format(value);
}
/**
* Reads one column for a backup.
*
* @param zonedTimestamps whether the product reads {@code TIMESTAMPTZ} as an offset date-time (PostgreSQL) rather
* than a UTC wall-clock time (MariaDB, whose sessions are pinned to UTC)
*/
static Object read(ResultSet rs, int i, String type, boolean zonedTimestamps) throws SQLException {
Object value = switch (base(type)) {
case "BIGINT" -> {
long v = rs.getLong(i);
yield rs.wasNull() ? null : Long.toString(v);
}
case "INTEGER", "SMALLINT" -> {
long v = rs.getLong(i);
yield rs.wasNull() ? null : v;
}
case "DECIMAL" -> {
BigDecimal v = rs.getBigDecimal(i);
yield v == null ? null : v.toPlainString();
}
case "DOUBLE" -> {
double v = rs.getDouble(i);
yield rs.wasNull() ? null : Double.isFinite(v) ? (Object) v : Double.toString(v);
}
case "BOOLEAN" -> {
boolean v = rs.getBoolean(i);
yield rs.wasNull() ? null : v;
}
case "VARCHAR", "TEXT", "JSON" -> rs.getString(i);
case "DATE" -> {
LocalDate v = rs.getObject(i, LocalDate.class);
yield v == null ? null : v.toString();
}
case "TIME" -> {
LocalTime v = rs.getObject(i, LocalTime.class);
yield v == null ? null : v.toString();
}
case "TIMESTAMP" -> {
LocalDateTime v = rs.getObject(i, LocalDateTime.class);
yield v == null ? null : v.toString();
}
case "TIMESTAMPTZ" -> {
if (zonedTimestamps) {
OffsetDateTime v = rs.getObject(i, OffsetDateTime.class);
yield v == null ? null : instant(v.toInstant());
}
LocalDateTime v = rs.getObject(i, LocalDateTime.class);
yield v == null ? null : instant(v.toInstant(ZoneOffset.UTC));
}
case "BYTES" -> {
byte[] v = rs.getBytes(i);
yield v == null ? null : Base64.getEncoder().encodeToString(v);
}
default -> throw new SQLException("column type cannot be backed up: " + type);
};
return value;
}
/**
* Binds one restored value by the target column's type.
*
* @param postgres whether the target is PostgreSQL (JSON is bound untyped, instants as offset date-times)
* @throws IllegalArgumentException when the value does not fit the type
*/
static void bind(PreparedStatement ps, int i, String type, Object value, boolean postgres) throws SQLException {
String base = base(type);
if (value == null) {
ps.setNull(i, sqlType(base));
return;
}
switch (base) {
case "BIGINT", "INTEGER", "SMALLINT" -> ps.setLong(i, integer(value));
case "DECIMAL" -> ps.setBigDecimal(i, new BigDecimal(text(value)));
case "DOUBLE" -> ps.setDouble(i, value instanceof Number n ? n.doubleValue()
: Double.parseDouble(text(value)));
case "BOOLEAN" -> {
if (!(value instanceof Boolean b)) {
throw new IllegalArgumentException("not a boolean");
}
ps.setBoolean(i, b);
}
case "VARCHAR", "TEXT" -> ps.setString(i, text(value));
case "JSON" -> {
if (postgres) {
ps.setObject(i, text(value), Types.OTHER);
} else {
ps.setString(i, text(value));
}
}
case "DATE" -> ps.setObject(i, LocalDate.parse(text(value)));
case "TIME" -> ps.setObject(i, LocalTime.parse(text(value)));
case "TIMESTAMP" -> ps.setObject(i, wallClock(text(value)));
case "TIMESTAMPTZ" -> {
Instant at = moment(text(value));
if (postgres) {
ps.setObject(i, at.atOffset(ZoneOffset.UTC));
} else {
ps.setObject(i, LocalDateTime.ofInstant(at, ZoneOffset.UTC));
}
}
case "BYTES" -> ps.setBytes(i, Base64.getDecoder().decode(text(value)));
default -> throw new IllegalArgumentException("column type cannot be restored: " + type);
}
}
private static int sqlType(String base) {
return switch (base) {
case "BIGINT" -> Types.BIGINT;
case "INTEGER" -> Types.INTEGER;
case "SMALLINT" -> Types.SMALLINT;
case "DECIMAL" -> Types.DECIMAL;
case "DOUBLE" -> Types.DOUBLE;
case "BOOLEAN" -> Types.BOOLEAN;
case "DATE" -> Types.DATE;
case "TIME" -> Types.TIME;
case "TIMESTAMP" -> Types.TIMESTAMP;
case "TIMESTAMPTZ" -> Types.TIMESTAMP_WITH_TIMEZONE;
case "BYTES" -> Types.VARBINARY;
case "JSON" -> Types.OTHER;
default -> Types.VARCHAR;
};
}
private static long integer(Object value) {
if (value instanceof Integer || value instanceof Long || value instanceof Short) {
return ((Number) value).longValue();
}
if (value instanceof BigInteger big) {
return big.longValueExact();
}
if (value instanceof String s) {
return Long.parseLong(s);
}
throw new IllegalArgumentException("not an integer");
}
private static String text(Object value) {
if (value instanceof String s) {
return s;
}
throw new IllegalArgumentException("not a string");
}
/** A wall-clock time; an archived instant ({@code …Z}) is taken in UTC. */
private static LocalDateTime wallClock(String text) {
return text.endsWith("Z") ? LocalDateTime.ofInstant(Instant.parse(text), ZoneOffset.UTC)
: LocalDateTime.parse(text);
}
/** An instant; an archived wall-clock time is taken as UTC. */
private static Instant moment(String text) {
return text.endsWith("Z") ? Instant.parse(text) : LocalDateTime.parse(text).toInstant(ZoneOffset.UTC);
}
}
@@ -0,0 +1,517 @@
package mx.quest.database.internal;
import java.nio.ByteBuffer;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.time.Duration;
import java.util.ArrayList;
import java.util.HexFormat;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import mx.quest.database.spi.Dialect;
/** PostgreSQL 14 or later: schemas in the configured database, transactional DDL, advisory locks. */
public final class PostgresEngine implements Engine {
static final int MIN_VERSION_NUM = 140000;
private static final String LOCK_NOT_AVAILABLE = "55P03";
private final Dialect dialect = new PostgresDialect();
@Override
public String id() {
return "postgresql";
}
@Override
public Dialect dialect() {
return dialect;
}
@Override
public int identifierMax() {
return 63;
}
@Override
public int defaultPort() {
return 5432;
}
@Override
public String quote(String name) {
return quoteIdent(name);
}
@Override
public String nowSql() {
return "now()";
}
@Override
public java.time.Instant instant(ResultSet rs, int column) throws SQLException {
java.time.OffsetDateTime t = rs.getObject(column, java.time.OffsetDateTime.class);
return t == null ? null : t.toInstant();
}
static String quoteIdent(String name) {
return "\"" + name.replace("\"", "\"\"") + "\"";
}
@Override
public String connectionInitSql(Duration statementTimeout, String collation) {
long ms = statementTimeout.toMillis();
return "SET TIME ZONE 'UTC'; SET statement_timeout = " + ms + "; SET lock_timeout = " + ms;
}
@Override
public String inspectServer(Connection c) throws SQLException {
try (Statement s = c.createStatement();
ResultSet rs = s.executeQuery("SELECT current_setting('server_version_num')::int, "
+ "current_setting('server_version'), current_setting('server_encoding')")) {
rs.next();
int num = rs.getInt(1);
String version = rs.getString(2);
String encoding = rs.getString(3);
if (num < MIN_VERSION_NUM) {
throw new UnsupportedServerException("PostgreSQL " + version + " is too old: 14 or later is needed");
}
if (!"UTF8".equalsIgnoreCase(encoding)) {
throw new UnsupportedServerException("the database's encoding is " + encoding + ": UTF8 is needed");
}
return "PostgreSQL " + version;
}
}
// --- binding --------------------------------------------------------------------------------------------
private static String searchPath(String schema) {
return quoteIdent(schema) + ", pg_temp";
}
@Override
public boolean bindSite(Connection c, String appSchema, String siteId, String schema, Duration timeout)
throws SQLException {
String sql = "SELECT set_config('search_path', ?, false), set_config('statement_timeout', ?, false) FROM "
+ quoteIdent(appSchema) + ".rw_sites WHERE site_id = ? AND schema_name = ? AND state = 'live'";
try (PreparedStatement ps = c.prepareStatement(sql)) {
ps.setString(1, searchPath(schema));
ps.setString(2, Long.toString(timeout.toMillis()));
ps.setString(3, siteId);
ps.setString(4, schema);
try (ResultSet rs = ps.executeQuery()) {
return rs.next();
}
}
}
@Override
public void bind(Connection c, String schema, Duration timeout) throws SQLException {
try (PreparedStatement ps = c.prepareStatement(
"SELECT set_config('search_path', ?, false), set_config('statement_timeout', ?, false)")) {
ps.setString(1, searchPath(schema));
ps.setString(2, Long.toString(timeout.toMillis()));
ps.executeQuery().close();
}
}
@Override
public void reset(Connection c) throws SQLException {
// Never DISCARD ALL: it would drop the driver's prepared statements behind its back.
try (Statement s = c.createStatement()) {
s.execute("DISCARD TEMP");
}
}
@Override
public void beginRead(Connection c) throws SQLException {
// The driver opens the transaction READ ONLY at the REPEATABLE READ level the caller set.
}
@Override
public boolean stillBound(Connection c, String schema) throws SQLException {
try (Statement s = c.createStatement();
ResultSet rs = s.executeQuery("SELECT current_setting('search_path')")) {
rs.next();
return searchPath(schema).equals(rs.getString(1));
}
}
// --- schemas --------------------------------------------------------------------------------------------
@Override
public void createSchema(Connection c, String schema, String collation) throws SQLException {
execute(c, "CREATE SCHEMA IF NOT EXISTS " + quoteIdent(schema));
}
@Override
public void dropSchema(Connection c, String schema) throws SQLException {
execute(c, "DROP SCHEMA IF EXISTS " + quoteIdent(schema) + " CASCADE");
}
@Override
public List<String> listSchemas(Connection c, String namespace) throws SQLException {
List<String> names = new ArrayList<>();
try (PreparedStatement ps = c.prepareStatement(
"SELECT nspname FROM pg_namespace WHERE nspname LIKE ? ESCAPE '\\' ORDER BY nspname")) {
ps.setString(1, namespace + "\\_%");
try (ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
names.add(rs.getString(1));
}
}
}
return names;
}
@Override
public List<String> registryDdl(String appSchema) {
String a = quoteIdent(appSchema);
return List.of(
"CREATE TABLE IF NOT EXISTS " + a + ".rw_install (key varchar(64) PRIMARY KEY, "
+ "value varchar(255) NOT NULL)",
"CREATE SEQUENCE IF NOT EXISTS " + a + ".rw_generation",
"CREATE TABLE IF NOT EXISTS " + a + ".rw_sites (site_id varchar(255) PRIMARY KEY, "
+ "schema_name varchar(64) NOT NULL UNIQUE, token char(32) NOT NULL, "
+ "generation bigint NOT NULL, state varchar(16) NOT NULL, created_at timestamptz NOT NULL)",
"CREATE TABLE IF NOT EXISTS " + a + ".rw_schemas (schema_name varchar(64) PRIMARY KEY, "
+ "site_id varchar(255) NOT NULL, generation bigint NOT NULL, state varchar(16) NOT NULL, "
+ "changed_at timestamptz NOT NULL)",
"CREATE TABLE IF NOT EXISTS " + a + ".rw_plugins (plugin_id varchar(255) PRIMARY KEY, "
+ "prefix varchar(24) NOT NULL UNIQUE, first_seen timestamptz NOT NULL)",
"CREATE TABLE IF NOT EXISTS " + a + ".rw_nodes (node_id varchar(64) PRIMARY KEY, "
+ "host varchar(255) NOT NULL, version varchar(32) NOT NULL, "
+ "started_at timestamptz NOT NULL, seen_at timestamptz NOT NULL)",
"CREATE TABLE IF NOT EXISTS " + a + ".rw_issues (schema_name varchar(64) NOT NULL, "
+ "plugin_id varchar(255) NOT NULL, state varchar(16) NOT NULL, version integer NOT NULL, "
+ "statement integer NOT NULL, detail varchar(1000) NOT NULL, at timestamptz NOT NULL, "
+ "PRIMARY KEY (schema_name, plugin_id))");
}
@Override
public String migrationsDdl(String schema) {
return "CREATE TABLE IF NOT EXISTS " + quoteIdent(schema) + ".rw_migrations (plugin_id varchar(255) NOT NULL, "
+ "version integer NOT NULL, name varchar(128) NOT NULL, checksum char(64) NOT NULL, "
+ "state varchar(16) NOT NULL, last_ok_statement integer NOT NULL, applied_at timestamptz, "
+ "PRIMARY KEY (plugin_id, version))";
}
@Override
public long nextGeneration(Connection c, String appSchema) throws SQLException {
try (PreparedStatement ps = c.prepareStatement("SELECT nextval(?::regclass)")) {
ps.setString(1, quoteIdent(appSchema) + ".rw_generation");
try (ResultSet rs = ps.executeQuery()) {
rs.next();
return rs.getLong(1);
}
}
}
// --- locks ------------------------------------------------------------------------------------------------
/** A 64-bit advisory lock key from the lock name. */
static long lockKey(String key) {
return ByteBuffer.wrap(HexFormat.of().parseHex(Names.sha256Hex(key)), 0, 8).getLong();
}
@Override
public boolean lock(Connection c, String key, Duration wait) throws SQLException {
execute(c, "SET lock_timeout = " + Math.max(1, wait.toMillis()));
try (PreparedStatement ps = c.prepareStatement("SELECT pg_advisory_lock(?)")) {
ps.setLong(1, lockKey(key));
ps.executeQuery().close();
return true;
} catch (SQLException e) {
if (LOCK_NOT_AVAILABLE.equals(e.getSQLState())) {
return false;
}
throw e;
}
}
@Override
public void unlock(Connection c, String key) throws SQLException {
try (PreparedStatement ps = c.prepareStatement("SELECT pg_advisory_unlock(?)")) {
ps.setLong(1, lockKey(key));
try (ResultSet rs = ps.executeQuery()) {
if (!rs.next() || !rs.getBoolean(1)) {
throw new SQLException("advisory lock was not held: " + key);
}
}
}
}
@Override
public boolean migrationLock(Connection c, String key, Duration wait) throws SQLException {
execute(c, "SET LOCAL lock_timeout = " + Math.max(1, wait.toMillis()));
try (PreparedStatement ps = c.prepareStatement("SELECT pg_advisory_xact_lock(?)")) {
ps.setLong(1, lockKey(key));
ps.executeQuery().close();
return true;
} catch (SQLException e) {
if (LOCK_NOT_AVAILABLE.equals(e.getSQLState())) {
return false;
}
throw e;
}
}
@Override
public void migrationUnlock(Connection c, String key) {
// Released by the transaction's end.
}
@Override
public boolean transactionalDdl() {
return true;
}
@Override
public void setLongTimeout(Connection c, Duration timeout) throws SQLException {
long ms = timeout.toMillis();
execute(c, "SET statement_timeout = " + ms + "; SET lock_timeout = " + ms);
}
// --- ownership --------------------------------------------------------------------------------------------
private static final String NOT_FROM_EXTENSION = " AND NOT EXISTS (SELECT 1 FROM pg_depend d WHERE d.classid = "
+ "'%s'::regclass AND d.objid = %s AND d.deptype = 'e')";
@Override
public Set<DbObject> ownedObjects(Connection c, String schema) throws SQLException {
Set<DbObject> objects = new LinkedHashSet<>();
// Relations: tables, partitioned tables, indexes (so every constraint that creates one), sequences, views,
// materialized views, foreign tables and composite types.
collect(c, schema, objects, "relation", "SELECT c.relname FROM pg_class c JOIN pg_namespace n "
+ "ON n.oid = c.relnamespace WHERE n.nspname = ? AND c.relkind IN ('r','p','i','I','S','v','m','f','c')"
+ NOT_FROM_EXTENSION.formatted("pg_class", "c.oid"));
collect(c, schema, objects, "routine", "SELECT p.proname FROM pg_proc p JOIN pg_namespace n "
+ "ON n.oid = p.pronamespace WHERE n.nspname = ?" + NOT_FROM_EXTENSION.formatted("pg_proc", "p.oid"));
// Types other than a relation's row type and array types: domains, enums, ranges (and their multiranges).
collect(c, schema, objects, "type", "SELECT t.typname FROM pg_type t JOIN pg_namespace n "
+ "ON n.oid = t.typnamespace WHERE n.nspname = ? AND t.typrelid = 0 AND t.typcategory <> 'A'"
+ NOT_FROM_EXTENSION.formatted("pg_type", "t.oid"));
return objects;
}
private static void collect(Connection c, String schema, Set<DbObject> into, String kind, String sql)
throws SQLException {
try (PreparedStatement ps = c.prepareStatement(sql)) {
ps.setString(1, schema);
try (ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
into.add(new DbObject(kind, rs.getString(1), null));
}
}
}
}
@Override
public List<String> tablesWithWrongEngine(Connection c, String schema) {
return List.of();
}
@Override
public void dropObject(Connection c, String schema, DbObject object) {
throw new UnsupportedOperationException("PostgreSQL migrations roll back instead");
}
// --- backup and restore ------------------------------------------------------------------------------------
@Override
public java.util.Map<String, List<Column>> tables(Connection c, String schema) throws SQLException {
java.util.Map<String, List<Column>> tables = new java.util.LinkedHashMap<>();
try (PreparedStatement ps = c.prepareStatement("SELECT c.table_name, c.column_name, c.data_type, "
+ "c.character_maximum_length, c.numeric_precision, c.numeric_scale, c.is_nullable, c.column_default, "
+ "c.is_identity, c.is_generated FROM information_schema.columns c JOIN information_schema.tables t "
+ "ON t.table_schema = c.table_schema AND t.table_name = c.table_name "
+ "WHERE c.table_schema = ? AND t.table_type = 'BASE TABLE' "
+ "ORDER BY c.table_name, c.ordinal_position")) {
ps.setString(1, schema);
try (ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
if ("ALWAYS".equals(rs.getString(10))) {
continue; // a generated column is derived: never backed up, never loaded
}
String type = portableType(rs.getString(3), (Integer) rs.getObject(4), (Integer) rs.getObject(5),
(Integer) rs.getObject(6));
boolean hasDefault = rs.getString(8) != null || "YES".equals(rs.getString(9));
tables.computeIfAbsent(rs.getString(1), k -> new ArrayList<>()).add(new Column(rs.getString(2),
type, "YES".equals(rs.getString(7)), hasDefault));
}
}
}
return tables;
}
static String portableType(String dataType, Integer length, Integer precision, Integer scale) {
return switch (dataType) {
case "bigint" -> "BIGINT";
case "integer" -> "INTEGER";
case "smallint" -> "SMALLINT";
case "numeric" -> precision == null ? "DECIMAL" : "DECIMAL(" + precision + "," + (scale == null ? 0 : scale)
+ ")";
case "double precision", "real" -> "DOUBLE";
case "boolean" -> "BOOLEAN";
case "character varying", "character" -> length == null ? "TEXT" : "VARCHAR(" + length + ")";
case "text" -> "TEXT";
case "date" -> "DATE";
case "time without time zone" -> "TIME";
case "timestamp without time zone" -> "TIMESTAMP";
case "timestamp with time zone" -> "TIMESTAMPTZ";
case "bytea" -> "BYTES";
case "json", "jsonb" -> "JSON";
default -> Portable.UNSUPPORTED + dataType;
};
}
@Override
public List<Sequence> sequences(Connection c, String schema) throws SQLException {
List<Sequence> out = new ArrayList<>();
try (PreparedStatement ps = c.prepareStatement("SELECT sequencename, last_value, start_value, increment_by "
+ "FROM pg_sequences WHERE schemaname = ? ORDER BY sequencename")) {
ps.setString(1, schema);
try (ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
long last = rs.getLong(2);
boolean called = !rs.wasNull();
long increment = rs.getLong(4);
out.add(new Sequence(rs.getString(1), called ? last + increment : rs.getLong(3), increment));
}
}
}
return out;
}
@Override
public void setSequence(Connection c, String schema, String name, long next) throws SQLException {
try (PreparedStatement ps = c.prepareStatement("SELECT setval(?::regclass, ?, false)")) {
ps.setString(1, quoteIdent(schema) + "." + quoteIdent(name));
ps.setLong(2, next);
ps.executeQuery().close();
}
}
@Override
public List<String> suspendForLoad(Connection c, String schema, java.util.Collection<String> tables)
throws SQLException {
List<String> restore = new ArrayList<>();
String s = quoteIdent(schema) + ".";
java.sql.Array names = c.createArrayOf("text", tables.toArray());
try (PreparedStatement ps = c.prepareStatement("SELECT t.relname, con.conname, pg_get_constraintdef(con.oid) "
+ "FROM pg_constraint con JOIN pg_class t ON t.oid = con.conrelid "
+ "JOIN pg_class r ON r.oid = con.confrelid JOIN pg_namespace n ON n.oid = con.connamespace "
+ "WHERE con.contype = 'f' AND n.nspname = ? AND (t.relname = ANY(?) OR r.relname = ANY(?)) "
+ "ORDER BY t.relname, con.conname")) {
ps.setString(1, schema);
ps.setArray(2, names);
ps.setArray(3, names);
List<String[]> fks = new ArrayList<>();
try (ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
fks.add(new String[] {rs.getString(1), rs.getString(2), rs.getString(3)});
}
}
for (String[] fk : fks) {
execute(c, "ALTER TABLE " + s + quoteIdent(fk[0]) + " DROP CONSTRAINT " + quoteIdent(fk[1]));
restore.add("ALTER TABLE " + s + quoteIdent(fk[0]) + " ADD CONSTRAINT " + quoteIdent(fk[1]) + " "
+ fk[2]);
}
}
for (String table : tables) {
execute(c, "ALTER TABLE " + s + quoteIdent(table) + " DISABLE TRIGGER USER");
restore.add("ALTER TABLE " + s + quoteIdent(table) + " ENABLE TRIGGER USER");
}
return restore;
}
@Override
public void bindValue(PreparedStatement ps, int index, String portableType, Object value) throws SQLException {
Portable.bind(ps, index, portableType, value, true);
}
@Override
public Object readValue(ResultSet rs, int index, String portableType) throws SQLException {
return Portable.read(rs, index, portableType, true);
}
@Override
public long schemaSize(Connection c, String schema) throws SQLException {
try (PreparedStatement ps = c.prepareStatement(
"SELECT COALESCE(SUM(pg_total_relation_size(c.oid)), 0) FROM pg_class c JOIN pg_namespace n "
+ "ON n.oid = c.relnamespace WHERE n.nspname = ? AND c.relkind IN ('r', 'p', 'm')")) {
ps.setString(1, schema);
try (ResultSet rs = ps.executeQuery()) {
rs.next();
return rs.getLong(1);
}
}
}
// --- failure categories -----------------------------------------------------------------------------------
@Override
public ConnectFailure classify(SQLException failure) {
if (failure instanceof UnsupportedServerException) {
return ConnectFailure.UNSUPPORTED_SERVER;
}
if (Failures.hasTlsCause(failure)) {
return ConnectFailure.TLS;
}
String state = failure.getSQLState() == null ? "" : failure.getSQLState();
// 08004 also when TLS was asked of a server that has it off: pgjdbc says "The server does not support SSL."
// (translated with the JVM's locale, but "SSL" stays), which is a TLS problem, not a refused password.
if (state.equals("08004") && failure.getMessage() != null && failure.getMessage().contains("SSL")) {
return ConnectFailure.TLS;
}
// 08004: the driver itself refuses, e.g. an empty password when the server asks for one.
if (state.equals("28P01") || state.equals("28000") || state.equals("08004")) {
return ConnectFailure.AUTHENTICATION;
}
if (state.equals("3D000")) {
return ConnectFailure.DATABASE_MISSING;
}
if (state.startsWith("08") || Failures.hasNetworkCause(failure)) {
return ConnectFailure.UNREACHABLE;
}
return ConnectFailure.OTHER;
}
static void execute(Connection c, String sql) throws SQLException {
try (Statement s = c.createStatement()) {
s.execute(sql);
}
}
/** {@code nextval}/{@code currval} on a sequence in the bound schema. */
static final class PostgresDialect implements Dialect {
@Override
public String id() {
return "postgresql";
}
@Override
public String nextValue(String sequence) {
return "nextval('" + Failures.requireSimpleName(sequence) + "')";
}
@Override
public long lastValue(Connection connection, String sequence) throws SQLException {
try (Statement s = connection.createStatement();
ResultSet rs = s.executeQuery("SELECT currval('" + Failures.requireSimpleName(sequence) + "')")) {
rs.next();
return rs.getLong(1);
}
}
@Override
public String quote(String name) {
return quoteIdent(name);
}
}
}
@@ -0,0 +1,128 @@
package mx.quest.database.internal;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Optional;
import java.util.Set;
import mx.quest.database.spi.DatabaseProvider;
import mx.quest.database.spi.ProviderSettings;
/**
* Which provider the database plugin uses, and with which settings. The {@code provider} setting is {@code auto}
* (the default: the one provider plugin installed), {@code postgresql} or {@code mariadb}; the server's settings
* come from the chosen provider plugin (since 2.0.0).
*
* <p>Every problem is refused with a reason an operator can act on, in two kinds: {@link NoProviderException} when a
* plugin must be installed or removed, plain {@link IllegalArgumentException} when a setting must change. Both are
* fixed by a restart, which is what the runtime's status says.
*/
public final class ProviderChoice {
/** The provider setting's value that picks the one installed provider. */
public static final String AUTO = "auto";
/** The provider to use and the checked settings to use it with. */
public record Chosen(DatabaseProvider provider, DatabaseConfig config) {
}
/** A provider plugin is missing, or two offer the same product: install or remove one. */
public static final class NoProviderException extends IllegalArgumentException {
NoProviderException(String message) {
super(message);
}
}
private ProviderChoice() {
}
/**
* The provider the running application uses, with its running settings.
*
* @throws NoProviderException when the chosen provider plugin is not installed, or two are
* @throws IllegalArgumentException when a setting is missing or unusable
*/
public static Chosen running(DatabaseProps props, List<DatabaseProvider> installed) {
DatabaseProvider provider = pick(props.getProvider(), installed);
String plugin = plugin(provider.id());
ProviderSettings server = provider.runningSettings().orElseThrow(() -> tooOld(plugin));
if (server.isEmpty()) {
List<String> moved = props.legacyKeys();
if (!moved.isEmpty()) {
throw new IllegalArgumentException("the server settings moved to the " + plugin + " plugin in "
+ "database 2.0.0: move " + String.join(", ", moved) + " from plugin-settings/database.yml "
+ "to plugin-settings/" + plugin + ".yml (or enter them on that plugin's settings page)");
}
throw new IllegalArgumentException("no server is set: enter it on the " + plugin
+ " plugin's settings page");
}
return new Chosen(provider, check(props, provider, server));
}
/**
* One installed provider with the settings saved for it now, for the connection test.
*
* @throws IllegalArgumentException when the saved settings are missing or unusable
*/
public static Chosen saved(DatabaseProps props, DatabaseProvider provider) {
String plugin = plugin(provider.id());
ProviderSettings server = provider.savedSettings().orElseThrow(() -> tooOld(plugin));
if (server.isEmpty()) {
throw new IllegalArgumentException("no server is saved in the " + plugin + " plugin's settings");
}
return new Chosen(provider, check(props, provider, server));
}
/** The installed providers of products this plugin has SQL for, in the order found. */
public static List<DatabaseProvider> supported(List<DatabaseProvider> installed) {
return installed.stream().filter(p -> DatabaseConfig.PROVIDERS.contains(p.id())).toList();
}
/** The provider plugin's id for a product: {@code database-postgresql}, {@code database-mariadb}. */
public static String plugin(String product) {
return "database-" + product;
}
private static DatabaseProvider pick(String setting, List<DatabaseProvider> installed) {
String choice = Optional.ofNullable(DatabaseConfig.trimToNull(setting)).orElse(AUTO).toLowerCase(Locale.ROOT);
if (!choice.equals(AUTO) && !DatabaseConfig.PROVIDERS.contains(choice)) {
throw new IllegalArgumentException("unknown provider: " + choice + " (auto, postgresql or mariadb)");
}
List<DatabaseProvider> candidates = supported(installed);
if (choice.equals(AUTO)) {
Set<String> products = new LinkedHashSet<>(candidates.stream().map(DatabaseProvider::id).toList());
if (products.isEmpty()) {
throw new NoProviderException("no provider plugin is installed: install database-postgresql or "
+ "database-mariadb");
}
if (products.size() > 1) {
throw new IllegalArgumentException("both provider plugins are installed: choose one in the provider "
+ "setting");
}
choice = products.iterator().next();
}
String product = choice;
List<DatabaseProvider> matching = candidates.stream().filter(p -> p.id().equals(product)).toList();
if (matching.isEmpty()) {
throw new NoProviderException("the provider plugin for '" + product + "' (" + plugin(product)
+ ") is not installed");
}
if (matching.size() > 1) {
throw new NoProviderException("two provider plugins offer '" + product + "'; remove one");
}
return matching.get(0);
}
private static DatabaseConfig check(DatabaseProps props, DatabaseProvider provider, ProviderSettings server) {
try {
return DatabaseConfig.from(props, provider.id(), server);
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException(plugin(provider.id()) + " settings: " + e.getMessage());
}
}
private static IllegalArgumentException tooOld(String plugin) {
return new NoProviderException("the " + plugin + " plugin is older than 2.0.0 and holds no server settings: "
+ "install " + plugin + " 2.0.0");
}
}
@@ -0,0 +1,419 @@
package mx.quest.database.internal;
import java.net.InetAddress;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
/**
* Runway's own tables in {@code <ns>_app}: which schema each site uses ({@code rw_sites}), every schema ever created
* and its state ({@code rw_schemas}), the plugin prefixes ({@code rw_plugins}), the nodes seen ({@code rw_nodes}) and
* the migration problems the health screen lists ({@code rw_issues}). Every identifier column is binary, so a site
* id never matches another by case. Plain SQL that both products accept; the names are quoted by the engine.
*/
public final class Registry {
/** A site's live mapping. */
public record SiteRow(String siteId, String schema, String token, long generation, String state) {
}
/** A schema this install created, with its state: {@code creating}, {@code live}, {@code staging},
* {@code retired}. */
public record SchemaRow(String schema, String siteId, long generation, String state, Instant changedAt) {
}
/** A migration problem for one plugin in one schema. */
public record Issue(String schema, String pluginId, String state, int version, int statement, String detail,
Instant at) {
}
/** A node seen recently. */
public record Node(String nodeId, String host, String version, Instant startedAt, Instant seenAt) {
}
static final Duration GLOBAL_LOCK_WAIT = Duration.ofSeconds(30);
static final String FORMAT = "1";
private final DatabaseRuntime runtime;
private final Engine engine;
private final String app;
private final String appQ;
private final String nodeId = UUID.randomUUID().toString();
private final String host;
private final String version;
Registry(DatabaseRuntime runtime) {
this(runtime, Registry.class.getPackage().getImplementationVersion());
}
Registry(DatabaseRuntime runtime, String version) {
this.runtime = runtime;
this.engine = runtime.engine();
this.app = Names.appSchema(runtime.config().namespace());
this.appQ = engine.quote(app);
this.host = hostName();
this.version = version == null ? "dev" : version;
}
/** The app schema's name. */
public String appSchema() {
return app;
}
/** This JVM's node id. */
public String nodeId() {
return nodeId;
}
private static String hostName() {
try {
String h = InetAddress.getLocalHost().getHostName();
return h.length() > 255 ? h.substring(0, 255) : h;
} catch (Exception e) {
return "unknown";
}
}
// --- set-up -------------------------------------------------------------------------------------------------
/** Creates the app schema and the registry tables if missing, then records this node. Idempotent. */
void ensure() throws SQLException {
runtime.locks().global("registry", GLOBAL_LOCK_WAIT, () -> {
try (Connection c = runtime.setupConnection()) {
c.setAutoCommit(true);
Names.requireOwnSchema(runtime.config().namespace(), app, engine.identifierMax());
engine.createSchema(c, app, runtime.config().collation());
try (Statement s = c.createStatement()) {
for (String ddl : engine.registryDdl(app)) {
s.execute(ddl);
}
s.execute(engine.migrationsDdl(app));
}
String key = engine.quote("key");
boolean present;
try (PreparedStatement ps = c.prepareStatement("SELECT COUNT(*) FROM " + appQ + ".rw_install WHERE "
+ key + " = 'format'")) {
try (ResultSet rs = ps.executeQuery()) {
rs.next();
present = rs.getInt(1) > 0;
}
}
if (!present) {
try (PreparedStatement ps = c.prepareStatement("INSERT INTO " + appQ + ".rw_install (" + key
+ ", value) VALUES ('format', ?)")) {
ps.setString(1, FORMAT);
ps.executeUpdate();
}
}
}
return null;
});
try (Connection c = runtime.setupConnection()) {
c.setAutoCommit(true);
heartbeat(c);
}
}
/** How long a node that stopped sending heartbeats stays in {@code rw_nodes}. */
static final String NODE_RETENTION = "INTERVAL '1' DAY";
/**
* Records that this node is alive, and forgets nodes not seen for a day: every start is a new node id, so without
* the prune the table would grow by a row per restart, and the health screen reads all of it.
*/
void heartbeat(Connection c) throws SQLException {
int updated;
try (PreparedStatement ps = c.prepareStatement("UPDATE " + appQ + ".rw_nodes SET seen_at = "
+ engine.nowSql() + " WHERE node_id = ?")) {
ps.setString(1, nodeId);
updated = ps.executeUpdate();
}
if (updated == 0) {
try (PreparedStatement ps = c.prepareStatement("INSERT INTO " + appQ + ".rw_nodes (node_id, host, "
+ "version, started_at, seen_at) VALUES (?, ?, ?, " + engine.nowSql() + ", " + engine.nowSql()
+ ")")) {
ps.setString(1, nodeId);
ps.setString(2, host);
ps.setString(3, version.length() > 32 ? version.substring(0, 32) : version);
ps.executeUpdate();
}
}
try (Statement s = c.createStatement()) {
s.executeUpdate("DELETE FROM " + appQ + ".rw_nodes WHERE seen_at < " + engine.nowSql() + " - "
+ NODE_RETENTION);
}
}
// --- sites ----------------------------------------------------------------------------------------------------
/** A site's mapping, read on a consumer connection that is not bound to anything yet. */
Optional<SiteRow> site(Connection c, String siteId) throws SQLException {
try (PreparedStatement ps = c.prepareStatement("SELECT site_id, schema_name, token, generation, state FROM "
+ appQ + ".rw_sites WHERE site_id = ?")) {
ps.setString(1, siteId);
try (ResultSet rs = ps.executeQuery()) {
if (!rs.next()) {
return Optional.empty();
}
return Optional.of(new SiteRow(rs.getString(1), rs.getString(2), rs.getString(3), rs.getLong(4),
rs.getString(5)));
}
}
}
/** Every site mapping. */
List<SiteRow> sites(Connection c) throws SQLException {
List<SiteRow> rows = new ArrayList<>();
try (Statement s = c.createStatement();
ResultSet rs = s.executeQuery("SELECT site_id, schema_name, token, generation, state FROM " + appQ
+ ".rw_sites ORDER BY site_id")) {
while (rs.next()) {
rows.add(new SiteRow(rs.getString(1), rs.getString(2), rs.getString(3), rs.getLong(4),
rs.getString(5)));
}
}
return rows;
}
/** The next generation number. */
long nextGeneration(Connection c) throws SQLException {
return engine.nextGeneration(c, app);
}
/** Records a new schema before it is created, so a crash leaves a row the reconcile sweep can act on. */
void insertSchema(Connection c, String schema, String siteId, long generation, String state) throws SQLException {
try (PreparedStatement ps = c.prepareStatement("INSERT INTO " + appQ + ".rw_schemas (schema_name, site_id, "
+ "generation, state, changed_at) VALUES (?, ?, ?, ?, " + engine.nowSql() + ")")) {
ps.setString(1, schema);
ps.setString(2, siteId);
ps.setLong(3, generation);
ps.setString(4, state);
ps.executeUpdate();
}
}
/** Changes a schema's state. */
void schemaState(Connection c, String schema, String state) throws SQLException {
try (PreparedStatement ps = c.prepareStatement("UPDATE " + appQ + ".rw_schemas SET state = ?, changed_at = "
+ engine.nowSql() + " WHERE schema_name = ?")) {
ps.setString(1, state);
ps.setString(2, schema);
ps.executeUpdate();
}
}
/**
* Moves a schema from one state to another only when it is in {@code from} and no site maps to it.
*
* @return whether it moved
*/
boolean schemaStateIfUnmapped(Connection c, String schema, String from, String to) throws SQLException {
try (PreparedStatement ps = c.prepareStatement("UPDATE " + appQ + ".rw_schemas SET state = ?, changed_at = "
+ engine.nowSql() + " WHERE schema_name = ? AND state = ? AND NOT EXISTS (SELECT 1 FROM " + appQ
+ ".rw_sites WHERE schema_name = ?)")) {
ps.setString(1, to);
ps.setString(2, schema);
ps.setString(3, from);
ps.setString(4, schema);
return ps.executeUpdate() == 1;
}
}
/** Whether a site maps to the schema. */
boolean isMapped(Connection c, String schema) throws SQLException {
try (PreparedStatement ps = c.prepareStatement("SELECT 1 FROM " + appQ + ".rw_sites WHERE schema_name = ?")) {
ps.setString(1, schema);
try (var rs = ps.executeQuery()) {
return rs.next();
}
}
}
/** Forgets a dropped schema. */
void deleteSchema(Connection c, String schema) throws SQLException {
try (PreparedStatement ps = c.prepareStatement("DELETE FROM " + appQ + ".rw_schemas WHERE schema_name = ?")) {
ps.setString(1, schema);
ps.executeUpdate();
}
try (PreparedStatement ps = c.prepareStatement("DELETE FROM " + appQ + ".rw_issues WHERE schema_name = ?")) {
ps.setString(1, schema);
ps.executeUpdate();
}
}
/** Every schema this install recorded, with the database's own current time for age comparisons. */
record Schemas(List<SchemaRow> rows, Instant now) {
}
Schemas schemas(Connection c) throws SQLException {
List<SchemaRow> rows = new ArrayList<>();
Instant now = null;
try (Statement s = c.createStatement();
ResultSet rs = s.executeQuery("SELECT schema_name, site_id, generation, state, changed_at, "
+ engine.nowSql() + " FROM " + appQ + ".rw_schemas ORDER BY schema_name")) {
while (rs.next()) {
rows.add(new SchemaRow(rs.getString(1), rs.getString(2), rs.getLong(3), rs.getString(4),
engine.instant(rs, 5)));
now = engine.instant(rs, 6);
}
}
if (now == null) {
try (Statement s = c.createStatement(); ResultSet rs = s.executeQuery("SELECT " + engine.nowSql())) {
rs.next();
now = engine.instant(rs, 1);
}
}
return new Schemas(rows, now);
}
/** Points a site at a schema (insert or replace), in the caller's transaction. */
void putSite(Connection c, String siteId, String schema, String token, long generation, String state)
throws SQLException {
deleteSite(c, siteId);
try (PreparedStatement ps = c.prepareStatement("INSERT INTO " + appQ + ".rw_sites (site_id, schema_name, "
+ "token, generation, state, created_at) VALUES (?, ?, ?, ?, ?, " + engine.nowSql() + ")")) {
ps.setString(1, siteId);
ps.setString(2, schema);
ps.setString(3, token);
ps.setLong(4, generation);
ps.setString(5, state);
ps.executeUpdate();
}
}
/** Sets a site row's state. */
void siteState(Connection c, String siteId, String schema, String state) throws SQLException {
try (PreparedStatement ps = c.prepareStatement("UPDATE " + appQ + ".rw_sites SET state = ? "
+ "WHERE site_id = ? AND schema_name = ?")) {
ps.setString(1, state);
ps.setString(2, siteId);
ps.setString(3, schema);
ps.executeUpdate();
}
}
/** Removes a site's mapping. */
void deleteSite(Connection c, String siteId) throws SQLException {
try (PreparedStatement ps = c.prepareStatement("DELETE FROM " + appQ + ".rw_sites WHERE site_id = ?")) {
ps.setString(1, siteId);
ps.executeUpdate();
}
}
// --- plugins --------------------------------------------------------------------------------------------------
/** Every recorded plugin prefix, by plugin id. */
Map<String, String> prefixes(Connection c) throws SQLException {
Map<String, String> map = new LinkedHashMap<>();
try (Statement s = c.createStatement();
ResultSet rs = s.executeQuery("SELECT plugin_id, prefix FROM " + appQ
+ ".rw_plugins ORDER BY plugin_id")) {
while (rs.next()) {
map.put(rs.getString(1), rs.getString(2));
}
}
return map;
}
/** Records a plugin's prefix. */
void insertPrefix(Connection c, String pluginId, String prefix) throws SQLException {
try (PreparedStatement ps = c.prepareStatement("INSERT INTO " + appQ + ".rw_plugins (plugin_id, prefix, "
+ "first_seen) VALUES (?, ?, " + engine.nowSql() + ")")) {
ps.setString(1, pluginId);
ps.setString(2, prefix);
ps.executeUpdate();
}
}
// --- issues ---------------------------------------------------------------------------------------------------
/** Records (or replaces) the problem a plugin has in a schema. */
void putIssue(Connection c, String schema, String pluginId, String state, int version, int statement,
String detail) throws SQLException {
clearIssue(c, schema, pluginId);
try (PreparedStatement ps = c.prepareStatement("INSERT INTO " + appQ + ".rw_issues (schema_name, plugin_id, "
+ "state, version, statement, detail, at) VALUES (?, ?, ?, ?, ?, ?, " + engine.nowSql() + ")")) {
ps.setString(1, schema);
ps.setString(2, pluginId);
ps.setString(3, state);
ps.setInt(4, version);
ps.setInt(5, statement);
ps.setString(6, detail.length() > 1000 ? detail.substring(0, 999) + "…" : detail);
ps.executeUpdate();
}
}
/** A plugin's recorded problem in a schema, if any. */
Optional<Issue> issue(Connection c, String schema, String pluginId) throws SQLException {
try (PreparedStatement ps = c.prepareStatement("SELECT schema_name, plugin_id, state, version, statement, "
+ "detail, at FROM " + appQ + ".rw_issues WHERE schema_name = ? AND plugin_id = ?")) {
ps.setString(1, schema);
ps.setString(2, pluginId);
try (ResultSet rs = ps.executeQuery()) {
return rs.next() ? Optional.of(new Issue(rs.getString(1), rs.getString(2), rs.getString(3),
rs.getInt(4), rs.getInt(5), rs.getString(6), engine.instant(rs, 7))) : Optional.empty();
}
}
}
/** Clears a plugin's problem in a schema. */
void clearIssue(Connection c, String schema, String pluginId) throws SQLException {
try (PreparedStatement ps = c.prepareStatement("DELETE FROM " + appQ + ".rw_issues WHERE schema_name = ? "
+ "AND plugin_id = ?")) {
ps.setString(1, schema);
ps.setString(2, pluginId);
ps.executeUpdate();
}
}
/** Every recorded problem (screens read on the main pool: the setup pool may be busy with a long job). */
public List<Issue> issues() throws SQLException {
List<Issue> issues = new ArrayList<>();
try (Connection c = runtime.borrow(); Statement s = c.createStatement();
ResultSet rs = s.executeQuery("SELECT schema_name, plugin_id, state, version, statement, detail, at FROM "
+ appQ + ".rw_issues ORDER BY schema_name, plugin_id")) {
while (rs.next()) {
issues.add(new Issue(rs.getString(1), rs.getString(2), rs.getString(3), rs.getInt(4), rs.getInt(5),
rs.getString(6), engine.instant(rs, 7)));
}
}
return issues;
}
/** The nodes seen within {@code window}. */
public List<Node> nodes(Duration window) throws SQLException {
List<Node> nodes = new ArrayList<>();
Instant now = null;
try (Connection c = runtime.borrow(); Statement s = c.createStatement();
ResultSet rs = s.executeQuery("SELECT node_id, host, version, started_at, seen_at, " + engine.nowSql()
+ " FROM " + appQ + ".rw_nodes ORDER BY seen_at DESC")) {
while (rs.next()) {
now = engine.instant(rs, 6);
Instant seen = engine.instant(rs, 5);
if (seen != null && seen.isAfter(now.minus(window))) {
nodes.add(new Node(rs.getString(1), rs.getString(2), rs.getString(3), engine.instant(rs, 4), seen));
}
}
}
return nodes;
}
/** Counts live site schemas. */
public int liveSchemaCount() throws SQLException {
try (Connection c = runtime.borrow(); Statement s = c.createStatement();
ResultSet rs = s.executeQuery("SELECT COUNT(*) FROM " + appQ + ".rw_sites")) {
rs.next();
return rs.getInt(1);
}
}
}
@@ -0,0 +1,200 @@
package mx.quest.database.internal;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Objects;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import mx.quest.database.spi.DatabaseException;
import mx.quest.database.spi.DatabaseUnavailableException;
import mx.quest.database.spi.Scope;
import mx.quest.database.spi.ScopeNotReadyException;
import mx.quest.database.spi.SqlWork;
/**
* One consumer's scope: a site's schema or the app schema. Each outer call takes the site's in-flight slot, borrows
* one connection, binds it (checking the mapping in the same round trip), runs the work in one transaction and hands
* the connection back reset. A call on the same scope from inside the work joins the outer call; a call on another
* scope from inside it throws, so a consumer cannot hold two connections and starve the pool.
*/
final class ScopeImpl implements Scope {
/** The outer call this thread is inside, if any. */
private static final ThreadLocal<Active> ACTIVE = new ThreadLocal<>();
private record Active(String key, Connection connection, boolean readOnly) {
}
private final DatabaseCore core;
private final Consumer consumer;
private final Kind kind;
private final String siteId;
private final String key;
ScopeImpl(DatabaseCore core, Consumer consumer, Kind kind, String siteId) {
this.core = core;
this.consumer = consumer;
this.kind = kind;
this.siteId = siteId;
this.key = consumer.pluginId() + "|" + kind + "|" + (siteId == null ? "" : siteId);
}
@Override
public Kind kind() {
return kind;
}
@Override
public String siteId() {
return siteId;
}
@Override
public <T> T transaction(SqlWork<T> work) {
return call(work, false);
}
@Override
public <T> T read(SqlWork<T> work) {
return call(work, true);
}
private <T> T call(SqlWork<T> work, boolean readOnly) {
Objects.requireNonNull(work, "work");
Active active = ACTIVE.get();
if (active != null) {
if (!active.key().equals(key)) {
throw new IllegalStateException("a database call on one scope from inside a call on another scope; "
+ "finish the first call before starting the second");
}
if (active.readOnly() && !readOnly) {
throw new IllegalStateException("transaction() inside read(): a read-only call cannot write");
}
return runJoined(work, active.connection());
}
if (!consumer.scopes().contains(kind)) {
throw new IllegalStateException("plugin '" + consumer.pluginId() + "' did not declare the " + kind
+ " scope in its DatabaseConsumer");
}
DatabaseRuntime runtime = core.runtime();
if (!runtime.available()) {
throw new DatabaseUnavailableException("the database is not available");
}
Semaphore slots = kind == Kind.SITE ? core.siteSlots(siteId) : core.appSlots();
try {
if (!slots.tryAcquire(DatabaseRuntime.BORROW_TIMEOUT.toMillis(), TimeUnit.MILLISECONDS)) {
throw new DatabaseUnavailableException("too many database calls in flight for site '" + siteId + "'");
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new DatabaseUnavailableException("interrupted while waiting for a database connection");
}
try {
for (int attempt = 0; attempt < 2; attempt++) {
String schema = kind == Kind.SITE ? core.schemas().resolve(siteId)
: Names.appSchema(runtime.config().namespace());
core.migrator().ensure(consumer, kind, siteId, schema);
Connection c = runtime.borrow();
boolean bound;
try {
bound = bind(c, schema);
} catch (SQLException | RuntimeException e) {
runtime.evict(c);
throw new DatabaseUnavailableException("the connection could not be bound to the site's data", e);
}
if (!bound) {
close(c, false);
core.schemas().evict(siteId); // the mapping changed on another node: resolve again
continue;
}
return runOuter(work, c, readOnly);
}
throw new ScopeNotReadyException(ScopeNotReadyException.Reason.PREPARING,
"the site's data moved while the call started; try again");
} finally {
slots.release();
}
}
private boolean bind(Connection c, String schema) throws SQLException {
DatabaseRuntime runtime = core.runtime();
Engine engine = runtime.engine();
if (kind == Kind.SITE) {
return engine.bindSite(c, runtime.registry().appSchema(), siteId, schema,
runtime.config().statementTimeout());
}
engine.bind(c, schema, runtime.config().statementTimeout());
return true;
}
private <T> T runOuter(SqlWork<T> work, Connection c, boolean readOnly) {
Engine engine = core.runtime().engine();
boolean broken = false;
try {
c.setAutoCommit(false);
if (readOnly) {
c.setReadOnly(true);
c.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
engine.beginRead(c);
}
} catch (SQLException e) {
close(c, true);
throw new DatabaseUnavailableException("the connection could not start a transaction", e);
}
ACTIVE.set(new Active(key, c, readOnly));
try {
T result = work.run(c);
c.commit();
return result;
} catch (SQLException e) {
broken = !rollback(c);
throw new DatabaseException("the database call failed: " + DatabaseRuntime.describe(e), e);
} catch (RuntimeException | Error e) {
broken = !rollback(c);
throw e;
} finally {
ACTIVE.remove();
close(c, broken);
}
}
/** A call joined to the outer one: the same connection, no commit of its own; a throw rolls back the outer. */
private static <T> T runJoined(SqlWork<T> work, Connection c) {
try {
return work.run(c);
} catch (SQLException e) {
throw new DatabaseException("the database call failed: " + DatabaseRuntime.describe(e), e);
}
}
private static boolean rollback(Connection c) {
try {
c.rollback();
return true;
} catch (SQLException e) {
return false;
}
}
/** Resets and returns a connection, or throws it away when it may carry state the next borrower must not see. */
private void close(Connection c, boolean broken) {
DatabaseRuntime runtime = core.runtime();
if (!broken) {
try {
c.setAutoCommit(true);
runtime.engine().reset(c);
} catch (SQLException | RuntimeException e) {
broken = true;
}
}
if (broken) {
runtime.evict(c);
return;
}
try {
c.close();
} catch (SQLException ignored) {
// the pool discards it
}
}
}
@@ -0,0 +1,41 @@
package mx.quest.database.internal;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import java.util.TreeSet;
/** The few reads the console screens need from inside this package. */
public final class ScreenQueries {
private ScreenQueries() {
}
/** The plugins that keep tables in the app schema (they do not move with a change of database). */
public static List<String> appSchemaPlugins(DatabaseRuntime runtime) throws SQLException {
try (Connection c = runtime.borrow()) {
Map<String, String> prefixes = runtime.registry().prefixes(c);
TreeSet<String> plugins = new TreeSet<>();
for (String table : runtime.engine().tables(c, runtime.registry().appSchema()).keySet()) {
String owner = DatabaseBackup.owner(table, prefixes);
if (owner != null) {
plugins.add(owner);
}
}
return List.copyOf(plugins);
}
}
/** The size of a site's live schema in bytes, read on the main pool (it fails fast); empty when it has none. */
public static java.util.OptionalLong siteSize(DatabaseRuntime runtime, String siteId) throws SQLException {
try (Connection c = runtime.borrow()) {
java.util.Optional<Registry.SiteRow> row = runtime.registry().site(c, siteId);
if (row.isEmpty() || !Names.isSiteSchema(runtime.config().namespace(), row.get().schema(),
runtime.engine().identifierMax())) {
return java.util.OptionalLong.empty();
}
return java.util.OptionalLong.of(runtime.engine().schemaSize(c, row.get().schema()));
}
}
}
@@ -0,0 +1,14 @@
package mx.quest.database.internal;
import java.io.IOException;
import java.util.Optional;
/** A consumer plugin's migration scripts, by entry name ({@code db/<pluginId>/<dialect>/<app|site>/…}). */
public interface ScriptSource {
/** The plugin the scripts belong to. */
String pluginId();
/** An entry's bytes, or empty when the entry does not exist. */
Optional<byte[]> read(String entry) throws IOException;
}
@@ -0,0 +1,166 @@
package mx.quest.database.internal;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Migration scripts as text: the {@code index} file, the checksum and the statement splitting. Pure functions.
*
* <ul>
* <li>The index lists one script per line, {@code V<n>__<name>.sql}, in order; blank lines and {@code #} comments
* are skipped. Versions must start at 1 and rise by one, so a missing or reordered script is caught when the
* plugin starts using the database, not half-way through a migration.</li>
* <li>The checksum is the SHA-256 of the normalized text: BOM stripped, CRLF and CR turned into LF, trailing
* whitespace trimmed from every line and from the end. Comments stay in: MariaDB runs {@code /*! … *}{@code /}
* comments.</li>
* <li>Statements are separated by a line holding only {@value #SEPARATOR}. Each chunk is one
* {@code Statement.execute}. A chunk that switches the connection elsewhere ({@code USE},
* {@code SET search_path}, {@code SET SESSION}) is refused before anything runs.</li>
* </ul>
*/
public final class Scripts {
/** The statement separator line. */
public static final String SEPARATOR = "-- runway:next";
/** The largest script read, in bytes. */
public static final int MAX_SCRIPT_BYTES = 1 << 20;
private static final Pattern SCRIPT_NAME = Pattern.compile("V([1-9][0-9]{0,8})__([A-Za-z0-9_]{1,100})\\.sql");
private static final Pattern REFUSED = Pattern.compile(
"(?is)^(use\\b|set\\s+(session\\b|local\\s+search_path\\b|search_path\\b)|"
+ "select\\s+set_config\\s*\\(\\s*'search_path')");
private Scripts() {
}
/** One entry of an index. */
public record Entry(int version, String fileName) {
}
/**
* Parses an index file.
*
* @throws IllegalArgumentException on a malformed name, a duplicate, or a version that does not follow
*/
public static List<Entry> parseIndex(String text) {
List<Entry> entries = new ArrayList<>();
int line = 0;
for (String raw : normalize(text).split("\n", -1)) {
line++;
String name = raw.strip();
if (name.isEmpty() || name.startsWith("#")) {
continue;
}
Matcher m = SCRIPT_NAME.matcher(name);
if (!m.matches()) {
throw new IllegalArgumentException("index line " + line + " is not V<n>__<name>.sql: " + name);
}
int version = Integer.parseInt(m.group(1));
int expected = entries.size() + 1;
if (version != expected) {
throw new IllegalArgumentException("index line " + line + ": expected V" + expected + ", found "
+ name);
}
entries.add(new Entry(version, name));
}
return List.copyOf(entries);
}
/** Decodes script bytes as UTF-8 and normalizes them (see the class comment). */
public static String normalize(byte[] bytes) {
return normalize(new String(bytes, StandardCharsets.UTF_8));
}
/** Normalizes script text (see the class comment). */
public static String normalize(String text) {
String s = text;
if (!s.isEmpty() && s.charAt(0) == '') {
s = s.substring(1);
}
s = s.replace("\r\n", "\n").replace('\r', '\n');
StringBuilder out = new StringBuilder(s.length());
for (String line : s.split("\n", -1)) {
out.append(line.stripTrailing()).append('\n');
}
return out.toString().stripTrailing();
}
/** The checksum of normalized text. */
public static String checksum(String normalized) {
return Names.sha256Hex(normalized);
}
/**
* Splits normalized text into statements, skipping chunks that hold only whitespace and comments.
*
* @throws IllegalArgumentException when a statement would switch the connection's schema or session
*/
public static List<String> split(String normalized) {
List<String> statements = new ArrayList<>();
StringBuilder chunk = new StringBuilder();
for (String line : normalized.split("\n", -1)) {
if (line.strip().equals(SEPARATOR)) {
add(statements, chunk.toString());
chunk.setLength(0);
} else {
chunk.append(line).append('\n');
}
}
add(statements, chunk.toString());
return List.copyOf(statements);
}
private static void add(List<String> statements, String chunk) {
String body = chunk.strip();
String code = withoutLeadingComments(body);
if (code.isEmpty()) {
return;
}
if (REFUSED.matcher(code).find()) {
throw new IllegalArgumentException("statement " + (statements.size() + 1) + " changes the connection's "
+ "schema or session, which a migration may not do: " + firstLine(code));
}
statements.add(body);
}
/**
* The text after any leading whitespace, {@code --} line comments and ordinary block comments. A MariaDB
* executable comment ({@code /*!}) is code, so it ends the stripping and is checked like any statement.
*/
static String withoutLeadingComments(String text) {
int i = 0;
int n = text.length();
while (i < n) {
char c = text.charAt(i);
if (Character.isWhitespace(c)) {
i++;
} else if (text.startsWith("--", i)) {
int end = text.indexOf('\n', i);
i = end < 0 ? n : end + 1;
} else if (text.startsWith("/*", i) && !text.startsWith("/*!", i)) {
int end = text.indexOf("*/", i + 2);
i = end < 0 ? n : end + 2;
} else {
break;
}
}
String rest = text.substring(i);
if (rest.startsWith("/*!")) {
// Check what the executable comment runs: /*!USE x*/ or /*!50000 USE x*/.
String inner = rest.substring(3).replaceFirst("^[0-9]{5,6}", "");
return inner.stripLeading();
}
return rest;
}
private static String firstLine(String code) {
int nl = code.indexOf('\n');
String line = nl < 0 ? code : code.substring(0, nl);
return line.length() > 80 ? line.substring(0, 80) + "…" : line;
}
}
@@ -0,0 +1,752 @@
package mx.quest.database.internal;
import java.io.IOException;
import java.security.SecureRandom;
import java.sql.Connection;
import java.sql.SQLException;
import java.time.Duration;
import java.time.Instant;
import java.util.HashSet;
import java.util.HexFormat;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
import mx.quest.database.spi.DatabaseUnavailableException;
import mx.quest.database.spi.ScopeNotReadyException;
import mx.quest.runway.spi.service.PluginSiteFiles;
import mx.quest.runway.spi.service.Sites;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Which schema holds a site's data, and its life: allocation the first time a site uses the database, retirement
* when the site is deleted or the mapping turns out to belong to an earlier site with the same id, and removal.
*
* <p><b>The incarnation token.</b> Allocation records the mapping with a random token and then writes the same token,
* with the site id it was issued for, to the site's own folder ({@value #TOKEN_FILE}); every resolution compares the
* two. What the folder says decides:
* <ul>
* <li><b>the same token</b>: the mapping is the site's;</li>
* <li><b>a token issued for another site id, or the {@code fresh} marker</b>: the folder came with another site's
* backup, or the site is new. It must never bind to the data the registry has for the id, so that mapping is
* retired and a new generation is allocated. Creating a site retires such data at once
* ({@link #retireEarlierSite}), or marks the folder when the database cannot be reached;</li>
* <li><b>another token of this site, or the {@code adopt} marker</b>: a restore put back a folder from another
* moment of the same site (a backup carries the token of the generation that was live when it was taken). The
* registry is the authority: the live mapping's token is written back and its data stays. Retiring here would
* lose a site's data to an ordinary restore, or to one that failed half way;</li>
* <li><b>no token file</b> with live data mapped: a restore whose first step has not run yet, or a site re-created
* while the plugin was off. Neither binding nor retiring is safe, so resolution answers "being prepared"; the
* restore writes the token back, or the sweep retires the data after finding no token on two passes;</li>
* <li><b>a folder that cannot be read</b>: nothing is decided and nothing is changed; the call fails as
* unavailable and the sweep skips the site. "Cannot tell" is never taken for "absent".</li>
* </ul>
* The registry is changed first and the token written after, so a failure between the two leaves a folder that does
* not name the new mapping, which is then retired (allocation) or adopted (a restore's switch), never an old mapping
* named by a new folder.
*
* <p><b>Caching.</b> A resolved mapping is cached per node; every borrow re-checks it against the registry in the
* same round trip that binds the connection ({@link Engine#bindSite}), so a mapping changed on another node is
* noticed at once.
*/
public final class SiteSchemas {
private static final Logger log = LoggerFactory.getLogger(SiteSchemas.class);
/** The token file in the site's database folder; declared personal, so transfer copies leave it out. */
public static final String TOKEN_FILE = "schema.yml";
/** The line a restore writes when it cannot reach the database: adopt whatever the registry has live. */
static final String ADOPT_LINE = "adopt: live";
/**
* The line written when a site is created (or restored from a backup without database data) while the database
* cannot be reached: whatever the registry has for this id belongs to an earlier site, never to this one.
*/
static final String FRESH_LINE = "fresh: new site";
static final Duration PREPARE_WAIT = Duration.ofSeconds(10);
static final Duration DROP_WAIT = Duration.ofSeconds(60);
static final Duration RETIRED_GRACE = Duration.ofMinutes(10);
static final String CREATING = "creating";
static final String LIVE = "live";
static final String STAGING = "staging";
static final String RETIRED = "retired";
static final String DROPPING = "dropping";
private static final SecureRandom RANDOM = new SecureRandom();
private final DatabaseRuntime runtime;
private final PluginSiteFiles files;
private final Sites sites;
private final Map<String, String> cache = new ConcurrentHashMap<>();
/** Sites whose folder had no token on the sweep's last pass (with live data mapped). */
private final Set<String> absentLastSweep = ConcurrentHashMap.newKeySet();
/** A test seam: runs after the sweep has read the registry and before it acts on what it read. */
volatile Runnable afterSweepSnapshot = () -> { };
public SiteSchemas(DatabaseRuntime runtime, PluginSiteFiles files, Sites sites) {
this.runtime = runtime;
this.files = files;
this.sites = sites;
}
/**
* The live schema for a site, allocating it the first time.
*
* @throws ScopeNotReadyException when another node or thread is preparing the site's data for too long
*/
public String resolve(String siteId) {
String cached = cache.get(siteId);
if (cached != null) {
return cached;
}
Folder folder = folderOrUnavailable(siteId);
Optional<Registry.SiteRow> row;
try (Connection c = runtime.borrow()) {
row = runtime.registry().site(c, siteId);
} catch (SQLException e) {
if (DatabaseRuntime.isConnectionFailure(e)) {
runtime.markOutage(e);
}
throw new DatabaseUnavailableException("the database is not reachable", e);
}
if (row.isPresent() && LIVE.equals(row.get().state()) && folder.names(row.get())) {
cache.put(siteId, row.get().schema());
return row.get().schema();
}
return allocate(siteId);
}
/** Forgets a cached mapping (a failed bind, a site event, a restore). */
public void evict(String siteId) {
cache.remove(siteId);
}
/** Forgets every cached mapping. */
void evictAll() {
cache.clear();
}
private String allocate(String siteId) {
try {
String schema = runtime.locks().site(siteId, PREPARE_WAIT, () -> allocateLocked(siteId));
cache.put(siteId, schema);
return schema;
} catch (Locks.LockTimeoutException e) {
throw new ScopeNotReadyException(ScopeNotReadyException.Reason.PREPARING,
"site data is being prepared; try again shortly");
} catch (SQLException e) {
if (DatabaseRuntime.isConnectionFailure(e)) {
runtime.markOutage(e); // not for a busy setup pool or a refused statement: those fail this call only
}
throw new DatabaseUnavailableException("the site's schema could not be prepared: "
+ DatabaseRuntime.describe(e), e);
} catch (UnreadableFolderException e) {
throw unavailable(e);
}
}
private String allocateLocked(String siteId) throws SQLException {
Registry registry = runtime.registry();
Engine engine = runtime.engine();
String ns = runtime.config().namespace();
try (Connection c = runtime.setupConnection()) {
c.setAutoCommit(true);
Folder folder = folder(siteId);
Optional<Registry.SiteRow> row = registry.site(c, siteId);
if (row.isPresent() && folder.names(row.get())) {
Registry.SiteRow r = row.get();
if (LIVE.equals(r.state())) {
return r.schema();
}
if (CREATING.equals(r.state())) {
create(c, siteId, r.schema()); // finish what a crash interrupted
return r.schema();
}
}
if (row.isPresent() && LIVE.equals(row.get().state()) && folder.adoptable()) {
adopt(siteId, row.get(), folder);
return row.get().schema();
}
if (row.isPresent() && LIVE.equals(row.get().state()) && folder.state() == FolderState.ABSENT) {
// No token at all: a restore whose first step has not run yet (it writes the token back), or a site
// re-created while the plugin was off. Binding could hand an earlier site's data to a new one, and
// retiring could lose a restored site's live data: neither is done here. The restore settles it, or
// the sweep retires the data when it finds the folder still empty on its next pass.
throw new ScopeNotReadyException(ScopeNotReadyException.Reason.PREPARING,
"site data is being prepared; try again shortly");
}
if (sites.find(siteId).isEmpty()) {
throw new IllegalArgumentException("no site with id " + siteId);
}
String fresh = newToken();
long generation = registry.nextGeneration(c);
String schema = Names.requireOwnSchema(ns, Names.siteSchema(ns, siteId, generation,
engine.identifierMax()), engine.identifierMax());
c.setAutoCommit(false);
try {
if (row.isPresent()) {
// The folder says the data is not this site's (an earlier site with this id, a token copied from
// another site, or a crashed allocation). Never bind to it; retire it in the same transaction
// that records the new generation.
log.info("database: site '{}' has a schema '{}' from an earlier site with the same id; retiring "
+ "it", siteId, row.get().schema());
registry.deleteSite(c, siteId);
registry.schemaState(c, row.get().schema(), RETIRED);
}
registry.insertSchema(c, schema, siteId, generation, CREATING);
registry.putSite(c, siteId, schema, fresh, generation, CREATING);
c.commit();
} catch (SQLException | RuntimeException e) {
c.rollback();
throw e;
} finally {
c.setAutoCommit(true);
}
// After the commit: if the folder cannot take it (the site was just deleted), the folder names nothing,
// the CREATING row is retired on the next use and the sweep drops it.
writeToken(siteId, fresh);
create(c, siteId, schema);
log.info("database: site '{}' now keeps its data in schema '{}'", siteId, schema);
return schema;
}
}
/** Creates a recorded schema and its migrations table, then marks it live. */
private void create(Connection c, String siteId, String schema) throws SQLException {
Engine engine = runtime.engine();
Names.requireOwnSchema(runtime.config().namespace(), schema, engine.identifierMax());
engine.createSchema(c, schema, runtime.config().collation());
Jdbc.execute(c, engine.migrationsDdl(schema));
c.setAutoCommit(false);
try {
runtime.registry().schemaState(c, schema, LIVE);
runtime.registry().siteState(c, siteId, schema, LIVE);
c.commit();
} catch (SQLException | RuntimeException e) {
c.rollback();
throw e;
} finally {
c.setAutoCommit(true);
}
}
/** Removes a site's mapping and marks its schema retired, in one transaction; the sweep drops it later. */
void retire(Connection c, String siteId, String schema) throws SQLException {
boolean auto = c.getAutoCommit();
c.setAutoCommit(false);
try {
runtime.registry().deleteSite(c, siteId);
runtime.registry().schemaState(c, schema, RETIRED);
c.commit();
} catch (SQLException | RuntimeException e) {
c.rollback();
throw e;
} finally {
c.setAutoCommit(auto);
}
evict(siteId);
}
// --- staging generations (restore) -----------------------------------------------------------------------------
/** A new, empty generation for a site that no reader resolves to; the caller holds the site lock. */
String createStaging(String siteId) throws SQLException {
Engine engine = runtime.engine();
String ns = runtime.config().namespace();
try (Connection c = runtime.setupConnection()) {
c.setAutoCommit(true);
long generation = runtime.registry().nextGeneration(c);
String schema = Names.requireOwnSchema(ns, Names.siteSchema(ns, siteId, generation,
engine.identifierMax()), engine.identifierMax());
runtime.registry().insertSchema(c, schema, siteId, generation, STAGING);
engine.createSchema(c, schema, runtime.config().collation());
Jdbc.execute(c, engine.migrationsDdl(schema));
return schema;
}
}
/** The generation number recorded for a schema. */
long generationOf(Connection c, String schema) throws SQLException {
return runtime.registry().schemas(c).rows().stream().filter(r -> r.schema().equals(schema))
.mapToLong(Registry.SchemaRow::generation).findFirst()
.orElseThrow(() -> new SQLException("schema not recorded: " + schema));
}
/**
* Makes a staging generation the site's live one: one transaction points the registry at it and retires the
* previous generation, then the fresh token goes to the site folder. If that write fails, the folder still names
* the previous generation, and the next resolution adopts the registry's (the restored data). The caller holds the
* site lock.
*/
void switchTo(String siteId, String staging) throws SQLException {
Registry registry = runtime.registry();
String fresh = newToken();
try (Connection c = runtime.setupConnection()) {
c.setAutoCommit(true);
Optional<Registry.SiteRow> previous = registry.site(c, siteId);
long generation = generationOf(c, staging);
c.setAutoCommit(false);
try {
if (previous.isPresent()) {
registry.schemaState(c, previous.get().schema(), RETIRED);
}
registry.putSite(c, siteId, staging, fresh, generation, LIVE);
registry.schemaState(c, staging, LIVE);
c.commit();
} catch (SQLException | RuntimeException e) {
c.rollback();
throw e;
} finally {
c.setAutoCommit(true);
}
}
evict(siteId);
try {
writeToken(siteId, fresh);
} catch (RuntimeException e) {
log.warn("database: site '{}' now uses schema '{}', but its folder could not take the new token; it is "
+ "written on the next use: {}", siteId, staging, DatabaseRuntime.describe(e));
}
}
/**
* The first step of a restore, after the kernel has swapped in the archive's folder: makes the folder name the
* live generation again, so whatever the rest of the restore does (finish, fail, or find no database data in the
* archive), the site keeps the data it had until a restore actually replaces it. With the database unreachable, a
* folder left without a token gets the {@code adopt} marker instead, which the next resolution honours.
*
* @param wait how long to wait for the site lock
* @throws UnreadableFolderException when the folder cannot be read (the restore then stops; nothing was changed)
*/
void keepLiveDataAcrossRestore(String siteId, Duration wait) {
Folder folder = folder(siteId);
if (runtime.available()) {
try {
runtime.locks().site(siteId, wait, () -> {
try (Connection c = runtime.setupConnection()) {
c.setAutoCommit(true);
Optional<Registry.SiteRow> row = runtime.registry().site(c, siteId);
Folder now = folder(siteId);
if (row.isPresent() && LIVE.equals(row.get().state()) && !now.names(row.get())) {
if (now.state() == FolderState.ABSENT || now.adoptable()) {
adopt(siteId, row.get(), now);
} else {
retire(c, siteId, row.get().schema()); // a token another site was given, or new site
}
}
}
return null;
});
return;
} catch (SQLException | RuntimeException e) {
log.warn("database: could not re-check the live data of restored site '{}': {}", siteId,
DatabaseRuntime.describe(e));
}
}
if (folder.state() == FolderState.ABSENT) {
writeFile(siteId, "# Written by the database plugin during a restore: keep the site's live data.\n"
+ ADOPT_LINE + "\n");
}
}
/** Marks the site's folder so that whatever the registry has for it is retired on its next use. */
void markFresh(String siteId) {
writeFile(siteId, "# Written by the database plugin: none of the data the database has for this id is this "
+ "site's.\n" + FRESH_LINE + "\n");
}
/** Whether the registry maps the site to this schema, live (read on a fresh connection). */
boolean isLive(String siteId, String schema) throws SQLException {
try (Connection c = runtime.setupConnection()) {
c.setAutoCommit(true);
Optional<Registry.SiteRow> row = runtime.registry().site(c, siteId);
return row.isPresent() && row.get().schema().equals(schema) && LIVE.equals(row.get().state());
}
}
/** Writes the registry's token back to a folder that names another generation of the same site. */
private void adopt(String siteId, Registry.SiteRow row, Folder folder) {
writeToken(siteId, row.token());
evict(siteId);
log.info("database: site '{}' {}; keeping its live data in schema '{}'", siteId,
folder.state() == FolderState.ADOPT ? "was restored while the database was unreachable"
: "has a restored folder that names another generation of its data", row.schema());
}
/** Drops a staging generation a failed restore leaves behind; if that fails, the sweep drops it. */
void abandonStaging(String staging) {
try (Connection c = runtime.setupConnection()) {
c.setAutoCommit(true);
// Only a schema still staging and mapped by no site: a switch that committed and then reported an error
// has made it the site's live data.
if (runtime.registry().schemaStateIfUnmapped(c, staging, STAGING, RETIRED)) {
dropRecorded(c, staging);
} else {
log.warn("database: schema '{}' is no longer a staging generation; it is not dropped", staging);
}
} catch (SQLException | RuntimeException e) {
log.warn("database: could not drop the abandoned schema '{}' now; the sweep will: {}", staging,
DatabaseRuntime.describe(e));
}
}
/**
* Whether the site's folder says it has database data (a token, or the adopt marker).
*
* @throws IOException when the folder cannot be read: a caller must not take that for "no data" (a backup would
* then record the site as having none, and restoring it would retire the data)
*/
public boolean hasToken(String siteId) throws IOException {
try {
FolderState state = folder(siteId).state();
return state == FolderState.TOKEN || state == FolderState.ADOPT;
} catch (UnreadableFolderException e) {
throw new IOException(e.getMessage(), e.getCause());
}
}
// --- removal ----------------------------------------------------------------------------------------------------
/**
* After a site is deleted (on the node that deleted it): retires and drops its schema unless the site exists
* again with a token that matches. Runs on the executor.
*/
public void dropDeleted(String siteId) {
evict(siteId);
if (!runtime.available()) {
return; // the reconcile sweep catches it when the database is back
}
try {
runtime.locks().site(siteId, DROP_WAIT, () -> {
try (Connection c = runtime.setupConnection()) {
c.setAutoCommit(true);
Optional<Registry.SiteRow> row = runtime.registry().site(c, siteId);
if (row.isEmpty()) {
return null;
}
Folder folder = folder(siteId); // read first: a folder that cannot be read is never taken for none
if (sites.find(siteId).isPresent() && folder.names(row.get())) {
return null; // the site is back (restored with this very data): it keeps it
}
retire(c, siteId, row.get().schema());
dropRecorded(c, row.get().schema());
}
return null;
});
} catch (SQLException | RuntimeException e) {
log.warn("database: could not remove the data of deleted site '{}' now; the sweep will: {}", siteId,
DatabaseRuntime.describe(e));
}
}
/** Drops a recorded schema and forgets it. The name, and that no site maps to it, are checked before the DROP. */
private void dropRecorded(Connection c, String schema) throws SQLException {
Engine engine = runtime.engine();
String ns = runtime.config().namespace();
if (!Names.isSiteSchema(ns, schema, engine.identifierMax())) {
throw new IllegalStateException("refusing to drop a schema that is not a site schema: " + schema);
}
if (runtime.registry().isMapped(c, schema)) {
throw new IllegalStateException("refusing to drop a schema a site maps to: " + schema);
}
runtime.registry().schemaState(c, schema, DROPPING);
engine.dropSchema(c, schema);
runtime.registry().deleteSchema(c, schema);
log.info("database: dropped schema '{}'", schema);
}
/**
* The reconcile sweep: retires mappings whose site is gone or whose folder says the data is not the site's, and
* drops retired schemas past the grace period, staging generations no restore is building, and creations a crash
* interrupted. Schemas in the namespace that the registry never recorded are reported, never dropped. A site
* folder that cannot be read leaves that site's data alone; a site that is gone, or whose folder has no token on
* two passes in a row, only has its data retired (dropped after the grace period), never dropped at once.
*/
public void reconcile() {
if (!runtime.available()) {
return;
}
try {
List<Registry.SiteRow> mappings;
Registry.Schemas recorded;
try (Connection c = runtime.setupConnection()) {
mappings = runtime.registry().sites(c);
recorded = runtime.registry().schemas(c);
reportUnrecorded(c, recorded);
}
afterSweepSnapshot.run();
Set<String> absentNow = new HashSet<>();
for (Registry.SiteRow row : mappings) {
try {
reconcile(row, absentNow);
} catch (UnreadableFolderException e) {
log.warn("database: {}; the sweep leaves its data alone", e.getMessage());
} catch (RuntimeException e) {
log.warn("database: the sweep skipped site '{}': {}", row.siteId(), DatabaseRuntime.describe(e));
}
}
absentLastSweep.clear();
absentLastSweep.addAll(absentNow);
Set<String> mapped = mappings.stream().map(Registry.SiteRow::schema).collect(Collectors.toSet());
for (Registry.SchemaRow s : recorded.rows()) {
if (droppable(s, mapped, recorded.now())) {
dropIfStillDroppable(s.siteId(), s.schema());
}
}
} catch (SQLException | RuntimeException e) {
log.warn("database: the reconcile sweep stopped early: {}", DatabaseRuntime.describe(e));
}
}
private void reconcile(Registry.SiteRow row, Set<String> absentNow) {
String siteId = row.siteId();
Folder folder = folder(siteId); // first: a folder that cannot be read is never taken for a missing site
boolean gone = sites.find(siteId).isEmpty();
if (!gone && (!LIVE.equals(row.state()) || folder.names(row))) {
return;
}
if (!gone && folder.state() == FolderState.ABSENT && !absentLastSweep.contains(siteId)) {
absentNow.add(siteId); // a restore may be about to write the token back: decided on the next pass
return;
}
boolean wasAbsent = !gone && folder.state() == FolderState.ABSENT;
lockedSilently(siteId, c -> {
// Decided again under the lock, from fresh reads: a restore or an allocation may have just finished.
Optional<Registry.SiteRow> again = runtime.registry().site(c, siteId);
Folder now = folder(siteId);
if (again.isEmpty() || now.names(again.get())) {
return;
}
if (sites.find(siteId).isEmpty()) {
log.info("database: site '{}' no longer exists; retiring its data", siteId);
retire(c, siteId, again.get().schema());
} else if (!LIVE.equals(again.get().state())) {
return;
} else if (now.adoptable()) {
adopt(siteId, again.get(), now);
} else if (now.state() != FolderState.ABSENT || wasAbsent) {
log.info("database: site '{}' has no token naming schema '{}'; retiring it", siteId,
again.get().schema());
retire(c, siteId, again.get().schema());
}
});
}
/**
* After a site is created (on the node that created it): data the registry still has for this id belongs to an
* earlier site with the same id (deleted while the database was unreachable or the plugin off), so it is retired,
* unless the folder already names it (a backup import that finished first). With the database unreachable the
* folder is marked instead, and the next use retires it. Runs on the executor.
*/
public void retireEarlierSite(String siteId) {
try {
if (!runtime.available()) {
FolderState state = folder(siteId).state();
if (state != FolderState.TOKEN && state != FolderState.FRESH) {
markFresh(siteId);
}
return;
}
runtime.locks().site(siteId, DROP_WAIT, () -> {
try (Connection c = runtime.setupConnection()) {
c.setAutoCommit(true);
Optional<Registry.SiteRow> row = runtime.registry().site(c, siteId);
if (row.isPresent() && !folder(siteId).names(row.get())) {
log.info("database: new site '{}' has an id an earlier site used; retiring that site's "
+ "data in schema '{}'", siteId, row.get().schema());
retire(c, siteId, row.get().schema());
}
}
return null;
});
} catch (SQLException | RuntimeException e) {
log.warn("database: could not check new site '{}' for an earlier site's data now; its first use will: "
+ "{}", siteId, DatabaseRuntime.describe(e));
}
}
/**
* Drops a schema the sweep found droppable, deciding again under the site lock from fresh reads: the sweep's
* snapshot is stale once the lock is ours (a restore that held it may have just made this very schema live).
*/
void dropIfStillDroppable(String siteId, String schema) {
lockedSilently(siteId, c -> {
Registry.Schemas fresh = runtime.registry().schemas(c);
Set<String> mappedNow = runtime.registry().sites(c).stream().map(Registry.SiteRow::schema)
.collect(Collectors.toSet());
for (Registry.SchemaRow now : fresh.rows()) {
if (now.schema().equals(schema) && droppable(now, mappedNow, fresh.now())) {
dropRecorded(c, now.schema());
}
}
});
}
/**
* Whether the sweep may drop a recorded schema: never one a site maps to; a retired one past its grace; one left
* half dropped; a staging one (a restore builds it under the site lock, so once the sweep holds that lock it is a
* leftover); a creation a crash interrupted.
*/
static boolean droppable(Registry.SchemaRow s, Set<String> mapped, Instant now) {
if (mapped.contains(s.schema())) {
return false;
}
return switch (s.state()) {
case RETIRED -> s.changedAt() != null && s.changedAt().plus(RETIRED_GRACE).isBefore(now);
case DROPPING, STAGING, CREATING -> true;
default -> false;
};
}
private void reportUnrecorded(Connection c, Registry.Schemas recorded) throws SQLException {
String ns = runtime.config().namespace();
Set<String> known = recorded.rows().stream().map(Registry.SchemaRow::schema).collect(Collectors.toSet());
known.add(Names.appSchema(ns));
for (String name : runtime.engine().listSchemas(c, ns)) {
if (!known.contains(name)) {
log.warn("database: schema '{}' is in this install's namespace but not in its registry; leaving it "
+ "alone (another install sharing the namespace?)", name);
}
}
}
@FunctionalInterface
private interface ConnectionWork {
void run(Connection c) throws SQLException;
}
private void lockedSilently(String siteId, ConnectionWork work) {
try {
runtime.locks().site(siteId, DROP_WAIT, () -> {
try (Connection c = runtime.setupConnection()) {
c.setAutoCommit(true);
work.run(c);
}
return null;
});
} catch (SQLException | RuntimeException e) {
log.warn("database: sweep step for site '{}' failed: {}", siteId, DatabaseRuntime.describe(e));
}
}
// --- the token ----------------------------------------------------------------------------------------------
static String newToken() {
byte[] bytes = new byte[16];
RANDOM.nextBytes(bytes);
return HexFormat.of().formatHex(bytes);
}
/** What a site's folder says: {@link #TOKEN_FILE} absent, holding a token, or holding the adopt marker. */
/**
* What a site's folder says about its data: nothing ({@code ABSENT}); a token of this site ({@code TOKEN}); a
* token written for another site id, copied in with another site's backup ({@code FOREIGN}); keep what the
* registry has live, written by a restore that could not reach the database ({@code ADOPT}); a new site, so
* nothing the registry has is its data ({@code FRESH}).
*/
enum FolderState { ABSENT, TOKEN, FOREIGN, ADOPT, FRESH }
/** A site's folder as read; {@code token} is set for {@link FolderState#TOKEN} only. */
record Folder(FolderState state, String token) {
/** Whether the folder names exactly this mapping. */
boolean names(Registry.SiteRow row) {
return state == FolderState.TOKEN && token.equals(row.token());
}
/** Whether the folder comes from this site's own history, so the live data stays the site's. */
boolean adoptable() {
return state == FolderState.TOKEN || state == FolderState.ADOPT;
}
}
/** The site's folder could not be read, so nothing may be decided from it. */
static final class UnreadableFolderException extends RuntimeException {
private static final long serialVersionUID = 1L;
UnreadableFolderException(String siteId, Exception cause) {
super("the database folder of site '" + siteId + "' cannot be read (" + DatabaseRuntime.describe(cause)
+ ")", cause);
}
}
/**
* Reads the site's folder. A site that does not exist reads as {@link FolderState#ABSENT}; a file with neither a
* valid token nor the marker (edited by hand) too.
*
* @throws UnreadableFolderException when the file or its folder cannot be read
*/
Folder folder(String siteId) {
Optional<String> text;
try {
text = files.readText(siteId, TOKEN_FILE);
} catch (IOException | RuntimeException e) {
throw new UnreadableFolderException(siteId, e);
}
if (text.isEmpty()) {
return new Folder(FolderState.ABSENT, null);
}
return parse(siteId, text.get());
}
/** A token file's meaning for site {@code siteId}. */
static Folder parse(String siteId, String text) {
List<String> lines = text.lines().map(String::strip).toList();
Optional<String> token = parseToken(text);
if (token.isPresent()) {
// A file written before tokens named their site has no site line; one naming another id was copied in
// with that site's backup and says nothing about this site's data.
boolean ours = lines.stream().filter(l -> l.startsWith("site:"))
.allMatch(l -> l.substring("site:".length()).strip().equals(siteId));
return ours ? new Folder(FolderState.TOKEN, token.get()) : new Folder(FolderState.FOREIGN, null);
}
if (lines.contains(FRESH_LINE)) {
return new Folder(FolderState.FRESH, null);
}
return new Folder(lines.contains(ADOPT_LINE) ? FolderState.ADOPT : FolderState.ABSENT, null);
}
private Folder folderOrUnavailable(String siteId) {
try {
return folder(siteId);
} catch (UnreadableFolderException e) {
throw unavailable(e);
}
}
private static DatabaseUnavailableException unavailable(UnreadableFolderException e) {
return new DatabaseUnavailableException(e.getMessage() + "; its data is left as it is", e);
}
static Optional<String> parseToken(String text) {
for (String line : text.split("\n")) {
String t = line.strip();
if (t.startsWith("token:")) {
String v = t.substring("token:".length()).strip();
if (v.matches("[0-9a-f]{32}")) {
return Optional.of(v);
}
}
}
return Optional.empty();
}
private void writeToken(String siteId, String token) {
writeFile(siteId, "# Written by the database plugin: which database schema holds this site's data.\n"
+ "# Do not edit or copy it; a site without it gets a fresh schema.\nsite: " + siteId + "\ntoken: "
+ token + "\n");
}
private void writeFile(String siteId, String text) {
try {
files.writeText(siteId, TOKEN_FILE, text);
} catch (IOException | RuntimeException e) {
throw new IllegalArgumentException("the site's folder cannot take the database token (deleted site?)", e);
}
}
}
@@ -0,0 +1,13 @@
package mx.quest.database.internal;
import java.sql.SQLException;
/** The server answered, but it is not a product, version or configuration the database plugin supports. */
public class UnsupportedServerException extends SQLException {
private static final long serialVersionUID = 1L;
public UnsupportedServerException(String reason) {
super(reason);
}
}
@@ -0,0 +1,60 @@
package mx.quest.database.spi;
import java.nio.file.Path;
import java.time.Duration;
import java.util.Objects;
/**
* What a {@link DatabaseProvider} needs to build its {@code DataSource}: the server, the account and the TLS policy,
* every value already checked by the database plugin. A provider uses them as given and adds only the driver
* properties it pins itself; it never parses them into a URL beyond {@code scheme://host:port/database}.
*
* @param host an RFC-1123 host name, an IPv4 address or an IPv6 literal (without brackets)
* @param port 1–65535, or 0 for the product's default port
* @param database the database to connect to
* @param username the account
* @param password the account's password in clear; never logged ({@link #toString()} leaves it out)
* @param tls the TLS policy
* @param caCertificate a PEM file holding the CA (or the server certificate) to verify the server against when
* {@code tls} is {@link Tls#VERIFY_FULL}; {@code null} for the JVM's trust store
* @param connectTimeout how long opening a connection may take
* @param socketTimeout how long a read may block; longer than any statement timeout the database plugin sets
*/
public record ConnectionSettings(String host, int port, String database, String username, String password,
Tls tls, Path caCertificate, Duration connectTimeout, Duration socketTimeout) {
/** The TLS policy, from the {@code tls} setting. */
public enum Tls {
/** No TLS: for a database on the same host or a private network the operator trusts. */
DISABLE,
/** Encrypt, but do not check who the server is. */
REQUIRE,
/** Encrypt, check the certificate chain and that the certificate names {@link #host()}. */
VERIFY_FULL
}
public ConnectionSettings {
Objects.requireNonNull(host, "host");
Objects.requireNonNull(database, "database");
Objects.requireNonNull(username, "username");
Objects.requireNonNull(tls, "tls");
Objects.requireNonNull(connectTimeout, "connectTimeout");
Objects.requireNonNull(socketTimeout, "socketTimeout");
if (port < 0 || port > 65535) {
throw new IllegalArgumentException("port out of range: " + port);
}
password = password == null ? "" : password;
}
/** The port to use: {@link #port()}, or {@code defaultPort} when it is 0. */
public int portOr(int defaultPort) {
return port == 0 ? defaultPort : port;
}
/** Everything but the password. */
@Override
public String toString() {
return "ConnectionSettings[host=" + host + ", port=" + port + ", database=" + database + ", username="
+ username + ", tls=" + tls + ", caCertificate=" + caCertificate + "]";
}
}
@@ -0,0 +1,35 @@
package mx.quest.database.spi;
import java.util.Set;
/**
* A consumer plugin's declaration that it keeps data in the database. Implement it on one bean in your plugin's own
* jar; the database plugin collects every {@code DatabaseConsumer} by type.
*
* <p>The declaration is <b>checked, not trusted</b>: the database plugin works out which plugin the bean's class was
* loaded from (its jar's install folder, whose name the loader already requires to equal the plugin id) and refuses a
* bean whose {@link #pluginId()} names a different plugin, or a second bean for the same id. Migration scripts are
* then read only from that jar, under {@code db/<pluginId>/}, so two plugins on the shared class loader cannot pick
* up each other's scripts.
*
* <p>The plugin id also decides the plugin's <b>object prefix</b>: every table, sequence, view, routine and trigger
* its scripts create must start with it (see {@link PluginDatabase#prefix()}).
*/
public interface DatabaseConsumer {
/**
* The id from your {@code plugin.yml}.
*
* @return the plugin id, exactly as declared
*/
String pluginId();
/**
* Where your data lives: {@link Scope.Kind#SITE} for data that belongs to one site (the usual case; it travels
* in that site's backups), {@link Scope.Kind#APP} for data that belongs to no site. A scope not declared here
* refuses to open, and its migration folder is ignored.
*
* @return a non-empty set
*/
Set<Scope.Kind> scopes();
}
@@ -0,0 +1,20 @@
package mx.quest.database.spi;
/**
* A database call failed: the {@link java.sql.SQLException} a consumer's {@link SqlWork} threw, or one the scope met
* while preparing the connection, as its cause. Unchecked, so a consumer's service code is not forced to declare it;
* catch it where a failure has a useful answer (a form error, a fallback). Its message never contains a password or a
* connection URL.
*/
public class DatabaseException extends RuntimeException {
private static final long serialVersionUID = 1L;
/**
* @param message what failed, in words an operator can act on
* @param cause the underlying failure, or {@code null}
*/
public DatabaseException(String message, Throwable cause) {
super(message, cause);
}
}
@@ -0,0 +1,79 @@
package mx.quest.database.spi;
import java.util.Optional;
import javax.sql.DataSource;
/**
* A database product, contributed by a provider plugin that ships the product's JDBC driver in its {@code lib/}.
* When both providers are installed, the operator picks one by its {@link #id()} in the database plugin's
* {@code provider} setting; with one installed, that one is used.
*
* <p><b>The provider holds its server's settings</b> (since database 2.0.0): host, port, database, account,
* password and TLS are set on the provider plugin's own settings page, and handed over through
* {@link #runningSettings()} and {@link #savedSettings()}. The database plugin keeps only what applies to every
* product: the provider choice, the namespace and the limits. Those two methods hand over the password in clear and
* are for the database plugin alone; a consumer plugin never calls them. They are not a security boundary: plugins
* are trusted code in the same JVM, as the kernel's plugin guide says, and could read the settings file anyway.
*
* <p><b>A provider brings the driver, not the SQL.</b> Every statement Runway runs on the provider's connections —
* schema creation and removal, locks, the ownership checks, migrations, backup and restore — is written in the
* database plugin for each product it supports. So the checks that keep plugins and sites apart are reviewed in one
* place and a provider cannot weaken them. A provider's {@code id()} must therefore name a product the installed
* database plugin supports; an unknown id is refused with a reason on the health screen.
*
* <p>Register the provider as one bean in the provider plugin's {@code @Configuration}; the database plugin collects
* providers by type. Two providers with the same id are both refused.
*/
public interface DatabaseProvider {
/** The product id the {@code provider} setting names: {@code postgresql} or {@code mariadb}. */
String id();
/** The bundled driver's name and version, for the health screen, e.g. {@code "pgjdbc 42.7.10"}. */
String driverVersion();
/**
* An unpooled {@code DataSource} built from the provider's own driver classes, never through
* {@code DriverManager}. The database plugin pools it.
*
* <ul>
* <li>The URL is {@code scheme://host:port/database} and nothing more; the account goes in as properties.</li>
* <li>The provider pins every driver property that could reach outside the connection: no local file
* loading, no multi-statement queries, no redirects, no logger or socket factory taken from settings.</li>
* <li>TLS follows {@link ConnectionSettings#tls()} exactly; {@code VERIFY_FULL} checks the host name.</li>
* <li>Opening a connection honours {@link ConnectionSettings#connectTimeout()}, and reads honour
* {@link ConnectionSettings#socketTimeout()}, with TCP keep-alive on.</li>
* </ul>
*
* Building the {@code DataSource} must not connect.
*
* @param settings the checked settings
* @return a new, unpooled data source
*/
DataSource dataSource(ConnectionSettings settings);
/**
* The server settings the running application started with: what the database plugin connects with. Read from
* the provider plugin's own app-level settings, the password in clear
* ({@code PluginSettings.appSecret("password")}).
*
* @return the settings; empty only from a provider built before database 2.0.0, which the database plugin
* reports as too old
* @since database 2.0.0
*/
default Optional<ProviderSettings> runningSettings() {
return Optional.empty();
}
/**
* The server settings as saved now, which the next restart applies ({@code PluginSettings.savedApp}): what the
* connection test on the database plugin's settings page tries, so an operator can check a change before
* restarting.
*
* @return the settings; empty only from a provider built before database 2.0.0
* @since database 2.0.0
*/
default Optional<ProviderSettings> savedSettings() {
return Optional.empty();
}
}
@@ -0,0 +1,25 @@
package mx.quest.database.spi;
/**
* There is no database to use right now: none is configured, the configured provider is not installed, the server
* is unreachable or unsupported, or a site's connection cap stayed full. {@link PluginDatabase#available()} answers
* {@code false} in the first cases, so check it first where "no database" has a better answer than an error. The
* database plugin's console screen says which case it is.
*/
public class DatabaseUnavailableException extends DatabaseException {
private static final long serialVersionUID = 1L;
/** @param message why, in words an operator can act on */
public DatabaseUnavailableException(String message) {
super(message, null);
}
/**
* @param message why, in words an operator can act on
* @param cause the underlying failure
*/
public DatabaseUnavailableException(String message, Throwable cause) {
super(message, cause);
}
}
@@ -0,0 +1,17 @@
package mx.quest.database.spi;
/**
* The database plugin's entry point for consumers: inject it, and ask for your own handle.
*/
public interface Databases {
/**
* The handle for the plugin {@code me} belongs to.
*
* @param me your {@link DatabaseConsumer} bean
* @return your handle (the same instance on every call)
* @throws IllegalArgumentException when {@code me} was not registered as a bean, or its class is not from the
* plugin its {@link DatabaseConsumer#pluginId()} names
*/
PluginDatabase of(DatabaseConsumer me);
}
@@ -0,0 +1,65 @@
package mx.quest.database.spi;
import java.sql.Connection;
import java.sql.SQLException;
/**
* What a consumer needs to know about the running database product to write the few statements that differ between
* them. Everything else (schema binding, locks, backups) is the database plugin's job.
*
* <p>Write migration scripts for each dialect you support, under {@code db/<plugin-id>/<id()>/}. Both trees must
* produce the same tables, columns and nullability at every version, with lower-case unquoted names: a site backup
* taken on one product restores on the other only then.
*/
public interface Dialect {
/**
* The dialect id, also the migration folder name.
*
* @return {@code "postgresql"} or {@code "mariadb"}, or another provider's id
*/
String id();
/**
* An SQL expression that takes the next value of {@code sequence}: {@code nextval('s')} on PostgreSQL,
* {@code NEXTVAL(s)} on MariaDB.
*
* @param sequence an unqualified sequence name from your own scripts (it must carry your prefix)
* @return the expression
*/
String nextValue(String sequence);
/**
* The value {@code sequence} last handed out on this connection — read it right after the insert that used it,
* inside the same {@link Scope#transaction} call.
*
* @param connection the connection the insert ran on
* @param sequence an unqualified sequence name from your own scripts
* @return the value
* @throws SQLException when the sequence has not been used on this connection
*/
long lastValue(Connection connection, String sequence) throws SQLException;
/**
* {@code name} quoted as an identifier for this product.
*
* @param name an identifier
* @return it quoted, with embedded quote characters doubled
*/
String quote(String name);
/**
* A clause that limits a query to {@code limit} rows after skipping {@code offset}: {@code LIMIT n OFFSET m} on
* both supplied products, so this exists for providers that differ.
*
* @param limit rows to return, at least 0
* @param offset rows to skip, at least 0
* @return the clause, without leading or trailing space
*/
default String limitOffset(int limit, int offset) {
if (limit < 0 || offset < 0) {
throw new IllegalArgumentException("limit and offset must not be negative");
}
return "LIMIT " + limit + " OFFSET " + offset;
}
}
@@ -0,0 +1,80 @@
package mx.quest.database.spi;
import mx.quest.runway.spi.model.SiteRef;
/**
* One consumer plugin's handle on the database, from {@link Databases#of}. Everything it opens is bound to that
* plugin: its migrations, its object prefix, its failure state.
*
* <h2>Choosing the site</h2>
* <b>Never take a site id from request input</b> (a form field, a query parameter, a path segment): a site's admin
* could then name another site. Use {@link #currentSite()} while serving a request, {@link #site(SiteRef)} with the
* reference a Runway callback handed you (a backup, a site event), and {@link #siteInBackground(String)} only in
* background or application-console code that got the id from Runway.
*
* <p>Thread-safe.
*/
public interface PluginDatabase {
/**
* Whether a database is configured, its provider is installed, and the server answered and passed the
* provider's checks. It can change at any time (a restart, an outage, the server coming back).
*
* @return {@code true} when calls are expected to work
*/
boolean available();
/**
* The running database's dialect, for the few statements that differ between products.
*
* @return the dialect
* @throws DatabaseUnavailableException when {@link #available()} is false
*/
Dialect dialect();
/**
* The prefix every object this plugin's scripts create must start with: the plugin id lower-cased, every other
* character turned into {@code _}, then {@code __} (for example {@code runway_demo_database__}), shortened with
* a hash past 24 characters. A script that creates an object without it is refused.
*
* @return the prefix
*/
String prefix();
/**
* The scope of the site the current request is for.
*
* @return that site's scope
* @throws IllegalStateException outside a request for a site (an application-console request, a background
* thread)
*/
Scope currentSite();
/**
* The scope of a site Runway named to you, through a {@link SiteRef} it handed you.
*
* @param site the site
* @return that site's scope
* @throws IllegalArgumentException when no such site exists
*/
Scope site(SiteRef site);
/**
* The scope of a site, by id, for background and application-console code that got the id from Runway (a site
* listing, a scheduled task). Not for ids that arrived in a request.
*
* @param siteId the site id
* @return that site's scope
* @throws IllegalArgumentException when no such site exists
*/
Scope siteInBackground(String siteId);
/**
* The installation-wide scope, for data that belongs to no site. Keep a site's data in its site scope: the app
* scope is in no site backup, and does not move when the operator changes the database.
*
* @return the app scope
* @throws IllegalStateException when the consumer did not declare {@link Scope.Kind#APP}
*/
Scope app();
}
@@ -0,0 +1,71 @@
package mx.quest.database.spi;
import java.util.Optional;
import java.util.function.Function;
/**
* Where a provider's server is and how to reach it, as the operator set it on the provider plugin's own settings page
* (since database 2.0.0). Raw values: the database plugin checks every one of them before use and reports the first
* it cannot use, so a provider passes them on unchanged and never validates or repairs them itself.
*
* <p>A provider reads these from its own app-level settings, declared under the same keys as the components below.
* {@link #read(Function)} does that from one lookup, so both providers read their settings the same way.
*
* @param host the server's host name or address
* @param port the port, or blank for the product's default
* @param database the database to connect to
* @param username the account
* @param password the account's password in clear, possibly blank; never logged ({@link #toString()} leaves it
* out)
* @param tls {@code verify-full}, {@code require} or {@code disable}; blank for {@code verify-full}
* @param caCertificate a PEM certificate to verify the server against, or blank for the JVM's trust store
* @param collation MariaDB's collation for consumer tables, or blank for the server's best; always blank for a
* product without the setting
*/
public record ProviderSettings(String host, String port, String database, String username, String password,
String tls, String caCertificate, String collation) {
/** The setting keys, as both providers declare them in their {@code plugin.yml}. */
public static final String HOST = "host";
public static final String PORT = "port";
public static final String DATABASE = "database";
public static final String USERNAME = "username";
public static final String PASSWORD = "password";
public static final String TLS = "tls";
public static final String CA_CERTIFICATE = "caCertificate";
public static final String COLLATION = "collation";
/**
* Reads every key through one lookup, a blank or missing value becoming {@code null}.
*
* @param setting answers a setting key with its value; for {@link #PASSWORD} the value in clear
* @return the settings
*/
public static ProviderSettings read(Function<String, Optional<String>> setting) {
return new ProviderSettings(value(setting, HOST), value(setting, PORT), value(setting, DATABASE),
value(setting, USERNAME), value(setting, PASSWORD), value(setting, TLS),
value(setting, CA_CERTIFICATE), value(setting, COLLATION));
}
/** Whether nothing that names a server is set: the provider has not been set up yet. */
public boolean isEmpty() {
return blank(host) && blank(database) && blank(username);
}
/** Everything but the password. */
@Override
public String toString() {
return "ProviderSettings[host=" + host + ", port=" + port + ", database=" + database + ", username="
+ username + ", tls=" + tls + ", caCertificate=" + (blank(caCertificate) ? "none" : "set")
+ ", collation=" + collation + "]";
}
private static String value(Function<String, Optional<String>> setting, String key) {
Optional<String> v = setting.apply(key);
return v == null ? null : v.filter(s -> !s.isBlank()).orElse(null);
}
private static boolean blank(String s) {
return s == null || s.isBlank();
}
}
@@ -0,0 +1,99 @@
package mx.quest.database.spi;
import java.util.Optional;
/**
* A provider's server settings as Spring binds them from the running application: register one as a bean with
* {@code @ConfigurationProperties("runway.plugin.<provider-id>")} and turn it into {@link ProviderSettings} with
* {@link #toSettings(Optional)}, passing the password from {@code PluginSettings.appSecret("password")} (it binds here
* only in its stored {@code ENC(...)} form, so it has no field). Both providers bind this way, so the keys can never
* differ from the ones {@link ProviderSettings} names.
*
* @since database 2.0.0
*/
public class ProviderSettingsProps {
private String host;
private String port;
private String database;
private String username;
private String tls;
private String caCertificate;
private String collation;
/**
* The bound values with the given password.
*
* @param password the password in clear, or empty
* @return the settings, a blank value as {@code null}
*/
public ProviderSettings toSettings(Optional<String> password) {
return ProviderSettings.read(key -> Optional.ofNullable(switch (key) {
case ProviderSettings.HOST -> host;
case ProviderSettings.PORT -> port;
case ProviderSettings.DATABASE -> database;
case ProviderSettings.USERNAME -> username;
case ProviderSettings.TLS -> tls;
case ProviderSettings.CA_CERTIFICATE -> caCertificate;
case ProviderSettings.COLLATION -> collation;
case ProviderSettings.PASSWORD -> password == null ? null : password.orElse(null);
default -> null;
}));
}
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public String getPort() {
return port;
}
public void setPort(String port) {
this.port = port;
}
public String getDatabase() {
return database;
}
public void setDatabase(String database) {
this.database = database;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getTls() {
return tls;
}
public void setTls(String tls) {
this.tls = tls;
}
public String getCaCertificate() {
return caCertificate;
}
public void setCaCertificate(String caCertificate) {
this.caCertificate = caCertificate;
}
public String getCollation() {
return collation;
}
public void setCollation(String collation) {
this.collation = collation;
}
}
@@ -0,0 +1,75 @@
package mx.quest.database.spi;
/**
* One schema a consumer plugin works in: a site's, or the installation-wide one. Obtained from
* {@link PluginDatabase}; bound to that plugin, so its migrations are checked before the first call.
*
* <h2>Calls</h2>
* Each outer call borrows one pooled connection, binds it to the schema, runs the work and returns the connection.
* <ul>
* <li><b>Joining.</b> A {@code transaction} or {@code read} made inside another call on <b>this same scope</b>, on
* the same thread, joins it: the same connection, no commit of its own, and an exception rolls back the outer
* call too. A {@code read} inside a {@code transaction} joins it; a {@code transaction} inside a {@code read}
* throws {@link IllegalStateException}.</li>
* <li><b>No nesting across scopes.</b> A call on another scope (another site's, or the app scope) from inside a
* call throws {@link IllegalStateException}: it would hold two pooled connections at once, which is how a pool
* deadlocks. Make such calls one after the other.</li>
* <li><b>One connection per outer call</b> is what makes reading a new id back reliable: {@code INSERT … RETURNING}
* on PostgreSQL, {@code LASTVAL(seq)} on MariaDB, both on the same connection as the insert
* ({@link Dialect#lastValue}).</li>
* <li><b>Timeouts.</b> Every statement runs under the installation's statement timeout. A site has a cap on the
* connections it may hold at once, so one busy site cannot take the pool from the others; over it, the call
* waits briefly, then throws {@link DatabaseUnavailableException}.</li>
* </ul>
*
* <h2>Failures</h2>
* {@link DatabaseUnavailableException} when the database is not configured or not reachable;
* {@link ScopeNotReadyException} when this plugin's tables in this schema are not usable (a failed, refused or newer
* migration, or data being prepared); {@link DatabaseException} wrapping the {@link java.sql.SQLException} your work
* threw. All three are unchecked.
*
* <p>Thread-safe.
*/
public interface Scope {
/** The two kinds of scope a consumer can declare ({@link DatabaseConsumer#scopes()}). */
enum Kind {
/** Data that belongs to one site: it lives in that site's schema and travels in that site's backups. */
SITE,
/** Data that belongs to no site. It is in no site backup, and does not move when the database changes. */
APP
}
/**
* The kind of this scope.
*
* @return {@link Kind#SITE} or {@link Kind#APP}
*/
Kind kind();
/**
* The site this scope belongs to.
*
* @return the site id, or {@code null} for the app scope
*/
String siteId();
/**
* Runs {@code work} in one read-write transaction: committed when it returns, rolled back when it throws.
*
* @param work the work
* @param <T> what it returns
* @return what {@code work} returned
*/
<T> T transaction(SqlWork<T> work);
/**
* Runs {@code work} in one read-only transaction over a consistent snapshot: every query in it sees the data as
* it was when the first one ran, and a write fails.
*
* @param work the work
* @param <T> what it returns
* @return what {@code work} returned
*/
<T> T read(SqlWork<T> work);
}
@@ -0,0 +1,40 @@
package mx.quest.database.spi;
/**
* The database is there, but this plugin's tables in this schema are not usable. Only this plugin in this schema is
* affected: other plugins, and this plugin's other schemas, carry on.
*/
public class ScopeNotReadyException extends DatabaseException {
private static final long serialVersionUID = 1L;
/** Why the scope is not ready. May gain constants in a minor version. */
public enum Reason {
/** A migration script failed part-way; an operator retries or marks it applied on the database screen. */
MIGRATION_FAILED,
/** An applied script no longer matches the one the plugin ships; released migrations must never change. */
CHECKSUM_MISMATCH,
/** The schema is at a version newer than any script the installed plugin ships (after a downgrade). */
NEWER_THAN_INSTALLED,
/** The schema is being created, migrated or restored; retry shortly. */
PREPARING,
/** The plugin's object prefix clashes with another plugin's, or its scripts cannot be read; nothing ran. */
PLUGIN_REFUSED
}
private final Reason reason;
/**
* @param reason why
* @param message what to do about it, in words an operator can act on
*/
public ScopeNotReadyException(Reason reason, String message) {
super(message, null);
this.reason = reason;
}
/** @return why the scope is not ready */
public Reason reason() {
return reason;
}
}
@@ -0,0 +1,28 @@
package mx.quest.database.spi;
import java.sql.Connection;
import java.sql.SQLException;
/**
* Work done on one connection inside {@link Scope#transaction} or {@link Scope#read}.
*
* <p>The connection is lent for the duration of the call only: do not keep it, close it, commit it, roll it back,
* change its auto-commit, read-only or isolation settings, or switch its schema ({@code USE}, {@code SET
* search_path}). The scope does all of that, and resets the connection before the pool hands it to anyone else. Close
* the statements and result sets you open (try-with-resources).
*
* @param <T> what the work returns
*/
@FunctionalInterface
public interface SqlWork<T> {
/**
* Does the work.
*
* @param connection a connection bound to the scope's schema, inside the scope's transaction
* @return the result, which may be {@code null}
* @throws SQLException to roll the transaction back; the scope rethrows it wrapped in a
* {@link DatabaseException}
*/
T run(Connection connection) throws SQLException;
}
@@ -0,0 +1,31 @@
/**
* The database plugin's published interface: what a <b>consumer</b> plugin uses to keep its own data in the one
* database a Runway installation is configured with, and what a <b>provider</b> plugin implements to add a
* database product.
*
* <h2>For a consumer</h2>
* <ol>
* <li>Declare {@code requires: [ "database >= <the lowest version whose types you use>" ]} in {@code plugin.yml}
* and compile this package as {@code provided}: at runtime the shared plugin class loader supplies it.</li>
* <li>Register one {@link mx.quest.database.spi.DatabaseConsumer} bean. Ship your migration scripts under
* {@code db/<your-plugin-id>/<dialect>/<app|site>/}, with an {@code index} file listing them in order.</li>
* <li>Inject {@link mx.quest.database.spi.Databases} and call {@code of(yourConsumerBean)} for your own
* {@link mx.quest.database.spi.PluginDatabase}. Everything you do goes through its
* {@link mx.quest.database.spi.Scope scopes}: one per site, plus one for data that belongs to no site.</li>
* </ol>
* Never call it from a constructor, a {@code @Bean} method, {@code @PostConstruct} or
* {@code PluginLifecycle.started()}: the database may not be reachable yet, and Runway starts without it.
*
* <h2>For a provider</h2>
* Implement {@link mx.quest.database.spi.DatabaseProvider} in a plugin that {@code requires: database} and ships its
* driver in {@code lib/}. The provider declares its server's settings (the keys in
* {@link mx.quest.database.spi.ProviderSettings}) in its own {@code plugin.yml} and hands them over through
* {@link mx.quest.database.spi.DatabaseProvider#runningSettings()} and
* {@link mx.quest.database.spi.DatabaseProvider#savedSettings()}. With both providers installed, the operator picks
* one by its {@link mx.quest.database.spi.DatabaseProvider#id()} in the database plugin's settings.
*
* <h2>Stability</h2>
* This package evolves additively within a major version of the database plugin: interfaces gain {@code default}
* methods, records keep their old constructors. A breaking change ships under a new package or a new plugin id.
*/
package mx.quest.database.spi;
@@ -0,0 +1,243 @@
package mx.quest.database;
import static org.assertj.core.api.Assertions.assertThat;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Stream;
import javax.sql.DataSource;
import mx.quest.database.internal.DatabaseLifecycle;
import mx.quest.database.internal.DatabaseRuntime;
import mx.quest.database.spi.ConnectionSettings;
import mx.quest.database.spi.DatabaseProvider;
import mx.quest.database.spi.ProviderSettings;
import mx.quest.database.spi.Databases;
import mx.quest.runway.spi.BackupParticipant;
import mx.quest.runway.spi.model.PluginInfo;
import mx.quest.runway.spi.service.PluginSettings;
import mx.quest.runway.spi.service.PluginSiteFiles;
import mx.quest.runway.spi.service.SiteEventListener;
import mx.quest.runway.spi.testkit.FakePluginSettings;
import mx.quest.runway.spi.testkit.FakeSiteServices;
import mx.quest.runway.spi.testkit.TempDirSiteFiles;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.MapPropertySource;
class DatabasePluginConfigTest {
@TempDir
Path dir;
@Test
void theConfigurationWiresFromKernelServicesAloneAndConnectsNothingWhileStarting() throws Exception {
AtomicBoolean touched = new AtomicBoolean();
try (AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext()) {
ctx.registerBean(PluginSettings.class, FakePluginSettings::new);
ctx.registerBean(PluginSiteFiles.class, () -> new TempDirSiteFiles(dir.resolve("sites"), "database"));
ctx.registerBean(PluginInfo.class, () -> new PluginInfo("database", "1.0.0", dir.resolve("plugin")));
ctx.registerBean(FakeSiteServices.class, FakeSiteServices::new);
ctx.registerBean("otherPluginProvider", DatabaseProvider.class, () -> new DatabaseProvider() {
@Override
public String id() {
return "postgresql";
}
@Override
public String driverVersion() {
return "none";
}
@Override
public DataSource dataSource(ConnectionSettings settings) {
touched.set(true);
throw new IllegalStateException("must not be asked while starting");
}
@Override
public Optional<ProviderSettings> runningSettings() {
return Optional.of(ProviderSettings.read(key -> Optional.empty())); // installed, not set up
}
});
ctx.register(DatabasePluginConfig.class);
ctx.refresh();
for (String name : ctx.getBeanDefinitionNames()) {
if (ctx.getBeanDefinition(name).getFactoryMethodName() != null) {
assertThat(name).as("bean names carry the plugin id").startsWith("database");
}
}
assertThat(ctx.getBean(Databases.class)).isNotNull();
assertThat(ctx.getBeansOfType(BackupParticipant.class)).containsKey("databaseBackup");
assertThat(ctx.getBeansOfType(SiteEventListener.class)).containsKey("databaseSiteEvents");
ctx.getBean(DatabaseLifecycle.class).started(ctx.getBean(PluginInfo.class));
DatabaseRuntime runtime = ctx.getBean(DatabaseRuntime.class);
long deadline = System.nanoTime() + 5_000_000_000L;
while (runtime.status() == DatabaseRuntime.Status.CONNECTING && System.nanoTime() < deadline) {
Thread.sleep(20);
}
// No settings: nothing is configured, nothing was connected, and Runway carried on. (That a configured
// plugin connects only on its own thread is aConfiguredPluginConnectsOnItsOwnThreadNeverWhileRunwayStarts.)
assertThat(runtime.status()).isEqualTo(DatabaseRuntime.Status.NOT_CONFIGURED);
assertThat(runtime.available()).isFalse();
assertThat(touched).isFalse();
ctx.getBean(DatabaseLifecycle.class).stopping();
}
}
/** Turns on @ConfigurationProperties binding, as the kernel's context does. */
@Configuration(proxyBeanMethods = false)
@EnableConfigurationProperties
static class Binding {
}
@Test
void aConfiguredPluginConnectsOnItsOwnThreadNeverWhileRunwayStarts() throws Exception {
CountDownLatch release = new CountDownLatch(1);
AtomicReference<String> askedOn = new AtomicReference<>();
String startThread = Thread.currentThread().getName();
try (AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext()) {
ctx.getEnvironment().getPropertySources().addFirst(new MapPropertySource("test", Map.of(
"runway.plugin.database.provider", "postgresql")));
ctx.registerBean(PluginSettings.class, FakePluginSettings::new);
ctx.registerBean(PluginSiteFiles.class, () -> new TempDirSiteFiles(dir.resolve("sites"), "database"));
ctx.registerBean(PluginInfo.class, () -> new PluginInfo("database", "1.0.0", dir.resolve("plugin")));
ctx.registerBean(FakeSiteServices.class, FakeSiteServices::new);
ctx.registerBean("otherPluginProvider", DatabaseProvider.class, () -> new DatabaseProvider() {
@Override
public String id() {
return "postgresql";
}
@Override
public String driverVersion() {
return "none";
}
@Override
public DataSource dataSource(ConnectionSettings settings) {
askedOn.compareAndSet(null, Thread.currentThread().getName());
try {
release.await(10, TimeUnit.SECONDS); // a server that takes its time to answer
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
throw new IllegalStateException("no server here");
}
@Override
public Optional<ProviderSettings> runningSettings() {
return Optional.of(new ProviderSettings("127.0.0.1", "1", "runway", "runway", "x", "disable", null,
null));
}
});
ctx.register(Binding.class, DatabasePluginConfig.class);
long t0 = System.nanoTime();
ctx.refresh();
ctx.getBean(DatabaseLifecycle.class).started(ctx.getBean(PluginInfo.class));
long tookMillis = (System.nanoTime() - t0) / 1_000_000;
// Runway's start went on while the provider was still busy, and never asked it on the starting thread.
assertThat(tookMillis).as("start did not wait for the database").isLessThan(5_000);
assertThat(askedOn.get()).as("asked on the starting thread").isNotEqualTo(startThread);
release.countDown();
DatabaseRuntime runtime = ctx.getBean(DatabaseRuntime.class);
long deadline = System.nanoTime() + 10_000_000_000L;
while (askedOn.get() == null && System.nanoTime() < deadline) {
Thread.sleep(20);
}
assertThat(askedOn.get()).as("the settings were real: the background connect reached the provider")
.isNotNull().startsWith("runway-database-");
assertThat(runtime.available()).isFalse();
ctx.getBean(DatabaseLifecycle.class).stopping();
}
}
@Test
void oneXServerKeysLeftInTheDatabaseSettingsAreReportedAsMovedAndNeverUsed() throws Exception {
AtomicBoolean touched = new AtomicBoolean();
try (AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext()) {
// A 1.x database.yml after the upgrade: the server keys are still there, the provider page is empty.
ctx.getEnvironment().getPropertySources().addFirst(new MapPropertySource("test", Map.of(
"runway.plugin.database.provider", "postgresql", "runway.plugin.database.host", "127.0.0.1",
"runway.plugin.database.database", "runway", "runway.plugin.database.username", "runway",
"runway.plugin.database.password", "ENC(c2VjcmV0)", "runway.plugin.database.tls", "disable")));
ctx.registerBean(PluginSettings.class, FakePluginSettings::new);
ctx.registerBean(PluginSiteFiles.class, () -> new TempDirSiteFiles(dir.resolve("sites"), "database"));
ctx.registerBean(PluginInfo.class, () -> new PluginInfo("database", "2.0.0", dir.resolve("plugin")));
ctx.registerBean(FakeSiteServices.class, FakeSiteServices::new);
ctx.registerBean("otherPluginProvider", DatabaseProvider.class, () -> new DatabaseProvider() {
@Override
public String id() {
return "postgresql";
}
@Override
public String driverVersion() {
return "none";
}
@Override
public DataSource dataSource(ConnectionSettings settings) {
touched.set(true);
throw new IllegalStateException("must not connect with 1.x keys");
}
@Override
public Optional<ProviderSettings> runningSettings() {
return Optional.of(ProviderSettings.read(key -> Optional.empty()));
}
});
ctx.register(Binding.class, DatabasePluginConfig.class);
ctx.refresh();
ctx.getBean(DatabaseLifecycle.class).started(ctx.getBean(PluginInfo.class));
DatabaseRuntime runtime = ctx.getBean(DatabaseRuntime.class);
long deadline = System.nanoTime() + 5_000_000_000L;
while (runtime.status() == DatabaseRuntime.Status.CONNECTING && System.nanoTime() < deadline) {
Thread.sleep(20);
}
assertThat(runtime.status()).isEqualTo(DatabaseRuntime.Status.NOT_CONFIGURED);
assertThat(runtime.health().detail()).contains("moved to the database-postgresql plugin")
.contains("host, database, username, password, tls")
.contains("plugin-settings/database-postgresql.yml").doesNotContain("c2VjcmV0");
assertThat(touched).isFalse();
ctx.getBean(DatabaseLifecycle.class).stopping();
}
}
@Test
void theCompiledClassesLinkNoHostInternals() throws IOException {
Path classes = Path.of("target", "classes");
Pattern host = Pattern.compile("mx[/.]quest[/.]runway[/.](?!spi[/.])[\\w/.$]*");
List<String> problems = new ArrayList<>();
int scanned = 0;
try (Stream<Path> files = Files.walk(classes)) {
for (Path file : files.filter(p -> p.toString().endsWith(".class")).toList()) {
scanned++;
String rel = classes.relativize(file).toString().replace('\\', '/');
Matcher m = host.matcher(new String(Files.readAllBytes(file), StandardCharsets.ISO_8859_1));
while (m.find()) {
problems.add(rel + " → " + m.group());
}
}
}
assertThat(scanned).isGreaterThan(30);
assertThat(problems).isEmpty();
}
}
@@ -0,0 +1,84 @@
package mx.quest.database.internal;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import mx.quest.database.spi.ConnectionSettings.Tls;
import mx.quest.database.spi.ProviderSettings;
import org.junit.jupiter.api.Test;
class DatabaseConfigTest {
static ProviderSettings server() {
return server("db.example.com", null, null);
}
static ProviderSettings server(String host, String port, String tls) {
return new ProviderSettings(host, port, "runway", "runway", "s3cret", tls, null, null);
}
static ProviderSettings with(ProviderSettings s, String database, String ca, String collation) {
return new ProviderSettings(s.host(), s.port(), database, s.username(), s.password(), s.tls(), ca, collation);
}
@Test
void aCompleteSetOfSettingsIsCheckedWithSafeDefaults() {
DatabaseConfig c = DatabaseConfig.from(new DatabaseProps(), "postgresql", server());
assertThat(c.tls()).isEqualTo(Tls.VERIFY_FULL);
assertThat(c.namespace()).isEqualTo("rw");
assertThat(c.port()).isZero();
assertThat(c.poolMax()).isEqualTo(10);
assertThat(c.password()).isEqualTo("s3cret");
assertThat(c.toString()).doesNotContain("s3cret");
assertThat(server().toString()).doesNotContain("s3cret");
}
@Test
void hostsThatCouldSmuggleDriverSyntaxAreRefused() {
for (String bad : new String[] {"a,b", "h?ssl=false", "h/db", "u@h", "h:1:2:3", "address=(host=x)", "h h",
"h;x", "-h", "h-.com", "1.2.3.256", "999.1.1.1", "[::1]x", "fe80::1%eth0", "a..b", "h.",
"::1::2"}) {
assertThatThrownBy(() -> DatabaseConfig.from(new DatabaseProps(), "postgresql", server(bad, null, null)))
.as(bad).isInstanceOf(IllegalArgumentException.class);
}
for (String good : new String[] {"localhost", "db-1.internal", "10.0.0.5", "::1", "[2001:db8::1]",
"2001:db8:0:0:0:0:0:1", "::ffff:10.0.0.1"}) {
assertThat(DatabaseConfig.from(new DatabaseProps(), "postgresql", server(good, null, null)).host())
.as(good).doesNotContain("[");
}
}
@Test
void thePortIsBlankForTheDefaultOrANumberInRange() {
DatabaseProps p = new DatabaseProps();
assertThat(DatabaseConfig.from(p, "mariadb", server("h", " ", null)).port()).isZero();
assertThat(DatabaseConfig.from(p, "mariadb", server("h", "3307", null)).port()).isEqualTo(3307);
for (String bad : new String[] {"0", "65536", "-1", "33o6", "3306;x"}) {
assertThatThrownBy(() -> DatabaseConfig.from(p, "mariadb", server("h", bad, null))).as(bad)
.hasMessageContaining("port");
}
}
@Test
void theOtherFieldsAreCheckedToo() {
DatabaseProps p = new DatabaseProps();
assertThatThrownBy(() -> DatabaseConfig.from(p, "postgresql", with(server(), "run way", null, null)))
.hasMessageContaining("database name");
assertThatThrownBy(() -> DatabaseConfig.from(p, "postgresql", server("h", null, "prefer")))
.hasMessageContaining("tls");
assertThatThrownBy(() -> DatabaseConfig.from(p, "mysql", server())).hasMessageContaining("unknown provider");
assertThatThrownBy(() -> DatabaseConfig.from(p, " ", server())).hasMessageContaining("no provider");
assertThatThrownBy(() -> DatabaseConfig.from(p, "postgresql", with(server(), "runway", "not a certificate",
null))).hasMessageContaining("PEM");
assertThatThrownBy(() -> DatabaseConfig.from(p, "mariadb", with(server(), "runway", null, "utf8mb4; DROP")))
.hasMessageContaining("collation");
assertThatThrownBy(() -> DatabaseConfig.from(p, "postgresql", new ProviderSettings("h", null, "runway",
null, null, null, null, null))).hasMessageContaining("username");
DatabaseProps u = new DatabaseProps();
u.setPoolMax(100000);
u.setStatementTimeoutSeconds(0);
DatabaseConfig c = DatabaseConfig.from(u, "postgresql", server());
assertThat(c.poolMax()).isEqualTo(DatabaseConfig.POOL_MAX);
assertThat(c.statementTimeout().toSeconds()).isEqualTo(DatabaseConfig.TIMEOUT_MIN_S);
}
}
Loaded 100 of 268 files, more files were not shown because too many files have changed in this diff. Show more