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

knowledgepixels / nanopub-query / 31705923878

13 Aug 2026 01:38PM UTC coverage: 76.437% (+0.2%) from 76.255%
31705923878

push

github

web-flow
Merge pull request #187 from knowledgepixels/feat/protected-nanopub

feat: recognize npx:ProtectedNanopub type

836 of 1238 branches covered (67.53%)

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
                    req.response().setStatusCode(400).end(ex.getMessage());
402
                } else {
403
                    req.response().setStatusCode(500).end("Unexpected error: " + ex.getMessage());
404
                }
405
            });
406
        });
407

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

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

425
        HttpProxy grlcxProxy = HttpProxy.reverseProxy(httpClient);
426
        grlcxProxy.origin(proxyPort, proxy);
427

428
        grlcxProxy.addInterceptor(new ProxyInterceptor() {
×
429

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

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

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

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

487
        });
488
        proxyRouter.route(HttpMethod.GET, "/api/*").handler(ProxyHandler.create(grlcxProxy));
489

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

496
        proxyServer.requestHandler(req -> {
497
            applyGlobalHeaders(req.response());
498
            proxyRouter.handle(req);
499
        });
500
        proxyServer.listen(9393);
501

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

511

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

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

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

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

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

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

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

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

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

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