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

knowledgepixels / nanodash / 43454977307

13 Nov 2026 03:40PM UTC coverage: 55.99% (-0.01%) from 56.003%
43454977307

push

github

web-flow
Merge pull request #925 from knowledgepixels/fix/889-retry-after

fix(api-cache): wait as long as a refusing query server asks (#889)

6790 of 12996 branches covered (52.25%)

Branch coverage included in aggregate %.

11731 of 20083 relevant lines covered (58.41%)

9.68 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

59.34
src/main/java/com/knowledgepixels/nanodash/QueryApiAccess.java
1
package com.knowledgepixels.nanodash;
2

3
import org.apache.commons.lang3.tuple.Pair;
4
import org.eclipse.rdf4j.model.IRI;
5
import org.nanopub.extra.services.*;
6
import org.slf4j.Logger;
7
import org.slf4j.LoggerFactory;
8

9
import java.util.concurrent.ConcurrentHashMap;
10
import java.util.concurrent.ConcurrentMap;
11

12
/**
13
 * Utility class for accessing and managing API queries.
14
 * Provides methods to retrieve query results, manage query IDs, and fetch the latest versions of nanopublications.
15
 */
16
public class QueryApiAccess {
17

18
    private QueryApiAccess() {
19
    }  // no instances allowed
20

21
    // Query IDs (full id = RA.../query-name)
22
    public static final String GET_LATEST_NANOPUBS_FROM_PUBKEYS = "RAe-oA5eSmkCXCALZ99-0k4imnlI74KPqURfhHOmnzo6A/get-latest-nanopubs-from-pubkeys";
23
    public static final String GET_LATEST_NANOPUBS_FROM_USERID = "RAuy4N1h4vZ1wgBUMvTiWw2y_Y0_5oFYRTwdq-xj2qqNM/get-latest-nanopubs-from-userid";
24
    public static final String GET_LATEST_USERS = "RAr27GmRUKQmvPbfmB34N9l9lX-xYK7nQhvOMbQCk3byI/get-latest-users";
25
    public static final String GET_MOST_RECENT_NANOPUBS = "RAYNg6rfvXIVvJY2u8oS0EEjxnVvimLLVZG1rOar_nWIY/get-most-recent-nanopubs";
26
    public static final String GET_PUBLISHER_VERSION = "RAPGhXDRzeGu-Qk0AkjleEtxMxqAvJ-dZn7985gzAbyhs/get-publisher-version";
27
    public static final String GET_LATEST_VERSION_OF_NP = "RAiRsB2YywxjsBMkVRTREJBooXhf2ZOHoUs5lxciEl37I/get-latest-version-of-np";
28
    // Minimal single-lookup probe for whether a given nanopub has been loaded by the
29
    // answering Nanopub Query instance; used to time post-publish refreshes (issue #629).
30
    public static final String CHECK_NANOPUB_LOADED = "RAxqXyhP1fnjvDdX-K0z9TgnwoXf462FxV1wEAWRm_gos/check-nanopub-loaded";
31
    // The later milestone the space listing queries actually depend on: not that the
32
    // nanopub arrived, but that the authority resolver has worked out what it grants and
33
    // written that into the current space state.
34
    public static final String CHECK_NANOPUB_MATERIALIZED = "RAQyt1Xt3_EcDD1AomQgLIbduvwMiQQvHTm4PwTOlJPbE/check-nanopub-materialized";
35
    public static final String GET_ALL_USER_INTROS = "RAjHh6P11QFUaoPiMRBavdAnTq4YMJW4PB85oVFSBfYjU/get-all-user-intros";
36
    public static final String GET_ALL_USER_PROFILE_PICS = "RAtcodMPmTrmBvdOqwYIrNNFDO74f8B_xo0qsOcKlCwTA/get-all-user-profile-pics";
37
    // Profile pictures of spaces and maintained resources (issue #632), declared as
38
    // schema:image on the resource IRI. Unlike the user pictures above -- self-declared and
39
    // read from a subject-agnostic query -- these are gated on the declaring nanopub being
40
    // signed by a current admin of the governing space ref, so a third party cannot set a
41
    // space's picture. Ordered newest first; the first row wins.
42
    public static final String GET_RESOURCE_PROFILE_PICTURE = "RALK8_WQPtAbMUv2IvHeZyUU1WjD77V4a3hb0KsiZI0tI/get-resource-profile-picture";
43
    public static final String GET_ALL_USER_DEFAULT_LICENSE = "RA-_IwzReR2_HfTLz4YcNM6Mh3Vt16y0RUS12tpJTN9FI/get-all-user-default-license";
44
    public static final String GET_MONTHLY_TYPE_OVERVIEW_BY_PUBKEYS = "RAhI-C2KsqS_IvnxwyBrbMFsoj65dhLWE_CBo_KtcVEVA/get-monthly-type-overview-by-pubkeys";
45
    public static final String GET_INTRODUCING_NANOPUB = "RALZXWg5lZoJoQ0VHL5mpDgNxYpqU6FoDLWGp4rs8A6b8/get-introducing-nanopub";
46
    public static final String FULLTEXT_SEARCH = "RAxdh5xkc6K6SMLY23yKu__zTWJPXeRFc0qgNNxkbOkpY/fulltext-search";
47
    // Ordered newest first before the limit, so that a guided choice offers the newest ten
48
    // matches instead of an arbitrary ten (issue #797). The versions before this one are
49
    // still named by published templates, which NanopubQueryLookup reads as this one.
50
    public static final String FIND_THINGS = "RAom4OoQ8U2K6A629YRXKo9-XU-ZJM7-KZs1h11OD6c1w/find-things";
51
    public static final String GET_NEWER_VERSIONS_OF_NP = "RAqmmNSxQaRNWRYH0o4Da3GSOwvoFLObhXfAGUCOqEtfw/get-newer-versions-of-np";
52
    public static final String GET_LATEST_THING_NANOPUB = "RAzXDzCHoZmJITgYYquLwDDkSyNf3eKKQz9NfQPYB1cyE/get-latest-thing-nanopub";
53
    // Node-anchored variants (label/tag/unlisted read off the typed template node, so
54
    // templates with embedded identity list correctly); derived from, not superseding,
55
    // the RA6bgrU3/RA4bt3MQ/RAMcdiJp originals, which are update-locked to another key.
56
    // v3 dedups governed version pairs: a version declaring dct:isVersionOf +
57
    // gen:governedBy is listed only if it is its (kind, space) pair's current governed
58
    // winner (in-SPARQL Option A of the listing-dedup problem; the nanopub-query#138
59
    // canonical-version edge would replace these arms).
60
    // v4 (RAi6EPio/RA4ynLpm/RAxzYV8P, superseding RAoEo6jL/RAl2C9PT/RAGxzVO9) keeps the same
61
    // semantics but materializes the governed winners once, in a single-row group_concat
62
    // sub-select that shares no variables with the outer query, and tests membership by string
63
    // containment. The v3 arms joined that sub-select under an optional: correct only because
64
    // RDF4J's left join is non-standard (under strict SPARQL semantics the unbound cross-join
65
    // would drop every non-governed template), and at risk of re-evaluating the federated
66
    // spaces-repo SERVICE per row. Verified identical row counts (656/26/38) against v3.
67
    // The three listing queries require the typed template node to carry at least one
68
    // nt:hasStatement, as get-all-templates does: a nanopublication that only claims the
69
    // type -- a maintained-resource declaration of a template's version-independent IRI, a
70
    // preset assignment, an FDO/SHACL profile -- defines no form and cannot be parsed as a
71
    // template. Before this they were listed and then failed to load, with a stack trace per
72
    // entry (77 assertion, 1 provenance, 1 pubinfo rows network-wide).
73
    public static final String GET_ASSERTION_TEMPLATES = "RA1RlUGUZ1cUJYzT00k2PaX-nHgpczcJiFjVSzxMtXVTA/get-assertion-templates";
74
    public static final String GET_PROVENANCE_TEMPLATES = "RAd49_ERRKQxWqrXZ0Gdy9cluP9H8vbCTtW5Un4yKBVqw/get-provenance-templates";
75
    public static final String GET_PUBINFO_TEMPLATES = "RAi5QKbupXbqI0JGyHJBAZVB3MYfG3PkiPyJrI13XEQ8s/get-pubinfo-templates";
76
    public static final String GET_LATEST_ACCEPTED_BDJ = "RAkoDiXZG_CYt978-dZ_vffK-UTbN6e1bmtFy6qdmFzC4/get-latest-accepted-bdj";
77
    public static final String GET_LATEST_BIODIV_CANDIDATES = "RAgnLJH8kcI_e488VdoyQ0g3-wcumj4mSiusxPmeAYsSI/get-latest-biodiv-candidates";
78
    public static final String GET_LATEST_ACCEPTED_DS = "RATpsBysLf8yXeMpY7PHKj-aKNCa4-4Okg1hi97OLDXIo/get-latest-accepted-ds";
79
    public static final String GET_LATEST_DS_CANDIDATES = "RAFNTW3jhWKnNvhMSOfYvG53ZAurxrFv_-vnIJkZyfAuo/get-latest-ds-candidates";
80
    public static final String GET_DS_REACTIONS = "RA0FiH8gukovvEHPBMn72zUDdMQylQmUwtIGNLYBZXGfk/get-ds-reactions";
81
    public static final String GET_LATEST_ACCEPTED_RIO = "RAAXmnJdXHO86GqJs8VTdqapUWqCrHKRgRT2b4NfjAfgk/get-latest-accepted-rio";
82
    public static final String GET_LATEST_RIO_CANDIDATES = "RAehKOCOnZ3uDBmI0kkCNTh5k9Nl6YYNj7tyc20tVymxY/get-latest-rio-candidates";
83
    public static final String GET_REACTIONS = "RAe7k3L0oElPOrFoUMkUhqU9dGUqfBaUSw3cVplOUn3Fk/get-reactions";
84
    public static final String GET_TERM_DEFINITIONS = "RAZUsK7jU85oUYEVKvMPFlqbwn19oR55IQuFkXuiS_Tkg/get-term-definitions";
85
    // v10 (issue #302): standalone + preset-supplied views (unbound ?display), gated to
86
    // admins/maintainers of the owning space or the affected user themselves. Each
87
    // referenced view is resolved to its latest version server-side: the version tree's
88
    // most recent current head (a nanopub itself neither superseded nor validly retracted
89
    // via npx:invalidates), robust to backdated supersedes and retracted versions, so
90
    // ?view is already the latest and needs no separate per-view lookup. v10 wraps that
91
    // resolution in a run-once sub-SELECT so the cross-repo lookup federates once for the
92
    // whole view set instead of once per referenced view -- cut a 44-display page from
93
    // ~4.5s to ~1.7s (the per-view federation round-trips were the dominant cost).
94
    // RAlOsra- (supersedes the broken RAyXaBuR, which had a double-slash op IRI from a trailing
95
    // slash on the sub: prefix) gates the view-version-resolution npx:invalidates filters on the
96
    // version nanopub's own signing pubkey (issue #487); no-regression verified across resources
97
    // incl. a 45-display user page.
98
    // RA4TGV_z (supersedes RAd105Rj) replaces the bare-IRI isMaintainedBy? authority hop and the
99
    // dead RoleDeclaration maintainer arm with a single npa:hasGoverningSpaceRef gate keyed on the
100
    // materialized npa:hasRoleType (nanopub-query#130 / issue #510); fixes maintainer visibility and
101
    // cross-ref bleed. No-regression verified against RAd105Rj across resources.
102
    // RArKslem (supersedes RA4TGV_z) adds space-governed version resolution (gen:governedBy;
103
    // docs/views-and-presets-as-maintained-resources.md): a referenced version declaring a
104
    // governing space resolves to the newest member+-signed version of its (kind, space)
105
    // pair via a run-once governed sub-select, falling back to the pinned version.
106
    // RAWlJqJ5 (supersedes RArKslem): same semantics, endpoint rebased from the ViewDisplay
107
    // type repo onto repo/full, cutting the query from 5 SERVICE clauses to 2 (only the
108
    // repo/spaces state lookups remain federated). The per-hop federation was the main
109
    // amplifier of the rdf4j connection-pool deadlock behind the fleet-wide /api wedges
110
    // (nanopub-query, 2026-08-20 thread dump: 22 of 28 pool-blocked threads were this
111
    // query). Validated byte-identical across standalone/preset/governed/self-page cases.
112
    // RA3ekD-2 (supersedes RAWlJqJ5) adds the pending-account self-arm (issue #625 /
113
    // nanopub-query#195): the own-page branch of the authority gate additionally accepts
114
    // npa:PendingAccountState rows (mirrored from authoritative introductions of users not
115
    // trust-approved yet), so such a user's own page shows the view displays they signed
116
    // themselves. Display-only: the pending class is distinct from npa:AccountState, so the
117
    // admin/maintainer arm and the governed-version resolution keep requiring approved
118
    // accounts. Validated byte-identical to RAWlJqJ5 across approved resources.
119
    // RAwkiytr (supersedes RA3ekD-2) adds ?presetKind to the preset branch (issue #607): the
120
    // assigned preset's stable kind (dct:isVersionOf, falling back to the version IRI), so the
121
    // client keeps only the newest assignment per (preset kind, resource) -- the identity view
122
    // displays already have via view kind. Purely additive; every other column is unchanged
123
    // (validated identical across standalone, preset, governed, self-page and maintained-resource
124
    // cases).
125
    // RAvPNGog (supersedes RAwkiytr) is a performance rewrite with identical results (validated
126
    // across 40 resources): the authority gate becomes a single-row key string tested with
127
    // contains(), since joining its ?pubkey rows let rdf4j start from the signing keys and walk
128
    // every nanopub they signed; the latest-version resolution becomes a bound lookup per
129
    // referenced view instead of a run-once sub-select over every view in the repository; and
130
    // the governed winners are computed once as a single string instead of a per-row
131
    // SERVICE sub-select. ~0.3-0.8s instead of 3.5-12s, and 502s at the 60s cap under load.
132
    public static final String GET_VIEW_DISPLAYS = "RAvPNGogj0GqBiBYBxqvympNd_RHXoxMHKs19bBymAelo/get-view-displays";
133
    // Test head for dropping the server-side view-version resolution (its run-once resolution
134
    // sub-select was the query's dominant cost, linear in the repo-wide view count; see
135
    // nanopub-query doc/design-view-head-materialization.md): ref-scoped like the retired
136
    // GET_VIEW_DISPLAYS_REF (RActfK6C) it replaced -- same inputs (resource + root_np) and the
137
    // same columns plus ?viewKind and ?governedBySpace -- but ?view carries the referenced
138
    // version UNRESOLVED — except for gen:governedBy pins, where it is the space-governed
139
    // resolution. Supersedes-head resolution happens caller-side per view (View.get with
140
    // resolveLatest=true, memoized), which also covers the governed case, so the extra columns
141
    // need not be consulted.
142
    // RAkIkmSi (supersedes RAXdRFNL): endpoint rebased onto repo/full (5 SERVICE -> 2, see
143
    // GET_VIEW_DISPLAYS above); in particular the per-referenced-view pin lookups are now
144
    // local joins instead of one federated round-trip per view under a nested-loop join.
145
    // RAt7dfZO (supersedes RAkIkmSi) adds the same ?presetKind column as GET_VIEW_DISPLAYS
146
    // (issue #607); no other change.
147
    // RA1Pm-iK (supersedes RAt7dfZO) applies the same authority-gate and governed-winner
148
    // rewrites as GET_VIEW_DISPLAYS above; results identical across 35 space/root pairs.
149
    public static final String GET_VIEW_DISPLAYS_UNRESOLVED = "RA1Pm-iKXwZRA0Hl9eDXHts2JBhseuZQJDci9VvixqylA/get-view-displays-unresolved";
150

151
    // Spaces-repo queries (endpoint: nanopub-query .../repo/spaces)
152
    // v3: ref-aware get-spaces (adds ?ref + ?root so the client can key one space per
153
    // ref). Published as an independent nanopub (no npx:supersedes). Active query used by
154
    // SpaceRepository. Source at docs/queries/get-spaces-ref.trig. See
155
    // docs/space-ref-identity.md.
156
    // v4 (RAyXmrfs, supersedes RAD5KmWO) gates the npx:invalidates filter on a shared signing
157
    // pubkey between invalidator and the space-definition nanopub (issue #487).
158
    // RALHRpoL (supersedes RAyXmrfs) is that same query re-published with correct provenance:
159
    // v4 went out signed by the placeholder orcid:0000-0000-0000-0000 and without
160
    // nt:wasCreatedFrom*Template links. The SPARQL is byte-identical (296 rows either way).
161
    public static final String GET_SPACES_REF = "RALHRpoLzFDvEPk_9MWKk4IkQ_BC841f8cs0uXtQnVU4w/get-spaces";
162
    // Disambiguation claimants: one row per ref (root definition) claiming a space IRI, with that
163
    // ref's validated admins (admins_multi_iri). Pass the space IRI; replaces the per-ref
164
    // get-space-admins fan-out with a single fetch. Which ref is the representative (default) is
165
    // decided client-side. Source at docs/queries/list-space-claimants.trig.
166
    // RAYU2MLE (supersedes RApsQhJn) is that same query re-published with correct provenance
167
    // (the original was signed by the placeholder orcid:0000-0000-0000-0000 and carried no
168
    // nt:wasCreatedFrom*Template links); the SPARQL is byte-identical.
169
    public static final String LIST_SPACE_CLAIMANTS = "RAYU2MLEEkLhSfkRYbE9olhuBq19e6g3QY-jfJTmqh0OI/list-space-claimants";
170
    // Space-governed view-version resolution: given a definition kind (dct:isVersionOf
171
    // target), its governing space and the pinned version's nanopub (pin), returns at most
172
    // one row. With the kind validated as maintained by the space: the newest version
173
    // declaring gen:governedBy that space, signed by a current member+ of the space's
174
    // governing ref; empty result = the caller keeps its pinned version (the pin is the
175
    // floor). With the kind not maintained by the space: the single current head of the pin's own
176
    // same-key supersedes chain, as GET_LATEST_VERSION_OF_NP resolves it, so that a
177
    // gen:governedBy declared before the space maintains the kind no longer freezes the pin.
178
    // RAyB49tP supersedes RA833rrc, which superseded RAPSWgzH: RAPSWgzH took no pin and
179
    // returned nothing for a kind the space doesn't maintain, and both it and RA833rrc looked up the
180
    // versions once per member row, starting from every nanopub signed by a member key
181
    // (up to a minute for spaces whose members have signed many nanopubs). RAyB49tP
182
    // gathers the member keys into one row and starts the full-repo lookup from the kind,
183
    // so it runs once; results validated identical across all governed pairs, maintained-kind
184
    // median 0.5s -> 0.2s, worst case 20-60s -> about 1s. Source at
185
    // docs/queries/get-latest-governed-version.trig; see
186
    // docs/views-and-presets-as-maintained-resources.md.
187
    public static final String GET_LATEST_GOVERNED_VERSION = "RAyB49tPLdgMjwmG9alOjtK2wSvxLGPunfncFk57elB-Q/get-latest-governed-version";
188
    public static final String GET_SUB_SPACE_LINKS = "RAWgoQbP9_B9h3Bnwd1FGYX1gLYPyZFOxaeqIeA3TTPSU/get-sub-space-links";
189
    // The label is the resource's own rdfs:label from the declaring nanopublication's
190
    // assertion, falling back to that nanopublication's label. The previous version
191
    // RAOOq81R read only the nanopublication's label, so a nanopublication declaring
192
    // several maintained resources gave all of them the same name (one live nanopub
193
    // declares six) even though each resource carries its own label in the assertion.
194
    // Also one row per resource and space now, newest declaration by dct:created, rather
195
    // than one row per declaration: not a behaviour change, since build() already keeps
196
    // the first row per resource and the query already ordered by descending date, but it
197
    // puts the newest-wins contract in the query rather than in the consumer.
198
    public static final String GET_MAINTAINED_RESOURCES = "RAEdX-wzz7vfswC5Y6sbL7XeUyJrL2BKT-luDHPZZpmRY/get-maintained-resources";
199
    public static final String GET_SPACE_ADMINS = "RAaHOXMQ7Kq37T9syR9at0RqushclHenlPOFRwFDn0Cfs/get-space-admins";
200
    // Ref-scoped admins (Stage 2): takes the ref's root nanopub (root_np), matches admins
201
    // on npa:forSpaceRef, so multi-ref spaces don't merge admin sets across refs. Published
202
    // independently. Source at docs/queries/get-space-admins-ref.trig. See
203
    // docs/space-ref-identity.md.
204
    public static final String GET_SPACE_ADMINS_REF = "RAWM8qlKbV3DEH_NsPJ6hIyTrBwIp8sNeg9MGDgu8la1o/get-space-admins";
205
    public static final String GET_SPACE_ADMIN_PUBKEY_HASHES = "RAJvvNY6KXqveJivZKh-chTCntrsY_KJSGLVNRQdi0pUc/get-space-admin-pubkey-hashes";
206
    // Ref-scoped admin pubkey hashes (Stage 2): takes the ref's root nanopub (root_np),
207
    // matches admins on npa:forSpaceRef, so multi-ref spaces don't merge admin keys across
208
    // refs. Published independently. Source at docs/queries/get-space-admin-pubkey-hashes-ref.trig.
209
    public static final String GET_SPACE_ADMIN_PUBKEY_HASHES_REF = "RAO8KDdS4_Z0-R1qCSKqWcewg0WUSaiQDh_p1N1Bg-zic/get-space-admin-pubkey-hashes";
210
    // 2026-09-11: the six role-listing queries below (get-space-roles, get-space-roles-ref, list-space-observers-ref,
211
    // list-space-non-approved-ref, list-space-members-ref, list-space-roles-ref) were superseded to read the role name via
212
    // schema:name in BOTH schemes (http://schema.org/ and https://schema.org/): nanopub-java >= 1.93.0 blacklists the
213
    // http form, so new roles carry https://schema.org/name and showed up as a bare "role" in the About tab.
214
    public static final String GET_SPACE_ROLES = "RAr9zGmPYtJwRK2m0pOwGrhsfhS7i3bqog27mILED6wjc/get-space-roles";
215
    // Ref-scoped roles (Stage 2): takes the ref's root nanopub (root_np), matches
216
    // RoleAssignments on npa:forSpaceRef, so multi-ref spaces don't merge role sets across
217
    // refs. Published independently. Source at docs/queries/get-space-roles-ref.trig.
218
    public static final String GET_SPACE_ROLES_REF = "RATwohQqQwgra4nu0CYEmJCpc-Xo1xz2xb1IVc544D28U/get-space-roles";
219
    public static final String GET_SPACE_MEMBERS = "RAo0c4UNoD-uTP3xATU_-TB6vO-nMO4Ya-mvdaGjX5qVE/get-space-members";
220
    // Ref-scoped members (Stage 2): takes the ref's root nanopub (root_np), resolves the
221
    // ref + its space IRI, and returns ALL non-admin RoleInstantiations naming that IRI
222
    // (raw npa:spacesGraph, matching the looser pre-migration semantic), each with a
223
    // ?validated flag = whether it is also in the trust-state-validated current-state graph
224
    // (i.e. the agent's key has a trust-approved AccountState from an accepted intro). Shows
225
    // every self-declared member while flagging the un-introduced ones, rather than hiding
226
    // them. Published independently. Source at docs/queries/get-space-members-ref.trig.
227
    // RA2eGba0 (supersedes RAqp9TSM) gates the npx:invalidates filter on a shared signing pubkey
228
    // between invalidator and the member declaration (issue #487).
229
    // RAPYJ7HL (supersedes RA2eGba0) is that same query re-published with correct provenance
230
    // (RA2eGba0 was signed by the placeholder orcid:0000-0000-0000-0000 and carried no
231
    // nt:wasCreatedFrom*Template links); the SPARQL is byte-identical.
232
    public static final String GET_SPACE_MEMBERS_REF = "RAPYJ7HL7UiPQA1vHocyHYL99bKuaaKddfefrgW2zyA-Y/get-space-members";
233
    // Ref-scoped observers (Stage 2): takes the ref's root nanopub (root_np), lists observers
234
    // INCLUDING un-introduced self-declared ones (not in the validated state), each flagged
235
    // via a headerless ?unverified_noheader column (⚠️ when unvalidated). Drives the existing
236
    // Observers view's table (the view nanopub is left untouched). Published independently.
237
    // v3 (RAZ41V9K, supersedes RA58KSjh) (a) resolves owl:sameAs space aliases via the ref's
238
    // validated npa:sameAsSpace edges, so observer roles declared against an alias IRI of the
239
    // space are included, and (b) lists EVERY observer-tier association — no longer hiding users
240
    // who also hold a higher-tier (admin/maintainer/member) role, so an admin who is also a
241
    // participant appears here for that participant role. The built-in admin property and
242
    // genuine higher-tier role declarations are still excluded; non-approved higher-tier claims
243
    // go to LIST_SPACE_NON_APPROVED_REF. v4 (RAobkcQi, supersedes RAZ41V9K) gates the
244
    // npx:invalidates filter on a shared signing pubkey (npa:hasValidSignatureForPublicKeyHash)
245
    // between invalidator and target, so a foreign-key retraction can no longer hide an observer
246
    // (issue #487; mirrors the materializer's #112 same-publisher gate). v5 (RAUQdhb2, supersedes
247
    // RAobkcQi) fixes a regression introduced in v3: the space-alias resolution used a
248
    // `{ bind(?spaceIri as ?inSpace) } union { ... sameAsSpace ... }` pattern, but RDF4J does not
249
    // propagate the outer ?spaceIri into a BIND inside a UNION branch, leaving ?inSpace unbound so
250
    // the query returned ZERO observers for every space. Replaced with a non-union
251
    // `filter( ?inSpace = ?spaceIri || exists { ... sameAsSpace ... } )`. Source at
252
    // docs/queries/list-space-observers-ref-v5.trig.
253
    // Latest (RAoW4pMA, nanodash#498): a member is excluded from the observers list only when they
254
    // hold a VALIDATED higher tier, read directly off a gen:RoleInstantiation (npa:hasRoleType in
255
    // {AdminRole,MaintainerRole,MemberRole}) in the current space state — replacing the global
256
    // RoleDeclaration matching that mis-excluded observers whose predicate was declared at a higher
257
    // tier by another space (which had returned ZERO observers for spaces like vu/ucds). Enabled by
258
    // nanopub-query persisting tier on the instantiation (nanopub-query#125 + #127). RAZNHDFQ
259
    // (supersedes RAoW4pMA) drops the role-label coalesce to read schema:name only. Latest
260
    // (RAQylZL4, supersedes RAZNHDFQ) BUGFIX: the RAoW4pMA/#498 higher-tier exclusion dropped a
261
    // member from the observers list whenever they held ANY validated higher-tier role, so an
262
    // admin/maintainer/member who also holds a separate genuinely observer-tier role (e.g. an
263
    // admin who is also a planned attendant) was hidden from the observer list entirely — every
264
    // observer of a space whose observers are also its admins returned ZERO rows. The check is now
265
    // scoped to the SAME role property ((npa:regularProperty|npa:inverseProperty) ?roleProp on
266
    // ?vriH), so a higher tier held through a different property no longer suppresses the observer
267
    // association, while the #498 tier-collision fix (same property validated at a higher tier)
268
    // is preserved. RAt8PKQ2 (supersedes RARcL1s1, adding the hidden revokeAgent action-mapping column; RARcL1s1 superseded RAQylZL4) distinguishes pending accounts (issue #625 /
269
    // nanopub-query#195): an association validated only through a pending account — the
270
    // materialized RoleInstantiation carries npa:trustStatus npa:seen, produced by the
271
    // PendingAccountState self-arm for observer-tier self-signups of introduced-but-unapproved
272
    // users — shows ⏳ in the headerless flag column (empty = approved-validated, ⏳ =
273
    // pending-validated, ⚠️ = not validated at all). Latest (RANXPEIi, supersedes RAt8PKQ2) adds a
274
    // member_label column so each agent shows by name: the canonical foaf:name mirrored into the
275
    // current space state, falling back to the foaf:name asserted for that agent in the grant
276
    // nanopub's pubinfo. Most role holders have no key introduction of their own, so without the
277
    // fallback they rendered as bare ORCIDs; purely self-declared claims that carry no name
278
    // anywhere still show their IRI.
279
    public static final String LIST_SPACE_OBSERVERS_REF = "RAy7MVefpFPFBhxDBh5sFzw6S5H-gCH5yJ2dENH1ackKI/list-space-observers";
280

281
    // Ref-scoped non-approved role claims (root_np): agents holding a higher-tier role
282
    // instantiation (admin/maintainer/member) that is NOT in the validated state — a
283
    // self-assigned or otherwise ungranted claim awaiting approval by an equal-or-higher-tier
284
    // member. Observer-tier roles are excluded (self-assignable, so they need no approval and
285
    // are listed by LIST_SPACE_OBSERVERS_REF). Drives the "❓ Pending
286
    // Admins/Maintainers/Members" view. v3 (RA2BnCGv, supersedes RAZMAChi) resolves owl:sameAs
287
    // space aliases via the ref's validated npa:sameAsSpace edges, so a higher-tier claim made
288
    // against an alias IRI of the space is detected. v4 (RAwv7GRc, supersedes RA2BnCGv) gates the
289
    // npx:invalidates filter on a shared signing pubkey between invalidator and target, so a
290
    // foreign-key retraction can no longer suppress a pending claim (issue #487; mirrors the
291
    // materializer's #112 same-publisher gate). v5 (RAtSaYBH, supersedes RAwv7GRc) fixes the same
292
    // v3 regression as the observers query: the `{ bind(?spaceIri as ?inSpace) } union { ...
293
    // sameAsSpace ... }` alias pattern left ?inSpace unbound on RDF4J (BIND in a UNION branch does
294
    // not see the outer ?spaceIri), so the query returned ZERO rows for every space (no pending
295
    // claim could ever surface). Replaced with a non-union
296
    // `filter( ?inSpace = ?spaceIri || exists { ... sameAsSpace ... } )`. v6 (RAhSqdJ6, supersedes
297
    // RAtSaYBH via the RAPo1zp2 intermediate) adds an approve_np column with the granting
298
    // nanopub. Latest (RAVsaIwA, supersedes RAhSqdJ6; issue #603): the admin-only
299
    // roleAssignmentTemplate and agent_iri columns are replaced by a per-row
300
    // (approve_np, grant_template) pair — the grant nanopub and its own creation template
301
    // (nt:wasCreatedFromTemplate, free-form template as fallback) — so the view's approve
302
    // action can open the pending grant in derive mode for EVERY tier, not only for admin
303
    // grants. The tier column is deterministic (the highest tier among the member's pending
304
    // claims, rank-keyed min instead of a flapping sample), and the pair is computed from
305
    // the SAME grant via a rank-prefixed concatenated min preferring that highest tier, so
306
    // tier, derive target, and template always agree. A grant whose assertion defines a
307
    // Space itself (a competing root definition) is not offered for derivation; admin-tier
308
    // claims from such definitions pair with the built-in admin-assignment template instead
309
    // (the hasAdmin triple unifies), keeping the space-ref-conflict remedy.
310
    // Source at docs/queries/list-space-non-approved-ref-v7.trig. v8 (RAoX3Htu, supersedes
311
    // RAVsaIwA) adds a member_label column, sourced like the observers query above.
312
    public static final String LIST_SPACE_NON_APPROVED_REF = "RA8r_O22FL53frfrmudFKMB-g7S-H0HU78O7uDiOx4WZ4/list-space-non-approved";
313

314
    // Ref-scoped variants of three About-tab *view* display queries (distinct from the
315
    // GET_SPACE_*_REF client-authority queries above). Each takes the ref's root nanopub
316
    // (root_np), resolves the ref via npa:rootNanopub, and scopes by npa:forSpaceRef (members,
317
    // roles) or the ref-level npa:hasSubSpace edge (sub-spaces), so a ?root=-pinned space page
318
    // shows only that one ref's listings rather than merging all refs claiming the IRI. (The
319
    // maintained-resources listing did the same with the npa:hasMaintainedResource edge until
320
    // its view's own query took the space plus an optional root_np, so it is view-driven now.)
321
    // Column-compatible with the IRI-keyed view queries, so they drive the existing view
322
    // nanopubs unchanged (the observers pattern). Used by AboutSpacePanel with an IRI-keyed
323
    // fallback when the ref root is unknown. Published independently (no npx:supersedes).
324
    // Sources at docs/queries/list-*-ref.trig. See docs/space-ref-identity.md.
325
    // v3 (RApyKS9D): reads each membership's tier directly off the materialized gen:RoleInstantiation
326
    // (npa:hasRoleType) and its role (gen:hasRole) in the current space state, now that nanopub-query
327
    // persists tier on the instantiation (nanopub-query#125 + #127). Simplifies away the earlier
328
    // RoleAssignment-scoping workaround and the global RoleDeclaration matching that leaked observer-tier
329
    // members into the Approved listing. See nanodash#498. RAJ15No3 (supersedes RA7E54m5, adding the hidden revokeAgent action-mapping column; RA7E54m5 superseded RApyKS9D)
330
    // drops the role-label coalesce to read schema:name only. Latest (RA-90ZiE, supersedes RAJ15No3)
331
    // adds a member_label column, sourced like the observers query above, and orders rows by tier and
332
    // then by that display name.
333
    public static final String LIST_SPACE_MEMBERS_REF = "RAroCpts3CpuUpSsuPpccRbyKkwkOvVNQSjoY0ZYAVvBg/list-space-members";
334
    public static final String LIST_SPACE_ROLES_REF = "RAYOsITlBsY5vmlPmZuMnsJQvwIss9DfjdWW0VjgLkMjE/list-space-roles";
335
    public static final String LIST_SUB_SPACES_REF = "RA-j0DFqkNUHxF_WIds8wWJix6DkDFBmUBWmKXfG24XYQ/list-sub-spaces";
336

337
    // View-displays listing queries are no longer referenced here: the About-tab view-displays
338
    // tables are view-driven (gen:hasViewQuery on the space/user/maintained view nanopubs), and the
339
    // panels pass the resource + (for spaces/maintained) the ref's root nanopub as params. The
340
    // ref-scoped query requires root_np; the IRI-keyed variant backs the users' view. See
341
    // docs/queries/list-view-displays{,-ref}.trig.
342

343
    // The part view-displays listing is not referenced here either: AboutPartPanel takes it
344
    // from the part view nanopub's gen:hasViewQuery and passes resource + partid + partclass.
345

346
    // Ref-scoped preset-assignment listing (root_np): reads the server-materialised
347
    // npa:PresetAssignment rows scoped by npa:forSpaceRef from the validated current space-state
348
    // graph (nanopub-query #122 ref-stamps each admin-authored assignment per ref), with
349
    // latest-by-date-per-(preset,resource) + npa:isActivated gating (a deactivation is a newer
350
    // admin-authored row). Column-identical to the IRI-keyed list-preset-assignments, so it drives
351
    // the existing Preset assignments view unchanged. Used by AboutSpacePanel with an IRI-keyed
352
    // fallback when the ref root is unknown. Source at docs/queries/list-preset-assignments-ref.trig.
353
    // RArC6iR- (supersedes RA3zdn0g, itself the head this constant had been left behind by)
354
    // keys an assignment on the preset's stable kind rather than the pinned version, and adds the
355
    // version columns behind the view's "update to latest version" action (issue #607).
356
    // RArXnUQf (supersedes RArC6iR-) replaces the earlier blank-header notice with a proper
357
    // "version" column: version_label is the displayed verdict ("latest" / "⬆️ update available")
358
    // and version the dates behind it, since the renderer shows a literal column's _label
359
    // companion and puts the principal value in the tooltip. Column-compatible with the IRI-keyed
360
    // variant, which the view supplies for non-space pages.
361
    public static final String LIST_PRESET_ASSIGNMENTS_REF = "RArXnUQf2dQguqlteWMwKVWxIpnk5xzF4ppAokGkpuOn8/list-preset-assignments";
362

363
    private static final Logger logger = LoggerFactory.getLogger(QueryApiAccess.class);
9 ✔
364

365
    private static ConcurrentMap<String, Pair<Long, String>> latestVersionMap = new ConcurrentHashMap<>();
15 ✔
366

367
    private static final String queryIriPattern = "^(.*[^A-Za-z0-9-_])(RA[A-Za-z0-9-_]{43})[/#]([^/#]+)$";
368

369
    /**
370
     * Forces the retrieval of an API response for a given query name and parameters.
371
     * Retries for up to 30 seconds, until a valid response is received — unless the query
372
     * servers refuse the query. A refusal is a server asking not to be sent this query for
373
     * now, so asking again within the same attempt is exactly what it must not get; it goes
374
     * to the caller instead, which knows from it when to try again (issue #889).
375
     *
376
     * @param queryRef The query reference
377
     * @return The API response.
378
     * @throws org.nanopub.extra.services.QueryRefusedException If the query servers refused the query.
379
     */
380
    public static ApiResponse forcedGet(QueryRef queryRef) throws QueryRefusedException {
381
        long deadline = System.currentTimeMillis() + 30_000;
12 ✔
382
        long sleepMs = 1000;
6 ✔
383
        while (System.currentTimeMillis() < deadline) {
12 !
384
            try {
385
                ApiResponse resp = QueryApiAccess.get(queryRef);
9 ✔
386
                if (resp != null) {
6 ✔
387
                    return resp;
6 ✔
388
                }
389
            } catch (QueryRefusedException ex) {
3 ✔
390
                throw ex;
6 ✔
391
            } catch (Exception ex) {
×
392
                logger.error("Error while forcing API get for query {}", queryRef, ex);
×
393
            }
3 ✔
394
            try {
395
                Thread.sleep(Math.min(sleepMs, Math.max(0, deadline - System.currentTimeMillis())));
24 ✔
396
                sleepMs = Math.min(sleepMs * 2, 16_000);
18 ✔
397
            } catch (InterruptedException ex) {
×
398
                Thread.currentThread().interrupt();
×
399
                break;
×
400
            }
3 ✔
401
        }
402
        throw new RuntimeException("Timed out forcing API get for query: " + queryRef);
×
403
    }
404

405
    /**
406
     * Retrieves an API response for a given query reference.
407
     *
408
     * @param queryRef The query reference
409
     * @return The API response.
410
     * @throws org.nanopub.extra.services.FailedApiCallException         If the API call fails.
411
     * @throws org.nanopub.extra.services.APINotReachableException       If the API is not reachable.
412
     * @throws org.nanopub.extra.services.NotEnoughAPIInstancesException If there are not enough API instances.
413
     */
414
    public static ApiResponse get(QueryRef queryRef) throws FailedApiCallException, APINotReachableException, NotEnoughAPIInstancesException {
415
        if (!queryRef.getQueryId().matches("^RA[A-Za-z0-9-_]{43}/.*$")) {
15 !
416
            throw new IllegalArgumentException("QueryRef name must be full query ID: " + queryRef.getQueryId());
×
417
        }
418
        return QueryAccess.get(queryRef);
9 ✔
419
    }
420

421
    /**
422
     * Retrieves the latest version ID of a given nanopublication.
423
     *
424
     * @param nanopubId The ID of the nanopublication.
425
     * @return The latest version ID.
426
     */
427
    public static String getLatestVersionId(String nanopubId) {
428
        long currentTime = System.currentTimeMillis();
6 ✔
429
        if (!latestVersionMap.containsKey(nanopubId) || currentTime - latestVersionMap.get(nanopubId).getLeft() > 1000 * 60) {
48 !
430
            // Re-fetch if existing value is older than 1 minute
431
            try {
432
                ApiResponse r = ApiCache.retrieveResponseSync(new QueryRef(GET_LATEST_VERSION_OF_NP, "np", nanopubId), false);
27 ✔
433
                if (r != null && r.getData().size() == 1) {
21 !
434
                    String l = r.getData().getFirst().get("latest");
21 ✔
435
                    latestVersionMap.put(nanopubId, Pair.of(currentTime, l));
24 ✔
436
                }
437
            } catch (Exception ex) {
×
438
                logger.error("Error while getting latest version of nanopub '{}'", nanopubId, ex);
×
439
            }
3 ✔
440
        }
441
        Pair<Long, String> cached = latestVersionMap.get(nanopubId);
15 ✔
442
        return cached != null ? cached.getRight() : nanopubId;
24 ✔
443
    }
444

445
    /**
446
     * Drops the memoized latest-version lookup for a nanopub, so that the next
447
     * {@link #getLatestVersionId(String)} goes back to the query API instead of answering
448
     * from a memo that can be up to a minute old. For the places where the user explicitly
449
     * asks for current data, such as {@link View#refreshLatestVersion(String)}.
450
     *
451
     * @param nanopubId The ID of the nanopublication.
452
     */
453
    public static void forgetLatestVersion(String nanopubId) {
454
        latestVersionMap.remove(nanopubId);
×
455
    }
×
456

457
    /**
458
     * Checks whether the given nanopublication has been loaded by the query services,
459
     * with a single cheap indexed lookup. A negative answer only means the instance that
460
     * happened to answer does not have the nanopub yet.
461
     *
462
     * @param nanopubId The ID of the nanopublication.
463
     * @return True if the answering query service instance has the nanopub.
464
     * @throws org.nanopub.extra.services.FailedApiCallException         If the API call fails.
465
     * @throws org.nanopub.extra.services.APINotReachableException       If the API is not reachable.
466
     * @throws org.nanopub.extra.services.NotEnoughAPIInstancesException If there are not enough API instances.
467
     */
468
    public static boolean isNanopubLoaded(String nanopubId) throws FailedApiCallException, APINotReachableException, NotEnoughAPIInstancesException {
469
        ApiResponse r = get(new QueryRef(CHECK_NANOPUB_LOADED, "np", nanopubId));
×
470
        return r != null && !r.getData().isEmpty();
×
471
    }
472

473
    /**
474
     * Checks whether the given nanopublication has been materialized into the current space
475
     * state, i.e. whether the authority resolver has already recorded what it grants.
476
     * <p>
477
     * This is a strictly later milestone than {@link #isNanopubLoaded(String)}: the space
478
     * listing queries (members, observers, participants) read role instantiations out of the
479
     * current space state, so a role grant is invisible to them until the resolver has
480
     * processed it, however long it has been ingested. A refresh released on ingest alone
481
     * therefore re-runs the view query too early and finds the same rows as before.
482
     * <p>
483
     * An empty answer does not distinguish "not materialized yet" from "materialized but
484
     * granting nothing", so callers must bound how long they wait on it.
485
     *
486
     * @param nanopubId The ID of the nanopublication.
487
     * @return True if the answering query service instance has materialized the nanopub.
488
     * @throws org.nanopub.extra.services.FailedApiCallException         If the API call fails.
489
     * @throws org.nanopub.extra.services.APINotReachableException       If the API is not reachable.
490
     * @throws org.nanopub.extra.services.NotEnoughAPIInstancesException If there are not enough API instances.
491
     */
492
    public static boolean isNanopubMaterialized(String nanopubId) throws FailedApiCallException, APINotReachableException, NotEnoughAPIInstancesException {
493
        ApiResponse r = get(new QueryRef(CHECK_NANOPUB_MATERIALIZED, "np", nanopubId));
×
494
        return r != null && !r.getData().isEmpty();
×
495
    }
496

497
    /**
498
     * Checks whether the given IRI has already been used as the identifier of a resource,
499
     * i.e. whether some nanopublication already introduces it.
500
     * <p>
501
     * This is the question an identifier that carries no artifact code raises: nothing makes
502
     * it unique, so the same form filled with the same name twice yields the same IRI, and
503
     * the second nanopublication silently attaches itself to the first one's resource (#646).
504
     * The lookup runs against the meta repository, where {@code npx:introduces} is indexed.
505
     * <p>
506
     * A query service that cannot be reached answers false: a check that cannot be made is
507
     * not evidence of a collision, and publishing should not depend on the query services
508
     * being up.
509
     *
510
     * @param uri The IRI to check.
511
     * @return True if a nanopublication introducing the IRI was found.
512
     */
513
    public static boolean isUriIntroduced(String uri) {
514
        try {
515
            ApiResponse r = get(new QueryRef(GET_INTRODUCING_NANOPUB, "thing", uri));
24 ✔
516
            return r != null && !r.getData().isEmpty();
30 !
517
        } catch (Exception ex) {
3 ✔
518
            logger.error("Could not check whether IRI '{}' is already introduced", uri, ex);
15 ✔
519
            return false;
6 ✔
520
        }
521
    }
522

523
    /**
524
     * Extracts the query ID from a given query IRI.
525
     *
526
     * @param queryIri The query IRI.
527
     * @return The query ID, or null if the IRI is invalid.
528
     */
529
    public static String getQueryId(IRI queryIri) {
530
        if (queryIri == null) {
×
531
            return null;
×
532
        }
533
        if (!queryIri.stringValue().matches(queryIriPattern)) {
×
534
            return null;
×
535
        }
536
        return queryIri.stringValue().replaceFirst(queryIriPattern, "$2/$3");
×
537
    }
538

539
    /**
540
     * Extracts the query name from a given query IRI.
541
     *
542
     * @param queryIri The query IRI.
543
     * @return The query name, or null if the IRI is invalid.
544
     */
545
    public static String getQueryName(IRI queryIri) {
546
        if (queryIri == null) {
6 ✔
547
            return null;
6 ✔
548
        }
549
        if (!queryIri.stringValue().matches(queryIriPattern)) {
15 ✔
550
            return null;
6 ✔
551
        }
552
        return queryIri.stringValue().replaceFirst(queryIriPattern, "$3");
18 ✔
553
    }
554

555
}
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