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

knowledgepixels / nanopub-query / 40339307016

26 Oct 2026 02:24PM UTC coverage: 77.671% (+0.01%) from 77.661%
40339307016

push

github

web-flow
Merge pull request #229 from knowledgepixels/feat/declare-test-instance

feat: allow a query instance to declare itself a test instance

942 of 1360 branches covered (69.26%)

Branch coverage included in aggregate %.

2693 of 3320 relevant lines covered (81.11%)

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

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

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

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

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

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

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

247
        rdf4jProxy.addInterceptor(new ProxyInterceptor() {
×
248

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

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

278
        });
279
        // ----------
280

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

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

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

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

551
        HttpProxy grlcxProxy = HttpProxy.reverseProxy(httpClient);
552
        grlcxProxy.origin(proxyPort, proxy);
553

554
        grlcxProxy.addInterceptor(new ProxyInterceptor() {
×
555

556
            @Override
557
            @GeneratedFlagForDependentElements
558
            public Future<ProxyResponse> handleProxyRequest(ProxyContext context) {
559
                final ProxyRequest req = context.request();
560
                final String apiPattern = "^/api/(RA[a-zA-Z0-9-_]{43})/([a-zA-Z0-9-_]+)([.]csv|[.]json|[.]srx)?([?].*)?$";
561
                if (req.getURI().matches(apiPattern)) {
562
                    try {
563
                        req.setMethod(HttpMethod.POST);
564
                        if (req.getURI().matches(".*[.]csv([?].*)?$")) {
565
                            req.putHeader("Accept", "text/csv");
566
                            req.setURI(req.getURI().replaceFirst("[.]csv([?].*)?$", "$1"));
567
                        } else if (req.getURI().matches(".*[.]json([?].*)?$")) {
568
                            req.putHeader("Accept", "application/json");
569
                            req.setURI(req.getURI().replaceFirst("[.]json([?].*)?$", "$1"));
570
                        } else if (req.getURI().matches(".*[.]srx([?].*)?$")) {
571
                            req.putHeader("Accept", "application/xml");
572
                            req.setURI(req.getURI().replaceFirst("[.]srx([?].*)?$", "$1"));
573
                        }
574
                        GrlcSpec grlcSpec = new GrlcSpec(req.getURI(), req.proxiedRequest().params());
575

576
                        // Variant 1:
577
                        req.putHeader("Content-Type", "application/sparql-query");
578
                        req.setBody(Body.body(Buffer.buffer(grlcSpec.expandQuery())));
579
                        // Variant 2:
580
                        //req.putHeader("Content-Type", "application/x-www-form-urlencoded");
581
                        //req.setBody(Body.body(Buffer.buffer("query=" + URLEncoder.encode(grlcSpec.getExpandedQueryContent(), Charsets.UTF_8))));
582

583
                        req.setURI(Utils.appendQueryTimeout(
584
                                "/rdf4j-server/repositories/" + grlcSpec.getRepoName(), queryTimeoutSeconds));
585
                        logger.info("Forwarding apix request to /rdf4j-server/repositories/{}", grlcSpec.getRepoName());
586
                        context.set("queryPath", req.getURI().replaceFirst("[?].*$", "").replaceFirst("^/api/", ""));
587
                        context.set("queryStart", System.currentTimeMillis());
588
                    } catch (InvalidGrlcSpecException ex) {
589
                        logger.warn("Bad API request for '{}' with params {}: {}", req.getURI(), req.proxiedRequest().params(), ex.getMessage());
590
                        return Future.succeededFuture(context.request()
591
                                .response()
592
                                .setStatusCode(400)
593
                                .putHeader("Content-Type", "text/plain")
594
                                .setBody(Body.body(Buffer.buffer("Bad request: " + ex.getMessage()))));
595
                    } catch (Exception ex) {
596
                        logger.error("Unexpected error for API request '{}' with params {}", req.getURI(), req.proxiedRequest().params(), ex);
597
                        return Future.succeededFuture(context.request()
598
                                .response()
599
                                .setStatusCode(500)
600
                                .putHeader("Content-Type", "text/plain")
601
                                .setBody(Body.body(Buffer.buffer("Unexpected error: " + ex.getMessage()))));
602
                    }
603
                }
604
                return ProxyInterceptor.super.handleProxyRequest(context);
605
            }
606

607
            @Override
608
            @GeneratedFlagForDependentElements
609
            public Future<Void> handleProxyResponse(ProxyContext context) {
610
                String queryPath = context.get("queryPath", String.class);
611
                if (queryPath != null) {
612
                    Long start = context.get("queryStart", Long.class);
613
                    long durationMs = start != null ? System.currentTimeMillis() - start : -1;
614
                    int statusCode = context.response().getStatusCode();
615
                    logger.info("Query stats: path={} status={} durationMs={}", queryPath, statusCode, durationMs);
616
                }
617
                ProxyResponse resp = context.response();
618
                resp.putHeader("Access-Control-Allow-Origin", "*");
619
                resp.putHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS");
620
                resp.putHeader("Content-Disposition", "inline");
621
                return ProxyInterceptor.super.handleProxyResponse(context);
622
            }
623

624
        });
625
        proxyRouter.route(HttpMethod.GET, "/api/*").handler(ProxyHandler.create(grlcxProxy));
626

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

633
        proxyServer.requestHandler(req -> {
634
            applyGlobalHeaders(req.response());
635
            proxyRouter.handle(req);
636
        });
637
        Future<HttpServer> proxyListening = proxyServer.listen(9393);
638

639
        // Periodic metrics update. Runs on a dedicated single-thread scheduled executor
640
        // (not on the Vert.x event loop) because `updateMetrics` can fall through to a
641
        // synchronous HTTP call in `TripleStore.getRepositoryNames()` when the cache has
642
        // been invalidated. `scheduleWithFixedDelay` naturally serialises ticks and cannot
643
        // pile up if the work occasionally runs long. Same pattern as `JellyNanopubLoader.loadUpdates`
644
        // below.
645
        ScheduledExecutorService metricsExecutor = Executors.newSingleThreadScheduledExecutor();
646
        metricsExecutor.scheduleWithFixedDelay(collector::updateMetrics, 1, 1, TimeUnit.SECONDS);
647
        schedulers.add(metricsExecutor);
648

649

650
        new Thread(() -> {
651
            try {
652
                var status = StatusController.get().initialize();
653
                logger.info("Current state: {}, last committed counter: {}", status.state, status.loadCounter);
654
                // Restore or fetch the registry setup ID
655
                Long storedSetupId = StatusController.get().getRegistrySetupId();
656
                if (storedSetupId != null) {
657
                    JellyNanopubLoader.setLastKnownSetupId(storedSetupId);
658
                    logger.info("Restored registry setupId: {}", storedSetupId);
659
                } else if (status.state == StatusController.State.LAUNCHING
660
                        || status.state == StatusController.State.LOADING_INITIAL) {
661
                    // Fresh start or crashed during initial load – safe to adopt the current setupId
662
                    try {
663
                        var metadata = JellyNanopubLoader.fetchRegistryMetadata();
664
                        JellyNanopubLoader.setLastKnownSetupId(metadata.setupId());
665
                        if (metadata.setupId() != null) {
666
                            StatusController.get().setRegistrySetupId(metadata.setupId());
667
                            logger.info("Fetched initial registry setupId: {}", metadata.setupId());
668
                        }
669
                    } catch (Exception e) {
670
                        logger.warn("Could not fetch initial registry setupId", e);
671
                    }
672
                } else {
673
                    // Upgrade from a version without setupId tracking. The DB has data but
674
                    // we can't verify it matches the current registry state. Leave lastKnownSetupId
675
                    // as null so that loadUpdates() will trigger a resync.
676
                    logger.warn("No stored registry setupId but DB has data (state: {}, counter: {}). "
677
                            + "A resync will be triggered on the first update poll.",
678
                            status.state, status.loadCounter);
679
                }
680
                boolean forceResync = "true".equalsIgnoreCase(
681
                        Utils.getEnvString("FORCE_RESYNC", "false"));
682
                if (forceResync && status.state != StatusController.State.LAUNCHING) {
683
                    logger.warn("FORCE_RESYNC is set. Forcing full re-load from registry.");
684
                    var metadata = JellyNanopubLoader.fetchRegistryMetadata();
685
                    JellyNanopubLoader.setLastKnownSetupId(metadata.setupId());
686
                    if (metadata.setupId() != null) {
687
                        StatusController.get().setRegistrySetupId(metadata.setupId());
688
                    }
689
                    StatusController.get().setResetting();
690
                    StatusController.get().setLoadingInitial(-1);
691
                    JellyNanopubLoader.loadInitial(-1);
692
                    StatusController.get().setReady();
693
                } else if (status.state == StatusController.State.LAUNCHING || status.state == StatusController.State.LOADING_INITIAL) {
694
                    // Do the initial nanopublication loading
695
                    StatusController.get().setLoadingInitial(status.loadCounter);
696
                    // Fall back to local nanopub loading if the local files are present
697
                    if (!LocalNanopubLoader.init()) {
698
                        JellyNanopubLoader.loadInitial(status.loadCounter);
699
                    } else {
700
                        logger.info("Local nanopublication loading finished");
701
                    }
702
                    StatusController.get().setReady();
703
                } else {
704
                    logger.info("Initial load is already done");
705
                    StatusController.get().setReady();
706
                }
707
            } catch (Exception ex) {
708
                logger.info("Initial load failed, terminating...", ex);
709
                Runtime.getRuntime().exit(1);
710
            }
711

712
            // Seed the TrustStateRegistry from any persisted pointer before the
713
            // periodic poll begins, so the first tick doesn't re-materialize state
714
            // we already have.
715
            TrustStateLoader.bootstrap();
716

717
            // Drop any npass:* graph that isn't the current-pointer target —
718
            // leftovers from builds interrupted by a crash.
719
            if (FeatureFlags.spacesEnabled()) {
720
                AuthorityResolver.get().cleanOrphans();
721
            }
722

723
            // Start periodic nanopub loading
724
            logger.info("Starting periodic nanopub loading...");
725
            var executor = Executors.newSingleThreadScheduledExecutor();
726
            schedulers.add(executor);
727
            executor.scheduleWithFixedDelay(
728
                    JellyNanopubLoader::loadUpdates,
729
                    JellyNanopubLoader.UPDATES_POLL_INTERVAL,
730
                    JellyNanopubLoader.UPDATES_POLL_INTERVAL,
731
                    TimeUnit.MILLISECONDS
732
            );
733

734
            // Periodic shard-consistency sweep (issue #139): verifies that recently
735
            // loaded nanopubs actually landed in every shard repo their metadata
736
            // implies, and re-loads any that are missing. Own single-threaded
737
            // executor; scheduleWithFixedDelay serialises ticks. The tick itself
738
            // no-ops unless the reconciliation flag is on and the state is READY.
739
            // 5-minute cadence: completed loads (meta stamp present) are verified
740
            // on the first tick after they land, so this interval — not a grace
741
            // window — is the repair latency for a dropped shard, and the damage
742
            // window of a missing shard is exactly the post-publish minutes when
743
            // its author is actively using it. An idle tick is one bounded query.
744
            ScheduledExecutorService reconcilerExecutor = Executors.newSingleThreadScheduledExecutor();
745
            schedulers.add(reconcilerExecutor);
746
            reconcilerExecutor.scheduleWithFixedDelay(
747
                    () -> {
748
                        try {
749
                            ShardReconciler.tick();
750
                        } catch (Exception ex) {
751
                            logger.warn("Shard reconciliation tick failed", ex);
752
                        }
753
                    },
754
                    5, 5, TimeUnit.MINUTES
755
            );
756

757
            // Periodic authority-resolver tick: detects trust-state flips and
758
            // advances the current space-state graph by an incremental cycle on
759
            // each load-number delta. Same cadence as the nanopub-loading poll.
760
            //
761
            // The same single-threaded executor also runs periodicRebuildTick
762
            // every 10 min; that's the from-scratch rebuild triggered when an
763
            // incremental cycle DELETEs a structural derivation and raises the
764
            // npa:needsFullRebuild flag. Sharing one executor serialises the
765
            // two ticks naturally — they never overlap.
766
            if (FeatureFlags.spacesEnabled()) {
767
                var spacesExecutor = Executors.newSingleThreadScheduledExecutor();
768
                schedulers.add(spacesExecutor);
769
                spacesExecutor.scheduleWithFixedDelay(
770
                        () -> {
771
                            try {
772
                                AuthorityResolver.get().tick();
773
                            } catch (Exception ex) {
774
                                logger.warn("AuthorityResolver tick failed", ex);
775
                            }
776
                        },
777
                        JellyNanopubLoader.UPDATES_POLL_INTERVAL,
778
                        JellyNanopubLoader.UPDATES_POLL_INTERVAL,
779
                        TimeUnit.MILLISECONDS
780
                );
781
                spacesExecutor.scheduleWithFixedDelay(
782
                        () -> {
783
                            try {
784
                                AuthorityResolver.get().periodicRebuildTick();
785
                            } catch (Exception ex) {
786
                                logger.warn("AuthorityResolver periodic rebuild failed", ex);
787
                            }
788
                        },
789
                        10, 10, TimeUnit.MINUTES
790
                );
791
            }
792
        }).start();
793

794
        vertxRef = vertx;
795
        Runtime.getRuntime().addShutdownHook(new Thread(MainVerticle::shutdownGracefully));
796
        completeWhenListening(startPromise, metricsListening, proxyListening);
797
    }
798

799
    /**
800
     * Completes the start promise once all given servers listen, and fails it if one of them
801
     * cannot. Vert.x 5's launcher waits for the deployment to complete and stops the application
802
     * when it times out, so a promise that is never completed restarts the app every two minutes.
803
     *
804
     * @param startPromise the verticle's start promise
805
     * @param listening    the futures returned by {@code HttpServer.listen}
806
     */
807
    static void completeWhenListening(Promise<Void> startPromise, Future<?>... listening) {
808
        Future.all(List.of(listening)).onComplete(ar -> {
809
            if (ar.succeeded()) {
810
                startPromise.complete();
811
            } else {
812
                startPromise.fail(ar.cause());
813
            }
814
        });
815
    }
816

817
    private String getResourceAsString(String file) {
818
        InputStream is = getClass().getClassLoader().getResourceAsStream("com/knowledgepixels/query/" + file);
819
        try (Scanner s = new Scanner(is).useDelimiter("\\A")) {
820
            String fileContent = s.hasNext() ? s.next() : "";
821
            return fileContent;
822
        }
823
    }
824

825
    private static void handleRedirect(RoutingContext req, String path) {
826
        String queryString = "";
827
        if (!req.queryParam("query").isEmpty())
828
            queryString = "?query=" + URLEncoder.encode(req.queryParam("query").getFirst(), Charsets.UTF_8);
829
        if (req.queryParam("for-type").size() == 1) {
830
            String type = req.queryParam("for-type").getFirst();
831
            req.response().putHeader("location", path + "/type/" + Utils.createHash(type) + queryString);
832
            req.response().setStatusCode(301).end();
833
        } else if (req.queryParam("for-pubkey").size() == 1) {
834
            String type = req.queryParam("for-pubkey").getFirst();
835
            req.response().putHeader("location", path + "/pubkey/" + Utils.createHash(type) + queryString);
836
            req.response().setStatusCode(301).end();
837
        } else if (req.queryParam("for-user").size() == 1) {
838
            String type = req.queryParam("for-user").getFirst();
839
            req.response().putHeader("location", path + "/user/" + Utils.createHash(type) + queryString);
840
            req.response().setStatusCode(301).end();
841
        }
842
    }
843

844
    /**
845
     * Apply headers to the response that should be present for all requests.
846
     *
847
     * @param response The response to which the headers should be applied.
848
     */
849
    static void applyGlobalHeaders(HttpServerResponse response) {
850
        var state = StatusController.get().getState();
851
        response.putHeader("Nanopub-Query-Version", Utils.getVersion());
852
        response.putHeader("Nanopub-Query-Status", state.state.toString());
853
        response.putHeader("Nanopub-Query-Registry-Url", JellyNanopubLoader.registryUrl);
854
        Long setupId = StatusController.get().getRegistrySetupId();
855
        response.putHeader("Nanopub-Query-Registry-Setup-Id", setupId == null ? "" : setupId.toString());
856
        response.putHeader("Nanopub-Query-Load-Counter", String.valueOf(state.loadCounter));
857
        // Advertised only when set, so consumers can tell that this instance loads
858
        // npx:ProtectedNanopub nanopubs and must not be treated as a public source.
859
        if (FeatureFlags.localInstance()) {
860
            response.putHeader("Nanopub-Query-Local-Instance", "true");
861
        }
862
        // Likewise advertised only when set. Says something about this instance, not
863
        // about its registry: a staging instance that mirrors production data does so
864
        // from a production registry, so this is the only way it can be told apart
865
        // from the instances it mirrors (issue #200). Not to be confused with
866
        // Nanopub-Query-Registry-Test-Instance below, which forwards what the
867
        // attached registry reports about itself.
868
        if (FeatureFlags.testInstance()) {
869
            response.putHeader("Nanopub-Query-Test-Instance", "true");
870
        }
871
        // Forward registry metadata headers
872
        String coverageTypes = JellyNanopubLoader.lastCoverageTypes;
873
        response.putHeader("Nanopub-Query-Registry-Coverage-Types", coverageTypes != null ? coverageTypes : "all");
874
        String coverageAgents = JellyNanopubLoader.lastCoverageAgents;
875
        response.putHeader("Nanopub-Query-Registry-Coverage-Agents", coverageAgents != null ? coverageAgents : "viaSetting");
876
        String testInstance = JellyNanopubLoader.lastTestInstance;
877
        if (testInstance != null) {
878
            response.putHeader("Nanopub-Query-Registry-Test-Instance", testInstance);
879
        }
880
        String nanopubCount = JellyNanopubLoader.lastNanopubCount;
881
        if (nanopubCount != null) {
882
            response.putHeader("Nanopub-Query-Registry-Nanopub-Count", nanopubCount);
883
        }
884
        // Cached reads only. This method runs on the Vert.x event loop for every
885
        // inbound request, and the non-cached accessors fall back to a blocking store
886
        // read whenever the cache is cold — which it is after every restart. That
887
        // stalled the event loop on 2026-07-31 (BlockedThreadChecker fired five times
888
        // right after the 1.24.0 rollout), and with the store unreachable it would
889
        // block every request for the full 10 s connect timeout, taking the HTTP layer
890
        // down with RDF4J. NanopubLoader.primeHeaderCaches() keeps these warm from the
891
        // metrics tick; until it has run, the headers are simply omitted, exactly as
892
        // they already are before the first load.
893
        Long loadedCount = NanopubLoader.getCachedLoadedNanopubCount();
894
        if (loadedCount != null) {
895
            response.putHeader("Nanopub-Query-Loaded-Nanopub-Count", loadedCount.toString());
896
        }
897
        String loadedChecksum = NanopubLoader.getCachedLoadedNanopubChecksum();
898
        if (loadedChecksum != null) {
899
            response.putHeader("Nanopub-Query-Loaded-Nanopub-Checksum", loadedChecksum);
900
        }
901
        // Loader liveness over HTTP. The same value backs
902
        // registry.loader.last_successful_batch_age_seconds, but the metrics port is
903
        // bound to loopback, so anything off-host — nanopub-monitor in particular —
904
        // cannot read it. Without this, a stalled instance looks identical to a healthy
905
        // one from outside: it keeps answering queries and keeps reporting READY, which
906
        // is how the 2026-07-31 stall stayed invisible for hours.
907
        //
908
        // Omitted rather than sent as 0 before the first tick completes, so consumers can
909
        // tell "not started yet" from "just ticked".
910
        //
911
        // The value is only stamped after RDF4J has actually answered (see
912
        // JellyNanopubLoader#lastSuccessfulBatchAtMs), so on a caught-up instance it
913
        // cycles 0..JellyNanopubLoader.STORE_PROBE_INTERVAL_MS rather than sitting at 0.
914
        // Alert thresholds must therefore exceed that interval; minutes, not seconds.
915
        //
916
        // Initial loads and resyncs stamp it as well, so this reads as "seconds since
917
        // the loader last moved" in every state rather than only while polling for
918
        // updates. Interpret it alongside Nanopub-Query-Status: a climbing age under
919
        // LOADING_INITIAL is a resync that has stopped progressing, not a long one.
920
        long lastBatchAt = JellyNanopubLoader.lastSuccessfulBatchAtMs;
921
        if (lastBatchAt != 0L) {
922
            long ageSeconds = Math.max(0L, (System.currentTimeMillis() - lastBatchAt) / 1000L);
923
            response.putHeader("Nanopub-Query-Loader-Last-Success-Age-Seconds", String.valueOf(ageSeconds));
924
        }
925
    }
926
}
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