Skip to content

Commit 71852f7

Browse files
ctruedenclaude
andcommitted
scijava-discovery: make Discoverer yield lazy descriptors
Discoverer.discover now returns List<Discovery<U>> rather than List<U>. A Discovery is a descriptor with three access levels of increasing cost: implClassName()/attrs() load nothing, type() loads the class, get() constructs the object. Discoverer.instances(Class) covers the common case of wanting the objects. This is what lets an index-backed Discoverer report what is available without loading classes -- the property Fiji's menu construction depends on, and which the old signature made impossible to express. Op YAML metadata and ServiceLoader providers both map onto the same shape. Note a JPMS constraint found while implementing this: ServiceLoader resolves `uses` declarations against its *caller's* module, so scijava-discovery cannot perform a lookup on another module's behalf. The lookup function is therefore supplied by the consuming module, via Discoverer.usingProviders(c -> ServiceLoader.load(c).stream()). The one exception is Discoverer.all(), which looks up Discoverer itself -- a type this module does declare `uses` for. scijava-discovery now depends on scijava-priority, so that discoveries can carry a priority without being constructed. This is a breaking API change, which the repository's current adoption level permits. All call sites are updated. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_013gJpzGd3ksbME4CN6Tu2ni
1 parent 82cd7c8 commit 71852f7

18 files changed

Lines changed: 565 additions & 137 deletions

File tree

‎docs/migration-plan.md‎

Lines changed: 25 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -82,10 +82,10 @@ they need the corresponding SJC classes deprecated with pointers.
8282
Remaining SJC usage inside this repository:
8383

8484
- `scijava-legacy` — intentional; it is the bridge.
85-
- `scijava-ops-image` / `scijava-ops-flim` tests — `util.MersenneTwisterFast`
86-
(16 usages), `util.LongArray`, `util.ListUtils`, `io.location.FileLocation`,
87-
`Context`. Removable today (Phase 0).
88-
- `scijava-ops-tutorial` — one import in main code.
85+
- `scijava-ops-image` / `scijava-ops-flim` tests — `io.location.FileLocation`,
86+
imposed by SCIFIO's `ImgOpener` API. Gone once SCIFIO migrates; the utility
87+
usages were removed in Phase 0.
88+
- `scijava-ops-benchmarks` — three imports.
8989

9090
## Cross-cutting design decisions
9191

@@ -130,6 +130,22 @@ All three mechanisms map cleanly: `ServiceLoader.stream()` supplies
130130
`@Plugin` index supplies `implClassName` and `attrs` with no loading at all;
131131
op YAML files already have this shape.
132132

133+
**A JPMS constraint discovered while implementing this:** `ServiceLoader`
134+
resolves `uses` declarations against the module of its *caller*, so
135+
`scijava-discovery` cannot perform a `ServiceLoader` lookup on another
136+
module's behalf — doing so fails for every type that `org.scijava.discovery`
137+
does not itself declare `uses` for. The lookup function must therefore be
138+
supplied by the consuming module:
139+
140+
```java
141+
Discoverer.usingProviders(c -> ServiceLoader.load(c).stream())
142+
```
143+
144+
The one exception is `Discoverer.all()`, which looks up `Discoverer` itself —
145+
a type this module does declare `uses` for — and so can be a no-argument
146+
convenience. This is a real constraint on any generic discovery facade under
147+
JPMS, not an artifact of our design.
148+
133149
**This refactor should land before `scijava-context` is built on top of
134150
`Discoverer`.** It is mechanical now and expensive later. `ManualDiscoverer`
135151
— hand-feeding implementations, which is valuable for tests, scripts and
@@ -184,15 +200,18 @@ SLF4J, used directly, as `scijava-types` and `scijava-ops-engine` already do.
184200

185201
- Remove SJC usage where an SJ3 replacement already exists: switch the
186202
`ops-image` / `ops-flim` tests to `common3.MersenneTwisterFast` and
187-
`collections.LongArray`, replace `ListUtils`, fix the `ops-tutorial` import.
188-
Afterwards only `scijava-legacy` and `scijava-code-api` depend on SJC.
203+
`collections.LongArray`, replace `ListUtils`. **Done.** Note that the
204+
remaining `io.location.FileLocation` usage in the `ops-image` and `ops-flim`
205+
tests is imposed by SCIFIO's `ImgOpener` API, so it cannot go away until
206+
SCIFIO migrates; `scijava-ops-tutorial` turned out to have no SJC usage.
189207
- Add `@deprecated` javadoc pointers in SJC for everything already superseded
190208
(see the table above).
191209
- Start [migration.md](migration.md), scripting the mapping where possible.
192210
Note that `common3.Types` is not a superset of `util.Types`: `box`, `field`,
193211
`isBoolean` and friends moved to `Classes`, and `enumFromString` / `args`
194212
were dropped.
195213
- Refactor `Discoverer` to the `Discovery` descriptor API (see above).
214+
**Done.**
196215

197216
### Phase 1 — Standalone leaves
198217

‎scijava-discovery-test/src/main/java/org/scijava/discovery/test/ServiceBasedAdder.java‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,16 @@ public class ServiceBasedAdder implements BiFunction<Number, Number, Double>,
3939
Op
4040
{
4141

42+
/**
43+
* Whether this class has ever been constructed, so that tests can assert
44+
* that discovery does not instantiate what it discovers.
45+
*/
46+
public static volatile boolean constructed = false;
47+
48+
public ServiceBasedAdder() {
49+
constructed = true;
50+
}
51+
4252
@Override
4353
public Double apply(Number t, Number u) {
4454
return t.doubleValue() + u.doubleValue();
Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
/*-
2+
* #%L
3+
* Integration tests for the scijava-discovery library.
4+
* %%
5+
* Copyright (C) 2021 - 2025 SciJava developers.
6+
* %%
7+
* Redistribution and use in source and binary forms, with or without
8+
* modification, are permitted provided that the following conditions are met:
9+
*
10+
* 1. Redistributions of source code must retain the above copyright notice,
11+
* this list of conditions and the following disclaimer.
12+
* 2. Redistributions in binary form must reproduce the above copyright notice,
13+
* this list of conditions and the following disclaimer in the documentation
14+
* and/or other materials provided with the distribution.
15+
*
16+
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
17+
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18+
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19+
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
20+
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
21+
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
22+
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
23+
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
24+
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
25+
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
26+
* POSSIBILITY OF SUCH DAMAGE.
27+
* #L%
28+
*/
29+
30+
package org.scijava.discovery.test;
31+
32+
import java.util.List;
33+
import java.util.ServiceLoader;
34+
35+
import org.junit.jupiter.api.Assertions;
36+
import org.junit.jupiter.api.Test;
37+
import org.scijava.discovery.Discoverer;
38+
import org.scijava.discovery.Discovery;
39+
import org.scijava.ops.spi.Op;
40+
41+
/**
42+
* Tests that {@link Discovery} reports what is available without constructing
43+
* it - the property that lets metadata-only consumers, such as menu building,
44+
* avoid paying for objects they will never use.
45+
*
46+
* @author Curtis Rueden
47+
*/
48+
public class DiscoveryLazinessTest {
49+
50+
/**
51+
* A {@link Discoverer} backed by {@link ServiceLoader} must report the
52+
* implementation class name without constructing the implementation.
53+
*/
54+
@Test
55+
public void testServiceLoaderDiscoveryIsLazy() {
56+
final Discoverer d = Discoverer.usingProviders( //
57+
c -> ServiceLoader.load(c).stream());
58+
59+
final List<Discovery<Op>> discoveries = d.discover(Op.class);
60+
Assertions.assertEquals(1, discoveries.size());
61+
62+
final Discovery<Op> discovery = discoveries.get(0);
63+
Assertions.assertEquals(ServiceBasedAdder.class.getName(), //
64+
discovery.implClassName());
65+
Assertions.assertFalse(ServiceBasedAdder.constructed,
66+
"Discovery must not construct the implementation");
67+
68+
// Only now should the object come into existence.
69+
Assertions.assertNotNull(discovery.get());
70+
Assertions.assertTrue(ServiceBasedAdder.constructed);
71+
}
72+
73+
/** Discoveries of an unknown type yield nothing rather than failing. */
74+
@Test
75+
public void testUnknownTypeYieldsNothing() {
76+
final Discoverer d = Discoverer.usingProviders( //
77+
c -> ServiceLoader.load(c).stream());
78+
Assertions.assertTrue(d.discover(Runnable.class).isEmpty());
79+
}
80+
}

‎scijava-discovery-test/src/test/java/org/scijava/discovery/test/ServiceLoaderDiscovererTest.java‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ public class ServiceLoaderDiscovererTest {
4343

4444
@Test
4545
public void testServiceLoaderWithBoth() {
46-
Discoverer d = Discoverer.using(ServiceLoader::load);
46+
Discoverer d = Discoverer.usingProviders(c -> ServiceLoader.load(c).stream());
4747
assertDiscoveryRequirements(d, OpCollection.class,
4848
ServiceBasedMultipliers.class);
4949
assertDiscoveryRequirements(d, Op.class, ServiceBasedAdder.class);
@@ -53,7 +53,7 @@ public void testServiceLoaderWithBoth() {
5353
private static <T> void assertDiscoveryRequirements(Discoverer d,
5454
Class<T> discovery, Class<? extends T>... impls)
5555
{
56-
List<Class<T>> implementingClasses = d.discover(discovery).stream().map(
56+
List<Class<T>> implementingClasses = d.instances(discovery).stream().map(
5757
o -> (Class<T>) o.getClass()).collect(Collectors.toList());
5858
for (Class<? extends T> cls : impls)
5959
Assertions.assertTrue(implementingClasses.contains(cls));

‎scijava-discovery/pom.xml‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -86,6 +86,14 @@
8686
<license.copyrightOwners>SciJava developers.</license.copyrightOwners>
8787
</properties>
8888

89+
<dependencies>
90+
<dependency>
91+
<groupId>org.scijava</groupId>
92+
<artifactId>scijava-priority</artifactId>
93+
<version>${scijava-priority.version}</version>
94+
</dependency>
95+
</dependencies>
96+
8997
<build>
9098
<plugins>
9199
<plugin>

‎scijava-discovery/src/main/java/module-info.java‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,8 @@
3131

3232
exports org.scijava.discovery;
3333

34+
requires transitive org.scijava.priority;
35+
3436
uses org.scijava.discovery.Discoverer;
3537

3638
}

0 commit comments

Comments
 (0)