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

knowledgepixels / nanopub-query / 32135206585

18 Aug 2026 12:06PM UTC coverage: 76.413% (-0.05%) from 76.46%
32135206585

push

github

Ziroli
fix: Log Failed Query Requests in MainVerticle

  Bad grlc API requests (InvalidGrlcSpecException → HTTP 400) and
  unexpected errors (HTTP 500) were silently swallowed without any log
  entry, making it impossible to diagnose failing queries from the
  nanopub-query instance logs. The API proxy path now logs the request
  URI and query parameters alongside the error message.

835 of 1238 branches covered (67.45%)

Branch coverage included in aggregate %.

2463 of 3078 relevant lines covered (80.02%)

12.5 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
        if (FeatureFlags.localInstance()) {
76
            logger.warn("Instance declared local/private via NANOPUB_QUERY_LOCAL_INSTANCE=true — "
77
                    + "nanopubs typed npx:ProtectedNanopub will be loaded and served. Never use this setting on a public instance.");
78
        }
79
        HttpClient httpClient = vertx.createHttpClient(
80
                new HttpClientOptions()
81
                        .setConnectTimeout(Utils.getEnvInt("NANOPUB_QUERY_VERTX_CONNECT_TIMEOUT", 1000))
82
                        .setIdleTimeoutUnit(TimeUnit.SECONDS)
83
                        .setIdleTimeout(Utils.getEnvInt("NANOPUB_QUERY_VERTX_IDLE_TIMEOUT", 60))
84
                        .setReadIdleTimeout(Utils.getEnvInt("NANOPUB_QUERY_VERTX_IDLE_TIMEOUT", 60))
85
                        .setWriteIdleTimeout(Utils.getEnvInt("NANOPUB_QUERY_VERTX_IDLE_TIMEOUT", 60)),
86
                new PoolOptions().setHttp1MaxSize(200).setHttp2MaxSize(200)
87
        );
88

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

117
        // Metrics
118
        final var metricsHttpServer = vertx.createHttpServer();
119
        final var metricsRouter = Router.router(vertx);
120
        metricsHttpServer.requestHandler(metricsRouter).listen(9394);
121

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

133
        rdf4jProxy.addInterceptor(new ProxyInterceptor() {
×
134

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

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

163
        });
164
        // ----------
165

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

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

410
        proxyRouter.route(HttpMethod.GET, "/openapi/spec/*").handler(req -> {
411
            vertx.<String>executeBlocking(() -> {
412
                OpenApiSpecPage osp = new OpenApiSpecPage(req.normalizedPath(), req.queryParams());
413
                return osp.getSpec();
414
            }, false).onSuccess(spec -> {
415
                req.response().putHeader("content-type", "text/yaml").end(spec);
416
            }).onFailure(ex -> {
417
                if (ex instanceof InvalidGrlcSpecException) {
418
                    logger.warn("Bad openapi request for '{}': {}", req.normalizedPath(), ex.getMessage());
419
                    req.response().setStatusCode(400).end("Invalid grlc API definition: " + ex.getMessage());
420
                } else {
421
                    logger.error("Unexpected error for openapi request '{}'", req.normalizedPath(), ex);
422
                    req.response().setStatusCode(500).end("Unexpected error: " + ex.getMessage());
423
                }
424
            });
425
        });
426

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

429
        HttpProxy grlcxProxy = HttpProxy.reverseProxy(httpClient);
430
        grlcxProxy.origin(proxyPort, proxy);
431

432
        grlcxProxy.addInterceptor(new ProxyInterceptor() {
×
433

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

454
                        // Variant 1:
455
                        req.putHeader("Content-Type", "application/sparql-query");
456
                        req.setBody(Body.body(Buffer.buffer(grlcSpec.expandQuery())));
457
                        // Variant 2:
458
                        //req.putHeader("Content-Type", "application/x-www-form-urlencoded");
459
                        //req.setBody(Body.body(Buffer.buffer("query=" + URLEncoder.encode(grlcSpec.getExpandedQueryContent(), Charsets.UTF_8))));
460

461
                        req.setURI("/rdf4j-server/repositories/" + grlcSpec.getRepoName());
462
                        logger.info("Forwarding apix request to /rdf4j-server/repositories/{}", grlcSpec.getRepoName());
463
                    } catch (InvalidGrlcSpecException ex) {
464
                        logger.warn("Bad API request for '{}' with params {}: {}", req.getURI(), req.proxiedRequest().params(), ex.getMessage());
465
                        return Future.succeededFuture(context.request()
466
                                .response()
467
                                .setStatusCode(400)
468
                                .putHeader("Content-Type", "text/plain")
469
                                .setBody(Body.body(Buffer.buffer("Bad request: " + ex.getMessage()))));
470
                    } catch (Exception ex) {
471
                        logger.error("Unexpected error for API request '{}' with params {}", req.getURI(), req.proxiedRequest().params(), ex);
472
                        return Future.succeededFuture(context.request()
473
                                .response()
474
                                .setStatusCode(500)
475
                                .putHeader("Content-Type", "text/plain")
476
                                .setBody(Body.body(Buffer.buffer("Unexpected error: " + ex.getMessage()))));
477
                    }
478
                }
479
                return ProxyInterceptor.super.handleProxyRequest(context);
480
            }
481

482
            @Override
483
            @GeneratedFlagForDependentElements
484
            public Future<Void> handleProxyResponse(ProxyContext context) {
485
                logger.info("Receiving api response");
486
                ProxyResponse resp = context.response();
487
                resp.putHeader("Access-Control-Allow-Origin", "*");
488
                resp.putHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS");
489
                resp.putHeader("Content-Disposition", "inline");
490
                return ProxyInterceptor.super.handleProxyResponse(context);
491
            }
492

493
        });
494
        proxyRouter.route(HttpMethod.GET, "/api/*").handler(ProxyHandler.create(grlcxProxy));
495

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

502
        proxyServer.requestHandler(req -> {
503
            applyGlobalHeaders(req.response());
504
            proxyRouter.handle(req);
505
        });
506
        proxyServer.listen(9393);
507

508
        // Periodic metrics update. Runs on a dedicated single-thread scheduled executor
509
        // (not on the Vert.x event loop) because `updateMetrics` can fall through to a
510
        // synchronous HTTP call in `TripleStore.getRepositoryNames()` when the cache has
511
        // been invalidated. `scheduleWithFixedDelay` naturally serialises ticks and cannot
512
        // pile up if the work occasionally runs long. Same pattern as `JellyNanopubLoader.loadUpdates`
513
        // below.
514
        Executors.newSingleThreadScheduledExecutor()
515
                .scheduleWithFixedDelay(collector::updateMetrics, 1, 1, TimeUnit.SECONDS);
516

517

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

580
            // Seed the TrustStateRegistry from any persisted pointer before the
581
            // periodic poll begins, so the first tick doesn't re-materialize state
582
            // we already have.
583
            TrustStateLoader.bootstrap();
584

585
            // Drop any npass:* graph that isn't the current-pointer target —
586
            // leftovers from builds interrupted by a crash.
587
            if (FeatureFlags.spacesEnabled()) {
588
                AuthorityResolver.get().cleanOrphans();
589
            }
590

591
            // Start periodic nanopub loading
592
            logger.info("Starting periodic nanopub loading...");
593
            var executor = Executors.newSingleThreadScheduledExecutor();
594
            executor.scheduleWithFixedDelay(
595
                    JellyNanopubLoader::loadUpdates,
596
                    JellyNanopubLoader.UPDATES_POLL_INTERVAL,
597
                    JellyNanopubLoader.UPDATES_POLL_INTERVAL,
598
                    TimeUnit.MILLISECONDS
599
            );
600

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

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

658
        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
659
            try {
660
                logger.info("Gracefully shutting down...");
661
                TripleStore.get().shutdownRepositories();
662
                vertx.close().toCompletionStage().toCompletableFuture().get(5, TimeUnit.SECONDS);
663
                logger.info("Graceful shutdown completed");
664
            } catch (Exception ex) {
665
                logger.info("Graceful shutdown failed", ex);
666
            }
667
        }));
668
    }
669

670
    private String getResourceAsString(String file) {
671
        InputStream is = getClass().getClassLoader().getResourceAsStream("com/knowledgepixels/query/" + file);
672
        try (Scanner s = new Scanner(is).useDelimiter("\\A")) {
673
            String fileContent = s.hasNext() ? s.next() : "";
674
            return fileContent;
675
        }
676
    }
677

678
    private static void handleRedirect(RoutingContext req, String path) {
679
        String queryString = "";
680
        if (!req.queryParam("query").isEmpty())
681
            queryString = "?query=" + URLEncoder.encode(req.queryParam("query").getFirst(), Charsets.UTF_8);
682
        if (req.queryParam("for-type").size() == 1) {
683
            String type = req.queryParam("for-type").getFirst();
684
            req.response().putHeader("location", path + "/type/" + Utils.createHash(type) + queryString);
685
            req.response().setStatusCode(301).end();
686
        } else if (req.queryParam("for-pubkey").size() == 1) {
687
            String type = req.queryParam("for-pubkey").getFirst();
688
            req.response().putHeader("location", path + "/pubkey/" + Utils.createHash(type) + queryString);
689
            req.response().setStatusCode(301).end();
690
        } else if (req.queryParam("for-user").size() == 1) {
691
            String type = req.queryParam("for-user").getFirst();
692
            req.response().putHeader("location", path + "/user/" + Utils.createHash(type) + queryString);
693
            req.response().setStatusCode(301).end();
694
        }
695
    }
696

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