Runway 1.1.0
This commit is contained in:
1 parent
ce217fc952
commit
07d5bd7e9a
223 files changed
+21147
-255
No files matched your search
+13
-6
@@ -2,8 +2,8 @@
|
||||
|
||||
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
|
||||
folder under a Runway install's `external/plugins/<id>/`. The contract is **SPI `1.0.0`** (Runway `1.0.0`): the
|
||||
kernel blocks a plugin that links its internal classes. The SPI jars are not yet published to a Maven repository — see the authoring
|
||||
folder under a Runway install's `external/plugins/<id>/`. The contract is **SPI `1.1.0`** (Runway `1.1.0`; every `1.0.0`
|
||||
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.
|
||||
|
||||
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
|
||||
├── 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)
|
||||
└── 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,
|
||||
@@ -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
|
||||
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:
|
||||
**`lucene-provider`** has `docs/LUCENE-PROVIDER-PLUGIN.md` but no verify script — it is a code-less library bundle
|
||||
with no code of its own to verify.
|
||||
`scripts/verify-against-host.sh` that checks it against the packaged host. Three do not have their own verify script:
|
||||
**`lucene-provider`** is a code-less library bundle with no code of its own to verify, and the two database
|
||||
providers (**`database-postgresql`**, **`database-mariadb`**) are verified by `database/scripts/verify-against-host.sh`,
|
||||
which installs both.
|
||||
|
||||
## 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`) →
|
||||
[`discoverability/`](discoverability/).
|
||||
- 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
|
||||
|
||||
|
||||
@@ -157,6 +157,11 @@
|
||||
<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>
|
||||
@@ -169,6 +174,8 @@
|
||||
<dirset dir="${stage}"/>
|
||||
<dirset dir="${project.build.directory}" includes="blog"/>
|
||||
</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">
|
||||
<zipfileset dir="${project.build.directory}" includes="blog/**"/>
|
||||
</zip>
|
||||
|
||||
@@ -125,6 +125,8 @@
|
||||
entry's DOS time in the local header and again in the central dir. -->
|
||||
<dirset dir="${project.build.directory}" includes="carousel-manager"/>
|
||||
</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 the REAL staged directory rather than synthesising the folder
|
||||
with prefix=. Ant stamps a prefix-synthesised directory entry with
|
||||
|
||||
@@ -129,6 +129,8 @@
|
||||
<dirset dir="${stage}"/>
|
||||
<dirset dir="${project.build.directory}" includes="contact"/>
|
||||
</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">
|
||||
<zipfileset dir="${project.build.directory}" includes="contact/**"/>
|
||||
</zip>
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
# Changelog
|
||||
|
||||
All notable changes are recorded here. Versions follow [Semantic Versioning](https://semver.org/).
|
||||
|
||||
## [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.
|
||||
@@ -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.
|
||||
@@ -0,0 +1,14 @@
|
||||
# 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. Choose it with the database plugin's `provider: mariadb` setting.
|
||||
|
||||
- **Plugin id:** `database-mariadb` (v`1.0.0`) — install folder `external/plugins/database-mariadb/`
|
||||
- **Requires:** `database >= 1.0.0`, Runway SPI `1.1.0` or later
|
||||
- **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. 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,34 @@
|
||||
# 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`.
|
||||
@@ -0,0 +1,20 @@
|
||||
# =============================================================================
|
||||
# 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.
|
||||
#
|
||||
# Choose it 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: 1.0.0
|
||||
|
||||
mainClass: mx.quest.database.mariadb.MariaDbProviderConfig
|
||||
|
||||
# The database plugin publishes the DatabaseProvider interface this plugin implements.
|
||||
requires: [ "database >= 1.0.0" ]
|
||||
|
||||
requiresSpi: ">=1.1.0"
|
||||
@@ -0,0 +1,188 @@
|
||||
<?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>1.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.1.0 adds PluginSettings.appSecret. -->
|
||||
<runway.version>1.1.0</runway.version>
|
||||
<!-- The database plugin whose SPI this provider implements (provided: the shared plugin class loader
|
||||
supplies it; install ../database first). -->
|
||||
<database.version>1.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>
|
||||
<!-- 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,98 @@
|
||||
package mx.quest.database.mariadb;
|
||||
|
||||
import java.sql.SQLException;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import javax.sql.DataSource;
|
||||
import mx.quest.database.spi.ConnectionSettings;
|
||||
import mx.quest.database.spi.DatabaseProvider;
|
||||
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;
|
||||
|
||||
@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;
|
||||
}
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
package mx.quest.database.mariadb;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
/** Registers the MariaDB provider; the database plugin collects it by type. */
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
public class MariaDbProviderConfig {
|
||||
|
||||
@Bean
|
||||
public MariaDbProvider databaseMariadbProvider() {
|
||||
return new MariaDbProvider();
|
||||
}
|
||||
}
|
||||
+141
@@ -0,0 +1,141 @@
|
||||
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.TimeZone;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.stream.Stream;
|
||||
import mx.quest.database.spi.ConnectionSettings;
|
||||
import mx.quest.database.spi.ConnectionSettings.Tls;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
|
||||
|
||||
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");
|
||||
}
|
||||
|
||||
@Test
|
||||
void theConfigurationRegistersOneProviderNamedForThePlugin() {
|
||||
try (AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(
|
||||
MariaDbProviderConfig.class)) {
|
||||
assertThat(ctx.getBeanNamesForType(mx.quest.database.spi.DatabaseProvider.class))
|
||||
.containsExactly("databaseMariadbProvider");
|
||||
}
|
||||
}
|
||||
|
||||
@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();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
# Changelog
|
||||
|
||||
All notable changes are recorded here. Versions follow [Semantic Versioning](https://semver.org/).
|
||||
|
||||
## [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.
|
||||
@@ -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.
|
||||
@@ -0,0 +1,12 @@
|
||||
# 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. Choose it with the database plugin's `provider: postgresql` setting.
|
||||
|
||||
- **Plugin id:** `database-postgresql` (v`1.0.0`) — install folder `external/plugins/database-postgresql/`
|
||||
- **Requires:** `database >= 1.0.0`, Runway SPI `1.1.0` or later
|
||||
- **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. 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,23 @@
|
||||
# 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`.
|
||||
@@ -0,0 +1,19 @@
|
||||
# =============================================================================
|
||||
# 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.
|
||||
#
|
||||
# Choose it 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: 1.0.0
|
||||
|
||||
mainClass: mx.quest.database.postgresql.PostgresProviderConfig
|
||||
|
||||
# The database plugin publishes the DatabaseProvider interface this plugin implements.
|
||||
requires: [ "database >= 1.0.0" ]
|
||||
|
||||
requiresSpi: ">=1.1.0"
|
||||
@@ -0,0 +1,166 @@
|
||||
<?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>1.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.1.0 adds PluginSettings.appSecret. -->
|
||||
<runway.version>1.1.0</runway.version>
|
||||
<!-- The database plugin whose SPI this provider implements (provided: the shared plugin class loader
|
||||
supplies it; install ../database first). -->
|
||||
<database.version>1.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>
|
||||
<!-- 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>
|
||||
+79
@@ -0,0 +1,79 @@
|
||||
package mx.quest.database.postgresql;
|
||||
|
||||
import java.util.Objects;
|
||||
import javax.sql.DataSource;
|
||||
import mx.quest.database.spi.ConnectionSettings;
|
||||
import mx.quest.database.spi.DatabaseProvider;
|
||||
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";
|
||||
|
||||
@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));
|
||||
}
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
package mx.quest.database.postgresql;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
/** Registers the PostgreSQL provider; the database plugin collects it by type. */
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
public class PostgresProviderConfig {
|
||||
|
||||
@Bean
|
||||
public PostgresProvider databasePostgresqlProvider() {
|
||||
return new PostgresProvider();
|
||||
}
|
||||
}
|
||||
+94
@@ -0,0 +1,94 @@
|
||||
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.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.stream.Stream;
|
||||
import mx.quest.database.spi.ConnectionSettings;
|
||||
import mx.quest.database.spi.ConnectionSettings.Tls;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.postgresql.ds.PGSimpleDataSource;
|
||||
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
|
||||
|
||||
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");
|
||||
}
|
||||
|
||||
@Test
|
||||
void theConfigurationRegistersOneProviderNamedForThePlugin() {
|
||||
try (AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(
|
||||
PostgresProviderConfig.class)) {
|
||||
assertThat(ctx.getBeanNamesForType(mx.quest.database.spi.DatabaseProvider.class))
|
||||
.containsExactly("databasePostgresqlProvider");
|
||||
}
|
||||
}
|
||||
|
||||
@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();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
# Changelog
|
||||
|
||||
All notable changes are recorded here. Versions follow [Semantic Versioning](https://semver.org/).
|
||||
|
||||
## [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).
|
||||
@@ -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.
|
||||
@@ -0,0 +1,51 @@
|
||||
# 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 connection tests and recovery
|
||||
actions; 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; every statement Runway runs is written here.
|
||||
|
||||
- **Plugin id:** `database` (v`1.0.0`) — install folder `external/plugins/database/`
|
||||
- **Requires:** Runway with SPI `1.1.0` or later (`requiresSpi: ">=1.1.0"`) and one provider plugin
|
||||
- **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`)
|
||||
|
||||
## For operators
|
||||
|
||||
Installation, the server's grants, every setting, TLS, clusters, backups and recovery are in the kernel's
|
||||
**ADMINISTRATION §11.1**.
|
||||
|
||||
## 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).
|
||||
@@ -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.
|
||||
@@ -0,0 +1,233 @@
|
||||
# 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` → `DatabaseConfig` | Bound from `runway.plugin.database.*`; checked before any use. The password comes from `PluginSettings.appSecret("password")` (SPI 1.1.0). |
|
||||
| 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 and the dashboard line. |
|
||||
|
||||
**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`) to everything that decides where it goes, and the connection test reuses it
|
||||
only for exactly the running target.
|
||||
- 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`.
|
||||
@@ -0,0 +1,107 @@
|
||||
# Runway Database — English
|
||||
database.menu=Database
|
||||
|
||||
database.group.connection=Connection
|
||||
database.group.connection.help=The database server Runway connects to. Changes apply after a restart; in a cluster every node needs the same values.
|
||||
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=The database product. Install its provider plugin too: database-postgresql or database-mariadb.
|
||||
database.set.host=Host
|
||||
database.set.host.help=A host name or an IP address. One server only.
|
||||
database.set.port=Port
|
||||
database.set.port.help=Leave blank for the product's default (5432 for PostgreSQL, 3306 for MariaDB).
|
||||
database.set.database=Database
|
||||
database.set.database.help=An existing database on the server. Runway creates its schemas inside it (on MariaDB, databases next to it).
|
||||
database.set.username=Username
|
||||
database.set.password=Password
|
||||
database.set.tls=TLS
|
||||
database.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.set.caCertificate=CA certificate (PEM)
|
||||
database.set.caCertificate.help=The certificate authority that signed the server's certificate, when the Java trust store does not know it.
|
||||
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.set.collation=Collation (MariaDB)
|
||||
database.set.collation.help=For plugins' tables on MariaDB. Blank uses utf8mb4_uca1400_ai_ci (utf8mb4_unicode_ci before MariaDB 10.10).
|
||||
|
||||
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.tests=Connection tests
|
||||
database.console.testRunning=Test running connection
|
||||
database.console.testNew=Test these settings
|
||||
database.console.testNew.help=Try other settings without saving them. Nothing is changed.
|
||||
database.console.testNew.password=A blank password reuses the saved one only for the same provider, server, database, account and TLS settings.
|
||||
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.invalid=The settings cannot be used: {0}
|
||||
database.test.port=the port is not a number
|
||||
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.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,107 @@
|
||||
# Runway Database — español
|
||||
database.menu=Base de datos
|
||||
|
||||
database.group.connection=Conexión
|
||||
database.group.connection.help=El servidor de base de datos al que se conecta Runway. Los cambios se aplican al reiniciar; en un clúster, todos los nodos necesitan los mismos valores.
|
||||
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=El producto de base de datos. Instale también su plugin proveedor: database-postgresql o database-mariadb.
|
||||
database.set.host=Servidor
|
||||
database.set.host.help=Un nombre de host o una dirección IP. Un solo servidor.
|
||||
database.set.port=Puerto
|
||||
database.set.port.help=Déjelo en blanco para usar el predeterminado (5432 para PostgreSQL, 3306 para MariaDB).
|
||||
database.set.database=Base de datos
|
||||
database.set.database.help=Una base de datos existente en el servidor. Runway crea sus esquemas dentro de ella (en MariaDB, bases de datos junto a ella).
|
||||
database.set.username=Usuario
|
||||
database.set.password=Contraseña
|
||||
database.set.tls=TLS
|
||||
database.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.set.caCertificate=Certificado de la CA (PEM)
|
||||
database.set.caCertificate.help=La autoridad que firmó el certificado del servidor, cuando el almacén de confianza de Java no la conoce.
|
||||
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.set.collation=Intercalación (MariaDB)
|
||||
database.set.collation.help=Para las tablas de los plugins en MariaDB. En blanco se usa utf8mb4_uca1400_ai_ci (utf8mb4_unicode_ci antes de MariaDB 10.10).
|
||||
|
||||
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.tests=Pruebas de conexión
|
||||
database.console.testRunning=Probar la conexión en uso
|
||||
database.console.testNew=Probar estos ajustes
|
||||
database.console.testNew.help=Pruebe otros ajustes sin guardarlos. No se cambia nada.
|
||||
database.console.testNew.password=Una contraseña en blanco reutiliza la guardada solo con el mismo proveedor, servidor, base de datos, usuario y ajustes de TLS.
|
||||
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.invalid=Los ajustes no se pueden usar: {0}
|
||||
database.test.port=el puerto no es un número
|
||||
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.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
|
||||
@@ -0,0 +1,76 @@
|
||||
# =============================================================================
|
||||
# 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.
|
||||
#
|
||||
# The install folder name MUST equal this `id`: external/plugins/database/.
|
||||
# =============================================================================
|
||||
id: database
|
||||
name: Database
|
||||
version: 1.0.0
|
||||
|
||||
mainClass: mx.quest.database.DatabasePluginConfig
|
||||
|
||||
# SPI 1.1.0: PluginSettings.appSecret, which reads the Runway-wide password in clear.
|
||||
requiresSpi: ">=1.1.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: connection, label: database.group.connection, help: database.group.connection.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. Changing the server or the provider does not move data: move sites with backup and restore.
|
||||
settings:
|
||||
- { key: provider, type: enum, range: "postgresql,mariadb", default: postgresql, group: connection,
|
||||
label: database.set.provider, help: database.set.provider.help }
|
||||
- { key: host, type: string, group: connection, label: database.set.host, help: database.set.host.help }
|
||||
- { key: port, type: int, range: "1..65535", group: connection, label: database.set.port,
|
||||
help: database.set.port.help }
|
||||
- { key: database, type: string, group: connection, label: database.set.database,
|
||||
help: database.set.database.help }
|
||||
- { key: username, type: string, group: connection, label: database.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.set.password
|
||||
secretBoundTo: [provider, host, port, database, username, tls, caCertificate]
|
||||
- { key: tls, type: enum, range: "verify-full,require,disable", default: verify-full, group: connection,
|
||||
label: database.set.tls, help: database.set.tls.help }
|
||||
- { key: caCertificate, type: text, group: connection, advanced: true, label: database.set.caCertificate,
|
||||
help: database.set.caCertificate.help }
|
||||
- { key: namespace, type: string, default: rw, group: connection, 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 }
|
||||
- { key: collation, type: string, group: limits, advanced: true, label: database.set.collation,
|
||||
help: database.set.collation.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 }
|
||||
@@ -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>1.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.1.0 adds PluginSettings.appSecret. -->
|
||||
<runway.version>1.1.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>
|
||||
+156
@@ -0,0 +1,156 @@
|
||||
#!/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 database plugin pointed at a server you name, then checks:
|
||||
# - 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 its running-connection test passes;
|
||||
# - 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
|
||||
|
||||
# A hand-written plaintext password works like an encrypted one; this file is deleted with the scratch folder.
|
||||
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) ..."
|
||||
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'"
|
||||
|
||||
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'"
|
||||
ac -L "$BASE/__app/database/test-running" --data-urlencode "_csrf=$(token < "$SCRATCH/screen.html")" \
|
||||
> "$SCRATCH/tested.html"
|
||||
ck "Test running connection: connected" "grep -qE 'Connected: (PostgreSQL|MariaDB)' '$SCRATCH/tested.html'"
|
||||
ck "a POST without the CSRF token is refused" "[ \"\$(code -b '$SCRATCH/app.jar' -X POST '$BASE/__app/database/test-running')\" = 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 ]"
|
||||
|
||||
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,142 @@
|
||||
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.DatabaseConfig;
|
||||
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.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.PluginSettings;
|
||||
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, PluginSettings settings,
|
||||
ObjectProvider<DatabaseProvider> providers, PluginInfo self,
|
||||
ScheduledExecutorService databaseExecutor) {
|
||||
Supplier<List<DatabaseProvider>> found = () -> providers.orderedStream().toList();
|
||||
return new DatabaseRuntime(() -> DatabaseConfig.from(databaseProps, settings.appSecret("password")), found,
|
||||
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,
|
||||
ObjectProvider<DatabaseProvider> providers, PluginInfo self) {
|
||||
return new ConnectionTester(databaseRuntime, () -> 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");
|
||||
}
|
||||
}
|
||||
+183
@@ -0,0 +1,183 @@
|
||||
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.DatabaseProps;
|
||||
import mx.quest.database.internal.DatabaseRuntime;
|
||||
import mx.quest.database.internal.DatabasesImpl;
|
||||
import mx.quest.database.internal.Migrator;
|
||||
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, the two connection tests and
|
||||
* the migration recovery actions. 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";
|
||||
|
||||
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());
|
||||
}
|
||||
|
||||
@PostMapping("/test-new")
|
||||
@PreAuthorize(GATE)
|
||||
public String testNew(@RequestParam(name = "provider", defaultValue = "") String provider,
|
||||
@RequestParam(name = "namespace", defaultValue = "") String namespace,
|
||||
@RequestParam(name = "host", defaultValue = "") String host,
|
||||
@RequestParam(name = "port", defaultValue = "") String port,
|
||||
@RequestParam(name = "database", defaultValue = "") String database,
|
||||
@RequestParam(name = "username", defaultValue = "") String username,
|
||||
@RequestParam(name = "password", defaultValue = "") String password,
|
||||
@RequestParam(name = "tls", defaultValue = "") String tls,
|
||||
@RequestParam(name = "caCertificate", defaultValue = "") String caCertificate,
|
||||
RedirectAttributes flash) {
|
||||
DatabaseProps props = new DatabaseProps();
|
||||
props.setProvider(provider);
|
||||
props.setNamespace(namespace.isBlank() ? null : namespace);
|
||||
props.setHost(host);
|
||||
props.setDatabase(database);
|
||||
props.setUsername(username);
|
||||
props.setTls(tls);
|
||||
props.setCaCertificate(caCertificate);
|
||||
if (!port.isBlank()) {
|
||||
try {
|
||||
props.setPort(Integer.parseInt(port.strip()));
|
||||
} catch (NumberFormatException e) {
|
||||
return back(flash, FLASH_ERROR, console("database.test.invalid", "The settings cannot be used: {0}",
|
||||
console("database.test.port", "the port is not a number")));
|
||||
}
|
||||
}
|
||||
return result(flash, tester.newSettings(props, password));
|
||||
}
|
||||
|
||||
@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.");
|
||||
};
|
||||
return back(flash, result.category() == ConnectionTester.Category.OK ? FLASH : FLASH_ERROR, text);
|
||||
}
|
||||
|
||||
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,137 @@
|
||||
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.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 org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
/**
|
||||
* The console's two connection tests. 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>New settings</b>: opens one throwaway connection with short timeouts from typed values and saves nothing.
|
||||
* A blank password reuses the running one only when every setting the password is bound to (provider, host,
|
||||
* port, database, username, TLS, CA certificate) matches the running value, so the test cannot send the saved
|
||||
* password to a server of the tester's choosing.</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 Supplier<List<DatabaseProvider>> providers;
|
||||
private final Path workDir;
|
||||
|
||||
public ConnectionTester(DatabaseRuntime runtime, Supplier<List<DatabaseProvider>> providers, Path workDir) {
|
||||
this.runtime = runtime;
|
||||
this.providers = providers;
|
||||
this.workDir = workDir;
|
||||
}
|
||||
|
||||
/** 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 typed settings.
|
||||
*
|
||||
* @param props the typed values
|
||||
* @param password the typed password; blank to reuse the running one where the rule allows
|
||||
*/
|
||||
public Result newSettings(DatabaseProps props, String password) {
|
||||
DatabaseConfig typed;
|
||||
try {
|
||||
typed = DatabaseConfig.from(props, Optional.empty());
|
||||
} catch (IllegalArgumentException e) {
|
||||
return new Result(Category.INVALID_SETTINGS, e.getMessage());
|
||||
}
|
||||
String secret = password == null ? "" : password;
|
||||
if (secret.isEmpty()) {
|
||||
DatabaseConfig running = runtime.config();
|
||||
if (running != null && sameTarget(running, typed)) {
|
||||
secret = running.password();
|
||||
}
|
||||
}
|
||||
DatabaseConfig config;
|
||||
try {
|
||||
config = DatabaseConfig.from(props, Optional.of(secret));
|
||||
} catch (IllegalArgumentException e) {
|
||||
return new Result(Category.INVALID_SETTINGS, e.getMessage());
|
||||
}
|
||||
List<DatabaseProvider> matching = providers.get().stream().filter(p -> config.provider().equals(p.id()))
|
||||
.toList();
|
||||
if (matching.size() != 1) {
|
||||
return new Result(Category.NO_PROVIDER, "database-" + config.provider());
|
||||
}
|
||||
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: new-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: new-settings test against {} failed: {}", config, DatabaseRuntime.describe(e));
|
||||
return new Result(Category.OTHER, "");
|
||||
}
|
||||
}
|
||||
|
||||
/** Whether two settings point the password at the same place as the same account. */
|
||||
static boolean sameTarget(DatabaseConfig a, DatabaseConfig b) {
|
||||
return a.provider().equals(b.provider()) && a.host().equals(b.host()) && a.port() == b.port()
|
||||
&& a.database().equals(b.database()) && a.username().equals(b.username()) && a.tls() == b.tls()
|
||||
&& Objects.equals(a.caCertificate(), b.caCertificate());
|
||||
}
|
||||
|
||||
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,236 @@
|
||||
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;
|
||||
|
||||
/**
|
||||
* 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 password, and again by "Test new settings" from the form's values. 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 bound settings
|
||||
* @param password the password in clear, or empty
|
||||
* @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, Optional<String> password) {
|
||||
String provider = trimToNull(props.getProvider());
|
||||
if (provider == null) {
|
||||
throw new IllegalArgumentException("no provider is chosen");
|
||||
}
|
||||
provider = provider.toLowerCase(Locale.ROOT);
|
||||
if (!PROVIDERS.contains(provider)) {
|
||||
throw new IllegalArgumentException("unknown provider: " + provider);
|
||||
}
|
||||
String namespace = Names.namespace(Optional.ofNullable(trimToNull(props.getNamespace())).orElse("rw"));
|
||||
String host = checkHost(props.getHost());
|
||||
int port = props.getPort() == null ? 0 : props.getPort();
|
||||
if (port < 0 || port > 65535) {
|
||||
throw new IllegalArgumentException("the port must be between 1 and 65535, or blank for the default");
|
||||
}
|
||||
String database = trimToNull(props.getDatabase());
|
||||
if (database == null || !DATABASE.matcher(database).matches()) {
|
||||
throw new IllegalArgumentException("the database name must be 1 to 63 letters, digits, '_', '$' or '-'");
|
||||
}
|
||||
String username = trimToNull(props.getUsername());
|
||||
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 = password.orElse("");
|
||||
if (secret.length() > PASSWORD_MAX || hasControl(secret)) {
|
||||
throw new IllegalArgumentException("the password is too long or holds control characters");
|
||||
}
|
||||
Tls tls = tls(props.getTls());
|
||||
String ca = trimToNull(props.getCaCertificate());
|
||||
if (ca != null) {
|
||||
ca = checkPem(ca);
|
||||
}
|
||||
String collation = trimToNull(props.getCollation());
|
||||
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(provider, namespace, host, port, database, username, secret, tls, ca, poolMax,
|
||||
Duration.ofSeconds(timeout), budget * 1024L * 1024L, collation);
|
||||
}
|
||||
|
||||
/** 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,118 @@
|
||||
package mx.quest.database.internal;
|
||||
|
||||
/**
|
||||
* The database plugin's app-level settings as bound from {@code runway.plugin.database.*} at startup
|
||||
* ({@code external/plugin-settings/database.yml}). Raw values: {@link DatabaseConfig#from} checks them. The password
|
||||
* is not here: it is read in clear through {@code PluginSettings.appSecret("password")}.
|
||||
*/
|
||||
public class DatabaseProps {
|
||||
|
||||
private String provider;
|
||||
private String namespace = "rw";
|
||||
private String host;
|
||||
private Integer port;
|
||||
private String database;
|
||||
private String username;
|
||||
private String tls = "verify-full";
|
||||
private String caCertificate;
|
||||
private Integer poolMax = 10;
|
||||
private Integer statementTimeoutSeconds = 10;
|
||||
private Integer backupBudgetMiB = 128;
|
||||
private String collation;
|
||||
|
||||
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 String getHost() {
|
||||
return host;
|
||||
}
|
||||
|
||||
public void setHost(String host) {
|
||||
this.host = host;
|
||||
}
|
||||
|
||||
public Integer getPort() {
|
||||
return port;
|
||||
}
|
||||
|
||||
public void setPort(Integer 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 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 getCollation() {
|
||||
return collation;
|
||||
}
|
||||
|
||||
public void setCollation(String collation) {
|
||||
this.collation = collation;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,561 @@
|
||||
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 (or two are). */
|
||||
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<DatabaseConfig> configSource;
|
||||
private final Supplier<List<DatabaseProvider>> providers;
|
||||
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 configSource builds the checked settings; throws {@link IllegalArgumentException} with a reason
|
||||
* @param providers the provider beans installed
|
||||
* @param workDir the plugin's own folder for the CA file
|
||||
* @param executor the plugin's executor
|
||||
*/
|
||||
public DatabaseRuntime(Supplier<DatabaseConfig> configSource, Supplier<List<DatabaseProvider>> providers,
|
||||
Path workDir, ScheduledExecutorService executor) {
|
||||
this.configSource = Objects.requireNonNull(configSource, "configSource");
|
||||
this.providers = Objects.requireNonNull(providers, "providers");
|
||||
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();
|
||||
}
|
||||
|
||||
/** Reads the settings and finds the provider; false (with the status set) when that cannot work. */
|
||||
private boolean prepare() {
|
||||
DatabaseConfig c;
|
||||
try {
|
||||
c = configSource.get();
|
||||
} catch (IllegalArgumentException e) {
|
||||
status = Status.NOT_CONFIGURED;
|
||||
detail = e.getMessage();
|
||||
log.info("database: not configured: {}", e.getMessage());
|
||||
return false;
|
||||
}
|
||||
List<DatabaseProvider> matching = providers.get().stream().filter(p -> c.provider().equals(p.id())).toList();
|
||||
if (matching.size() != 1) {
|
||||
status = Status.NO_PROVIDER;
|
||||
detail = matching.isEmpty()
|
||||
? "the provider plugin for '" + c.provider() + "' (database-" + c.provider() + ") is not installed"
|
||||
: "two provider plugins offer '" + c.provider() + "'; remove one";
|
||||
log.warn("database: {}", detail);
|
||||
return false;
|
||||
}
|
||||
DatabaseProvider provider = matching.get(0);
|
||||
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,512 @@
|
||||
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: 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,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);
|
||||
}
|
||||
}
|
||||
}
|
||||
+13
@@ -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,45 @@
|
||||
package mx.quest.database.spi;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
|
||||
/**
|
||||
* A database product, contributed by a provider plugin that ships the product's JDBC driver in its {@code lib/}.
|
||||
* The operator picks one by its {@link #id()} in the database plugin's {@code provider} setting.
|
||||
*
|
||||
* <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);
|
||||
}
|
||||
+25
@@ -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,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,28 @@
|
||||
/**
|
||||
* 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 operator picks the provider 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,180 @@
|
||||
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.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.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");
|
||||
}
|
||||
});
|
||||
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", "runway.plugin.database.host", "127.0.0.1",
|
||||
"runway.plugin.database.port", "1", "runway.plugin.database.database", "runway",
|
||||
"runway.plugin.database.username", "runway", "runway.plugin.database.tls", "disable")));
|
||||
ctx.registerBean(PluginSettings.class, () -> new FakePluginSettings().appSecret("password", "x"));
|
||||
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");
|
||||
}
|
||||
});
|
||||
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 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,76 @@
|
||||
package mx.quest.database.internal;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
import java.util.Optional;
|
||||
import mx.quest.database.spi.ConnectionSettings.Tls;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class DatabaseConfigTest {
|
||||
|
||||
static DatabaseProps props() {
|
||||
DatabaseProps p = new DatabaseProps();
|
||||
p.setProvider("postgresql");
|
||||
p.setHost("db.example.com");
|
||||
p.setDatabase("runway");
|
||||
p.setUsername("runway");
|
||||
return p;
|
||||
}
|
||||
|
||||
@Test
|
||||
void aCompleteSetOfSettingsIsCheckedWithSafeDefaults() {
|
||||
DatabaseConfig c = DatabaseConfig.from(props(), Optional.of("s3cret"));
|
||||
assertThat(c.tls()).isEqualTo(Tls.VERIFY_FULL);
|
||||
assertThat(c.namespace()).isEqualTo("rw");
|
||||
assertThat(c.port()).isZero();
|
||||
assertThat(c.poolMax()).isEqualTo(10);
|
||||
assertThat(c.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"}) {
|
||||
DatabaseProps p = props();
|
||||
p.setHost(bad);
|
||||
assertThatThrownBy(() -> DatabaseConfig.from(p, Optional.empty())).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"}) {
|
||||
DatabaseProps p = props();
|
||||
p.setHost(good);
|
||||
assertThat(DatabaseConfig.from(p, Optional.empty()).host()).as(good).doesNotContain("[");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void theOtherFieldsAreCheckedToo() {
|
||||
DatabaseProps p = props();
|
||||
p.setDatabase("run way");
|
||||
assertThatThrownBy(() -> DatabaseConfig.from(p, Optional.empty())).hasMessageContaining("database name");
|
||||
DatabaseProps q = props();
|
||||
q.setTls("prefer");
|
||||
assertThatThrownBy(() -> DatabaseConfig.from(q, Optional.empty())).hasMessageContaining("tls");
|
||||
DatabaseProps r = props();
|
||||
r.setProvider("mysql");
|
||||
assertThatThrownBy(() -> DatabaseConfig.from(r, Optional.empty())).hasMessageContaining("unknown provider");
|
||||
DatabaseProps s = props();
|
||||
s.setCaCertificate("not a certificate");
|
||||
assertThatThrownBy(() -> DatabaseConfig.from(s, Optional.empty())).hasMessageContaining("PEM");
|
||||
DatabaseProps t = props();
|
||||
t.setCollation("utf8mb4; DROP");
|
||||
assertThatThrownBy(() -> DatabaseConfig.from(t, Optional.empty())).hasMessageContaining("collation");
|
||||
DatabaseProps u = props();
|
||||
u.setPoolMax(100000);
|
||||
u.setStatementTimeoutSeconds(0);
|
||||
DatabaseConfig c = DatabaseConfig.from(u, Optional.empty());
|
||||
assertThat(c.poolMax()).isEqualTo(DatabaseConfig.POOL_MAX);
|
||||
assertThat(c.statementTimeout().toSeconds()).isEqualTo(DatabaseConfig.TIMEOUT_MIN_S);
|
||||
DatabaseProps v = props();
|
||||
v.setProvider(null);
|
||||
assertThatThrownBy(() -> DatabaseConfig.from(v, Optional.empty())).hasMessageContaining("no provider");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,316 @@
|
||||
package mx.quest.database.internal;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
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.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.sql.Connection;
|
||||
import java.sql.SQLException;
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import javax.sql.DataSource;
|
||||
import mx.quest.database.spi.ConnectionSettings;
|
||||
import mx.quest.database.spi.DatabaseConsumer;
|
||||
import mx.quest.database.spi.DatabaseProvider;
|
||||
import mx.quest.database.spi.PluginDatabase;
|
||||
import mx.quest.database.spi.Scope;
|
||||
import mx.quest.runway.spi.model.BackupReader;
|
||||
import mx.quest.runway.spi.model.BackupWriter;
|
||||
import mx.quest.runway.spi.model.SiteView;
|
||||
import mx.quest.runway.spi.service.RequestContext;
|
||||
import mx.quest.runway.spi.service.Sites;
|
||||
import mx.quest.runway.spi.testkit.TempDirSiteFiles;
|
||||
import org.mariadb.jdbc.MariaDbDataSource;
|
||||
import org.postgresql.ds.PGSimpleDataSource;
|
||||
|
||||
/**
|
||||
* One "node" of the database plugin wired against a real server, without Spring: the runtime, the schemas, the
|
||||
* migrator, the backup participant, test providers built the way the provider plugins build theirs, and fake sites.
|
||||
* The servers come from system properties ({@code db.it.postgresql}, {@code db.it.mariadb} as host:port, and
|
||||
* {@code db.it.password-file}); without them the tests that need a server are skipped.
|
||||
*/
|
||||
final class Harness implements AutoCloseable {
|
||||
|
||||
static final String DATABASE = "runway";
|
||||
static final String USER = "runway";
|
||||
|
||||
/** A server under test. */
|
||||
record Endpoint(String host, int port, String password) {
|
||||
}
|
||||
|
||||
static Optional<Endpoint> endpoint(String engine) {
|
||||
String hostPort = System.getProperty("db.it." + engine);
|
||||
String file = System.getProperty("db.it.password-file");
|
||||
if (hostPort == null || file == null) {
|
||||
return Optional.empty();
|
||||
}
|
||||
try {
|
||||
String[] parts = hostPort.split(":");
|
||||
return Optional.of(new Endpoint(parts[0], Integer.parseInt(parts[1]),
|
||||
Files.readString(Path.of(file)).strip()));
|
||||
} catch (IOException e) {
|
||||
throw new IllegalStateException(e);
|
||||
}
|
||||
}
|
||||
|
||||
/** The provider the provider plugins will be: their own DataSource, pinned properties, no DriverManager. */
|
||||
static DatabaseProvider provider(String engine) {
|
||||
return new DatabaseProvider() {
|
||||
@Override
|
||||
public String id() {
|
||||
return engine;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String driverVersion() {
|
||||
return "test";
|
||||
}
|
||||
|
||||
@Override
|
||||
public DataSource dataSource(ConnectionSettings s) {
|
||||
if (engine.equals("postgresql")) {
|
||||
PGSimpleDataSource ds = new PGSimpleDataSource();
|
||||
ds.setServerNames(new String[] {s.host()});
|
||||
ds.setPortNumbers(new int[] {s.portOr(5432)});
|
||||
ds.setDatabaseName(s.database());
|
||||
ds.setUser(s.username());
|
||||
ds.setPassword(s.password());
|
||||
ds.setSslMode("disable");
|
||||
ds.setConnectTimeout((int) s.connectTimeout().toSeconds());
|
||||
ds.setSocketTimeout((int) s.socketTimeout().toSeconds());
|
||||
ds.setTcpKeepAlive(true);
|
||||
return ds;
|
||||
}
|
||||
try {
|
||||
// The properties database-mariadb's MariaDbProvider.url pins (no preserveInstants: see its test).
|
||||
MariaDbDataSource ds = new MariaDbDataSource("jdbc:mariadb://" + s.host() + ":" + s.portOr(3306)
|
||||
+ "/" + s.database() + "?allowLocalInfile=false&allowMultiQueries=false"
|
||||
+ "&permitRedirect=false&allowPublicKeyRetrieval=false&connectionTimeZone=UTC"
|
||||
+ "&sslMode=disable&tcpKeepAlive=true&connectTimeout="
|
||||
+ s.connectTimeout().toMillis() + "&socketTimeout=" + s.socketTimeout().toMillis());
|
||||
ds.setUser(s.username());
|
||||
ds.setPassword(s.password());
|
||||
return ds;
|
||||
} catch (SQLException e) {
|
||||
throw new IllegalStateException(e);
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/** Sites and the current request's site. */
|
||||
static final class FakeSites implements Sites, RequestContext {
|
||||
final Path root;
|
||||
final Map<String, SiteView> sites = new ConcurrentHashMap<>();
|
||||
/** Ids find() answers as missing although they exist (a kernel that cannot read the folder and says so). */
|
||||
final Set<String> hidden = ConcurrentHashMap.newKeySet();
|
||||
/** Ids find() throws for (a kernel that says it cannot tell). */
|
||||
final Set<String> throwing = ConcurrentHashMap.newKeySet();
|
||||
volatile String current;
|
||||
|
||||
FakeSites(Path root) {
|
||||
this.root = root;
|
||||
}
|
||||
|
||||
void add(String id) throws IOException {
|
||||
Files.createDirectories(root.resolve(id));
|
||||
sites.put(id, new SiteView(id, id, Locale.ENGLISH, List.of(Locale.ENGLISH), "https://" + id));
|
||||
}
|
||||
|
||||
void delete(String id) throws IOException {
|
||||
sites.remove(id);
|
||||
try (var walk = Files.walk(root.resolve(id))) {
|
||||
walk.sorted(java.util.Comparator.reverseOrder()).forEach(p -> p.toFile().delete());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<SiteView> find(String siteId) {
|
||||
if (throwing.contains(siteId)) {
|
||||
throw new java.io.UncheckedIOException(new IOException("cannot read site " + siteId));
|
||||
}
|
||||
if (hidden.contains(siteId)) {
|
||||
return Optional.empty();
|
||||
}
|
||||
return Optional.ofNullable(sites.get(siteId));
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<SiteView> site() {
|
||||
return current == null ? Optional.empty() : find(current);
|
||||
}
|
||||
}
|
||||
|
||||
/** Scripts held in memory, by entry name. */
|
||||
record MemoryScripts(String pluginId, Map<String, String> entries) implements ScriptSource {
|
||||
@Override
|
||||
public Optional<byte[]> read(String entry) {
|
||||
return Optional.ofNullable(entries.get(entry)).map(s -> s.getBytes(StandardCharsets.UTF_8));
|
||||
}
|
||||
}
|
||||
|
||||
final String engine;
|
||||
final String namespace;
|
||||
final Endpoint endpoint;
|
||||
final Path work;
|
||||
final FakeSites sites;
|
||||
final TempDirSiteFiles files;
|
||||
final ScheduledExecutorService executor = Executors.newScheduledThreadPool(4);
|
||||
final DatabaseProps props = new DatabaseProps();
|
||||
final List<DatabaseProvider> providers = new CopyOnWriteArrayList<>();
|
||||
final Map<String, ScriptSource> scripts = new ConcurrentHashMap<>();
|
||||
final DatabaseRuntime runtime;
|
||||
final SiteSchemas schemas;
|
||||
final Migrator migrator;
|
||||
final DatabaseCore core;
|
||||
final DatabasesImpl databases;
|
||||
final DatabaseBackup backup;
|
||||
volatile String password;
|
||||
|
||||
Harness(String engine, String namespace, Endpoint endpoint, Path work) throws IOException {
|
||||
this(engine, namespace, endpoint, work, new FakeSites(work.resolve("sites")));
|
||||
}
|
||||
|
||||
/** A second node: its own runtime and caches over the same sites and server. */
|
||||
Harness(String engine, String namespace, Endpoint endpoint, Path work, FakeSites sites) throws IOException {
|
||||
this.engine = engine;
|
||||
this.namespace = namespace;
|
||||
this.endpoint = endpoint;
|
||||
this.work = work;
|
||||
this.sites = sites;
|
||||
Files.createDirectories(sites.root);
|
||||
this.files = new TempDirSiteFiles(sites.root, "database");
|
||||
props.setProvider(engine);
|
||||
props.setNamespace(namespace);
|
||||
props.setHost(endpoint.host());
|
||||
props.setPort(endpoint.port());
|
||||
props.setDatabase(DATABASE);
|
||||
props.setUsername(USER);
|
||||
props.setTls("disable");
|
||||
password = endpoint.password();
|
||||
providers.add(provider(engine));
|
||||
runtime = new DatabaseRuntime(() -> DatabaseConfig.from(props, Optional.ofNullable(password)),
|
||||
() -> List.copyOf(providers), work.resolve("run-" + System.nanoTime()), executor);
|
||||
schemas = new SiteSchemas(runtime, files, sites);
|
||||
migrator = new Migrator(runtime);
|
||||
core = new DatabaseCore(runtime, schemas, migrator, sites, sites);
|
||||
databases = new DatabasesImpl(core, (cls, id) -> {
|
||||
ScriptSource s = scripts.get(id);
|
||||
if (s == null) {
|
||||
throw new IllegalArgumentException("not in the jar of plugin " + id);
|
||||
}
|
||||
return s;
|
||||
});
|
||||
backup = new DatabaseBackup(core, databases, files);
|
||||
migrator.parked(backup);
|
||||
}
|
||||
|
||||
Harness start() throws InterruptedException {
|
||||
runtime.start();
|
||||
long deadline = System.nanoTime() + Duration.ofSeconds(30).toNanos();
|
||||
while (!runtime.available() && System.nanoTime() < deadline
|
||||
&& runtime.status() != DatabaseRuntime.Status.NOT_CONFIGURED
|
||||
&& runtime.status() != DatabaseRuntime.Status.NO_PROVIDER) {
|
||||
Thread.sleep(50);
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
/** A consumer plugin with its scripts; returns its handle. */
|
||||
PluginDatabase consumer(String pluginId, Set<Scope.Kind> scopes, Map<String, String> entries) {
|
||||
scripts.put(pluginId, new MemoryScripts(pluginId, entries));
|
||||
return databases.of(new DatabaseConsumer() {
|
||||
@Override
|
||||
public String pluginId() {
|
||||
return pluginId;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Set<Scope.Kind> scopes() {
|
||||
return scopes;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
Consumer registered(String pluginId) {
|
||||
return databases.consumers().stream().filter(c -> c.pluginId().equals(pluginId)).findFirst().orElseThrow();
|
||||
}
|
||||
|
||||
/** A raw connection as the test account, outside every pool. */
|
||||
Connection raw() throws SQLException {
|
||||
return provider(engine).dataSource(DatabaseRuntime.settings(DatabaseConfig.from(props,
|
||||
Optional.of(endpoint.password())), null, Duration.ofSeconds(30))).getConnection();
|
||||
}
|
||||
|
||||
List<String> schemasInNamespace() throws SQLException {
|
||||
try (Connection c = raw()) {
|
||||
return runtime.engine() == null ? List.of()
|
||||
: DatabaseRuntime.engineFor(engine).listSchemas(c, namespace);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() throws SQLException {
|
||||
runtime.stop();
|
||||
executor.shutdownNow();
|
||||
}
|
||||
|
||||
/** Drops every schema of a namespace. */
|
||||
static void dropNamespace(String engine, Endpoint endpoint, String namespace, Path work) throws Exception {
|
||||
Harness h = new Harness(engine, namespace, endpoint, work.resolve("cleanup"));
|
||||
Engine e = DatabaseRuntime.engineFor(engine);
|
||||
try (Connection c = h.raw()) {
|
||||
for (String s : e.listSchemas(c, namespace)) {
|
||||
e.dropSchema(c, s);
|
||||
}
|
||||
} finally {
|
||||
h.close();
|
||||
}
|
||||
}
|
||||
|
||||
// --- an in-memory backup archive ---------------------------------------------------------------------------
|
||||
|
||||
static class MemoryArchive implements BackupWriter, BackupReader {
|
||||
final Map<String, byte[]> entries = new LinkedHashMap<>();
|
||||
final List<String> order = new ArrayList<>();
|
||||
|
||||
@Override
|
||||
public OutputStream put(String entry) {
|
||||
return new ByteArrayOutputStream() {
|
||||
@Override
|
||||
public void close() {
|
||||
entries.put(entry, toByteArray());
|
||||
order.add(entry);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean has(String entry) {
|
||||
return entries.containsKey(entry);
|
||||
}
|
||||
|
||||
@Override
|
||||
public InputStream open(String entry) throws IOException {
|
||||
byte[] b = entries.get(entry);
|
||||
if (b == null) {
|
||||
throw new IOException("missing " + entry);
|
||||
}
|
||||
return new ByteArrayInputStream(b);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package mx.quest.database.internal;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class MariaDbEngineTest {
|
||||
|
||||
@Test
|
||||
void mariaDbBefore1011IsRefusedByVersionNotByAReadOnlyVariable() throws Exception {
|
||||
assertThat(MariaDbEngine.checkServer("MariaDB", "10.11.0-MariaDB", "mariadb.org binary distribution"))
|
||||
.isEqualTo("MariaDB 10.11.0");
|
||||
assertThat(MariaDbEngine.checkServer("MariaDB", "11.4.5-MariaDB-ubu2404", "")).isEqualTo("MariaDB 11.4.5");
|
||||
for (String old : new String[] {"10.10.7-MariaDB", "10.6.21-MariaDB-log", "10.9.8-MariaDB", "5.5.68-MariaDB"}) {
|
||||
assertThatThrownBy(() -> MariaDbEngine.checkServer("MariaDB", old, ""))
|
||||
.isInstanceOf(UnsupportedServerException.class)
|
||||
.hasMessageContaining("too old: 10.11 or later is needed");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void mySqlIsNeverTakenForMariaDb() {
|
||||
assertThatThrownBy(() -> MariaDbEngine.checkServer("MySQL", "8.4.0", "MySQL Community Server - GPL"))
|
||||
.isInstanceOf(UnsupportedServerException.class).hasMessageContaining("MySQL is not supported");
|
||||
assertThatThrownBy(() -> MariaDbEngine.checkServer("MariaDB", "11.4.5-MariaDB", "MySQL fork"))
|
||||
.isInstanceOf(UnsupportedServerException.class).hasMessageContaining("MySQL is not supported");
|
||||
}
|
||||
|
||||
@Test
|
||||
void everySessionGetsExplicitTimestampDefaultsAndUtc() {
|
||||
String init = new MariaDbEngine().connectionInitSql(java.time.Duration.ofSeconds(30), null);
|
||||
assertThat(init).contains("explicit_defaults_for_timestamp = 1").contains("time_zone = '+00:00'");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
package mx.quest.database.internal;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class NamesTest {
|
||||
|
||||
@Test
|
||||
void theNamespaceIsALetterThenUpToElevenLettersOrDigitsWithNoUnderscore() {
|
||||
assertThat(Names.namespace("rw")).isEqualTo("rw");
|
||||
assertThat(Names.namespace("a12345678901")).isEqualTo("a12345678901");
|
||||
for (String bad : new String[] {"", "1rw", "r_w", "RW", "a123456789012", "rw-1", "rw;", null}) {
|
||||
assertThatThrownBy(() -> Names.namespace(bad)).isInstanceOf(IllegalArgumentException.class);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void siteIdsThatFoldAlikeStillGetDistinctSchemasThroughTheGeneration() {
|
||||
List<String> ids = List.of("acme.com", "acme_com", "a.b", "a_b", "A-B", "a-b", "Shop", "shop", "x".repeat(70));
|
||||
Set<String> names = new HashSet<>();
|
||||
long gen = 1;
|
||||
for (String id : ids) {
|
||||
String name = Names.siteSchema("rw", id, gen++, 63);
|
||||
assertThat(name).matches("rw_s_[a-z0-9_]+_[0-9]+").hasSizeLessThanOrEqualTo(63);
|
||||
assertThat(Names.isSiteSchema("rw", name, 63)).isTrue();
|
||||
names.add(name);
|
||||
}
|
||||
assertThat(names).hasSize(ids.size());
|
||||
assertThat(Names.siteSchema("rw", "Shop", 7, 63)).isEqualTo("rw_s_shop_7");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aLongSiteIdIsCutSoTheWholeNameFitsEachEngine() {
|
||||
String id = "very-long-site-id-".repeat(10);
|
||||
assertThat(Names.siteSchema("abcdefghijkl", id, Long.MAX_VALUE, 63)).hasSize(63);
|
||||
assertThat(Names.siteSchema("abcdefghijkl", id, Long.MAX_VALUE, 64)).hasSize(64);
|
||||
}
|
||||
|
||||
@Test
|
||||
void onlyThisInstallsNamesPassTheGuardBeforeDdl() {
|
||||
assertThat(Names.isOwnSchema("rw", "rw_app", 63)).isTrue();
|
||||
assertThat(Names.isOwnSchema("rw", "rw_s_acme_1", 63)).isTrue();
|
||||
assertThat(Names.isSiteSchema("rw", "rw_app", 63)).isFalse();
|
||||
for (String bad : new String[] {"rwx_app", "rw2_s_a_1", "public", "rw_s_", "rw_s_A_1", "rw_s_a-1",
|
||||
"rw_s_a;drop", "rw_other", "rw_s_" + "a".repeat(60), "mysql", "rw_app2"}) {
|
||||
assertThat(Names.isOwnSchema("rw", bad, 63)).as(bad).isFalse();
|
||||
}
|
||||
assertThatThrownBy(() -> Names.requireOwnSchema("rw", "public", 63))
|
||||
.isInstanceOf(IllegalStateException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
void prefixesEndInADoubleUnderscoreAndLongOnesAreCutWithAHash() {
|
||||
assertThat(Names.pluginPrefix("runway-demo-database")).isEqualTo("runway_demo_database__");
|
||||
assertThat(Names.pluginPrefix("Blog")).isEqualTo("blog__");
|
||||
String longer = Names.pluginPrefix("a-really-long-plugin-identifier");
|
||||
assertThat(longer).hasSize(Names.PREFIX_MAX).endsWith("__").startsWith("a_really_long_p_");
|
||||
assertThat(Names.pluginPrefix("a-really-long-plugin-identifier-2")).isNotEqualTo(longer);
|
||||
}
|
||||
|
||||
@Test
|
||||
void prefixesThatCouldOwnTheSameNameClash() {
|
||||
assertThat(Names.prefixesClash(Names.pluginPrefix("a-b"), Names.pluginPrefix("a_b"))).isTrue();
|
||||
assertThat(Names.prefixesClash(Names.pluginPrefix("Blog"), Names.pluginPrefix("blog"))).isTrue();
|
||||
assertThat(Names.prefixesClash(Names.pluginPrefix("a"), Names.pluginPrefix("a-"))).isTrue();
|
||||
assertThat(Names.prefixesClash(Names.pluginPrefix("runway"), Names.pluginPrefix("runway-demo"))).isFalse();
|
||||
assertThat(Names.isReservedPrefix(Names.pluginPrefix("rw"))).isTrue();
|
||||
assertThat(Names.isReservedPrefix(Names.pluginPrefix("rw-x"))).isTrue();
|
||||
assertThat(Names.isReservedPrefix(Names.pluginPrefix("rwx"))).isFalse();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package mx.quest.database.internal;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class PortableTest {
|
||||
|
||||
@Test
|
||||
void typesRestoreWithinTheirFamilyOnly() {
|
||||
assertThat(Portable.compatible("INTEGER", "BIGINT")).isTrue();
|
||||
assertThat(Portable.compatible("VARCHAR(80)", "TEXT")).isTrue();
|
||||
assertThat(Portable.compatible("JSON", "TEXT")).isTrue();
|
||||
assertThat(Portable.compatible("TIMESTAMPTZ", "TIMESTAMP")).isTrue();
|
||||
assertThat(Portable.compatible("DECIMAL(10,2)", "DECIMAL(12,4)")).isTrue();
|
||||
assertThat(Portable.compatible("TEXT", "BIGINT")).isFalse();
|
||||
assertThat(Portable.compatible("BOOLEAN", "SMALLINT")).isFalse();
|
||||
assertThat(Portable.compatible("UNSUPPORTED:uuid", "UNSUPPORTED:uuid")).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void bothEnginesMapTheirNativeTypesToTheSamePortableOnes() {
|
||||
assertThat(PostgresEngine.portableType("timestamp with time zone", null, null, null))
|
||||
.isEqualTo(MariaDbEngine.portableType("timestamp", "timestamp(6)", null, null, null));
|
||||
assertThat(PostgresEngine.portableType("boolean", null, null, null))
|
||||
.isEqualTo(MariaDbEngine.portableType("tinyint", "tinyint(1)", null, null, null));
|
||||
assertThat(PostgresEngine.portableType("numeric", null, 10, 2))
|
||||
.isEqualTo(MariaDbEngine.portableType("decimal", "decimal(10,2)", null, 10L, 2L));
|
||||
assertThat(PostgresEngine.portableType("character varying", 80, null, null))
|
||||
.isEqualTo(MariaDbEngine.portableType("varchar", "varchar(80)", 80L, null, null));
|
||||
assertThat(PostgresEngine.portableType("uuid", null, null, null)).startsWith(Portable.UNSUPPORTED);
|
||||
assertThat(MariaDbEngine.portableType("tinyint", "tinyint(4)", null, null, null)).isEqualTo("SMALLINT");
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,47 @@
|
||||
package mx.quest.database.internal;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class ScriptsTest {
|
||||
|
||||
@Test
|
||||
void theIndexListsVersionsInOrderStartingAtOne() {
|
||||
assertThat(Scripts.parseIndex("# scripts\nV1__init.sql\n\nV2__more.sql\n"))
|
||||
.extracting(Scripts.Entry::version).containsExactly(1, 2);
|
||||
assertThatThrownBy(() -> Scripts.parseIndex("V2__init.sql\n")).hasMessageContaining("expected V1");
|
||||
assertThatThrownBy(() -> Scripts.parseIndex("V1__a.sql\nV1__b.sql\n")).hasMessageContaining("expected V2");
|
||||
assertThatThrownBy(() -> Scripts.parseIndex("V1__../x.sql\n")).hasMessageContaining("not V<n>");
|
||||
assertThatThrownBy(() -> Scripts.parseIndex("init.sql\n")).hasMessageContaining("not V<n>");
|
||||
}
|
||||
|
||||
@Test
|
||||
void theChecksumIgnoresTheBomLineEndingsAndTrailingBlanksButNotComments() {
|
||||
String base = Scripts.checksum(Scripts.normalize("CREATE TABLE x (a int);\n-- note\n"));
|
||||
byte[] crlf = "CREATE TABLE x (a int); \r\n-- note\r\n\r\n".getBytes(StandardCharsets.UTF_8);
|
||||
assertThat(Scripts.checksum(Scripts.normalize(crlf))).isEqualTo(base);
|
||||
assertThat(Scripts.checksum(Scripts.normalize("CREATE TABLE x (a int);\n-- other\n"))).isNotEqualTo(base);
|
||||
}
|
||||
|
||||
@Test
|
||||
void statementsAreSplitOnlyOnTheSeparatorLine() {
|
||||
String text = Scripts.normalize("CREATE FUNCTION f() AS $$ BEGIN; END $$;\n-- runway:next\n"
|
||||
+ "-- only a comment\n-- runway:next\nCREATE TABLE t (a int);\n -- runway:next \n");
|
||||
assertThat(Scripts.split(text)).hasSize(2).first().asString().contains("BEGIN; END");
|
||||
}
|
||||
|
||||
@Test
|
||||
void statementsThatMoveTheConnectionAreRefusedBehindCommentsToo() {
|
||||
for (String bad : new String[] {"USE other", "use other;", "-- hi\nUSE other", "/* x */ SET search_path = a",
|
||||
"SET SESSION sql_mode = ''", "set local search_path to a", "/*!USE other*/",
|
||||
"/*!50000 USE other */", "SELECT set_config('search_path', 'a', false)"}) {
|
||||
assertThatThrownBy(() -> Scripts.split(Scripts.normalize(bad))).as(bad)
|
||||
.isInstanceOf(IllegalArgumentException.class);
|
||||
}
|
||||
assertThat(Scripts.split("SELECT 1 -- USE x")).hasSize(1);
|
||||
assertThat(Scripts.split("UPDATE t SET used = 1")).hasSize(1);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
<!-- Site dashboard card: whether this site keeps data in the database, its size, and the last database restore.
|
||||
Bare fragment; binding in dashboard.th.xml. -->
|
||||
<div class="card" id="dbd">
|
||||
<div class="card-body">
|
||||
<h3 class="card-title mb-2" id="dbd-title">Database</h3>
|
||||
<p class="mb-1" id="dbd-has"><span id="dbd-has-text">This site keeps plugin data in the database.</span>
|
||||
<span class="text-secondary" id="dbd-size">0.0 MiB</span></p>
|
||||
<p class="text-secondary mb-1" id="dbd-none">This site keeps no data in the database.</p>
|
||||
<p class="small mb-0" id="dbd-restore"><span id="dbd-l-restore">Last database restore</span>:
|
||||
<span id="dbd-restore-text">text</span></p>
|
||||
</div>
|
||||
</div>
|
||||
@@ -0,0 +1,15 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!-- Site dashboard card logic. Values from ${@databaseScreens.site(tenantSiteId)}, read once at the root. -->
|
||||
<thlogic>
|
||||
<attr sel="#dbd" th:with="dl=${@databaseScreens.site(tenantSiteId)}"/>
|
||||
<attr sel="#dbd-title" th:text="#{database.dashboard.title}"/>
|
||||
<attr sel="#dbd-has" th:if="${dl.hasData()}"/>
|
||||
<attr sel="#dbd-has-text" th:text="#{database.dashboard.has}"/>
|
||||
<attr sel="#dbd-size" th:text="${dl.size()}"/>
|
||||
<attr sel="#dbd-none" th:unless="${dl.hasData()}"
|
||||
th:text="#{database.dashboard.none}"/>
|
||||
<attr sel="#dbd-restore" th:unless="${dl.lastRestore().isEmpty()}"
|
||||
th:classappend="${dl.lastRestoreOk() ? '' : 'text-danger'}"/>
|
||||
<attr sel="#dbd-l-restore" th:text="#{database.dashboard.restore}"/>
|
||||
<attr sel="#dbd-restore-text" th:text="${dl.lastRestore()}"/>
|
||||
</thlogic>
|
||||
@@ -0,0 +1,235 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head><meta charset="utf-8"><title>Database</title></head>
|
||||
<body>
|
||||
<!-- The database screen (@ConsoleScreen, application console). Markup only: every binding is in health.th.xml.
|
||||
Every state change is a POST form carrying the console's CSRF token (.db-csrf). -->
|
||||
<div id="content">
|
||||
<div class="page-header d-print-none mb-3">
|
||||
<div class="row align-items-center">
|
||||
<div class="col">
|
||||
<div class="page-pretitle" id="db-pretitle">Application</div>
|
||||
<h2 class="page-title" id="db-heading">Database</h2>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="db-flash" class="alert alert-success" role="status"><span id="db-flash-text">done</span></div>
|
||||
<div id="db-error" class="alert alert-danger" role="alert"><span id="db-error-text">error</span></div>
|
||||
|
||||
<div class="row row-cards">
|
||||
<!-- Status -->
|
||||
<div class="col-lg-6">
|
||||
<div class="card">
|
||||
<div class="card-header">
|
||||
<h3 class="card-title" id="db-status-title">Status</h3>
|
||||
<div class="card-actions">
|
||||
<span class="badge bg-success-lt" id="db-badge-ok">Available</span>
|
||||
<span class="badge bg-danger-lt" id="db-badge-down">Not available</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="card-body">
|
||||
<p class="text-secondary" id="db-detail">detail</p>
|
||||
<div class="datagrid">
|
||||
<div class="datagrid-item">
|
||||
<div class="datagrid-title" id="db-l-provider">Provider</div>
|
||||
<div class="datagrid-content" id="db-provider">postgresql</div>
|
||||
</div>
|
||||
<div class="datagrid-item">
|
||||
<div class="datagrid-title" id="db-l-server">Server</div>
|
||||
<div class="datagrid-content" id="db-server">PostgreSQL 17</div>
|
||||
</div>
|
||||
<div class="datagrid-item">
|
||||
<div class="datagrid-title" id="db-l-driver">Driver</div>
|
||||
<div class="datagrid-content" id="db-driver">pgjdbc</div>
|
||||
</div>
|
||||
<div class="datagrid-item">
|
||||
<div class="datagrid-title" id="db-l-target">Database</div>
|
||||
<div class="datagrid-content"><code id="db-target">host/db</code></div>
|
||||
</div>
|
||||
<div class="datagrid-item">
|
||||
<div class="datagrid-title" id="db-l-tls">TLS</div>
|
||||
<div class="datagrid-content" id="db-tls">verify-full</div>
|
||||
</div>
|
||||
<div class="datagrid-item">
|
||||
<div class="datagrid-title" id="db-l-namespace">Namespace</div>
|
||||
<div class="datagrid-content"><code id="db-namespace">rw</code></div>
|
||||
</div>
|
||||
<div class="datagrid-item">
|
||||
<div class="datagrid-title" id="db-l-pool">Connections in use</div>
|
||||
<div class="datagrid-content" id="db-pool">0 / 10</div>
|
||||
</div>
|
||||
<div class="datagrid-item">
|
||||
<div class="datagrid-title" id="db-l-schemas">Sites with data</div>
|
||||
<div class="datagrid-content" id="db-schemas">0</div>
|
||||
</div>
|
||||
</div>
|
||||
<p class="text-danger small mt-3 mb-0" id="db-last-error"><span id="db-l-last-error">Last error</span>:
|
||||
<span id="db-last-error-at">time</span> — <span id="db-last-error-text">text</span></p>
|
||||
<p class="text-danger small mt-2 mb-0" id="db-problem">problem</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Connection tests -->
|
||||
<div class="col-lg-6">
|
||||
<div class="card">
|
||||
<div class="card-header"><h3 class="card-title" id="db-test-title">Connection tests</h3></div>
|
||||
<div class="card-body">
|
||||
<form method="post" action="/__app/database/test-running" class="mb-3">
|
||||
<input class="db-csrf" type="hidden" name="_csrf" value="">
|
||||
<button type="submit" class="btn btn-outline-primary" id="db-test-running">Test running
|
||||
connection</button>
|
||||
</form>
|
||||
<p class="text-secondary small" id="db-test-new-help">Try other settings without saving them.</p>
|
||||
<form method="post" action="/__app/database/test-new" autocomplete="off">
|
||||
<input class="db-csrf" type="hidden" name="_csrf" value="">
|
||||
<div class="row g-2">
|
||||
<div class="col-md-4">
|
||||
<label class="form-label" for="db-f-provider" id="db-fl-provider">Provider</label>
|
||||
<select class="form-select" id="db-f-provider" name="provider">
|
||||
<option value="postgresql">postgresql</option>
|
||||
<option value="mariadb">mariadb</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="col-md-5">
|
||||
<label class="form-label" for="db-f-host" id="db-fl-host">Host</label>
|
||||
<input class="form-control" id="db-f-host" name="host" type="text" value="">
|
||||
</div>
|
||||
<div class="col-md-3">
|
||||
<label class="form-label" for="db-f-port" id="db-fl-port">Port</label>
|
||||
<input class="form-control" id="db-f-port" name="port" type="text" value="">
|
||||
</div>
|
||||
<div class="col-md-4">
|
||||
<label class="form-label" for="db-f-database" id="db-fl-database">Database</label>
|
||||
<input class="form-control" id="db-f-database" name="database" type="text" value="">
|
||||
</div>
|
||||
<div class="col-md-4">
|
||||
<label class="form-label" for="db-f-username" id="db-fl-username">Username</label>
|
||||
<input class="form-control" id="db-f-username" name="username" type="text" value="">
|
||||
</div>
|
||||
<div class="col-md-4">
|
||||
<label class="form-label" for="db-f-password" id="db-fl-password">Password</label>
|
||||
<input class="form-control" id="db-f-password" name="password" type="password"
|
||||
value="">
|
||||
</div>
|
||||
<div class="col-md-4">
|
||||
<label class="form-label" for="db-f-tls" id="db-fl-tls">TLS</label>
|
||||
<select class="form-select" id="db-f-tls" name="tls">
|
||||
<option value="verify-full">verify-full</option>
|
||||
<option value="require">require</option>
|
||||
<option value="disable">disable</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="col-md-8">
|
||||
<label class="form-label" for="db-f-ca" id="db-fl-ca">CA certificate (PEM)</label>
|
||||
<textarea class="form-control font-monospace" id="db-f-ca" name="caCertificate"
|
||||
rows="2"></textarea>
|
||||
</div>
|
||||
</div>
|
||||
<p class="text-secondary small mt-2" id="db-test-password-note">A blank password reuses the
|
||||
saved one only for the same server, database, account and TLS settings.</p>
|
||||
<button type="submit" class="btn btn-primary" id="db-test-new">Test these settings</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Migration problems -->
|
||||
<div class="col-12">
|
||||
<div class="card">
|
||||
<div class="card-header"><h3 class="card-title" id="db-issues-title">Plugin tables needing
|
||||
attention</h3></div>
|
||||
<div class="card-body" id="db-issues-none"><p class="text-secondary mb-0" id="db-issues-none-text">
|
||||
None.</p></div>
|
||||
<div class="table-responsive" id="db-issues">
|
||||
<table class="table table-vcenter card-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th id="db-h-schema">Schema</th>
|
||||
<th id="db-h-plugin">Plugin</th>
|
||||
<th id="db-h-state">Problem</th>
|
||||
<th id="db-h-detail">Detail</th>
|
||||
<th id="db-h-actions">Actions</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr id="db-issue-row">
|
||||
<td><code class="db-issue-schema">schema</code></td>
|
||||
<td class="db-issue-plugin">plugin</td>
|
||||
<td><span class="badge bg-warning-lt db-issue-state">FAILED</span></td>
|
||||
<td class="small db-issue-detail">detail</td>
|
||||
<td class="text-nowrap">
|
||||
<form method="post" action="/__app/database/recover" class="d-inline db-form-retry">
|
||||
<input class="db-csrf" type="hidden" name="_csrf" value="">
|
||||
<input type="hidden" name="schema" class="db-issue-schema-in" value="">
|
||||
<input type="hidden" name="plugin" class="db-issue-plugin-in" value="">
|
||||
<input type="hidden" name="action" value="retry">
|
||||
<button type="submit" class="btn btn-sm btn-outline-primary db-retry">Retry</button>
|
||||
</form>
|
||||
<form method="post" action="/__app/database/recover" class="d-inline db-form-applied">
|
||||
<input class="db-csrf" type="hidden" name="_csrf" value="">
|
||||
<input type="hidden" name="schema" class="db-issue-schema-in" value="">
|
||||
<input type="hidden" name="plugin" class="db-issue-plugin-in" value="">
|
||||
<input type="hidden" name="action" value="mark_applied">
|
||||
<button type="submit" class="btn btn-sm btn-outline-secondary db-applied">Mark
|
||||
applied</button>
|
||||
</form>
|
||||
<form method="post" action="/__app/database/recover" class="d-inline db-form-checksum">
|
||||
<input class="db-csrf" type="hidden" name="_csrf" value="">
|
||||
<input type="hidden" name="schema" class="db-issue-schema-in" value="">
|
||||
<input type="hidden" name="plugin" class="db-issue-plugin-in" value="">
|
||||
<input type="hidden" name="action" value="accept_checksum">
|
||||
<button type="submit" class="btn btn-sm btn-outline-warning db-checksum">Accept
|
||||
shipped checksum</button>
|
||||
</form>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Plugins, nodes, backups -->
|
||||
<div class="col-lg-4">
|
||||
<div class="card">
|
||||
<div class="card-header"><h3 class="card-title" id="db-consumers-title">Plugins using it</h3></div>
|
||||
<div class="card-body">
|
||||
<ul class="list-unstyled mb-0" id="db-consumers"><li id="db-consumer-row"><code
|
||||
class="db-consumer">plugin</code></li></ul>
|
||||
<p class="text-secondary mb-0" id="db-consumers-none">None.</p>
|
||||
<p class="text-warning small mt-3 mb-0" id="db-app-warning"><span id="db-app-warning-text">These
|
||||
plugins keep Runway-wide data, which does not move with a change of database:</span>
|
||||
<span id="db-app-plugins">plugin</span></p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-lg-4">
|
||||
<div class="card">
|
||||
<div class="card-header"><h3 class="card-title" id="db-nodes-title">Nodes seen recently</h3></div>
|
||||
<div class="card-body">
|
||||
<ul class="list-unstyled mb-0"><li id="db-node-row"><span class="db-node-host">host</span>
|
||||
<span class="text-secondary small db-node-seen">seen</span></li></ul>
|
||||
<p class="text-secondary small mt-2 mb-0" id="db-nodes-help">More than one node is normal in a
|
||||
cluster. Unknown nodes may mean another installation shares this namespace.</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-lg-4">
|
||||
<div class="card">
|
||||
<div class="card-header"><h3 class="card-title" id="db-backups-title">Backups</h3></div>
|
||||
<div class="card-body">
|
||||
<p class="mb-1"><span id="db-l-largest">Largest site backup</span>:
|
||||
<span id="db-largest">—</span></p>
|
||||
<p class="text-warning small" id="db-budget-warning">Close to the backup budget: raise it, or
|
||||
back the database up with its own tools.</p>
|
||||
<p class="text-danger small mb-0" id="db-restore-failure"><span id="db-l-restore-failure">Last
|
||||
failed restore</span>: <span id="db-restore-failure-text">text</span></p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,106 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!--
|
||||
Decoupled logic of the database screen. `db` is the DatabaseScreens.Health record the controller put in the model;
|
||||
besides it, the template uses only what a console screen may rely on: _csrf and #{..} messages. `//` reaches nested
|
||||
elements of an iterated row. Form actions are constants in the markup.
|
||||
-->
|
||||
<thlogic>
|
||||
<attr sel="#db-pretitle" th:text="#{database.console.pretitle}"/>
|
||||
<attr sel="#db-heading" th:text="#{database.console.heading}"/>
|
||||
|
||||
<attr sel="#db-flash" th:if="${databaseFlash != null}"/>
|
||||
<attr sel="#db-flash-text" th:text="${databaseFlash}"/>
|
||||
<attr sel="#db-error" th:if="${databaseError != null}"/>
|
||||
<attr sel="#db-error-text" th:text="${databaseError}"/>
|
||||
|
||||
<attr sel=".db-csrf"
|
||||
th:attr="name=${_csrf != null ? _csrf.parameterName : '_csrf'},value=${_csrf != null ? _csrf.token : ''}"/>
|
||||
|
||||
<!-- Status -->
|
||||
<attr sel="#db-status-title" th:text="#{database.console.status}"/>
|
||||
<attr sel="#db-badge-ok" th:if="${db.available()}" th:text="#{database.console.available}"/>
|
||||
<attr sel="#db-badge-down" th:unless="${db.available()}" th:text="#{database.console.unavailable}"/>
|
||||
<attr sel="#db-detail" th:text="#{'database.status.' + ${db.runtime().status().name()}(${db.runtime().detail()})}"/>
|
||||
<attr sel="#db-l-provider" th:text="#{database.console.provider}"/>
|
||||
<attr sel="#db-provider" th:text="${db.provider().isEmpty() ? '—' : db.provider()}"/>
|
||||
<attr sel="#db-l-server" th:text="#{database.console.server}"/>
|
||||
<attr sel="#db-server" th:text="${db.runtime().server() == null ? '—' : db.runtime().server()}"/>
|
||||
<attr sel="#db-l-driver" th:text="#{database.console.driver}"/>
|
||||
<attr sel="#db-driver" th:text="${db.runtime().driver() == null ? '—' : db.runtime().driver()}"/>
|
||||
<attr sel="#db-l-target" th:text="#{database.console.target}"/>
|
||||
<attr sel="#db-target" th:text="${db.target().isEmpty() ? '—' : db.target()}"/>
|
||||
<attr sel="#db-l-tls" th:text="#{database.console.tls}"/>
|
||||
<attr sel="#db-tls" th:text="${db.tls().isEmpty() ? '—' : db.tls()}"/>
|
||||
<attr sel="#db-l-namespace" th:text="#{database.console.namespace}"/>
|
||||
<attr sel="#db-namespace" th:text="${db.namespace().isEmpty() ? '—' : db.namespace()}"/>
|
||||
<attr sel="#db-l-pool" th:text="#{database.console.pool}"/>
|
||||
<attr sel="#db-pool" th:text="${db.runtime().poolActive()} + ' / ' + ${db.runtime().poolMax()}"/>
|
||||
<attr sel="#db-l-schemas" th:text="#{database.console.schemas}"/>
|
||||
<attr sel="#db-schemas" th:text="${db.liveSchemas()}"/>
|
||||
<attr sel="#db-last-error" th:if="${db.runtime().lastError() != null}"/>
|
||||
<attr sel="#db-l-last-error" th:text="#{database.console.lastError}"/>
|
||||
<attr sel="#db-last-error-at" th:text="${db.runtime().lastErrorAt()}"/>
|
||||
<attr sel="#db-last-error-text" th:text="${db.runtime().lastError()}"/>
|
||||
<attr sel="#db-problem" th:if="${db.problem() != null}" th:text="${db.problem()}"/>
|
||||
|
||||
<!-- Connection tests -->
|
||||
<attr sel="#db-test-title" th:text="#{database.console.tests}"/>
|
||||
<attr sel="#db-test-running" th:text="#{database.console.testRunning}"/>
|
||||
<attr sel="#db-test-new-help" th:text="#{database.console.testNew.help}"/>
|
||||
<attr sel="#db-fl-provider" th:text="#{database.set.provider}"/>
|
||||
<attr sel="#db-fl-host" th:text="#{database.set.host}"/>
|
||||
<attr sel="#db-fl-port" th:text="#{database.set.port}"/>
|
||||
<attr sel="#db-fl-database" th:text="#{database.set.database}"/>
|
||||
<attr sel="#db-fl-username" th:text="#{database.set.username}"/>
|
||||
<attr sel="#db-fl-password" th:text="#{database.set.password}"/>
|
||||
<attr sel="#db-fl-tls" th:text="#{database.set.tls}"/>
|
||||
<attr sel="#db-fl-ca" th:text="#{database.set.caCertificate}"/>
|
||||
<attr sel="#db-test-password-note" th:text="#{database.console.testNew.password}"/>
|
||||
<attr sel="#db-test-new" th:text="#{database.console.testNew}"/>
|
||||
|
||||
<!-- Migration problems -->
|
||||
<attr sel="#db-issues-title" th:text="#{database.console.issues}"/>
|
||||
<attr sel="#db-issues-none" th:if="${db.issues().isEmpty()}"/>
|
||||
<attr sel="#db-issues-none-text" th:text="#{database.console.none}"/>
|
||||
<attr sel="#db-issues" th:unless="${db.issues().isEmpty()}"/>
|
||||
<attr sel="#db-h-schema" th:text="#{database.console.schema}"/>
|
||||
<attr sel="#db-h-plugin" th:text="#{database.console.plugin}"/>
|
||||
<attr sel="#db-h-state" th:text="#{database.console.problem}"/>
|
||||
<attr sel="#db-h-detail" th:text="#{database.console.detail}"/>
|
||||
<attr sel="#db-h-actions" th:text="#{database.console.actions}"/>
|
||||
<attr sel="#db-issue-row" th:each="i : ${db.issues()}"/>
|
||||
<attr sel="#db-issue-row//.db-issue-schema" th:text="${i.schema()}"/>
|
||||
<attr sel="#db-issue-row//.db-issue-plugin" th:text="${i.pluginId()}"/>
|
||||
<attr sel="#db-issue-row//.db-issue-state" th:text="#{'database.issue.' + ${i.state()}}"/>
|
||||
<attr sel="#db-issue-row//.db-issue-detail" th:text="${i.detail()}"/>
|
||||
<attr sel="#db-issue-row//.db-issue-schema-in" th:value="${i.schema()}"/>
|
||||
<attr sel="#db-issue-row//.db-issue-plugin-in" th:value="${i.pluginId()}"/>
|
||||
<attr sel="#db-issue-row//.db-form-retry" th:if="${i.state() == 'FAILED'}"/>
|
||||
<attr sel="#db-issue-row//.db-form-applied" th:if="${i.state() == 'FAILED'}"/>
|
||||
<attr sel="#db-issue-row//.db-form-checksum" th:if="${i.state() == 'CHECKSUM'}"/>
|
||||
<attr sel="#db-issue-row//.db-retry" th:text="#{database.recover.retry}"/>
|
||||
<attr sel="#db-issue-row//.db-applied" th:text="#{database.recover.markApplied}"/>
|
||||
<attr sel="#db-issue-row//.db-checksum" th:text="#{database.recover.acceptChecksum}"/>
|
||||
|
||||
<!-- Plugins, nodes, backups -->
|
||||
<attr sel="#db-consumers-title" th:text="#{database.console.consumers}"/>
|
||||
<attr sel="#db-consumers" th:unless="${db.consumers().isEmpty()}"/>
|
||||
<attr sel="#db-consumer-row" th:each="p : ${db.consumers()}"/>
|
||||
<attr sel="#db-consumer-row//.db-consumer" th:text="${p}"/>
|
||||
<attr sel="#db-consumers-none" th:if="${db.consumers().isEmpty()}" th:text="#{database.console.none}"/>
|
||||
<attr sel="#db-app-warning" th:unless="${db.appSchemaPlugins().isEmpty()}"/>
|
||||
<attr sel="#db-app-warning-text" th:text="#{database.console.appWarning}"/>
|
||||
<attr sel="#db-app-plugins" th:text="${#strings.listJoin(db.appSchemaPlugins(), ', ')}"/>
|
||||
<attr sel="#db-nodes-title" th:text="#{database.console.nodes}"/>
|
||||
<attr sel="#db-node-row" th:each="n : ${db.nodes()}"/>
|
||||
<attr sel="#db-node-row//.db-node-host" th:text="${n.host()}"/>
|
||||
<attr sel="#db-node-row//.db-node-seen" th:text="${n.seenAt()}"/>
|
||||
<attr sel="#db-nodes-help" th:text="#{database.console.nodes.help}"/>
|
||||
<attr sel="#db-backups-title" th:text="#{database.console.backups}"/>
|
||||
<attr sel="#db-l-largest" th:text="#{database.console.largest}"/>
|
||||
<attr sel="#db-largest" th:text="${db.largestBackup() == null ? '—' : db.largestBackup()}"/>
|
||||
<attr sel="#db-budget-warning" th:if="${db.backupBudgetWarning()}" th:text="#{database.console.budgetWarning}"/>
|
||||
<attr sel="#db-restore-failure" th:if="${db.lastRestoreFailure() != null}"/>
|
||||
<attr sel="#db-l-restore-failure" th:text="#{database.console.restoreFailure}"/>
|
||||
<attr sel="#db-restore-failure-text" th:text="${db.lastRestoreFailure()}"/>
|
||||
</thlogic>
|
||||
@@ -2,6 +2,20 @@
|
||||
|
||||
All notable changes are recorded here. Versions follow [Semantic Versioning](https://semver.org/).
|
||||
|
||||
## [2.1.1] — 2026-10-29
|
||||
|
||||
### Security
|
||||
|
||||
- **The feedback form asks the site's CAPTCHA.** The public "leave a message" form (`POST /demo/feedback`) had a
|
||||
honeypot, a length cap and a per-address rate limit, but never asked the challenge a site manager can turn on in
|
||||
the site's protection settings, so a site with a CAPTCHA configured still took messages from scripts. The form now
|
||||
shows the site's challenge, and the route keeps no message without it solved (`?demo-feedback=captcha`). A site
|
||||
with no CAPTCHA configured sees no change.
|
||||
|
||||
### Upgrade
|
||||
|
||||
Replace the plugin folder with this release's zip and restart. No setting or stored file changes.
|
||||
|
||||
## [2.1.0] — 2026-10-21
|
||||
|
||||
First public release of `runway-demo`, the reference ("kitchen-sink") plugin: it exercises every extension axis and
|
||||
|
||||
@@ -30,7 +30,7 @@ mvn verify
|
||||
The first build downloads its Maven dependencies, and needs the `runway-spi` jars installed in `~/.m2` as the
|
||||
[authoring guide §2](../docs/PLUGIN-AUTHORING-GUIDE.md#2-prerequisites) describes.
|
||||
|
||||
Runs 82 unit tests (over the SPI testkit's fakes, plus a scan proving the compiled classes link nothing of the host
|
||||
Runs 84 unit tests (over the SPI testkit's fakes, plus a scan proving the compiled classes link nothing of the host
|
||||
but the SPI) and produces the thin `target/runway-plugin-demo.jar` and **both** installable forms:
|
||||
`target/runway-demo/` (the install-ready folder) and `target/runway-plugin-runway-demo-<version>.zip` (the archive
|
||||
the management UI upload expects). Two builds produce byte-identical artifacts. The zip is named after the plugin id,
|
||||
@@ -76,7 +76,7 @@ Copy this folder, rename the descriptor `id`, the Maven `artifactId`, the Java p
|
||||
bean-name prefix (`runwayDemo…` → your id in lowerCamelCase), and delete what you do not need. Keep the tests that
|
||||
check the contract (`DemoPluginConfigTest`, `DemoTemplatesTest`) — they are the cheapest way to stay inside it.
|
||||
|
||||
_Java package `mx.quest.demo` · plugin id `runway-demo` · version 2.1.0 · `requiresSpi: ">=1.0.0"`._
|
||||
_Java package `mx.quest.demo` · plugin id `runway-demo` · version 2.1.1 · `requiresSpi: ">=1.0.0"`._
|
||||
|
||||
## License
|
||||
|
||||
|
||||
@@ -7,10 +7,10 @@
|
||||
> shows them working.
|
||||
|
||||
- **id** `runway-demo` · **install folder** `external/plugins/runway-demo/` · **Java package** `mx.quest.demo`
|
||||
- **version** `2.1.0` · **`requiresSpi`** `">=1.0.0"` · links **only** `mx.quest.runway.spi`
|
||||
- **version** `2.1.1` · **`requiresSpi`** `">=1.0.0"` · links **only** `mx.quest.runway.spi`
|
||||
- **jar** `runway-plugin-demo.jar` (thin: 18 top-level classes, nothing bundled) · **Maven artifactId**
|
||||
`runway-plugin-runway-demo` · **release zip** `runway-plugin-runway-demo-<version>.zip`
|
||||
- **Verified** live against the packaged kernel (§9) and by 82 unit tests with 20 mutation checks (§8).
|
||||
- **Verified** live against the packaged kernel (§9) and by 84 unit tests with 21 mutation checks (§8).
|
||||
|
||||
---
|
||||
|
||||
@@ -20,7 +20,7 @@
|
||||
|---|---|---|
|
||||
| A generator `<meta>`, the plugin stylesheet and an inert analytics `<script>` in every page's `<head>` | visitors | `HeadContributor` + `PluginSettings` |
|
||||
| A notice callout at `data-widget="demo-notice/<instance>"` | visitors | `ContentWidget` + `PluginSettings` + `Messages.site` |
|
||||
| A "leave a message" form at `data-widget="demo-feedback/<instance>"`, posting without a CSRF token | visitors | `ContentWidget` + an **anonymous** `POST` route |
|
||||
| A "leave a message" form at `data-widget="demo-feedback/<instance>"`, posting without a CSRF token, with the site's CAPTCHA when it has one | visitors | `ContentWidget` + an **anonymous** `POST` route + `CaptchaService` |
|
||||
| `/demo/hello.txt`, `/demo/echo.json`, `/demo/notes.json` (permission-gated) | visitors / operators | `EndpointContributor` + `AccessCheck` + `Messages.site` |
|
||||
| SEO advice in the page editor (long title, no description, no `<h1>`) | site managers | `PageQualityCheck` + `PluginSettings` |
|
||||
| Per-site **notes** (operator notes, visitors' messages, a settings audit note), personal data | operators | `PluginSiteFiles` + `siteData.personal` |
|
||||
@@ -125,7 +125,7 @@ are not here: they bind through `@ConfigurationProperties` under `runway.plugin.
|
||||
|
||||
`started(PluginInfo self)` runs once the platform is up, in plugin load order; `stopping()` at shutdown, in reverse
|
||||
order, only if `started` returned normally. Both block the host's thread — keep them short. The demo logs
|
||||
`runway-demo 2.1.0 started — install dir …; built against SPI 1.0.0, running on SPI 1.0.0`:
|
||||
`runway-demo 2.1.1 started — install dir …; built against SPI 1.0.0, running on SPI 1.1.0`:
|
||||
`RunwaySpi.VERSION` is a compile-time constant (what the plugin was **built against**, copied into the plugin's
|
||||
classes), `RunwaySpi.runtimeVersion()` is the running kernel's. **Use it** to open an
|
||||
index, start your own executor, warm a cache — and to close them again.
|
||||
@@ -303,11 +303,18 @@ A form on a page every visitor shares (and caches) cannot carry a per-session CS
|
||||
has no session. Declaring the route `anonymous` exempts **exactly that method and path** from CSRF; the kernel
|
||||
makes that safe by running the handler with **no principal** (`AccessCheck.may` is `false` even for a signed-in
|
||||
administrator) and accepting only an `application/x-www-form-urlencoded` body (`415` otherwise). The handler keeps
|
||||
its own guards — a honeypot field, a length cap, five messages per minute per `req.clientIp()` (the address after
|
||||
the kernel's trusted-proxy gate; never a header) — reads the fields from `req.form()` only (personal text never in
|
||||
its own guards — a honeypot field, a length cap, the site's CAPTCHA, five messages per minute per `req.clientIp()`
|
||||
(the address after the kernel's trusted-proxy gate; never a header) — reads the fields from `req.form()` only (personal text never in
|
||||
a URL), and answers `303` back with only an outcome flag the widget renders. **Use it** only for a form any visitor
|
||||
may submit with no account; never for an action on something a signed-in user owns.
|
||||
|
||||
**The site's CAPTCHA.** A public form asks the site's challenge through `CaptchaService`, a platform service every
|
||||
plugin can inject. The widget appends `captcha.widgetForSite(siteId).html()` inside its form, and the route, after the
|
||||
honeypot and length checks, calls `captcha.verify(siteId, <the widget's tokenField()>, req.clientIp())` when
|
||||
`widgetForSite(siteId).active()`; an unsolved challenge answers `?demo-feedback=captcha` and keeps nothing. A site
|
||||
with no CAPTCHA configured gets an inactive widget (no markup) and every message through, so the form works either
|
||||
way; the site manager turns the challenge on in the site's protection settings, not in this plugin.
|
||||
|
||||
---
|
||||
|
||||
## 5. The axes (pure functions of their inputs)
|
||||
@@ -359,11 +366,11 @@ and counted on the plugins screen.
|
||||
|
||||
## 8. Tests
|
||||
|
||||
`mvn verify` runs 82 tests over `runway-spi-testkit` (no kernel, no Spring Boot):
|
||||
`mvn verify` runs 84 tests over `runway-spi-testkit` (no kernel, no Spring Boot):
|
||||
|
||||
| Class | Covers |
|
||||
|---|---|
|
||||
| `DemoSpiUnitTest` | head, both widgets, quality check, every endpoint route incl. the anonymous feedback POST (honeypot, blank, query ignored, rate limit, foreign return path), lowercase header names |
|
||||
| `DemoSpiUnitTest` | head, both widgets, quality check, every endpoint route incl. the anonymous feedback POST (honeypot, blank, the site's CAPTCHA, query ignored, rate limit, foreign return path), lowercase header names |
|
||||
| `DemoNotesStoreTest` | the notes over `TempDirSiteFiles`: a read shows the welcome and writes nothing, the first append keeps it, order, caps, isolation, lenient reads, an unreadable file never overwritten, a missing site, unsafe ids |
|
||||
| `DemoShowcaseTest` | publish/unpublish announce through `EventDispatch`, the source's refs/body/resolve, `updatedAt`, the TTL backstop, eviction on a replayed change and on wholesale events only, the kernel's refusal from inside a callback |
|
||||
| `DemoActivityTest` | own vs other plugins' settings, `local`, URLs before/after, the bound, wholesale drops, failures contained |
|
||||
@@ -371,7 +378,7 @@ and counted on the plugins screen.
|
||||
| `DemoTemplatesTest` | every `POST` action has a form carrying the CSRF field; no link points at an action; no repeated id; every selector matches |
|
||||
| `DemoPluginConfigTest` | wiring from SPI fakes alone, bean names, forbidden Spring types, the controller's gates and mappings, template bean references, descriptor (floor, version, personal data, menu, secrets), i18n, **the compiled classes link no `mx.quest.runway` class outside `.spi`**, the removed classes are gone |
|
||||
|
||||
Mutation-checked: 20 deliberate breaks (the `local` gate, each eviction, each announcement, the honeypot, the rate
|
||||
Mutation-checked: 21 deliberate breaks (the `local` gate, each eviction, each announcement, the honeypot, the CAPTCHA, the rate
|
||||
limit boundary, the permission gates, body-only fields, a missing `@PreAuthorize`, the notes bound, the
|
||||
personal-data declaration, the TTL boundary, escaping, the open-redirect guard, a form's CSRF field, an
|
||||
unprefixed bean name, the clamp) — each makes a test fail.
|
||||
@@ -391,12 +398,12 @@ JAVA_HOME=/path/to/jdk-25 HOST_JAR=…/runway-app-1.0.0-exec.jar VERIFY_TMPDIR=
|
||||
The first build downloads its Maven dependencies, and needs the `runway-spi` jars installed in `~/.m2` as the
|
||||
[authoring guide §2](../../docs/PLUGIN-AUTHORING-GUIDE.md#2-prerequisites) describes.
|
||||
|
||||
The verify script never runs `mvn install`. Its result for 2.1.0: **58 passed, 0 failed**.
|
||||
The verify script never runs `mvn install`. Its result for 2.1.1, against Runway 1.1.0: **58 passed, 0 failed**.
|
||||
From the host log:
|
||||
|
||||
```
|
||||
plugins: 1 registered, 0 blocked
|
||||
runway-demo 2.1.0 started — install dir …/plugins/runway-demo; built against SPI 1.0.0, running on SPI 1.0.0
|
||||
runway-demo 2.1.1 started — install dir …/plugins/runway-demo; built against SPI 1.0.0, running on SPI 1.1.0
|
||||
runway-demo settings changed for site 'default': audit note appended (now 4 notes)
|
||||
transfer export: blanked 1 secret value(s) in runway-demo.yml: [analytics.site-token]
|
||||
```
|
||||
|
||||
@@ -41,6 +41,7 @@ runwaydemo.feedback.send=Send
|
||||
runwaydemo.feedback.thanks=Thank you — your message was kept.
|
||||
runwaydemo.feedback.invalid=Please write a message first.
|
||||
runwaydemo.feedback.limited=Too many messages from your address — please try again in a minute.
|
||||
runwaydemo.feedback.captcha=Please complete the challenge and try again.
|
||||
runwaydemo.showcase.title=Showcase
|
||||
runwaydemo.page.title=Runway demo
|
||||
|
||||
|
||||
@@ -33,6 +33,7 @@ runwaydemo.feedback.send=Enviar
|
||||
runwaydemo.feedback.thanks=Gracias — guardamos tu mensaje.
|
||||
runwaydemo.feedback.invalid=Escribe un mensaje primero.
|
||||
runwaydemo.feedback.limited=Demasiados mensajes desde tu dirección — inténtalo de nuevo en un minuto.
|
||||
runwaydemo.feedback.captcha=Completa el desafío e inténtalo de nuevo.
|
||||
runwaydemo.showcase.title=Escaparate
|
||||
runwaydemo.page.title=Demo de Runway
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
# =============================================================================
|
||||
id: runway-demo
|
||||
name: Runway Demo (Kitchen-Sink Plugin)
|
||||
version: 2.1.0
|
||||
version: 2.1.1
|
||||
|
||||
# The lowest SPI level this plugin needs; a kernel below it BLOCKS the plugin at startup with a reason. Declare the
|
||||
# floor of the NEWEST type you use: without it, an older kernel would load the plugin and fail at the first request
|
||||
|
||||
@@ -21,7 +21,7 @@
|
||||
<!-- runway-plugin-<plugin id>, as for every plugin in this repository: the release zip is named after it
|
||||
(runway-plugin-runway-demo-<version>.zip under the tag runway-demo-<version>). -->
|
||||
<artifactId>runway-plugin-runway-demo</artifactId>
|
||||
<version>2.1.0</version>
|
||||
<version>2.1.1</version>
|
||||
<packaging>jar</packaging>
|
||||
<name>Runway Demo Plugin</name>
|
||||
<licenses>
|
||||
@@ -47,7 +47,7 @@
|
||||
<!-- Reproducible builds: pins every archive entry's timestamp so two builds of the same source
|
||||
produce byte-identical artifacts. Without it a jar embeds the build time, so a rebuild can
|
||||
never match what was published. Bump at each release. -->
|
||||
<project.build.outputTimestamp>2026-10-21T17:23:00Z</project.build.outputTimestamp>
|
||||
<project.build.outputTimestamp>2026-10-29T00:00:00Z</project.build.outputTimestamp>
|
||||
<!-- The Runway SPI this plugin compiles against: a RELEASED kernel (its SPI jars installed
|
||||
from that release's assets). The plugin's runtime floor is plugin.yml's
|
||||
requiresSpi, not this number. -->
|
||||
@@ -169,6 +169,8 @@
|
||||
<dirset dir="${stage}"/>
|
||||
<dirset dir="${project.build.directory}" includes="runway-demo"/>
|
||||
</touch>
|
||||
<!-- The stamped files predate any earlier zip, so <zip> would skip the rebuild. -->
|
||||
<delete file="${project.build.directory}/${project.artifactId}-${project.version}.zip"/>
|
||||
<zip destfile="${project.build.directory}/${project.artifactId}-${project.version}.zip">
|
||||
<zipfileset dir="${project.build.directory}" includes="runway-demo/**"/>
|
||||
</zip>
|
||||
|
||||
Loaded 100 of 223 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user