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

knowledgepixels / nanopub-query / 31482905986

11 Aug 2026 10:35AM UTC coverage: 75.976% (-0.2%) from 76.141%
31482905986

push

github

web-flow
Merge pull request #181 from knowledgepixels/fix/federation-pool-hardening

Bound the federation connection leak: server idle timeout, lower pool cap

817 of 1222 branches covered (66.86%)

Branch coverage included in aggregate %.

2412 of 3028 relevant lines covered (79.66%)

12.45 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.prometheus.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.Executors;
30
import java.util.concurrent.TimeUnit;
31

32
/**
33
 * Main verticle that coordinates the incoming HTTP requests.
34
 */
35
@GeneratedFlagForDependentElements
36
public class MainVerticle extends AbstractVerticle {
37

38
    private static String css = null;
39

40
    private static final Logger logger = LoggerFactory.getLogger(MainVerticle.class);
41

42
    /**
43
     * Start the main verticle.
44
     *
45
     * @param startPromise the promise to complete when the verticle is started
46
     * @throws Exception if an error occurs during startup
47
     */
48
    @Override
49
    public void start(Promise<Void> startPromise) throws Exception {
50
        if (!FeatureFlags.trustStateEnabled()) {
51
            logger.warn("Trust state feature disabled via NANOPUB_QUERY_ENABLE_TRUST_STATE=false — "
52
                    + "no trust snapshots will be fetched or materialised, and the 'trust' repo will not be auto-created.");
53
        }
54
        if (!FeatureFlags.spacesEnabled()) {
55
            logger.warn("Spaces feature disabled via NANOPUB_QUERY_ENABLE_SPACES=false — "
56
                    + "no space-relevant nanopubs will be extracted into npa:spacesGraph, "
57
                    + "and the 'spaces' repo will not be auto-created.");
58
        }
59
        if (!FeatureFlags.fullRepoEnabled()) {
60
            logger.warn("Writes to the 'full' repo disabled via NANOPUB_QUERY_ENABLE_FULL_REPO=false — "
61
                    + "generic SPARQL queries against /repo/full will return an empty store.");
62
        }
63
        if (!FeatureFlags.textRepoEnabled()) {
64
            logger.warn("Writes to the 'text' repo disabled via NANOPUB_QUERY_ENABLE_TEXT_REPO=false — "
65
                    + "full-text search via /repo/text will return nothing.");
66
        }
67
        if (!FeatureFlags.last30dRepoEnabled()) {
68
            logger.warn("Writes to the 'last30d' repo disabled via NANOPUB_QUERY_ENABLE_LAST30D_REPO=false — "
69
                    + "the /repo/last30d endpoint will be empty; rewrite queries against /repo/full with a date filter.");
70
        }
71
        if (!FeatureFlags.reconciliationEnabled()) {
72
            logger.warn("Shard reconciliation disabled via NANOPUB_QUERY_ENABLE_RECONCILIATION=false — "
73
                    + "nanopubs silently missing from individual shard repos (issue #139) will not be detected or repaired.");
74
        }
75
        HttpClient httpClient = vertx.createHttpClient(
76
                new HttpClientOptions()
77
                        .setConnectTimeout(Utils.getEnvInt("NANOPUB_QUERY_VERTX_CONNECT_TIMEOUT", 1000))
78
                        .setIdleTimeoutUnit(TimeUnit.SECONDS)
79
                        .setIdleTimeout(Utils.getEnvInt("NANOPUB_QUERY_VERTX_IDLE_TIMEOUT", 60))
80
                        .setReadIdleTimeout(Utils.getEnvInt("NANOPUB_QUERY_VERTX_IDLE_TIMEOUT", 60))
81
                        .setWriteIdleTimeout(Utils.getEnvInt("NANOPUB_QUERY_VERTX_IDLE_TIMEOUT", 60)),
82
                new PoolOptions().setHttp1MaxSize(200).setHttp2MaxSize(200)
83
        );
84

85
        // Idle timeout on the *server* side, which was previously unset ("wait forever").
86
        // SERVICE clauses in /api queries loop back into this server via
87
        // NANOPUB_QUERY_INTERNAL_URL, so the RDF4J server holds a pooled connection here
88
        // for every federated evaluation. When RDF4J leaks such a lease (the ValueStore
89
        // ReadTxn leak, eclipse-rdf4j/rdf4j#5970), nothing on this end ever closes the
90
        // socket: it stays ESTABLISHED, Apache's evictExpiredConnections never sees it as
91
        // stale, and the slot is gone until Tomcat restarts. Observed on 2026-08-11:
92
        // 100/100 connections to this port held ESTABLISHED while all 157 Tomcat worker
93
        // threads sat idle in their task queue, i.e. a fully leased pool with zero work in
94
        // flight, and every federated query failing with "Timeout waiting for connection
95
        // from pool" until the store was restarted by hand.
96
        //
97
        // Closing idle connections turns that permanent wedge into a self-healing one: a
98
        // leaked lease is closed by this end, goes stale, and is evicted from RDF4J's pool.
99
        // The default is deliberately far above any legitimate idle period on that route —
100
        // RDF4J's own client uses a 10 s socket timeout for SERVICE evaluation — while
101
        // still bounding the leak. Note this counts *any* inactivity, including a slow
102
        // query that has not started streaming its response, so do not lower it below the
103
        // slowest query this instance is expected to serve.
104
        HttpServer proxyServer = vertx.createHttpServer(
105
                new HttpServerOptions()
106
                        .setMaxInitialLineLength(65536)
107
                        .setIdleTimeoutUnit(TimeUnit.SECONDS)
108
                        .setIdleTimeout(Utils.getEnvInt("NANOPUB_QUERY_VERTX_SERVER_IDLE_TIMEOUT", 300))
109
        );
110
        Router proxyRouter = Router.router(vertx);
111
        proxyRouter.route().handler(CorsHandler.create().addRelativeOrigin(".*"));
112

113
        // Metrics
114
        final var metricsHttpServer = vertx.createHttpServer();
115
        final var metricsRouter = Router.router(vertx);
116
        metricsHttpServer.requestHandler(metricsRouter).listen(9394);
117

118
        final var metricsRegistry = (PrometheusMeterRegistry) BackendRegistries.getDefaultNow();
119
        final var collector = new MetricsCollector(metricsRegistry);
120
        metricsRouter.route("/metrics").handler(PrometheusScrapingHandler.create(metricsRegistry));
121
        // ----------
122
        // This part is only used if the redirection is not done through Nginx.
123
        // See nginx.conf and this bug report: https://github.com/eclipse-rdf4j/rdf4j/discussions/5120
124
        HttpProxy rdf4jProxy = HttpProxy.reverseProxy(httpClient);
125
        String proxy = Utils.getEnvString("RDF4J_PROXY_HOST", "rdf4j");
126
        int proxyPort = Utils.getEnvInt("RDF4J_PROXY_PORT", 8080);
127
        rdf4jProxy.origin(proxyPort, proxy);
128

129
        rdf4jProxy.addInterceptor(new ProxyInterceptor() {
×
130

131
            @Override
132
            @GeneratedFlagForDependentElements
133
            public Future<ProxyResponse> handleProxyRequest(ProxyContext context) {
134
                ProxyRequest request = context.request();
135
                request.setURI(request.getURI().replaceAll("/", "_").replaceFirst("^_repo_", "/rdf4j-server/repositories/"));
136
                // For later to try to get HTML tables out:
137
//                                if (request.headers().get("Accept") == null) {
138
//                                        request.putHeader("Accept", "text/html");
139
//                                }
140
//                                request.putHeader("Accept", "application/json");
141
                return ProxyInterceptor.super.handleProxyRequest(context);
142
            }
143

144
            @Override
145
            @GeneratedFlagForDependentElements
146
            public Future<Void> handleProxyResponse(ProxyContext context) {
147
                ProxyResponse resp = context.response();
148
                resp.putHeader("Access-Control-Allow-Origin", "*");
149
                resp.putHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS");
150
                // For later to try to get HTML tables out:
151
//                                String acceptHeader = context.request().headers().get("Accept");
152
//                                if (acceptHeader != null && acceptHeader.contains("text/html")) {
153
//                                        resp.putHeader("Content-Type", "text/html");
154
//                                        resp.setBody(Body.body(Buffer.buffer("<html><body><strong>test</strong></body></html>")));
155
//                                }
156
                return ProxyInterceptor.super.handleProxyResponse(context);
157
            }
158

159
        });
160
        // ----------
161

162
        proxyRouter.route(HttpMethod.GET, "/repo").handler(req -> handleRedirect(req, "/repo"));
163
        proxyRouter.route(HttpMethod.GET, "/repo/*").handler(ProxyHandler.create(rdf4jProxy));
164
        proxyRouter.route(HttpMethod.POST, "/repo/*").handler(ProxyHandler.create(rdf4jProxy));
165
        proxyRouter.route(HttpMethod.HEAD, "/repo/*").handler(ProxyHandler.create(rdf4jProxy));
166
        proxyRouter.route(HttpMethod.OPTIONS, "/repo/*").handler(ProxyHandler.create(rdf4jProxy));
167
        proxyRouter.route(HttpMethod.GET, "/tools/*").handler(req -> {
168
            final String yasguiPattern = "^/tools/([a-zA-Z0-9-_]+)(/([a-zA-Z0-9-_]+))?/yasgui\\.html$";
169
            if (req.normalizedPath().matches(yasguiPattern)) {
170
                String repo = req.normalizedPath().replaceFirst(yasguiPattern, "$1$2");
171
                req.response()
172
                        .putHeader("content-type", "text/html")
173
                        .end("<!DOCTYPE html>\n"
174
                             + "<html lang=\"en\">\n"
175
                             + "<head>\n"
176
                             + "<meta charset=\"utf-8\">\n"
177
                             + "<meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">\n"
178
                             + "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n"
179
                             + "<title>Nanopub Query SPARQL Editor for repository: " + repo + "</title>\n"
180
                             + "<link rel=\"stylesheet\" href=\"/style.css\">\n"
181
                             + "<link href='https://cdn.jsdelivr.net/yasgui/2.6.1/yasgui.min.css' rel='stylesheet' type='text/css'/>\n"
182
                             + "<style>.yasgui .endpointText {display:none !important;}</style>\n"
183
                             + "<script type=\"text/javascript\">localStorage.clear();</script>\n"
184
                             + "</head>\n"
185
                             + "<body>\n"
186
                             + "<h3>Nanopub Query SPARQL Editor for repository: " + repo + "</h3>\n"
187
                             + "<div id='yasgui'></div>\n"
188
                             + "<script src='https://cdn.jsdelivr.net/yasgui/2.6.1/yasgui.min.js'></script>\n"
189
                             + "<script type=\"text/javascript\">\n"
190
                             + "var yasgui = YASGUI(document.getElementById(\"yasgui\"), {\n"
191
                             + "  yasqe:{sparql:{endpoint:'/repo/" + repo + "'},value:'" + Utils.defaultQuery.replaceAll("\n", "\\\\n") + "'}\n"
192
                             + "});\n"
193
                             + "</script>\n"
194
                             + "</body>\n"
195
                             + "</html>");
196
            } else {
197
                req.response()
198
                        .putHeader("content-type", "text/plain")
199
                        .setStatusCode(404)
200
                        .end("not found");
201
            }
202
        });
203
        proxyRouter.route(HttpMethod.GET, "/page").handler(req -> handleRedirect(req, "/page"));
204
        proxyRouter.route(HttpMethod.GET, "/page/*").handler(req -> {
205
            final String pagePattern = "^/page/([a-zA-Z0-9-_]+)(/([a-zA-Z0-9-_]+))?$";
206
            if (req.normalizedPath().matches(pagePattern)) {
207
                String repo = req.normalizedPath().replaceFirst(pagePattern, "$1$2");
208
                req.response()
209
                        .putHeader("content-type", "text/html")
210
                        .end("<!DOCTYPE html>\n"
211
                             + "<html lang=\"en\">\n"
212
                             + "<head>\n"
213
                             + "<meta charset=\"utf-8\">\n"
214
                             + "<meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">\n"
215
                             + "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n"
216
                             + "<title>Nanopub Query repo: " + repo + "</title>\n"
217
                             + "<link rel=\"stylesheet\" href=\"/style.css\">\n"
218
                             + "</head>\n"
219
                             + "<body>\n"
220
                             + "<h3>Nanopub Query repo: " + repo + "</h3>\n"
221
                             + "<p>Endpoint: <a href=\"/repo/" + repo + "\">/repo/" + repo + "</a></p>"
222
                             + "<p>YASGUI: <a href=\"/tools/" + repo + "/yasgui.html\">/tools/" + repo + "/yasgui.hml</a></p>"
223
                             + "</body>\n"
224
                             + "</html>");
225
            } else {
226
                req.response()
227
                        .putHeader("content-type", "text/plain")
228
                        .setStatusCode(404)
229
                        .end("not found");
230
            }
231
        });
232
        proxyRouter.route(HttpMethod.GET, "/").handler(req -> {
233
            vertx.<String>executeBlocking(() -> {
234
                String repos = "";
235
                List<String> repoList = new ArrayList<>(TripleStore.get().getRepositoryNames());
236
                Collections.sort(repoList);
237
                for (String s : repoList) {
238
                    if (s.startsWith("pubkey_") || s.startsWith("type_")) continue;
239
                    repos += "<li><code><a href=\"/page/" + s + "\">" + s + "</a></code></li>";
240
                }
241
                String pinnedApisValue = Utils.getEnvString("NANOPUB_QUERY_PINNED_APIS", "");
242
                String[] pinnedApis = pinnedApisValue.split(" ");
243
                String pinnedApiLinks = "";
244
                if (!pinnedApisValue.isEmpty()) {
245
                    for (String s : pinnedApis) {
246
                        pinnedApiLinks = pinnedApiLinks + "<li><a href=\"openapi/?url=spec/" + s + "%3Fapi-version=latest\">" + s.replaceFirst("^.*/", "") + "</a></li>";
247
                    }
248
                    pinnedApiLinks = "<p>Pinned APIs:</p>\n" +
249
                                     "<ul>\n" +
250
                                     pinnedApiLinks +
251
                                     "</ul>\n";
252
                }
253
                return "<!DOCTYPE html>\n"
254
                     + "<html lang='en'>\n"
255
                     + "<head>\n"
256
                     + "<title>Nanopub Query</title>\n"
257
                     + "<meta charset='utf-8'>\n"
258
                     + "<link rel=\"stylesheet\" href=\"/style.css\">\n"
259
                     + "</head>\n"
260
                     + "<body>\n"
261
                     + "<h1>Nanopub Query</h1>"
262
                     + "<p>General repos:</p>"
263
                     + "<ul>" + repos + "</ul>"
264
                     + "<p>Specific repos:</p>"
265
                     + "<ul>"
266
                     + "<li><a href=\"/pubkeys\">Pubkey Repos</a></li>"
267
                     + "<li><a href=\"/types\">Type Repos</a></li>"
268
                     + "</ul>"
269
                     + (FeatureFlags.spacesEnabled()
270
                             ? "<p>Spaces:</p>"
271
                               + "<ul><li><a href=\"/spaces\">Spaces</a></li></ul>"
272
                             : "")
273
                     + pinnedApiLinks
274
                     + "</body>\n"
275
                     + "</html>";
276
            }, false).onSuccess(html -> {
277
                req.response().putHeader("content-type", "text/html").end(html);
278
            }).onFailure(ex -> {
279
                req.response().setStatusCode(500).end("Error: " + ex.getMessage());
280
            });
281
        });
282
        proxyRouter.route(HttpMethod.GET, "/pubkeys").handler(req -> {
283
            vertx.<String>executeBlocking(() -> {
284
                String repos = "";
285
                List<String> repoList = new ArrayList<>(TripleStore.get().getRepositoryNames());
286
                Collections.sort(repoList);
287
                for (String s : repoList) {
288
                    if (!s.startsWith("pubkey_")) continue;
289
                    String hash = s.replaceFirst("^([a-zA-Z0-9-]+)_([a-zA-Z0-9-_]+)$", "$2");
290
                    Value hashObj = Utils.getObjectForHash(hash);
291
                    String label;
292
                    if (hashObj == null) {
293
                        label = "";
294
                    } else {
295
                        label = " (" + Utils.getShortPubkeyName(hashObj.stringValue()) + ")";
296
                    }
297
                    s = s.replaceFirst("^([a-zA-Z0-9-]+)_([a-zA-Z0-9-_]+)$", "$1/$2");
298
                    repos += "<li><code><a href=\"/page/" + s + "\">" + s + "</a>" + label + "</code></li>";
299
                }
300
                return "<!DOCTYPE html>\n"
301
                     + "<html lang='en'>\n"
302
                     + "<head>\n"
303
                     + "<title>Nanopub Query: Pubkey Repos</title>\n"
304
                     + "<meta charset='utf-8'>\n"
305
                     + "<link rel=\"stylesheet\" href=\"/style.css\">\n"
306
                     + "</head>\n"
307
                     + "<body>\n"
308
                     + "<h3>Pubkey Repos</h3>"
309
                     + "<p>Repos:</p>"
310
                     + "<ul>" + repos + "</ul>"
311
                     + "</body>\n"
312
                     + "</html>";
313
            }, false).onSuccess(html -> {
314
                req.response().putHeader("content-type", "text/html").end(html);
315
            }).onFailure(ex -> {
316
                req.response().setStatusCode(500).end("Error: " + ex.getMessage());
317
            });
318
        });
319
        proxyRouter.route(HttpMethod.GET, "/types").handler(req -> {
320
            vertx.<String>executeBlocking(() -> {
321
                String repos = "";
322
                List<String> repoList = new ArrayList<>(TripleStore.get().getRepositoryNames());
323
                Collections.sort(repoList);
324
                for (String s : repoList) {
325
                    if (!s.startsWith("type_")) continue;
326
                    String hash = s.replaceFirst("^([a-zA-Z0-9-]+)_([a-zA-Z0-9-_]+)$", "$2");
327
                    Value hashObj = Utils.getObjectForHash(hash);
328
                    String label;
329
                    if (hashObj == null) {
330
                        label = "";
331
                    } else {
332
                        label = " (" + hashObj.stringValue() + ")";
333
                    }
334
                    s = s.replaceFirst("^([a-zA-Z0-9-]+)_([a-zA-Z0-9-_]+)$", "$1/$2");
335
                    repos += "<li><code><a href=\"/page/" + s + "\">" + s + "</a>" + label + "</code></li>";
336
                }
337
                return "<!DOCTYPE html>\n"
338
                     + "<html lang='en'>\n"
339
                     + "<head>\n"
340
                     + "<title>Nanopub Query: Type Repos</title>\n"
341
                     + "<meta charset='utf-8'>\n"
342
                     + "<link rel=\"stylesheet\" href=\"/style.css\">\n"
343
                     + "</head>\n"
344
                     + "<body>\n"
345
                     + "<h3>Type Repos</h3>"
346
                     + "<p>Repos:</p>"
347
                     + "<ul>" + repos + "</ul>"
348
                     + "</body>\n"
349
                     + "</html>";
350
            }, false).onSuccess(html -> {
351
                req.response().putHeader("content-type", "text/html").end(html);
352
            }).onFailure(ex -> {
353
                req.response().setStatusCode(500).end("Error: " + ex.getMessage());
354
            });
355
        });
356
        io.vertx.core.Handler<RoutingContext> spacesHandler = req -> {
357
            if (!FeatureFlags.spacesEnabled()) {
358
                req.response().setStatusCode(404)
359
                        .putHeader("content-type", "text/plain")
360
                        .end("Spaces feature is disabled");
361
                return;
362
            }
363
            // Path suffix wins over Accept header so /spaces.json is unambiguous.
364
            boolean wantJson = req.normalizedPath().endsWith(".json")
365
                    || "application/json".equalsIgnoreCase(req.request().getHeader("Accept"));
366
            vertx.<String>executeBlocking(() -> {
367
                var rows = SpacesListingRoute.fetchRows();
368
                return wantJson
369
                        ? SpacesListingRoute.renderJson(rows)
370
                        : SpacesListingRoute.renderHtml(rows);
371
            }, false).onSuccess(body -> {
372
                req.response().putHeader(
373
                        "content-type",
374
                        wantJson ? "application/json" : "text/html").end(body);
375
            }).onFailure(ex -> {
376
                req.response().setStatusCode(500).end("Error: " + ex.getMessage());
377
            });
378
        };
379
        proxyRouter.route(HttpMethod.GET, "/spaces").handler(spacesHandler);
380
        proxyRouter.route(HttpMethod.GET, "/spaces.json").handler(spacesHandler);
381
        proxyRouter.route(HttpMethod.GET, "/style.css").handler(req -> {
382
            if (css == null) {
383
                css = getResourceAsString("style.css");
384
            }
385
            req.response().end(css);
386
        });
387

388
        // TODO This is no longer needed and can be removed at some point:
389
        proxyRouter.route(HttpMethod.GET, "/grlc-spec/*").handler(req -> {
390
            vertx.<String>executeBlocking(() -> {
391
                GrlcSpec gsp = new GrlcSpec(req.normalizedPath(), req.queryParams());
392
                return gsp.getSpec();
393
            }, false).onSuccess(spec -> {
394
                req.response().putHeader("content-type", "text/yaml").end(spec);
395
            }).onFailure(ex -> {
396
                if (ex instanceof InvalidGrlcSpecException) {
397
                    req.response().setStatusCode(400).end(ex.getMessage());
398
                } else {
399
                    req.response().setStatusCode(500).end("Unexpected error: " + ex.getMessage());
400
                }
401
            });
402
        });
403

404
        proxyRouter.route(HttpMethod.GET, "/openapi/spec/*").handler(req -> {
405
            vertx.<String>executeBlocking(() -> {
406
                OpenApiSpecPage osp = new OpenApiSpecPage(req.normalizedPath(), req.queryParams());
407
                return osp.getSpec();
408
            }, false).onSuccess(spec -> {
409
                req.response().putHeader("content-type", "text/yaml").end(spec);
410
            }).onFailure(ex -> {
411
                if (ex instanceof InvalidGrlcSpecException) {
412
                    req.response().setStatusCode(400).end("Invalid grlc API definition: " + ex.getMessage());
413
                } else {
414
                    req.response().setStatusCode(500).end("Unexpected error: " + ex.getMessage());
415
                }
416
            });
417
        });
418

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

421
        HttpProxy grlcxProxy = HttpProxy.reverseProxy(httpClient);
422
        grlcxProxy.origin(proxyPort, proxy);
423

424
        grlcxProxy.addInterceptor(new ProxyInterceptor() {
×
425

426
            @Override
427
            @GeneratedFlagForDependentElements
428
            public Future<ProxyResponse> handleProxyRequest(ProxyContext context) {
429
                final ProxyRequest req = context.request();
430
                final String apiPattern = "^/api/(RA[a-zA-Z0-9-_]{43})/([a-zA-Z0-9-_]+)([.]csv|[.]json|[.]srx)?([?].*)?$";
431
                if (req.getURI().matches(apiPattern)) {
432
                    try {
433
                        req.setMethod(HttpMethod.POST);
434
                        if (req.getURI().matches(".*[.]csv([?].*)?$")) {
435
                            req.putHeader("Accept", "text/csv");
436
                            req.setURI(req.getURI().replaceFirst("[.]csv([?].*)?$", "$1"));
437
                        } else if (req.getURI().matches(".*[.]json([?].*)?$")) {
438
                            req.putHeader("Accept", "application/json");
439
                            req.setURI(req.getURI().replaceFirst("[.]json([?].*)?$", "$1"));
440
                        } else if (req.getURI().matches(".*[.]srx([?].*)?$")) {
441
                            req.putHeader("Accept", "application/xml");
442
                            req.setURI(req.getURI().replaceFirst("[.]srx([?].*)?$", "$1"));
443
                        }
444
                        GrlcSpec grlcSpec = new GrlcSpec(req.getURI(), req.proxiedRequest().params());
445

446
                        // Variant 1:
447
                        req.putHeader("Content-Type", "application/sparql-query");
448
                        req.setBody(Body.body(Buffer.buffer(grlcSpec.expandQuery())));
449
                        // Variant 2:
450
                        //req.putHeader("Content-Type", "application/x-www-form-urlencoded");
451
                        //req.setBody(Body.body(Buffer.buffer("query=" + URLEncoder.encode(grlcSpec.getExpandedQueryContent(), Charsets.UTF_8))));
452

453
                        req.setURI("/rdf4j-server/repositories/" + grlcSpec.getRepoName());
454
                        logger.info("Forwarding apix request to /rdf4j-server/repositories/{}", grlcSpec.getRepoName());
455
                    } catch (InvalidGrlcSpecException ex) {
456
                        return Future.succeededFuture(context.request()
457
                                .response()
458
                                .setStatusCode(400)
459
                                .putHeader("Content-Type", "text/plain")
460
                                .setBody(Body.body(Buffer.buffer("Bad request: " + ex.getMessage()))));
461
                    } catch (Exception ex) {
462
                        return Future.succeededFuture(context.request()
463
                                .response()
464
                                .setStatusCode(500)
465
                                .putHeader("Content-Type", "text/plain")
466
                                .setBody(Body.body(Buffer.buffer("Unexpected error: " + ex.getMessage()))));
467
                    }
468
                }
469
                return ProxyInterceptor.super.handleProxyRequest(context);
470
            }
471

472
            @Override
473
            @GeneratedFlagForDependentElements
474
            public Future<Void> handleProxyResponse(ProxyContext context) {
475
                logger.info("Receiving api response");
476
                ProxyResponse resp = context.response();
477
                resp.putHeader("Access-Control-Allow-Origin", "*");
478
                resp.putHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS");
479
                resp.putHeader("Content-Disposition", "inline");
480
                return ProxyInterceptor.super.handleProxyResponse(context);
481
            }
482

483
        });
484
        proxyRouter.route(HttpMethod.GET, "/api/*").handler(ProxyHandler.create(grlcxProxy));
485

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

492
        proxyServer.requestHandler(req -> {
493
            applyGlobalHeaders(req.response());
494
            proxyRouter.handle(req);
495
        });
496
        proxyServer.listen(9393);
497

498
        // Periodic metrics update. Runs on a dedicated single-thread scheduled executor
499
        // (not on the Vert.x event loop) because `updateMetrics` can fall through to a
500
        // synchronous HTTP call in `TripleStore.getRepositoryNames()` when the cache has
501
        // been invalidated. `scheduleWithFixedDelay` naturally serialises ticks and cannot
502
        // pile up if the work occasionally runs long. Same pattern as `JellyNanopubLoader.loadUpdates`
503
        // below.
504
        Executors.newSingleThreadScheduledExecutor()
505
                .scheduleWithFixedDelay(collector::updateMetrics, 1, 1, TimeUnit.SECONDS);
506

507

508
        new Thread(() -> {
509
            try {
510
                var status = StatusController.get().initialize();
511
                logger.info("Current state: {}, last committed counter: {}", status.state, status.loadCounter);
512
                // Restore or fetch the registry setup ID
513
                Long storedSetupId = StatusController.get().getRegistrySetupId();
514
                if (storedSetupId != null) {
515
                    JellyNanopubLoader.setLastKnownSetupId(storedSetupId);
516
                    logger.info("Restored registry setupId: {}", storedSetupId);
517
                } else if (status.state == StatusController.State.LAUNCHING
518
                        || status.state == StatusController.State.LOADING_INITIAL) {
519
                    // Fresh start or crashed during initial load – safe to adopt the current setupId
520
                    try {
521
                        var metadata = JellyNanopubLoader.fetchRegistryMetadata();
522
                        JellyNanopubLoader.setLastKnownSetupId(metadata.setupId());
523
                        if (metadata.setupId() != null) {
524
                            StatusController.get().setRegistrySetupId(metadata.setupId());
525
                            logger.info("Fetched initial registry setupId: {}", metadata.setupId());
526
                        }
527
                    } catch (Exception e) {
528
                        logger.warn("Could not fetch initial registry setupId", e);
529
                    }
530
                } else {
531
                    // Upgrade from a version without setupId tracking. The DB has data but
532
                    // we can't verify it matches the current registry state. Leave lastKnownSetupId
533
                    // as null so that loadUpdates() will trigger a resync.
534
                    logger.warn("No stored registry setupId but DB has data (state: {}, counter: {}). "
535
                            + "A resync will be triggered on the first update poll.",
536
                            status.state, status.loadCounter);
537
                }
538
                boolean forceResync = "true".equalsIgnoreCase(
539
                        Utils.getEnvString("FORCE_RESYNC", "false"));
540
                if (forceResync && status.state != StatusController.State.LAUNCHING) {
541
                    logger.warn("FORCE_RESYNC is set. Forcing full re-load from registry.");
542
                    var metadata = JellyNanopubLoader.fetchRegistryMetadata();
543
                    JellyNanopubLoader.setLastKnownSetupId(metadata.setupId());
544
                    if (metadata.setupId() != null) {
545
                        StatusController.get().setRegistrySetupId(metadata.setupId());
546
                    }
547
                    StatusController.get().setResetting();
548
                    StatusController.get().setLoadingInitial(-1);
549
                    JellyNanopubLoader.loadInitial(-1);
550
                    StatusController.get().setReady();
551
                } else if (status.state == StatusController.State.LAUNCHING || status.state == StatusController.State.LOADING_INITIAL) {
552
                    // Do the initial nanopublication loading
553
                    StatusController.get().setLoadingInitial(status.loadCounter);
554
                    // Fall back to local nanopub loading if the local files are present
555
                    if (!LocalNanopubLoader.init()) {
556
                        JellyNanopubLoader.loadInitial(status.loadCounter);
557
                    } else {
558
                        logger.info("Local nanopublication loading finished");
559
                    }
560
                    StatusController.get().setReady();
561
                } else {
562
                    logger.info("Initial load is already done");
563
                    StatusController.get().setReady();
564
                }
565
            } catch (Exception ex) {
566
                logger.info("Initial load failed, terminating...", ex);
567
                Runtime.getRuntime().exit(1);
568
            }
569

570
            // Seed the TrustStateRegistry from any persisted pointer before the
571
            // periodic poll begins, so the first tick doesn't re-materialize state
572
            // we already have.
573
            TrustStateLoader.bootstrap();
574

575
            // Drop any npass:* graph that isn't the current-pointer target —
576
            // leftovers from builds interrupted by a crash.
577
            if (FeatureFlags.spacesEnabled()) {
578
                AuthorityResolver.get().cleanOrphans();
579
            }
580

581
            // Start periodic nanopub loading
582
            logger.info("Starting periodic nanopub loading...");
583
            var executor = Executors.newSingleThreadScheduledExecutor();
584
            executor.scheduleWithFixedDelay(
585
                    JellyNanopubLoader::loadUpdates,
586
                    JellyNanopubLoader.UPDATES_POLL_INTERVAL,
587
                    JellyNanopubLoader.UPDATES_POLL_INTERVAL,
588
                    TimeUnit.MILLISECONDS
589
            );
590

591
            // Periodic shard-consistency sweep (issue #139): verifies that recently
592
            // loaded nanopubs actually landed in every shard repo their metadata
593
            // implies, and re-loads any that are missing. Own single-threaded
594
            // executor; scheduleWithFixedDelay serialises ticks. The tick itself
595
            // no-ops unless the reconciliation flag is on and the state is READY.
596
            // 5-minute cadence: completed loads (meta stamp present) are verified
597
            // on the first tick after they land, so this interval — not a grace
598
            // window — is the repair latency for a dropped shard, and the damage
599
            // window of a missing shard is exactly the post-publish minutes when
600
            // its author is actively using it. An idle tick is one bounded query.
601
            Executors.newSingleThreadScheduledExecutor().scheduleWithFixedDelay(
602
                    () -> {
603
                        try {
604
                            ShardReconciler.tick();
605
                        } catch (Exception ex) {
606
                            logger.warn("Shard reconciliation tick failed", ex);
607
                        }
608
                    },
609
                    5, 5, TimeUnit.MINUTES
610
            );
611

612
            // Periodic authority-resolver tick: detects trust-state flips and
613
            // advances the current space-state graph by an incremental cycle on
614
            // each load-number delta. Same cadence as the nanopub-loading poll.
615
            //
616
            // The same single-threaded executor also runs periodicRebuildTick
617
            // every 10 min; that's the from-scratch rebuild triggered when an
618
            // incremental cycle DELETEs a structural derivation and raises the
619
            // npa:needsFullRebuild flag. Sharing one executor serialises the
620
            // two ticks naturally — they never overlap.
621
            if (FeatureFlags.spacesEnabled()) {
622
                var spacesExecutor = Executors.newSingleThreadScheduledExecutor();
623
                spacesExecutor.scheduleWithFixedDelay(
624
                        () -> {
625
                            try {
626
                                AuthorityResolver.get().tick();
627
                            } catch (Exception ex) {
628
                                logger.warn("AuthorityResolver tick failed", ex);
629
                            }
630
                        },
631
                        JellyNanopubLoader.UPDATES_POLL_INTERVAL,
632
                        JellyNanopubLoader.UPDATES_POLL_INTERVAL,
633
                        TimeUnit.MILLISECONDS
634
                );
635
                spacesExecutor.scheduleWithFixedDelay(
636
                        () -> {
637
                            try {
638
                                AuthorityResolver.get().periodicRebuildTick();
639
                            } catch (Exception ex) {
640
                                logger.warn("AuthorityResolver periodic rebuild failed", ex);
641
                            }
642
                        },
643
                        10, 10, TimeUnit.MINUTES
644
                );
645
            }
646
        }).start();
647

648
        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
649
            try {
650
                logger.info("Gracefully shutting down...");
651
                TripleStore.get().shutdownRepositories();
652
                vertx.close().toCompletionStage().toCompletableFuture().get(5, TimeUnit.SECONDS);
653
                logger.info("Graceful shutdown completed");
654
            } catch (Exception ex) {
655
                logger.info("Graceful shutdown failed", ex);
656
            }
657
        }));
658
    }
659

660
    private String getResourceAsString(String file) {
661
        InputStream is = getClass().getClassLoader().getResourceAsStream("com/knowledgepixels/query/" + file);
662
        try (Scanner s = new Scanner(is).useDelimiter("\\A")) {
663
            String fileContent = s.hasNext() ? s.next() : "";
664
            return fileContent;
665
        }
666
    }
667

668
    private static void handleRedirect(RoutingContext req, String path) {
669
        String queryString = "";
670
        if (!req.queryParam("query").isEmpty())
671
            queryString = "?query=" + URLEncoder.encode(req.queryParam("query").getFirst(), Charsets.UTF_8);
672
        if (req.queryParam("for-type").size() == 1) {
673
            String type = req.queryParam("for-type").getFirst();
674
            req.response().putHeader("location", path + "/type/" + Utils.createHash(type) + queryString);
675
            req.response().setStatusCode(301).end();
676
        } else if (req.queryParam("for-pubkey").size() == 1) {
677
            String type = req.queryParam("for-pubkey").getFirst();
678
            req.response().putHeader("location", path + "/pubkey/" + Utils.createHash(type) + queryString);
679
            req.response().setStatusCode(301).end();
680
        } else if (req.queryParam("for-user").size() == 1) {
681
            String type = req.queryParam("for-user").getFirst();
682
            req.response().putHeader("location", path + "/user/" + Utils.createHash(type) + queryString);
683
            req.response().setStatusCode(301).end();
684
        }
685
    }
686

687
    /**
688
     * Apply headers to the response that should be present for all requests.
689
     *
690
     * @param response The response to which the headers should be applied.
691
     */
692
    static void applyGlobalHeaders(HttpServerResponse response) {
693
        var state = StatusController.get().getState();
694
        response.putHeader("Nanopub-Query-Version", Utils.getVersion());
695
        response.putHeader("Nanopub-Query-Status", state.state.toString());
696
        response.putHeader("Nanopub-Query-Registry-Url", JellyNanopubLoader.registryUrl);
697
        Long setupId = StatusController.get().getRegistrySetupId();
698
        response.putHeader("Nanopub-Query-Registry-Setup-Id", setupId == null ? "" : setupId.toString());
699
        response.putHeader("Nanopub-Query-Load-Counter", String.valueOf(state.loadCounter));
700
        // Forward registry metadata headers
701
        String coverageTypes = JellyNanopubLoader.lastCoverageTypes;
702
        response.putHeader("Nanopub-Query-Registry-Coverage-Types", coverageTypes != null ? coverageTypes : "all");
703
        String coverageAgents = JellyNanopubLoader.lastCoverageAgents;
704
        response.putHeader("Nanopub-Query-Registry-Coverage-Agents", coverageAgents != null ? coverageAgents : "viaSetting");
705
        String testInstance = JellyNanopubLoader.lastTestInstance;
706
        if (testInstance != null) {
707
            response.putHeader("Nanopub-Query-Registry-Test-Instance", testInstance);
708
        }
709
        String nanopubCount = JellyNanopubLoader.lastNanopubCount;
710
        if (nanopubCount != null) {
711
            response.putHeader("Nanopub-Query-Registry-Nanopub-Count", nanopubCount);
712
        }
713
        // Cached reads only. This method runs on the Vert.x event loop for every
714
        // inbound request, and the non-cached accessors fall back to a blocking store
715
        // read whenever the cache is cold — which it is after every restart. That
716
        // stalled the event loop on 2026-07-31 (BlockedThreadChecker fired five times
717
        // right after the 1.24.0 rollout), and with the store unreachable it would
718
        // block every request for the full 10 s connect timeout, taking the HTTP layer
719
        // down with RDF4J. NanopubLoader.primeHeaderCaches() keeps these warm from the
720
        // metrics tick; until it has run, the headers are simply omitted, exactly as
721
        // they already are before the first load.
722
        Long loadedCount = NanopubLoader.getCachedLoadedNanopubCount();
723
        if (loadedCount != null) {
724
            response.putHeader("Nanopub-Query-Loaded-Nanopub-Count", loadedCount.toString());
725
        }
726
        String loadedChecksum = NanopubLoader.getCachedLoadedNanopubChecksum();
727
        if (loadedChecksum != null) {
728
            response.putHeader("Nanopub-Query-Loaded-Nanopub-Checksum", loadedChecksum);
729
        }
730
        // Loader liveness over HTTP. The same value backs
731
        // registry.loader.last_successful_batch_age_seconds, but the metrics port is
732
        // bound to loopback, so anything off-host — nanopub-monitor in particular —
733
        // cannot read it. Without this, a stalled instance looks identical to a healthy
734
        // one from outside: it keeps answering queries and keeps reporting READY, which
735
        // is how the 2026-07-31 stall stayed invisible for hours.
736
        //
737
        // Omitted rather than sent as 0 before the first tick completes, so consumers can
738
        // tell "not started yet" from "just ticked".
739
        //
740
        // The value is only stamped after RDF4J has actually answered (see
741
        // JellyNanopubLoader#lastSuccessfulBatchAtMs), so on a caught-up instance it
742
        // cycles 0..JellyNanopubLoader.STORE_PROBE_INTERVAL_MS rather than sitting at 0.
743
        // Alert thresholds must therefore exceed that interval; minutes, not seconds.
744
        //
745
        // Initial loads and resyncs stamp it as well, so this reads as "seconds since
746
        // the loader last moved" in every state rather than only while polling for
747
        // updates. Interpret it alongside Nanopub-Query-Status: a climbing age under
748
        // LOADING_INITIAL is a resync that has stopped progressing, not a long one.
749
        long lastBatchAt = JellyNanopubLoader.lastSuccessfulBatchAtMs;
750
        if (lastBatchAt != 0L) {
751
            long ageSeconds = Math.max(0L, (System.currentTimeMillis() - lastBatchAt) / 1000L);
752
            response.putHeader("Nanopub-Query-Loader-Last-Success-Age-Seconds", String.valueOf(ageSeconds));
753
        }
754
    }
755
}
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