• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

knowledgepixels / nanopub-query / 41996390169

05 Nov 2026 08:41AM UTC coverage: 78.002% (+0.4%) from 77.65%
41996390169

push

github

web-flow
Merge pull request #247 from knowledgepixels/fix/api-duplicate-query-guard

fix: stop retries of an identical /api request from piling up in RDF4J

973 of 1392 branches covered (69.9%)

Branch coverage included in aggregate %.

2736 of 3363 relevant lines covered (81.36%)

12.79 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

0.0
src/main/java/com/knowledgepixels/query/MainVerticle.java
1
package com.knowledgepixels.query;
2

3
import com.github.jsonldjava.shaded.com.google.common.base.Charsets;
4
import com.knowledgepixels.query.GrlcSpec.InvalidGrlcSpecException;
5
import io.micrometer.prometheusmetrics.PrometheusMeterRegistry;
6
import io.vertx.core.AbstractVerticle;
7
import io.vertx.core.Future;
8
import io.vertx.core.Promise;
9
import io.vertx.core.buffer.Buffer;
10
import io.vertx.core.http.*;
11
import io.vertx.ext.web.Router;
12
import io.vertx.ext.web.RoutingContext;
13
import io.vertx.ext.web.handler.CorsHandler;
14
import io.vertx.ext.web.handler.StaticHandler;
15
import io.vertx.ext.web.proxy.handler.ProxyHandler;
16
import io.vertx.httpproxy.*;
17
import io.vertx.micrometer.PrometheusScrapingHandler;
18
import io.vertx.micrometer.backends.BackendRegistries;
19
import org.eclipse.rdf4j.model.Value;
20
import org.slf4j.Logger;
21
import org.slf4j.LoggerFactory;
22

23
import java.io.InputStream;
24
import java.net.URLEncoder;
25
import java.util.ArrayList;
26
import java.util.Collections;
27
import java.util.List;
28
import java.util.Scanner;
29
import java.util.concurrent.CopyOnWriteArrayList;
30
import java.util.concurrent.Executors;
31
import java.util.concurrent.ScheduledExecutorService;
32
import java.util.concurrent.TimeUnit;
33
import java.util.concurrent.atomic.AtomicBoolean;
34

35
/**
36
 * Main verticle that coordinates the incoming HTTP requests.
37
 */
38
@GeneratedFlagForDependentElements
39
public class MainVerticle extends AbstractVerticle {
40

41
    private static String css = null;
42

43
    private static final Logger logger = LoggerFactory.getLogger(MainVerticle.class);
44

45
    /**
46
     * Every periodic scheduler started by {@link #start}, so shutdown can stop them
47
     * before anything closes the store underneath a running tick.
48
     */
49
    private static final List<ScheduledExecutorService> schedulers = new CopyOnWriteArrayList<>();
50

51
    /** Set once {@link #shutdownGracefully} has run, so a second signal is a no-op. */
52
    private static final AtomicBoolean shutdownDone = new AtomicBoolean(false);
53

54
    /** The Vert.x instance to close on shutdown; {@code vertx} itself is per-verticle state. */
55
    private static volatile io.vertx.core.Vertx vertxRef;
56

57
    /** Caps repeated identical /api requests; see {@link ApiQueryGuard}. */
58
    private ApiQueryGuard apiQueryGuard;
59

60
    /**
61
     * Budget for letting in-flight work finish during shutdown, in seconds. Must stay
62
     * comfortably below the container's {@code stop_grace_period} (150 s in
63
     * docker-compose.yml), or the runtime's SIGKILL lands in the middle of exactly the
64
     * write this wait exists to protect.
65
     */
66
    private static final int SHUTDOWN_QUIESCE_SECONDS = Integer.parseInt(
67
            Utils.getEnvString("NANOPUB_QUERY_SHUTDOWN_QUIESCE_SECONDS", "90"));
68

69
    /**
70
     * Ordered, write-quiescing shutdown. Runs from the JVM shutdown hook, i.e. on
71
     * SIGTERM from {@code docker stop} / {@code compose down} / a restart.
72
     *
73
     * <p>The order is the point. An LMDB write that is still in flight when the store
74
     * goes down gets aborted, and an aborted write is the incomplete-rollback condition
75
     * behind the value-ID remap corruption (eclipse-rdf4j/rdf4j#4775) that scrambled
76
     * metadata and swallowed nanopubs on 2026-08-20 and 2026-08-24. So:
77
     *
78
     * <ol>
79
     *   <li>stop the schedulers, so no new load / materializer / reconciler tick starts;</li>
80
     *   <li>wait for the tick that is already running to finish on its own — a full
81
     *       space-state build measured ~70 s, so the budget is generous by design;</li>
82
     *   <li>suspend store writes and wait until no repo write lock is held, which is
83
     *       the point at which nothing is inside a transaction;</li>
84
     *   <li>only then close the repositories and the HTTP server.</li>
85
     * </ol>
86
     *
87
     * <p>Each step is bounded and logged. Exceeding a budget is reported as a WARN
88
     * naming what was still running: that line is the difference between "we shut down
89
     * cleanly" and "this stop is a corruption candidate", and the fleet has needed that
90
     * distinction after the fact more than once.
91
     */
92
    static void shutdownGracefully() {
93
        if (!shutdownDone.compareAndSet(false, true)) return;
94
        long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(SHUTDOWN_QUIESCE_SECONDS);
95
        logger.info("Gracefully shutting down (quiesce budget {}s)...", SHUTDOWN_QUIESCE_SECONDS);
96
        try {
97
            for (ScheduledExecutorService scheduler : schedulers) {
98
                scheduler.shutdown();
99
            }
100
            boolean ticksFinished = true;
101
            for (ScheduledExecutorService scheduler : schedulers) {
102
                long remaining = deadline - System.nanoTime();
103
                if (remaining <= 0 || !scheduler.awaitTermination(remaining, TimeUnit.NANOSECONDS)) {
104
                    ticksFinished = false;
105
                    break;
106
                }
107
            }
108
            if (!ticksFinished) {
109
                logger.warn("Shutdown: a periodic tick was still running when the quiesce budget ran out");
110
            }
111
            long remaining = Math.max(0, deadline - System.nanoTime());
112
            boolean quiesced = NanopubLoader.suspendWritesAndAwaitQuiescence(
113
                    TimeUnit.NANOSECONDS.toMillis(remaining));
114
            if (quiesced && ticksFinished) {
115
                logger.info("Shutdown: all writes quiesced; closing repositories");
116
            } else {
117
                logger.warn("Shutdown: closing repositories WITHOUT full write quiescence "
118
                        + "(ticksFinished={}, writesQuiesced={}) — if this stop is followed by store "
119
                        + "corruption, this line is the reason to suspect it (rdf4j#4775)",
120
                        ticksFinished, quiesced);
121
            }
122
            TripleStore.get().shutdownRepositories();
123
            if (vertxRef != null) {
124
                vertxRef.close().toCompletionStage().toCompletableFuture().get(5, TimeUnit.SECONDS);
125
            }
126
            logger.info("Graceful shutdown completed");
127
        } catch (InterruptedException ex) {
128
            Thread.currentThread().interrupt();
129
            logger.warn("Graceful shutdown interrupted", ex);
130
        } catch (Exception ex) {
131
            logger.info("Graceful shutdown failed", ex);
132
        }
133
    }
134

135
    /**
136
     * Start the main verticle.
137
     *
138
     * @param startPromise the promise to complete when the verticle is started
139
     * @throws Exception if an error occurs during startup
140
     */
141
    @Override
142
    public void start(Promise<Void> startPromise) throws Exception {
143
        if (!FeatureFlags.trustStateEnabled()) {
144
            logger.warn("Trust state feature disabled via NANOPUB_QUERY_ENABLE_TRUST_STATE=false — "
145
                    + "no trust snapshots will be fetched or materialised, and the 'trust' repo will not be auto-created.");
146
        }
147
        if (!FeatureFlags.spacesEnabled()) {
148
            logger.warn("Spaces feature disabled via NANOPUB_QUERY_ENABLE_SPACES=false — "
149
                    + "no space-relevant nanopubs will be extracted into npa:spacesGraph, "
150
                    + "and the 'spaces' repo will not be auto-created.");
151
        }
152
        if (!FeatureFlags.fullRepoEnabled()) {
153
            logger.warn("Writes to the 'full' repo disabled via NANOPUB_QUERY_ENABLE_FULL_REPO=false — "
154
                    + "generic SPARQL queries against /repo/full will return an empty store.");
155
        }
156
        if (!FeatureFlags.textRepoEnabled()) {
157
            logger.warn("Writes to the 'text' repo disabled via NANOPUB_QUERY_ENABLE_TEXT_REPO=false — "
158
                    + "full-text search via /repo/text will return nothing.");
159
        }
160
        if (!FeatureFlags.last30dRepoEnabled()) {
161
            logger.warn("Writes to the 'last30d' repo disabled via NANOPUB_QUERY_ENABLE_LAST30D_REPO=false — "
162
                    + "the /repo/last30d endpoint will be empty; rewrite queries against /repo/full with a date filter.");
163
        }
164
        if (!FeatureFlags.pendingAccountsEnabled()) {
165
            logger.warn("Pending-account mirror disabled via NANOPUB_QUERY_ENABLE_PENDING_ACCOUNTS=false — "
166
                    + "introduced-but-not-yet-approved accounts stay invisible: their self-signed observer "
167
                    + "roles do not materialise and their own view displays stay hidden (issue #195).");
168
        }
169
        if (!FeatureFlags.reconciliationEnabled()) {
170
            logger.warn("Shard reconciliation disabled via NANOPUB_QUERY_ENABLE_RECONCILIATION=false — "
171
                    + "nanopubs silently missing from individual shard repos (issue #139) will not be detected or repaired.");
172
        }
173
        if (FeatureFlags.localInstance()) {
174
            logger.warn("Instance declared local/private via NANOPUB_QUERY_LOCAL_INSTANCE=true — "
175
                    + "nanopubs typed npx:ProtectedNanopub will be loaded and served. Never use this setting on a public instance.");
176
        }
177
        if (FeatureFlags.allowTestRegistry()) {
178
            logger.warn("Test-registry ingestion enabled via NANOPUB_QUERY_ALLOW_TEST_REGISTRY=true — "
179
                    + "content will be loaded even from a registry that reports itself as a test instance. "
180
                    + "Never use this setting on a production instance.");
181
        }
182
        if (FeatureFlags.testInstance()) {
183
            logger.warn("Instance declared a test instance via NANOPUB_QUERY_TEST_INSTANCE=true — "
184
                    + "every response reports Nanopub-Query-Test-Instance: true, and consumers such as "
185
                    + "nanopub-monitor will not compare it against production instances. This says nothing "
186
                    + "about the registry it loads from: to ingest from a registry that reports itself as a "
187
                    + "test instance, set NANOPUB_QUERY_ALLOW_TEST_REGISTRY=true as well.");
188
        }
189
        HttpClient httpClient = vertx.createHttpClient(
190
                new HttpClientOptions()
191
                        .setConnectTimeout(Utils.getEnvInt("NANOPUB_QUERY_VERTX_CONNECT_TIMEOUT", 1000))
192
                        .setIdleTimeoutUnit(TimeUnit.SECONDS)
193
                        .setIdleTimeout(Utils.getEnvInt("NANOPUB_QUERY_VERTX_IDLE_TIMEOUT", 60))
194
                        .setReadIdleTimeout(Utils.getEnvInt("NANOPUB_QUERY_VERTX_IDLE_TIMEOUT", 60))
195
                        .setWriteIdleTimeout(Utils.getEnvInt("NANOPUB_QUERY_VERTX_IDLE_TIMEOUT", 60)),
196
                new PoolOptions().setHttp1MaxSize(200).setHttp2MaxSize(200)
197
        );
198

199
        // Idle timeout on the *server* side, which was previously unset ("wait forever").
200
        // SERVICE clauses in /api queries loop back into this server via
201
        // NANOPUB_QUERY_INTERNAL_URL, so the RDF4J server holds a pooled connection here
202
        // for every federated evaluation. When RDF4J leaks such a lease (the ValueStore
203
        // ReadTxn leak, eclipse-rdf4j/rdf4j#5970), nothing on this end ever closes the
204
        // socket: it stays ESTABLISHED, Apache's evictExpiredConnections never sees it as
205
        // stale, and the slot is gone until Tomcat restarts. Observed on 2026-08-11:
206
        // 100/100 connections to this port held ESTABLISHED while all 157 Tomcat worker
207
        // threads sat idle in their task queue, i.e. a fully leased pool with zero work in
208
        // flight, and every federated query failing with "Timeout waiting for connection
209
        // from pool" until the store was restarted by hand.
210
        //
211
        // Closing idle connections turns that permanent wedge into a self-healing one: a
212
        // leaked lease is closed by this end, goes stale, and is evicted from RDF4J's pool.
213
        // The default is deliberately far above any legitimate idle period on that route —
214
        // RDF4J's own client uses a 10 s socket timeout for SERVICE evaluation — while
215
        // still bounding the leak. Note this counts *any* inactivity, including a slow
216
        // query that has not started streaming its response, so do not lower it below the
217
        // slowest query this instance is expected to serve.
218
        HttpServer proxyServer = vertx.createHttpServer(
219
                new HttpServerOptions()
220
                        .setMaxInitialLineLength(65536)
221
                        .setIdleTimeoutUnit(TimeUnit.SECONDS)
222
                        .setIdleTimeout(Utils.getEnvInt("NANOPUB_QUERY_VERTX_SERVER_IDLE_TIMEOUT", 300))
223
        );
224
        Router proxyRouter = Router.router(vertx);
225
        proxyRouter.route().handler(CorsHandler.create().addOriginWithRegex(".*"));
226

227
        // Metrics
228
        final var metricsHttpServer = vertx.createHttpServer();
229
        final var metricsRouter = Router.router(vertx);
230
        Future<HttpServer> metricsListening = metricsHttpServer.requestHandler(metricsRouter).listen(9394);
231

232
        final var metricsRegistry = (PrometheusMeterRegistry) BackendRegistries.getDefaultNow();
233
        final var collector = new MetricsCollector(metricsRegistry);
234
        metricsRouter.route("/metrics").handler(PrometheusScrapingHandler.create(metricsRegistry));
235
        // ----------
236
        // This part is only used if the redirection is not done through Nginx.
237
        // See nginx.conf and this bug report: https://github.com/eclipse-rdf4j/rdf4j/discussions/5120
238
        HttpProxy rdf4jProxy = HttpProxy.reverseProxy(httpClient);
239
        String proxy = Utils.getEnvString("RDF4J_PROXY_HOST", "rdf4j");
240
        int proxyPort = Utils.getEnvInt("RDF4J_PROXY_PORT", 8080);
241
        rdf4jProxy.origin(proxyPort, proxy);
242

243
        // Server-side query evaluation limit injected into every proxied rdf4j request
244
        // (see Utils.appendQueryTimeout). The public edge cuts clients at 10s, but that
245
        // never stops the server-side evaluation; this does. Kept well above the edge
246
        // timeout so aborts stay rare: interrupted evaluations concurrent with writes
247
        // are a suspected LMDB corruption trigger upstream (rdf4j#5960/#4806).
248
        int queryTimeoutSeconds = Utils.getEnvInt("RDF4J_QUERY_TIMEOUT_SECONDS", 60);
249

250
        // Since evaluations outlive the edge timeout, repeated identical /api requests are
251
        // capped so that a query that never finishes in time cannot occupy every core.
252
        apiQueryGuard = ApiQueryGuard.fromEnvironment(queryTimeoutSeconds);
253
        vertx.setPeriodic(60_000, id -> apiQueryGuard.purge(System.currentTimeMillis()));
254

255
        rdf4jProxy.addInterceptor(new ProxyInterceptor() {
×
256

257
            @Override
258
            @GeneratedFlagForDependentElements
259
            public Future<ProxyResponse> handleProxyRequest(ProxyContext context) {
260
                ProxyRequest request = context.request();
261
                request.setURI(request.getURI().replaceAll("/", "_").replaceFirst("^_repo_", "/rdf4j-server/repositories/"));
262
                request.setURI(Utils.appendQueryTimeout(request.getURI(), queryTimeoutSeconds));
263
                // For later to try to get HTML tables out:
264
//                                if (request.headers().get("Accept") == null) {
265
//                                        request.putHeader("Accept", "text/html");
266
//                                }
267
//                                request.putHeader("Accept", "application/json");
268
                return ProxyInterceptor.super.handleProxyRequest(context);
269
            }
270

271
            @Override
272
            @GeneratedFlagForDependentElements
273
            public Future<Void> handleProxyResponse(ProxyContext context) {
274
                ProxyResponse resp = context.response();
275
                resp.putHeader("Access-Control-Allow-Origin", "*");
276
                resp.putHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS");
277
                // For later to try to get HTML tables out:
278
//                                String acceptHeader = context.request().headers().get("Accept");
279
//                                if (acceptHeader != null && acceptHeader.contains("text/html")) {
280
//                                        resp.putHeader("Content-Type", "text/html");
281
//                                        resp.setBody(Body.body(Buffer.buffer("<html><body><strong>test</strong></body></html>")));
282
//                                }
283
                return ProxyInterceptor.super.handleProxyResponse(context);
284
            }
285

286
        });
287
        // ----------
288

289
        proxyRouter.route(HttpMethod.GET, "/repo").handler(req -> handleRedirect(req, "/repo"));
290
        proxyRouter.route(HttpMethod.GET, "/repo/*").handler(ProxyHandler.create(rdf4jProxy));
291
        proxyRouter.route(HttpMethod.POST, "/repo/*").handler(ProxyHandler.create(rdf4jProxy));
292
        proxyRouter.route(HttpMethod.HEAD, "/repo/*").handler(ProxyHandler.create(rdf4jProxy));
293
        proxyRouter.route(HttpMethod.OPTIONS, "/repo/*").handler(ProxyHandler.create(rdf4jProxy));
294
        proxyRouter.route(HttpMethod.GET, "/tools/*").handler(req -> {
295
            final String yasguiPattern = "^/tools/([a-zA-Z0-9-_]+)(/([a-zA-Z0-9-_]+))?/yasgui\\.html$";
296
            if (req.normalizedPath().matches(yasguiPattern)) {
297
                String repo = req.normalizedPath().replaceFirst(yasguiPattern, "$1$2");
298
                req.response()
299
                        .putHeader("content-type", "text/html")
300
                        .end("<!DOCTYPE html>\n"
301
                             + "<html lang=\"en\">\n"
302
                             + "<head>\n"
303
                             + "<meta charset=\"utf-8\">\n"
304
                             + "<meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">\n"
305
                             + "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n"
306
                             + "<title>Nanopub Query SPARQL Editor for repository: " + repo + "</title>\n"
307
                             + "<link rel=\"stylesheet\" href=\"/style.css\">\n"
308
                             + "<link href='https://cdn.jsdelivr.net/yasgui/2.6.1/yasgui.min.css' rel='stylesheet' type='text/css'/>\n"
309
                             + "<style>.yasgui .endpointText {display:none !important;}</style>\n"
310
                             + "<script type=\"text/javascript\">localStorage.clear();</script>\n"
311
                             + "</head>\n"
312
                             + "<body>\n"
313
                             + "<h3>Nanopub Query SPARQL Editor for repository: " + repo + "</h3>\n"
314
                             + "<div id='yasgui'></div>\n"
315
                             + "<script src='https://cdn.jsdelivr.net/yasgui/2.6.1/yasgui.min.js'></script>\n"
316
                             + "<script type=\"text/javascript\">\n"
317
                             + "var yasgui = YASGUI(document.getElementById(\"yasgui\"), {\n"
318
                             + "  yasqe:{sparql:{endpoint:'/repo/" + repo + "'},value:'" + Utils.defaultQuery.replaceAll("\n", "\\\\n") + "'}\n"
319
                             + "});\n"
320
                             + "</script>\n"
321
                             + "</body>\n"
322
                             + "</html>");
323
            } else if (req.normalizedPath().matches(SparqlEditorRoute.PATH_PATTERN)) {
324
                // SIB's sparql-editor, offered alongside the plain YASGUI page above
325
                // rather than instead of it (issue #51).
326
                req.response()
327
                        .putHeader("content-type", "text/html")
328
                        .end(SparqlEditorRoute.renderHtml(SparqlEditorRoute.repoFromPath(req.normalizedPath())));
329
            } else {
330
                req.response()
331
                        .putHeader("content-type", "text/plain")
332
                        .setStatusCode(404)
333
                        .end("not found");
334
            }
335
        });
336
        proxyRouter.route(HttpMethod.GET, "/page").handler(req -> handleRedirect(req, "/page"));
337
        proxyRouter.route(HttpMethod.GET, "/page/*").handler(req -> {
338
            final String pagePattern = "^/page/([a-zA-Z0-9-_]+)(/([a-zA-Z0-9-_]+))?$";
339
            if (req.normalizedPath().matches(pagePattern)) {
340
                String repo = req.normalizedPath().replaceFirst(pagePattern, "$1$2");
341
                req.response()
342
                        .putHeader("content-type", "text/html")
343
                        .end("<!DOCTYPE html>\n"
344
                             + "<html lang=\"en\">\n"
345
                             + "<head>\n"
346
                             + "<meta charset=\"utf-8\">\n"
347
                             + "<meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">\n"
348
                             + "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n"
349
                             + "<title>Nanopub Query repo: " + repo + "</title>\n"
350
                             + "<link rel=\"stylesheet\" href=\"/style.css\">\n"
351
                             + "</head>\n"
352
                             + "<body>\n"
353
                             + "<h3>Nanopub Query repo: " + repo + "</h3>\n"
354
                             + "<p>Endpoint: <a href=\"/repo/" + repo + "\">/repo/" + repo + "</a></p>"
355
                             + "<p>YASGUI: <a href=\"/tools/" + repo + "/yasgui.html\">/tools/" + repo + "/yasgui.html</a></p>"
356
                             + "<p>SPARQL editor: <a href=\"/tools/" + repo + "/sparql-editor.html\">/tools/" + repo + "/sparql-editor.html</a></p>"
357
                             + "</body>\n"
358
                             + "</html>");
359
            } else {
360
                req.response()
361
                        .putHeader("content-type", "text/plain")
362
                        .setStatusCode(404)
363
                        .end("not found");
364
            }
365
        });
366
        proxyRouter.route(HttpMethod.GET, "/").handler(req -> {
367
            vertx.<String>executeBlocking(() -> {
368
                String repos = "";
369
                List<String> repoList = new ArrayList<>(TripleStore.get().getRepositoryNames());
370
                Collections.sort(repoList);
371
                for (String s : repoList) {
372
                    if (s.startsWith("pubkey_") || s.startsWith("type_")) continue;
373
                    repos += "<li><code><a href=\"/page/" + s + "\">" + s + "</a></code></li>";
374
                }
375
                String pinnedApisValue = Utils.getEnvString("NANOPUB_QUERY_PINNED_APIS", "");
376
                String[] pinnedApis = pinnedApisValue.split(" ");
377
                String pinnedApiLinks = "";
378
                if (!pinnedApisValue.isEmpty()) {
379
                    for (String s : pinnedApis) {
380
                        pinnedApiLinks = pinnedApiLinks + "<li><a href=\"openapi/?url=spec/" + s + "%3Fapi-version=latest\">" + s.replaceFirst("^.*/", "") + "</a></li>";
381
                    }
382
                    pinnedApiLinks = "<p>Pinned APIs:</p>\n" +
383
                                     "<ul>\n" +
384
                                     pinnedApiLinks +
385
                                     "</ul>\n";
386
                }
387
                return "<!DOCTYPE html>\n"
388
                     + "<html lang='en'>\n"
389
                     + "<head>\n"
390
                     + "<title>Nanopub Query</title>\n"
391
                     + "<meta charset='utf-8'>\n"
392
                     + "<link rel=\"stylesheet\" href=\"/style.css\">\n"
393
                     + "</head>\n"
394
                     + "<body>\n"
395
                     + "<h1>Nanopub Query</h1>"
396
                     + "<p>General repos:</p>"
397
                     + "<ul>" + repos + "</ul>"
398
                     + "<p>Specific repos:</p>"
399
                     + "<ul>"
400
                     + "<li><a href=\"/pubkeys\">Pubkey Repos</a></li>"
401
                     + "<li><a href=\"/types\">Type Repos</a></li>"
402
                     + "</ul>"
403
                     + (FeatureFlags.spacesEnabled()
404
                             ? "<p>Spaces:</p>"
405
                               + "<ul><li><a href=\"/spaces\">Spaces</a></li></ul>"
406
                             : "")
407
                     + pinnedApiLinks
408
                     + "</body>\n"
409
                     + "</html>";
410
            }, false).onSuccess(html -> {
411
                req.response().putHeader("content-type", "text/html").end(html);
412
            }).onFailure(ex -> {
413
                req.response().setStatusCode(500).end("Error: " + ex.getMessage());
414
            });
415
        });
416
        proxyRouter.route(HttpMethod.GET, "/pubkeys").handler(req -> {
417
            vertx.<String>executeBlocking(() -> {
418
                String repos = "";
419
                List<String> repoList = new ArrayList<>(TripleStore.get().getRepositoryNames());
420
                Collections.sort(repoList);
421
                for (String s : repoList) {
422
                    if (!s.startsWith("pubkey_")) continue;
423
                    String hash = s.replaceFirst("^([a-zA-Z0-9-]+)_([a-zA-Z0-9-_]+)$", "$2");
424
                    Value hashObj = Utils.getObjectForHash(hash);
425
                    String label;
426
                    if (hashObj == null) {
427
                        label = "";
428
                    } else {
429
                        label = " (" + Utils.getShortPubkeyName(hashObj.stringValue()) + ")";
430
                    }
431
                    s = s.replaceFirst("^([a-zA-Z0-9-]+)_([a-zA-Z0-9-_]+)$", "$1/$2");
432
                    repos += "<li><code><a href=\"/page/" + s + "\">" + s + "</a>" + label + "</code></li>";
433
                }
434
                return "<!DOCTYPE html>\n"
435
                     + "<html lang='en'>\n"
436
                     + "<head>\n"
437
                     + "<title>Nanopub Query: Pubkey Repos</title>\n"
438
                     + "<meta charset='utf-8'>\n"
439
                     + "<link rel=\"stylesheet\" href=\"/style.css\">\n"
440
                     + "</head>\n"
441
                     + "<body>\n"
442
                     + "<h3>Pubkey Repos</h3>"
443
                     + "<p>Repos:</p>"
444
                     + "<ul>" + repos + "</ul>"
445
                     + "</body>\n"
446
                     + "</html>";
447
            }, false).onSuccess(html -> {
448
                req.response().putHeader("content-type", "text/html").end(html);
449
            }).onFailure(ex -> {
450
                req.response().setStatusCode(500).end("Error: " + ex.getMessage());
451
            });
452
        });
453
        proxyRouter.route(HttpMethod.GET, "/types").handler(req -> {
454
            vertx.<String>executeBlocking(() -> {
455
                String repos = "";
456
                List<String> repoList = new ArrayList<>(TripleStore.get().getRepositoryNames());
457
                Collections.sort(repoList);
458
                for (String s : repoList) {
459
                    if (!s.startsWith("type_")) continue;
460
                    String hash = s.replaceFirst("^([a-zA-Z0-9-]+)_([a-zA-Z0-9-_]+)$", "$2");
461
                    Value hashObj = Utils.getObjectForHash(hash);
462
                    String label;
463
                    if (hashObj == null) {
464
                        label = "";
465
                    } else {
466
                        label = " (" + hashObj.stringValue() + ")";
467
                    }
468
                    s = s.replaceFirst("^([a-zA-Z0-9-]+)_([a-zA-Z0-9-_]+)$", "$1/$2");
469
                    repos += "<li><code><a href=\"/page/" + s + "\">" + s + "</a>" + label + "</code></li>";
470
                }
471
                return "<!DOCTYPE html>\n"
472
                     + "<html lang='en'>\n"
473
                     + "<head>\n"
474
                     + "<title>Nanopub Query: Type Repos</title>\n"
475
                     + "<meta charset='utf-8'>\n"
476
                     + "<link rel=\"stylesheet\" href=\"/style.css\">\n"
477
                     + "</head>\n"
478
                     + "<body>\n"
479
                     + "<h3>Type Repos</h3>"
480
                     + "<p>Repos:</p>"
481
                     + "<ul>" + repos + "</ul>"
482
                     + "</body>\n"
483
                     + "</html>";
484
            }, false).onSuccess(html -> {
485
                req.response().putHeader("content-type", "text/html").end(html);
486
            }).onFailure(ex -> {
487
                req.response().setStatusCode(500).end("Error: " + ex.getMessage());
488
            });
489
        });
490
        io.vertx.core.Handler<RoutingContext> spacesHandler = req -> {
491
            if (!FeatureFlags.spacesEnabled()) {
492
                req.response().setStatusCode(404)
493
                        .putHeader("content-type", "text/plain")
494
                        .end("Spaces feature is disabled");
495
                return;
496
            }
497
            // Path suffix wins over Accept header so /spaces.json is unambiguous.
498
            boolean wantJson = req.normalizedPath().endsWith(".json")
499
                    || "application/json".equalsIgnoreCase(req.request().getHeader("Accept"));
500
            vertx.<String>executeBlocking(() -> {
501
                var rows = SpacesListingRoute.fetchRows();
502
                return wantJson
503
                        ? SpacesListingRoute.renderJson(rows)
504
                        : SpacesListingRoute.renderHtml(rows);
505
            }, false).onSuccess(body -> {
506
                req.response().putHeader(
507
                        "content-type",
508
                        wantJson ? "application/json" : "text/html").end(body);
509
            }).onFailure(ex -> {
510
                req.response().setStatusCode(500).end("Error: " + ex.getMessage());
511
            });
512
        };
513
        proxyRouter.route(HttpMethod.GET, "/spaces").handler(spacesHandler);
514
        proxyRouter.route(HttpMethod.GET, "/spaces.json").handler(spacesHandler);
515
        proxyRouter.route(HttpMethod.GET, "/style.css").handler(req -> {
516
            if (css == null) {
517
                css = getResourceAsString("style.css");
518
            }
519
            req.response().end(css);
520
        });
521

522
        // TODO This is no longer needed and can be removed at some point:
523
        proxyRouter.route(HttpMethod.GET, "/grlc-spec/*").handler(req -> {
524
            vertx.<String>executeBlocking(() -> {
525
                GrlcSpec gsp = new GrlcSpec(req.normalizedPath(), req.queryParams());
526
                return gsp.getSpec();
527
            }, false).onSuccess(spec -> {
528
                req.response().putHeader("content-type", "text/yaml").end(spec);
529
            }).onFailure(ex -> {
530
                if (ex instanceof InvalidGrlcSpecException) {
531
                    logger.warn("Bad grlc request for '{}': {}", req.normalizedPath(), ex.getMessage());
532
                    req.response().setStatusCode(400).end(ex.getMessage());
533
                } else {
534
                    logger.error("Unexpected error for grlc request '{}'", req.normalizedPath(), ex);
535
                    req.response().setStatusCode(500).end("Unexpected error: " + ex.getMessage());
536
                }
537
            });
538
        });
539

540
        proxyRouter.route(HttpMethod.GET, "/openapi/spec/*").handler(req -> {
541
            vertx.<String>executeBlocking(() -> {
542
                OpenApiSpecPage osp = new OpenApiSpecPage(req.normalizedPath(), req.queryParams());
543
                return osp.getSpec();
544
            }, false).onSuccess(spec -> {
545
                req.response().putHeader("content-type", "text/yaml").end(spec);
546
            }).onFailure(ex -> {
547
                if (ex instanceof InvalidGrlcSpecException) {
548
                    logger.warn("Bad openapi request for '{}': {}", req.normalizedPath(), ex.getMessage());
549
                    req.response().setStatusCode(400).end("Invalid grlc API definition: " + ex.getMessage());
550
                } else {
551
                    logger.error("Unexpected error for openapi request '{}'", req.normalizedPath(), ex);
552
                    req.response().setStatusCode(500).end("Unexpected error: " + ex.getMessage());
553
                }
554
            });
555
        });
556

557
        proxyRouter.route("/openapi/*").handler(StaticHandler.create("com/knowledgepixels/query/swagger"));
558

559
        HttpProxy grlcxProxy = HttpProxy.reverseProxy(httpClient);
560
        grlcxProxy.origin(proxyPort, proxy);
561

562
        grlcxProxy.addInterceptor(new ProxyInterceptor() {
×
563

564
            @Override
565
            @GeneratedFlagForDependentElements
566
            public Future<ProxyResponse> handleProxyRequest(ProxyContext context) {
567
                final ProxyRequest req = context.request();
568
                final String apiPattern = "^/api/(RA[a-zA-Z0-9-_]{43})/([a-zA-Z0-9-_]+)([.]csv|[.]json|[.]srx)?([?].*)?$";
569
                if (req.getURI().matches(apiPattern)) {
570
                    try {
571
                        req.setMethod(HttpMethod.POST);
572
                        if (req.getURI().matches(".*[.]csv([?].*)?$")) {
573
                            req.putHeader("Accept", "text/csv");
574
                            req.setURI(req.getURI().replaceFirst("[.]csv([?].*)?$", "$1"));
575
                        } else if (req.getURI().matches(".*[.]json([?].*)?$")) {
576
                            req.putHeader("Accept", "application/json");
577
                            req.setURI(req.getURI().replaceFirst("[.]json([?].*)?$", "$1"));
578
                        } else if (req.getURI().matches(".*[.]srx([?].*)?$")) {
579
                            req.putHeader("Accept", "application/xml");
580
                            req.setURI(req.getURI().replaceFirst("[.]srx([?].*)?$", "$1"));
581
                        }
582
                        GrlcSpec grlcSpec = new GrlcSpec(req.getURI(), req.proxiedRequest().params());
583
                        context.set("queryPath", req.getURI().replaceFirst("[?].*$", "").replaceFirst("^/api/", ""));
584
                        String fullUri = req.getURI();
585
                        int qIdx = fullUri.indexOf('?');
586
                        context.set("queryParams", qIdx >= 0 ? fullUri.substring(qIdx + 1) : "");
587
                        context.set("queryStart", System.currentTimeMillis());
588

589
                        // Variant 1:
590
                        req.putHeader("Content-Type", "application/sparql-query");
591
                        req.setBody(Body.body(Buffer.buffer(grlcSpec.expandQuery())));
592
                        // Variant 2:
593
                        //req.putHeader("Content-Type", "application/x-www-form-urlencoded");
594
                        //req.setBody(Body.body(Buffer.buffer("query=" + URLEncoder.encode(grlcSpec.getExpandedQueryContent(), Charsets.UTF_8))));
595

596
                        req.setURI(Utils.appendQueryTimeout(
597
                                "/rdf4j-server/repositories/" + grlcSpec.getRepoName(), queryTimeoutSeconds));
598

599
                        String guardKey = context.get("queryPath", String.class) + "?" + context.get("queryParams", String.class);
600
                        ApiQueryGuard.Admission admission = apiQueryGuard.admit(guardKey, System.currentTimeMillis());
601
                        if (admission instanceof ApiQueryGuard.Refused refused) {
602
                            logger.info("Refused API request {}: {}", guardKey, refused.reason());
603
                            return Future.succeededFuture(context.request()
604
                                    .response()
605
                                    .setStatusCode(503)
606
                                    .putHeader("Retry-After", String.valueOf(refused.retryAfterSeconds()))
607
                                    .putHeader("Content-Type", "text/plain")
608
                                    .setBody(Body.body(Buffer.buffer("Query not started: " + refused.reason()
609
                                            + ". Try again in " + refused.retryAfterSeconds() + " s."))));
610
                        }
611
                        releaseWhenDone(req.proxiedRequest().response(), (ApiQueryGuard.Admitted) admission);
612
                        logger.info("Forwarding apix request to /rdf4j-server/repositories/{}", grlcSpec.getRepoName());
613
                    } catch (InvalidGrlcSpecException ex) {
614
                        logger.warn("Bad API request for '{}' with params {}: {}", req.getURI(), req.proxiedRequest().params(), ex.getMessage());
615
                        return Future.succeededFuture(context.request()
616
                                .response()
617
                                .setStatusCode(400)
618
                                .putHeader("Content-Type", "text/plain")
619
                                .setBody(Body.body(Buffer.buffer("Bad request: " + ex.getMessage()))));
620
                    } catch (Exception ex) {
621
                        logger.error("Unexpected error for API request '{}' with params {}", req.getURI(), req.proxiedRequest().params(), ex);
622
                        return Future.succeededFuture(context.request()
623
                                .response()
624
                                .setStatusCode(500)
625
                                .putHeader("Content-Type", "text/plain")
626
                                .setBody(Body.body(Buffer.buffer("Unexpected error: " + ex.getMessage()))));
627
                    }
628
                }
629
                return ProxyInterceptor.super.handleProxyRequest(context);
630
            }
631

632
            @Override
633
            @GeneratedFlagForDependentElements
634
            public Future<Void> handleProxyResponse(ProxyContext context) {
635
                String queryPath = context.get("queryPath", String.class);
636
                if (queryPath != null) {
637
                    Long start = context.get("queryStart", Long.class);
638
                    long durationMs = start != null ? System.currentTimeMillis() - start : -1;
639
                    int statusCode = context.response().getStatusCode();
640
                    String queryParams = context.get("queryParams", String.class);
641
                    logger.info("Query stats: path={} status={} durationMs={} params={}", queryPath, statusCode, durationMs, queryParams != null ? queryParams : "");
642
                }
643
                ProxyResponse resp = context.response();
644
                resp.putHeader("Access-Control-Allow-Origin", "*");
645
                resp.putHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS");
646
                resp.putHeader("Content-Disposition", "inline");
647
                return ProxyInterceptor.super.handleProxyResponse(context);
648
            }
649

650
        });
651
        proxyRouter.route(HttpMethod.GET, "/api/*").handler(ProxyHandler.create(grlcxProxy));
652

653
        // Handle HEAD requests for all paths not already covered (e.g. /repo/* has its own HEAD handler).
654
        // Global headers are applied before routing, so we just end the response with no body.
655
        proxyRouter.route(HttpMethod.HEAD, "/*").handler(req -> {
656
            req.response().setStatusCode(200).end();
657
        });
658

659
        proxyServer.requestHandler(req -> {
660
            applyGlobalHeaders(req.response());
661
            proxyRouter.handle(req);
662
        });
663
        Future<HttpServer> proxyListening = proxyServer.listen(9393);
664

665
        // Periodic metrics update. Runs on a dedicated single-thread scheduled executor
666
        // (not on the Vert.x event loop) because `updateMetrics` can fall through to a
667
        // synchronous HTTP call in `TripleStore.getRepositoryNames()` when the cache has
668
        // been invalidated. `scheduleWithFixedDelay` naturally serialises ticks and cannot
669
        // pile up if the work occasionally runs long. Same pattern as `JellyNanopubLoader.loadUpdates`
670
        // below.
671
        ScheduledExecutorService metricsExecutor = Executors.newSingleThreadScheduledExecutor();
672
        metricsExecutor.scheduleWithFixedDelay(collector::updateMetrics, 1, 1, TimeUnit.SECONDS);
673
        schedulers.add(metricsExecutor);
674

675

676
        new Thread(() -> {
677
            try {
678
                var status = StatusController.get().initialize();
679
                logger.info("Current state: {}, last committed counter: {}", status.state, status.loadCounter);
680
                // Restore or fetch the registry setup ID
681
                Long storedSetupId = StatusController.get().getRegistrySetupId();
682
                if (storedSetupId != null) {
683
                    JellyNanopubLoader.setLastKnownSetupId(storedSetupId);
684
                    logger.info("Restored registry setupId: {}", storedSetupId);
685
                } else if (status.state == StatusController.State.LAUNCHING
686
                        || status.state == StatusController.State.LOADING_INITIAL) {
687
                    // Fresh start or crashed during initial load – safe to adopt the current setupId
688
                    try {
689
                        var metadata = JellyNanopubLoader.fetchRegistryMetadata();
690
                        JellyNanopubLoader.setLastKnownSetupId(metadata.setupId());
691
                        if (metadata.setupId() != null) {
692
                            StatusController.get().setRegistrySetupId(metadata.setupId());
693
                            logger.info("Fetched initial registry setupId: {}", metadata.setupId());
694
                        }
695
                    } catch (Exception e) {
696
                        logger.warn("Could not fetch initial registry setupId", e);
697
                    }
698
                } else {
699
                    // Upgrade from a version without setupId tracking. The DB has data but
700
                    // we can't verify it matches the current registry state. Leave lastKnownSetupId
701
                    // as null so that loadUpdates() will trigger a resync.
702
                    logger.warn("No stored registry setupId but DB has data (state: {}, counter: {}). "
703
                            + "A resync will be triggered on the first update poll.",
704
                            status.state, status.loadCounter);
705
                }
706
                boolean forceResync = "true".equalsIgnoreCase(
707
                        Utils.getEnvString("FORCE_RESYNC", "false"));
708
                if (forceResync && status.state != StatusController.State.LAUNCHING) {
709
                    logger.warn("FORCE_RESYNC is set. Forcing full re-load from registry.");
710
                    var metadata = JellyNanopubLoader.fetchRegistryMetadata();
711
                    JellyNanopubLoader.setLastKnownSetupId(metadata.setupId());
712
                    if (metadata.setupId() != null) {
713
                        StatusController.get().setRegistrySetupId(metadata.setupId());
714
                    }
715
                    StatusController.get().setResetting();
716
                    StatusController.get().setLoadingInitial(-1);
717
                    JellyNanopubLoader.loadInitial(-1);
718
                    StatusController.get().setReady();
719
                } else if (status.state == StatusController.State.LAUNCHING || status.state == StatusController.State.LOADING_INITIAL) {
720
                    // Do the initial nanopublication loading
721
                    StatusController.get().setLoadingInitial(status.loadCounter);
722
                    // Fall back to local nanopub loading if the local files are present
723
                    if (!LocalNanopubLoader.init()) {
724
                        JellyNanopubLoader.loadInitial(status.loadCounter);
725
                    } else {
726
                        logger.info("Local nanopublication loading finished");
727
                    }
728
                    StatusController.get().setReady();
729
                } else {
730
                    logger.info("Initial load is already done");
731
                    StatusController.get().setReady();
732
                }
733
            } catch (Exception ex) {
734
                logger.info("Initial load failed, terminating...", ex);
735
                Runtime.getRuntime().exit(1);
736
            }
737

738
            // Seed the TrustStateRegistry from any persisted pointer before the
739
            // periodic poll begins, so the first tick doesn't re-materialize state
740
            // we already have.
741
            TrustStateLoader.bootstrap();
742

743
            // Drop any npass:* graph that isn't the current-pointer target —
744
            // leftovers from builds interrupted by a crash.
745
            if (FeatureFlags.spacesEnabled()) {
746
                AuthorityResolver.get().cleanOrphans();
747
            }
748

749
            // Start periodic nanopub loading
750
            logger.info("Starting periodic nanopub loading...");
751
            var executor = Executors.newSingleThreadScheduledExecutor();
752
            schedulers.add(executor);
753
            executor.scheduleWithFixedDelay(
754
                    JellyNanopubLoader::loadUpdates,
755
                    JellyNanopubLoader.UPDATES_POLL_INTERVAL,
756
                    JellyNanopubLoader.UPDATES_POLL_INTERVAL,
757
                    TimeUnit.MILLISECONDS
758
            );
759

760
            // Periodic shard-consistency sweep (issue #139): verifies that recently
761
            // loaded nanopubs actually landed in every shard repo their metadata
762
            // implies, and re-loads any that are missing. Own single-threaded
763
            // executor; scheduleWithFixedDelay serialises ticks. The tick itself
764
            // no-ops unless the reconciliation flag is on and the state is READY.
765
            // 5-minute cadence: completed loads (meta stamp present) are verified
766
            // on the first tick after they land, so this interval — not a grace
767
            // window — is the repair latency for a dropped shard, and the damage
768
            // window of a missing shard is exactly the post-publish minutes when
769
            // its author is actively using it. An idle tick is one bounded query.
770
            ScheduledExecutorService reconcilerExecutor = Executors.newSingleThreadScheduledExecutor();
771
            schedulers.add(reconcilerExecutor);
772
            reconcilerExecutor.scheduleWithFixedDelay(
773
                    () -> {
774
                        try {
775
                            ShardReconciler.tick();
776
                        } catch (Exception ex) {
777
                            logger.warn("Shard reconciliation tick failed", ex);
778
                        }
779
                    },
780
                    5, 5, TimeUnit.MINUTES
781
            );
782

783
            // Periodic authority-resolver tick: detects trust-state flips and
784
            // advances the current space-state graph by an incremental cycle on
785
            // each load-number delta. Same cadence as the nanopub-loading poll.
786
            //
787
            // The same single-threaded executor also runs periodicRebuildTick
788
            // every 10 min; that's the from-scratch rebuild triggered when an
789
            // incremental cycle DELETEs a structural derivation and raises the
790
            // npa:needsFullRebuild flag. Sharing one executor serialises the
791
            // two ticks naturally — they never overlap.
792
            if (FeatureFlags.spacesEnabled()) {
793
                var spacesExecutor = Executors.newSingleThreadScheduledExecutor();
794
                schedulers.add(spacesExecutor);
795
                spacesExecutor.scheduleWithFixedDelay(
796
                        () -> {
797
                            try {
798
                                AuthorityResolver.get().tick();
799
                            } catch (Exception ex) {
800
                                logger.warn("AuthorityResolver tick failed", ex);
801
                            }
802
                        },
803
                        JellyNanopubLoader.UPDATES_POLL_INTERVAL,
804
                        JellyNanopubLoader.UPDATES_POLL_INTERVAL,
805
                        TimeUnit.MILLISECONDS
806
                );
807
                spacesExecutor.scheduleWithFixedDelay(
808
                        () -> {
809
                            try {
810
                                AuthorityResolver.get().periodicRebuildTick();
811
                            } catch (Exception ex) {
812
                                logger.warn("AuthorityResolver periodic rebuild failed", ex);
813
                            }
814
                        },
815
                        10, 10, TimeUnit.MINUTES
816
                );
817
            }
818
        }).start();
819

820
        vertxRef = vertx;
821
        Runtime.getRuntime().addShutdownHook(new Thread(MainVerticle::shutdownGracefully));
822
        completeWhenListening(startPromise, metricsListening, proxyListening);
823
    }
824

825
    /**
826
     * Completes the start promise once all given servers listen, and fails it if one of them
827
     * cannot. Vert.x 5's launcher waits for the deployment to complete and stops the application
828
     * when it times out, so a promise that is never completed restarts the app every two minutes.
829
     *
830
     * @param startPromise the verticle's start promise
831
     * @param listening    the futures returned by {@code HttpServer.listen}
832
     */
833
    static void completeWhenListening(Promise<Void> startPromise, Future<?>... listening) {
834
        Future.all(List.of(listening)).onComplete(ar -> {
835
            if (ar.succeeded()) {
836
                startPromise.complete();
837
            } else {
838
                startPromise.fail(ar.cause());
839
            }
840
        });
841
    }
842

843
    /**
844
     * Releases an admitted /api request once its response has ended or its connection has
845
     * closed, whichever comes first. A closed connection counts as not completed: the client
846
     * (typically the edge, after 10 s) gave up, and RDF4J may still be evaluating the query.
847
     *
848
     * @param response the client-facing response
849
     * @param admitted the guard's admission for the request
850
     */
851
    void releaseWhenDone(HttpServerResponse response, ApiQueryGuard.Admitted admitted) {
852
        AtomicBoolean released = new AtomicBoolean(false);
853
        response.endHandler(v -> {
854
            if (released.compareAndSet(false, true)) {
855
                apiQueryGuard.release(admitted, response.getStatusCode() < 500, System.currentTimeMillis());
856
            }
857
        });
858
        response.closeHandler(v -> {
859
            if (released.compareAndSet(false, true)) {
860
                apiQueryGuard.release(admitted, false, System.currentTimeMillis());
861
            }
862
        });
863
    }
864

865
    private String getResourceAsString(String file) {
866
        InputStream is = getClass().getClassLoader().getResourceAsStream("com/knowledgepixels/query/" + file);
867
        try (Scanner s = new Scanner(is).useDelimiter("\\A")) {
868
            String fileContent = s.hasNext() ? s.next() : "";
869
            return fileContent;
870
        }
871
    }
872

873
    private static void handleRedirect(RoutingContext req, String path) {
874
        String queryString = "";
875
        if (!req.queryParam("query").isEmpty())
876
            queryString = "?query=" + URLEncoder.encode(req.queryParam("query").getFirst(), Charsets.UTF_8);
877
        if (req.queryParam("for-type").size() == 1) {
878
            String type = req.queryParam("for-type").getFirst();
879
            req.response().putHeader("location", path + "/type/" + Utils.createHash(type) + queryString);
880
            req.response().setStatusCode(301).end();
881
        } else if (req.queryParam("for-pubkey").size() == 1) {
882
            String type = req.queryParam("for-pubkey").getFirst();
883
            req.response().putHeader("location", path + "/pubkey/" + Utils.createHash(type) + queryString);
884
            req.response().setStatusCode(301).end();
885
        } else if (req.queryParam("for-user").size() == 1) {
886
            String type = req.queryParam("for-user").getFirst();
887
            req.response().putHeader("location", path + "/user/" + Utils.createHash(type) + queryString);
888
            req.response().setStatusCode(301).end();
889
        }
890
    }
891

892
    /**
893
     * Apply headers to the response that should be present for all requests.
894
     *
895
     * @param response The response to which the headers should be applied.
896
     */
897
    static void applyGlobalHeaders(HttpServerResponse response) {
898
        var state = StatusController.get().getState();
899
        response.putHeader("Nanopub-Query-Version", Utils.getVersion());
900
        response.putHeader("Nanopub-Query-Status", state.state.toString());
901
        response.putHeader("Nanopub-Query-Registry-Url", JellyNanopubLoader.registryUrl);
902
        Long setupId = StatusController.get().getRegistrySetupId();
903
        response.putHeader("Nanopub-Query-Registry-Setup-Id", setupId == null ? "" : setupId.toString());
904
        response.putHeader("Nanopub-Query-Load-Counter", String.valueOf(state.loadCounter));
905
        // Advertised only when set, so consumers can tell that this instance loads
906
        // npx:ProtectedNanopub nanopubs and must not be treated as a public source.
907
        if (FeatureFlags.localInstance()) {
908
            response.putHeader("Nanopub-Query-Local-Instance", "true");
909
        }
910
        // Likewise advertised only when set. Says something about this instance, not
911
        // about its registry: a staging instance that mirrors production data does so
912
        // from a production registry, so this is the only way it can be told apart
913
        // from the instances it mirrors (issue #200). Not to be confused with
914
        // Nanopub-Query-Registry-Test-Instance below, which forwards what the
915
        // attached registry reports about itself.
916
        if (FeatureFlags.testInstance()) {
917
            response.putHeader("Nanopub-Query-Test-Instance", "true");
918
        }
919
        // Forward registry metadata headers
920
        String coverageTypes = JellyNanopubLoader.lastCoverageTypes;
921
        response.putHeader("Nanopub-Query-Registry-Coverage-Types", coverageTypes != null ? coverageTypes : "all");
922
        String coverageAgents = JellyNanopubLoader.lastCoverageAgents;
923
        response.putHeader("Nanopub-Query-Registry-Coverage-Agents", coverageAgents != null ? coverageAgents : "viaSetting");
924
        String testInstance = JellyNanopubLoader.lastTestInstance;
925
        if (testInstance != null) {
926
            response.putHeader("Nanopub-Query-Registry-Test-Instance", testInstance);
927
        }
928
        String nanopubCount = JellyNanopubLoader.lastNanopubCount;
929
        if (nanopubCount != null) {
930
            response.putHeader("Nanopub-Query-Registry-Nanopub-Count", nanopubCount);
931
        }
932
        // Cached reads only. This method runs on the Vert.x event loop for every
933
        // inbound request, and the non-cached accessors fall back to a blocking store
934
        // read whenever the cache is cold — which it is after every restart. That
935
        // stalled the event loop on 2026-07-31 (BlockedThreadChecker fired five times
936
        // right after the 1.24.0 rollout), and with the store unreachable it would
937
        // block every request for the full 10 s connect timeout, taking the HTTP layer
938
        // down with RDF4J. NanopubLoader.primeHeaderCaches() keeps these warm from the
939
        // metrics tick; until it has run, the headers are simply omitted, exactly as
940
        // they already are before the first load.
941
        Long loadedCount = NanopubLoader.getCachedLoadedNanopubCount();
942
        if (loadedCount != null) {
943
            response.putHeader("Nanopub-Query-Loaded-Nanopub-Count", loadedCount.toString());
944
        }
945
        String loadedChecksum = NanopubLoader.getCachedLoadedNanopubChecksum();
946
        if (loadedChecksum != null) {
947
            response.putHeader("Nanopub-Query-Loaded-Nanopub-Checksum", loadedChecksum);
948
        }
949
        // Loader liveness over HTTP. The same value backs
950
        // registry.loader.last_successful_batch_age_seconds, but the metrics port is
951
        // bound to loopback, so anything off-host — nanopub-monitor in particular —
952
        // cannot read it. Without this, a stalled instance looks identical to a healthy
953
        // one from outside: it keeps answering queries and keeps reporting READY, which
954
        // is how the 2026-07-31 stall stayed invisible for hours.
955
        //
956
        // Omitted rather than sent as 0 before the first tick completes, so consumers can
957
        // tell "not started yet" from "just ticked".
958
        //
959
        // The value is only stamped after RDF4J has actually answered (see
960
        // JellyNanopubLoader#lastSuccessfulBatchAtMs), so on a caught-up instance it
961
        // cycles 0..JellyNanopubLoader.STORE_PROBE_INTERVAL_MS rather than sitting at 0.
962
        // Alert thresholds must therefore exceed that interval; minutes, not seconds.
963
        //
964
        // Initial loads and resyncs stamp it as well, so this reads as "seconds since
965
        // the loader last moved" in every state rather than only while polling for
966
        // updates. Interpret it alongside Nanopub-Query-Status: a climbing age under
967
        // LOADING_INITIAL is a resync that has stopped progressing, not a long one.
968
        long lastBatchAt = JellyNanopubLoader.lastSuccessfulBatchAtMs;
969
        if (lastBatchAt != 0L) {
970
            long ageSeconds = Math.max(0L, (System.currentTimeMillis() - lastBatchAt) / 1000L);
971
            response.putHeader("Nanopub-Query-Loader-Last-Success-Age-Seconds", String.valueOf(ageSeconds));
972
        }
973
    }
974
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc