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

knowledgepixels / nanopub-query / 40339179938

26 Oct 2026 02:23PM UTC coverage: 77.661% (+0.02%) from 77.642%
40339179938

push

github

web-flow
Merge pull request #197 from knowledgepixels/feat/sib-sparql-editor

feat(tools): add SIB SPARQL editor page alongside YASGUI

942 of 1360 branches covered (69.26%)

Branch coverage included in aggregate %.

2691 of 3318 relevant lines covered (81.1%)

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
        HttpClient httpClient = vertx.createHttpClient(
180
                new HttpClientOptions()
181
                        .setConnectTimeout(Utils.getEnvInt("NANOPUB_QUERY_VERTX_CONNECT_TIMEOUT", 1000))
182
                        .setIdleTimeoutUnit(TimeUnit.SECONDS)
183
                        .setIdleTimeout(Utils.getEnvInt("NANOPUB_QUERY_VERTX_IDLE_TIMEOUT", 60))
184
                        .setReadIdleTimeout(Utils.getEnvInt("NANOPUB_QUERY_VERTX_IDLE_TIMEOUT", 60))
185
                        .setWriteIdleTimeout(Utils.getEnvInt("NANOPUB_QUERY_VERTX_IDLE_TIMEOUT", 60)),
186
                new PoolOptions().setHttp1MaxSize(200).setHttp2MaxSize(200)
187
        );
188

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

217
        // Metrics
218
        final var metricsHttpServer = vertx.createHttpServer();
219
        final var metricsRouter = Router.router(vertx);
220
        Future<HttpServer> metricsListening = metricsHttpServer.requestHandler(metricsRouter).listen(9394);
221

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

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

240
        rdf4jProxy.addInterceptor(new ProxyInterceptor() {
×
241

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

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

271
        });
272
        // ----------
273

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

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

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

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

544
        HttpProxy grlcxProxy = HttpProxy.reverseProxy(httpClient);
545
        grlcxProxy.origin(proxyPort, proxy);
546

547
        grlcxProxy.addInterceptor(new ProxyInterceptor() {
×
548

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

569
                        // Variant 1:
570
                        req.putHeader("Content-Type", "application/sparql-query");
571
                        req.setBody(Body.body(Buffer.buffer(grlcSpec.expandQuery())));
572
                        // Variant 2:
573
                        //req.putHeader("Content-Type", "application/x-www-form-urlencoded");
574
                        //req.setBody(Body.body(Buffer.buffer("query=" + URLEncoder.encode(grlcSpec.getExpandedQueryContent(), Charsets.UTF_8))));
575

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

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

617
        });
618
        proxyRouter.route(HttpMethod.GET, "/api/*").handler(ProxyHandler.create(grlcxProxy));
619

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

626
        proxyServer.requestHandler(req -> {
627
            applyGlobalHeaders(req.response());
628
            proxyRouter.handle(req);
629
        });
630
        Future<HttpServer> proxyListening = proxyServer.listen(9393);
631

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

642

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

705
            // Seed the TrustStateRegistry from any persisted pointer before the
706
            // periodic poll begins, so the first tick doesn't re-materialize state
707
            // we already have.
708
            TrustStateLoader.bootstrap();
709

710
            // Drop any npass:* graph that isn't the current-pointer target —
711
            // leftovers from builds interrupted by a crash.
712
            if (FeatureFlags.spacesEnabled()) {
713
                AuthorityResolver.get().cleanOrphans();
714
            }
715

716
            // Start periodic nanopub loading
717
            logger.info("Starting periodic nanopub loading...");
718
            var executor = Executors.newSingleThreadScheduledExecutor();
719
            schedulers.add(executor);
720
            executor.scheduleWithFixedDelay(
721
                    JellyNanopubLoader::loadUpdates,
722
                    JellyNanopubLoader.UPDATES_POLL_INTERVAL,
723
                    JellyNanopubLoader.UPDATES_POLL_INTERVAL,
724
                    TimeUnit.MILLISECONDS
725
            );
726

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

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

787
        vertxRef = vertx;
788
        Runtime.getRuntime().addShutdownHook(new Thread(MainVerticle::shutdownGracefully));
789
        completeWhenListening(startPromise, metricsListening, proxyListening);
790
    }
791

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

810
    private String getResourceAsString(String file) {
811
        InputStream is = getClass().getClassLoader().getResourceAsStream("com/knowledgepixels/query/" + file);
812
        try (Scanner s = new Scanner(is).useDelimiter("\\A")) {
813
            String fileContent = s.hasNext() ? s.next() : "";
814
            return fileContent;
815
        }
816
    }
817

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

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