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

knowledgepixels / nanopub-query / 31673600835

13 Aug 2026 06:22AM UTC coverage: 76.255% (+0.2%) from 76.024%
31673600835

push

github

web-flow
Merge pull request #185 from knowledgepixels/feat/trust-state-endorsement-links

Materialize endorsement links from the trust state snapshot

829 of 1234 branches covered (67.18%)

Branch coverage included in aggregate %.

2453 of 3070 relevant lines covered (79.9%)

12.5 hits per line

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

97.73
src/main/java/com/knowledgepixels/query/TrustStateSnapshot.java
1
package com.knowledgepixels.query;
2

3
import java.time.Instant;
4
import java.time.ZonedDateTime;
5
import java.util.ArrayList;
6
import java.util.Collections;
7
import java.util.List;
8

9
import io.vertx.core.json.JsonArray;
10
import io.vertx.core.json.JsonObject;
11

12
/**
13
 * Parsed envelope of a {@code /trust-state/<hash>.json} response from the
14
 * registry. Immutable; produced by {@link #parse(String)}.
15
 *
16
 * <p>The {@code trustStateCounter} field arrives as MongoDB extended JSON
17
 * (e.g. {@code {"$numberLong": "1"}}) when the registry's serializer chooses
18
 * to wrap a long. The parser handles either wrapped or plain numeric form.
19
 *
20
 * <p>The {@code createdAt} field uses Java's {@code ZonedDateTime.toString()}
21
 * shape — ISO-8601 plus an optional {@code [Etc/UTC]} zone bracket — which
22
 * {@link ZonedDateTime#parse(CharSequence)} reads natively.
23
 *
24
 * @param trustStateHash the hash advertised by the registry for this snapshot
25
 * @param trustStateCounter monotonic counter; matches the registry's value
26
 * @param createdAt when the registry committed this snapshot
27
 * @param accounts one entry per non-{@code "$"} account in the trust graph
28
 * @param edges one entry per non-invalidated endorsement edge between published
29
 *              accounts (nanopub-query#184); empty when running against a
30
 *              registry whose snapshot predates the field — additive
31
 *              non-breaking schema, so absence must be tolerated during the
32
 *              fleet rollout
33
 */
34
public record TrustStateSnapshot(
54 ✔
35
        String trustStateHash,
36
        long trustStateCounter,
37
        Instant createdAt,
38
        List<AccountEntry> accounts,
39
        List<EdgeEntry> edges
40
) {
41

42
    /**
43
     * Back-compat constructor without {@code edges} (defaults to an empty list) —
44
     * the field is additive (nanopub-query#184). Convenient for call sites that
45
     * predate it; production parsing always uses the canonical constructor.
46
     */
47
    public TrustStateSnapshot(String trustStateHash, long trustStateCounter,
48
            Instant createdAt, List<AccountEntry> accounts) {
49
        this(trustStateHash, trustStateCounter, createdAt, accounts, List.of());
21 ✔
50
    }
3 ✔
51

52
    /**
53
     * One account in a trust state snapshot. Mirrors the fields the registry
54
     * exposes; consumers (e.g. authority queries) decide which {@code status}
55
     * values count as "approved".
56
     *
57
     * <p>{@code pathCount}, {@code ratio}, and {@code quota} can be {@code null}
58
     * for accounts with {@code status == "skipped"} (trust calculation rejected
59
     * them, so those stats aren't meaningful). {@code name} and {@code nameCreatedAt}
60
     * are {@code null} when the declaring intro nanopub asserted no
61
     * {@code foaf:name} on the agent (or when running against a registry that
62
     * predates the field — additive non-breaking schema). Boxed types preserve
63
     * the absence.
64
     *
65
     * @param pubkey hex-encoded public key
66
     * @param agent agent IRI (typically an ORCID, but any IRI is allowed)
67
     * @param status one of the registry's {@code EntryStatus} values
68
     *               (e.g. {@code "loaded"}, {@code "toLoad"}, {@code "skipped"})
69
     * @param depth steps from the trust seed
70
     * @param pathCount number of independent trust paths, or {@code null} for skipped accounts
71
     * @param ratio aggregated trust score, or {@code null} for skipped accounts
72
     * @param quota allocated upload quota, or {@code null} for skipped accounts
73
     * @param name {@code foaf:name} from the declaring intro nanopub, or {@code null} if absent
74
     * @param nameCreatedAt {@code dct:created} of the declaring intro, or {@code null} if absent.
75
     *                      Used to break ties when multiple intros declare the same {@code (agent, pubkey)};
76
     *                      consumers picking one canonical name per agent across keys typically use
77
     *                      {@code MAX(ratio)} with this as a secondary tiebreaker.
78
     * @param introNanopub IRI of the authorizing introduction nanopub for this {@code (agent, pubkey)}
79
     *                     (the intro carrying the key declaration; nanopub-registry#117/#118), or
80
     *                     {@code null} when running against a registry whose snapshot predates the
81
     *                     field — additive non-breaking schema, so absence must be tolerated during
82
     *                     the fleet rollout. Tracks the same name-winning intro as {@code name}.
83
     */
84
    public record AccountEntry(
99 ✔
85
            String pubkey,
86
            String agent,
87
            String status,
88
            Integer depth,
89
            Integer pathCount,
90
            Double ratio,
91
            Long quota,
92
            String name,
93
            Instant nameCreatedAt,
94
            String introNanopub
95
    ) {
96
        /**
97
         * Back-compat constructor without {@code introNanopub} (defaults to {@code null}) —
98
         * the field is additive (nanopub-registry#117/#118). Convenient for call sites that
99
         * predate it; production parsing always uses the canonical constructor.
100
         */
101
        public AccountEntry(String pubkey, String agent, String status, Integer depth,
102
                            Integer pathCount, Double ratio, Long quota, String name,
103
                            Instant nameCreatedAt) {
104
            this(pubkey, agent, status, depth, pathCount, ratio, quota, name, nameCreatedAt, null);
36 ✔
105
        }
3 ✔
106
    }
107

108
    /**
109
     * One agent-level endorsement edge in a trust state snapshot
110
     * (nanopub-query#184): the {@code (fromAgent, fromPubkey)} account endorsed
111
     * the {@code (toAgent, toPubkey)} account via the endorsement nanopub
112
     * {@code viaNanopub}. The registry lists edges per pubkey pair, so the same
113
     * agent-level edge can appear more than once; consumers folding to agent
114
     * level (e.g. {@link TrustStateLoader}) deduplicate on
115
     * {@code (fromAgent, toAgent, viaNanopub)}.
116
     *
117
     * @param fromAgent agent IRI of the endorsing account
118
     * @param fromPubkey hex-encoded public key of the endorsing account
119
     * @param toAgent agent IRI of the endorsed account
120
     * @param toPubkey hex-encoded public key of the endorsed account
121
     * @param viaNanopub full URI of the endorsement nanopub carrying the
122
     *                   {@code npx:approvesOf} assertion, or {@code null} if the
123
     *                   registry omitted it — tolerated like the other additive
124
     *                   fields
125
     */
126
    public record EdgeEntry(
54 ✔
127
            String fromAgent,
128
            String fromPubkey,
129
            String toAgent,
130
            String toPubkey,
131
            String viaNanopub
132
    ) {
133
    }
134

135
    /**
136
     * Parses a {@code /trust-state/<hash>.json} envelope from its JSON
137
     * serialization. Throws {@link IllegalArgumentException} if the JSON is
138
     * malformed or missing required fields.
139
     *
140
     * @param json the response body as a string
141
     * @return the parsed snapshot
142
     * @throws IllegalArgumentException if parsing fails
143
     */
144
    public static TrustStateSnapshot parse(String json) {
145
        JsonObject obj;
146
        try {
147
            obj = new JsonObject(json);
15 ✔
148
        } catch (Exception ex) {
3 ✔
149
            throw new IllegalArgumentException("Trust state envelope is not valid JSON", ex);
18 ✔
150
        }
3 ✔
151

152
        String hash = requireString(obj, "trustStateHash");
12 ✔
153
        long counter = unwrapLong(obj, "trustStateCounter");
12 ✔
154

155
        String rawCreatedAt = requireString(obj, "createdAt");
12 ✔
156
        Instant createdAt;
157
        try {
158
            createdAt = ZonedDateTime.parse(rawCreatedAt).toInstant();
12 ✔
159
        } catch (Exception ex) {
3 ✔
160
            throw new IllegalArgumentException(
21 ✔
161
                    "Cannot parse createdAt as ZonedDateTime: " + rawCreatedAt, ex);
162
        }
3 ✔
163

164
        JsonArray accountsArray = obj.getJsonArray("accounts");
12 ✔
165
        if (accountsArray == null) {
6 ✔
166
            throw new IllegalArgumentException("Trust state envelope is missing 'accounts' array");
15 ✔
167
        }
168
        List<AccountEntry> accounts = new ArrayList<>(accountsArray.size());
18 ✔
169
        for (int i = 0; i < accountsArray.size(); i++) {
24 ✔
170
            JsonObject a;
171
            try {
172
                a = accountsArray.getJsonObject(i);
12 ✔
173
            } catch (ClassCastException ex) {
3 ✔
174
                throw new IllegalArgumentException(
21 ✔
175
                        "Trust state account entry " + i + " is not a JSON object", ex);
176
            }
3 ✔
177
            accounts.add(new AccountEntry(
21 ✔
178
                    requireString(a, "pubkey"),
9 ✔
179
                    requireString(a, "agent"),
9 ✔
180
                    requireString(a, "status"),
9 ✔
181
                    a.getInteger("depth"),
9 ✔
182
                    a.getInteger("pathCount"),
9 ✔
183
                    a.getDouble("ratio"),
9 ✔
184
                    unwrapLongNullable(a, "quota"),
9 ✔
185
                    a.getString("name"),
9 ✔
186
                    unwrapDateNullable(a, "nameCreatedAt"),
9 ✔
187
                    a.getString("introNanopub")
6 ✔
188
            ));
189
        }
190

191
        // Additive (nanopub-query#184): snapshots from registries predating the
192
        // field have no 'edges' array — treat that as empty rather than failing.
193
        List<EdgeEntry> edges;
194
        JsonArray edgesArray;
195
        try {
196
            edgesArray = obj.getJsonArray("edges");
12 ✔
197
        } catch (ClassCastException ex) {
3 ✔
198
            throw new IllegalArgumentException("Trust state 'edges' field is not an array", ex);
18 ✔
199
        }
3 ✔
200
        if (edgesArray == null) {
6 ✔
201
            edges = List.of();
9 ✔
202
        } else {
203
            edges = new ArrayList<>(edgesArray.size());
18 ✔
204
            for (int i = 0; i < edgesArray.size(); i++) {
24 ✔
205
                JsonObject e;
206
                try {
207
                    e = edgesArray.getJsonObject(i);
12 ✔
208
                } catch (ClassCastException ex) {
×
209
                    throw new IllegalArgumentException(
×
210
                            "Trust state edge entry " + i + " is not a JSON object", ex);
211
                }
3 ✔
212
                edges.add(new EdgeEntry(
21 ✔
213
                        requireString(e, "fromAgent"),
9 ✔
214
                        requireString(e, "fromPubkey"),
9 ✔
215
                        requireString(e, "toAgent"),
9 ✔
216
                        requireString(e, "toPubkey"),
9 ✔
217
                        e.getString("viaNanopub")
6 ✔
218
                ));
219
            }
220
            edges = Collections.unmodifiableList(edges);
9 ✔
221
        }
222

223
        return new TrustStateSnapshot(hash, counter, createdAt,
21 ✔
224
                Collections.unmodifiableList(accounts), edges);
9 ✔
225
    }
226

227
    private static String requireString(JsonObject obj, String key) {
228
        String s = obj.getString(key);
12 ✔
229
        if (s == null) {
6 ✔
230
            throw new IllegalArgumentException("Trust state envelope is missing required field: " + key);
18 ✔
231
        }
232
        return s;
6 ✔
233
    }
234

235
    /**
236
     * Reads a required long-typed field, transparently handling MongoDB
237
     * extended JSON ({@code {"$numberLong": "..."}}) as well as plain numeric
238
     * or string forms. Throws if the field is missing or null.
239
     */
240
    private static long unwrapLong(JsonObject obj, String key) {
241
        Long v = unwrapLongNullable(obj, key);
12 ✔
242
        if (v == null) {
6 ✔
243
            throw new IllegalArgumentException("Trust state envelope is missing required field: " + key);
18 ✔
244
        }
245
        return v;
9 ✔
246
    }
247

248
    /**
249
     * Reads an optional date-typed field. Handles MongoDB extended JSON
250
     * ({@code {"$date": "..."}} or {@code {"$date": {"$numberLong": "..."}}}),
251
     * plain ISO-8601 strings, and JSON {@code null}/missing. Returns {@code null}
252
     * for any of those last cases so the field is fully optional — consumers
253
     * working with snapshots from a registry that predates the {@code nameCreatedAt}
254
     * field still parse cleanly.
255
     */
256
    private static Instant unwrapDateNullable(JsonObject obj, String key) {
257
        Object v = obj.getValue(key);
12 ✔
258
        if (v == null) return null;
12 ✔
259
        if (v instanceof JsonObject j) {
18 ✔
260
            Object dateVal = j.getValue("$date");
12 ✔
261
            if (dateVal instanceof String s) {
18 ✔
262
                try {
263
                    return Instant.parse(s);
9 ✔
264
                } catch (Exception ex) {
3 ✔
265
                    throw new IllegalArgumentException("Cannot parse " + key + " as ISO-8601 instant: " + s, ex);
24 ✔
266
                }
267
            }
268
            if (dateVal instanceof JsonObject inner) {
18 ✔
269
                String numberLong = inner.getString("$numberLong");
12 ✔
270
                if (numberLong != null) return Instant.ofEpochMilli(Long.parseLong(numberLong));
18 !
271
            }
272
            if (dateVal instanceof Number n) return Instant.ofEpochMilli(n.longValue());
30 ✔
273
            throw new IllegalArgumentException("Cannot unwrap " + key + " from extended JSON $date: " + j);
24 ✔
274
        }
275
        if (v instanceof String s) {
18 ✔
276
            try {
277
                return Instant.parse(s);
9 ✔
278
            } catch (Exception ex) {
3 ✔
279
                throw new IllegalArgumentException("Cannot parse " + key + " as ISO-8601 instant: " + s, ex);
24 ✔
280
            }
281
        }
282
        if (v instanceof Number n) return Instant.ofEpochMilli(n.longValue());
30 ✔
283
        throw new IllegalArgumentException("Cannot unwrap " + key + " as date: " + v);
24 ✔
284
    }
285

286
    /**
287
     * Reads an optional long-typed field, returning {@code null} if the field
288
     * is absent or its value is JSON {@code null}. Same extended-JSON handling
289
     * as {@link #unwrapLong(JsonObject, String)}.
290
     */
291
    private static Long unwrapLongNullable(JsonObject obj, String key) {
292
        Object v = obj.getValue(key);
12 ✔
293
        if (v == null) return null;
12 ✔
294
        if (v instanceof Number n) return n.longValue();
30 ✔
295
        if (v instanceof JsonObject j) {
18 ✔
296
            String s = j.getString("$numberLong");
12 ✔
297
            if (s != null) return Long.parseLong(s);
18 ✔
298
        }
299
        if (v instanceof String s) return Long.parseLong(s);
30 ✔
300
        throw new IllegalArgumentException("Cannot unwrap " + key + " as long: " + v);
24 ✔
301
    }
302

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