Runway 1.1.0

This commit is contained in:
Runway committed 2026-10-29 09:22:38 -06:00
1 parent ce217fc952
commit 07d5bd7e9a
223 files changed
+21147 -255

No files matched your search

@@ -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");
}
}
@@ -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);
}
}
}
@@ -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);
}
@@ -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);
}
}