Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.function.Supplier;
import javax.validation.constraints.NotEmpty;
import lombok.extern.slf4j.Slf4j;
import org.apache.jena.sparql.modify.request.UpdateDeleteWhere;
Expand Down Expand Up @@ -54,8 +55,8 @@ public class RdfResource {
public static final String COLLECTION_PATH = "/v1/rdf";
private static final int MIN_GRAPH_DEPTH = 1;
private static final int MAX_GRAPH_DEPTH = 5;
private volatile RdfRepository rdfRepository;
private final Authorizer authorizer;
private final Supplier<RdfRepository> repositorySupplier;
private volatile SemanticSearchEngine semanticSearchEngine;
private OpenMetadataApplicationConfig config;

Expand All @@ -68,24 +69,33 @@ public class RdfResource {
public static final String SPARQL_CSV = "text/csv";

public RdfResource(Authorizer authorizer) {
this(authorizer, RdfRepository::getInstanceOrNull);
}

RdfResource(Authorizer authorizer, Supplier<RdfRepository> repositorySupplier) {
this.authorizer = authorizer;
this.repositorySupplier = repositorySupplier;
}

private RdfRepository getRdfRepository() {
if (rdfRepository == null) {
rdfRepository = RdfRepository.getInstanceOrNull();
}
return rdfRepository;
// Resolve the live singleton on every call rather than pinning the first instance.
// RdfUpdater.initialize() calls RdfRepository.reset() and rebuilds the singleton (durable live
// projection / reindex), so a pinned reference would keep serving a closed store after a swap
// (e.g. #33098's live-projection path), surfacing as 500s on the RDF endpoints.
return repositorySupplier.get();
}
Comment thread
gitar-bot[bot] marked this conversation as resolved.
Resolved

private SemanticSearchEngine getSemanticSearchEngine() {
SemanticSearchEngine local = semanticSearchEngine;
if (local == null) {
synchronized (this) {
local = semanticSearchEngine;
if (local == null && getRdfRepository() != null) {
local = new SemanticSearchEngine(getRdfRepository(), Entity.getSearchRepository());
semanticSearchEngine = local;
if (local == null) {
RdfRepository repository = getRdfRepository();
if (repository != null) {
local = new SemanticSearchEngine(repository, Entity.getSearchRepository());
semanticSearchEngine = local;
}
}
}
}
Expand Down Expand Up @@ -115,9 +125,12 @@ public void initialize(OpenMetadataApplicationConfig config) {
})
public Response getRdfStatus(@Context SecurityContext securityContext) {
authorizer.authorizeAdmin(securityContext);
boolean enabled = getRdfRepository() != null && getRdfRepository().isEnabled();
boolean inferenceEnabled = enabled && getRdfRepository().isInferenceEnabledByDefault();
String defaultInferenceLevel = enabled ? getRdfRepository().getDefaultInferenceLevel() : "NONE";
// Snapshot the repository once per request: getRdfRepository() now resolves the live singleton,
// which RdfUpdater can null during a reset(), so re-reading it mid-handler could NPE.
final RdfRepository repository = getRdfRepository();
boolean enabled = repository != null && repository.isEnabled();
boolean inferenceEnabled = enabled && repository.isInferenceEnabledByDefault();
String defaultInferenceLevel = enabled ? repository.getDefaultInferenceLevel() : "NONE";
ProjectionState projectionState =
enabled
? new RdfProjectionStateResolver(Entity.getCollectionDAO().appExtensionTimeSeriesDao())
Expand All @@ -141,7 +154,7 @@ public Response getRdfStatus(@Context SecurityContext securityContext) {
enabled,
inferenceEnabled,
defaultInferenceLevel,
enabled ? getRdfRepository().getConfig().getStorageType() : "N/A",
enabled ? repository.getConfig().getStorageType() : "N/A",
projectionState);

return Response.ok().entity(statusJson).type(MediaType.APPLICATION_JSON).build();
Expand All @@ -163,13 +176,14 @@ public Response getRdfStatus(@Context SecurityContext securityContext) {
})
public Response debugGlossaryRelations(@Context SecurityContext securityContext) {
authorizer.authorizeAdmin(securityContext);
if (getRdfRepository() == null || !getRdfRepository().isEnabled()) {
final RdfRepository repository = getRdfRepository();
if (repository == null || !repository.isEnabled()) {
return Response.status(Response.Status.SERVICE_UNAVAILABLE)
.entity("{\"error\": \"RDF service not enabled\"}")
.build();
}

String result = getRdfRepository().debugGlossaryTermRelations();
String result = repository.debugGlossaryTermRelations();
return Response.ok(result, MediaType.APPLICATION_JSON).build();
}

Expand Down Expand Up @@ -203,7 +217,8 @@ public Response getEntityAsRdf(
String format) {
authorizer.authorizeAdmin(securityContext);
try {
if (getRdfRepository() == null || !getRdfRepository().isEnabled()) {
final RdfRepository repository = getRdfRepository();
if (repository == null || !repository.isEnabled()) {
return Response.status(Response.Status.SERVICE_UNAVAILABLE)
.entity("{\"error\": \"RDF service not enabled\"}")
.build();
Expand All @@ -213,19 +228,19 @@ public Response getEntityAsRdf(
MediaType mediaType =
switch (format.toLowerCase()) {
case "turtle", "ttl" -> {
result = getRdfRepository().getEntityAsRdf(entityType, id, "turtle");
result = repository.getEntityAsRdf(entityType, id, "turtle");
yield MediaType.valueOf(TURTLE);
}
case "rdfxml", "xml" -> {
result = getRdfRepository().getEntityAsRdf(entityType, id, "rdfxml");
result = repository.getEntityAsRdf(entityType, id, "rdfxml");
yield MediaType.valueOf(RDF_XML);
}
case "ntriples", "nt" -> {
result = getRdfRepository().getEntityAsRdf(entityType, id, "ntriples");
result = repository.getEntityAsRdf(entityType, id, "ntriples");
yield MediaType.valueOf(N_TRIPLES);
}
default -> {
result = getRdfRepository().getEntityAsJsonLd(entityType, id);
result = repository.getEntityAsJsonLd(entityType, id);
yield MediaType.valueOf(JSON_LD);
}
};
Expand Down Expand Up @@ -278,20 +293,20 @@ public Response exploreEntityGraph(
try {
String validatedEntityType = validateEntityType(entityType);
int clampedDepth = clampGraphDepth(depth);
if (getRdfRepository() == null || !getRdfRepository().isEnabled()) {
final RdfRepository repository = getRdfRepository();
if (repository == null || !repository.isEnabled()) {
return Response.status(Response.Status.SERVICE_UNAVAILABLE)
.entity(buildErrorResponse("RDF service not enabled"))
.build();
}

String graphData =
getRdfRepository()
.getEntityGraph(
entityId,
validatedEntityType,
clampedDepth,
parseCsvFilter(entityTypes),
parseCsvFilter(relationshipTypes));
repository.getEntityGraph(
entityId,
validatedEntityType,
clampedDepth,
parseCsvFilter(entityTypes),
parseCsvFilter(relationshipTypes));
return Response.ok(graphData, MediaType.APPLICATION_JSON).build();
} catch (IllegalArgumentException e) {
return Response.status(Response.Status.BAD_REQUEST)
Expand Down Expand Up @@ -341,21 +356,21 @@ public Response exportEntityGraph(
String validatedEntityType = validateEntityType(entityType);
int clampedDepth = clampGraphDepth(depth);
String normalizedFormat = RdfRepository.normalizeEntityGraphExportFormat(format);
if (getRdfRepository() == null || !getRdfRepository().isEnabled()) {
final RdfRepository repository = getRdfRepository();
if (repository == null || !repository.isEnabled()) {
return Response.status(Response.Status.SERVICE_UNAVAILABLE)
.entity(buildErrorResponse("RDF service not enabled"))
.build();
}

String result =
getRdfRepository()
.exportEntityGraph(
entityId,
validatedEntityType,
clampedDepth,
parseCsvFilter(entityTypes),
parseCsvFilter(relationshipTypes),
normalizedFormat);
repository.exportEntityGraph(
entityId,
validatedEntityType,
clampedDepth,
parseCsvFilter(entityTypes),
parseCsvFilter(relationshipTypes),
normalizedFormat);

MediaType mediaType =
switch (normalizedFormat) {
Expand Down Expand Up @@ -484,15 +499,16 @@ public Response updateSparql(
@Context SecurityContext securityContext,
@Parameter(description = "SPARQL UPDATE query", required = true) SparqlQuery sparqlQuery) {
authorizer.authorizeAdmin(securityContext);
if (getRdfRepository() == null || !getRdfRepository().isEnabled()) {
final RdfRepository repository = getRdfRepository();
if (repository == null || !repository.isEnabled()) {
return Response.status(Response.Status.SERVICE_UNAVAILABLE)
.entity("RDF repository is not enabled")
.build();
}

try {
validateSparqlUpdate(sparqlQuery.getQuery());
getRdfRepository().executeSparqlUpdate(sparqlQuery.getQuery());
repository.executeSparqlUpdate(sparqlQuery.getQuery());
return Response.ok().entity("{\"status\": \"success\"}").build();
} catch (IllegalArgumentException exception) {
return Response.status(Response.Status.BAD_REQUEST).entity(exception.getMessage()).build();
Expand Down Expand Up @@ -526,7 +542,8 @@ private static boolean hasWhereClause(Update update) {
}

private Response executeSparqlQuery(String query, String format, String inference) {
if (getRdfRepository() == null || !getRdfRepository().isEnabled()) {
final RdfRepository repository = getRdfRepository();
if (repository == null || !repository.isEnabled()) {
return Response.status(Response.Status.SERVICE_UNAVAILABLE)
.entity("RDF repository is not enabled")
.build();
Expand All @@ -536,9 +553,9 @@ private Response executeSparqlQuery(String query, String format, String inferenc
String mimeType = getMimeTypeForFormat(format);
String results;
if (!"none".equalsIgnoreCase(inference)) {
results = getRdfRepository().executeSparqlQueryWithInference(query, mimeType, inference);
results = repository.executeSparqlQueryWithInference(query, mimeType, inference);
} else {
results = getRdfRepository().executeSparqlQuery(query, mimeType);
results = repository.executeSparqlQuery(query, mimeType);
}
return Response.ok(results).type(mimeType).build();
} catch (IllegalArgumentException e) {
Expand Down Expand Up @@ -593,16 +610,16 @@ public Response getFullLineage(
authorizer.authorizeAdmin(securityContext);
try {
String validatedEntityType = validateEntityType(entityType);
if (getRdfRepository() == null || !getRdfRepository().isEnabled()) {
final RdfRepository repository = getRdfRepository();
if (repository == null || !repository.isEnabled()) {
return Response.status(Response.Status.SERVICE_UNAVAILABLE)
.entity(buildErrorResponse("RDF service not enabled"))
.build();
}

String query =
buildLineageQuery(
entityId, validatedEntityType, direction, getRdfRepository().getBaseUri());
String results = getRdfRepository().executeSparqlQueryDirect(query, SPARQL_JSON);
buildLineageQuery(entityId, validatedEntityType, direction, repository.getBaseUri());
String results = repository.executeSparqlQueryDirect(query, SPARQL_JSON);
return Response.ok(results).build();
} catch (IllegalArgumentException e) {
return Response.status(Response.Status.BAD_REQUEST)
Expand Down Expand Up @@ -724,16 +741,16 @@ public Response getGlossaryTermGraph(
boolean includeIsolated) {
authorizer.authorizeAdmin(securityContext);
try {
if (getRdfRepository() == null || !getRdfRepository().isEnabled()) {
final RdfRepository repository = getRdfRepository();
if (repository == null || !repository.isEnabled()) {
return Response.status(Response.Status.SERVICE_UNAVAILABLE)
.entity("{\"error\": \"RDF service not enabled\"}")
.build();
}

String graphData =
getRdfRepository()
.getGlossaryTermGraph(
glossaryId, glossaryTermId, relationTypes, limit, offset, includeIsolated);
repository.getGlossaryTermGraph(
glossaryId, glossaryTermId, relationTypes, limit, offset, includeIsolated);
return Response.ok(graphData, MediaType.APPLICATION_JSON).build();

} catch (Exception e) {
Expand Down Expand Up @@ -767,7 +784,8 @@ public Response semanticSearch(
@DefaultValue("10")
int limit) {
authorizer.authorizeAdmin(securityContext);
if (getRdfRepository() == null || !getRdfRepository().isEnabled()) {
final RdfRepository repository = getRdfRepository();
if (repository == null || !repository.isEnabled()) {
return Response.status(Response.Status.SERVICE_UNAVAILABLE)
.entity("{\"error\": \"RDF service not enabled\"}")
.build();
Expand Down Expand Up @@ -808,7 +826,8 @@ public Response findSimilar(
@DefaultValue("10")
int limit) {
authorizer.authorizeAdmin(securityContext);
if (getRdfRepository() == null || !getRdfRepository().isEnabled()) {
final RdfRepository repository = getRdfRepository();
if (repository == null || !repository.isEnabled()) {
return Response.status(Response.Status.SERVICE_UNAVAILABLE)
.entity("{\"error\": \"RDF service not enabled\"}")
.build();
Expand Down Expand Up @@ -861,13 +880,14 @@ public Response exportGlossaryAsOntology(
boolean includeRelations) {
authorizer.authorizeAdmin(securityContext);
try {
if (getRdfRepository() == null || !getRdfRepository().isEnabled()) {
final RdfRepository repository = getRdfRepository();
if (repository == null || !repository.isEnabled()) {
return Response.status(Response.Status.SERVICE_UNAVAILABLE)
.entity("{\"error\": \"RDF service not enabled\"}")
.build();
}

String result = getRdfRepository().exportGlossaryAsOntology(id, format, includeRelations);
String result = repository.exportGlossaryAsOntology(id, format, includeRelations);
String mediaType =
switch (format.toLowerCase()) {
case "rdfxml", "xml" -> RDF_XML;
Expand Down Expand Up @@ -920,7 +940,8 @@ public Response getRecommendations(
@DefaultValue("10")
int limit) {
authorizer.authorizeAdmin(securityContext);
if (getRdfRepository() == null || !getRdfRepository().isEnabled()) {
final RdfRepository repository = getRdfRepository();
if (repository == null || !repository.isEnabled()) {
return Response.status(Response.Status.SERVICE_UNAVAILABLE)
.entity("{\"error\": \"RDF service not enabled\"}")
.build();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@

import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.core.SecurityContext;
import java.lang.reflect.Field;
import java.util.UUID;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
Expand All @@ -45,12 +44,6 @@ void setUp() {
rdfResource = new RdfResource(authorizer);
}

private void setRdfRepository(RdfRepository repository) throws Exception {
Field field = RdfResource.class.getDeclaredField("rdfRepository");
field.setAccessible(true);
field.set(rdfResource, repository);
}

@Test
void exploreEntityGraphRejectsInvalidEntityType() {
Response response =
Expand Down Expand Up @@ -105,7 +98,7 @@ void getGlossaryTermGraphPassesGlossaryTermIdFilter() throws Exception {
when(repository.isEnabled()).thenReturn(true);
when(repository.getGlossaryTermGraph(glossaryId, glossaryTermId, null, 500, 0, true))
.thenReturn("{\"nodes\":[],\"edges\":[]}");
setRdfRepository(repository);
rdfResource = new RdfResource(authorizer, () -> repository);

Response response =
rdfResource.getGlossaryTermGraph(
Expand All @@ -119,7 +112,7 @@ void getGlossaryTermGraphPassesGlossaryTermIdFilter() throws Exception {
void rejectsMultipleWhereBearingUpdateOperationsBeforeRepositoryExecution() throws Exception {
RdfRepository repository = Mockito.mock(RdfRepository.class);
when(repository.isEnabled()).thenReturn(true);
setRdfRepository(repository);
rdfResource = new RdfResource(authorizer, () -> repository);
String update =
"DELETE WHERE { <urn:first> ?predicate ?object }; "
+ "DELETE WHERE { <urn:second> ?predicate ?object }";
Expand All @@ -139,7 +132,7 @@ void rejectsMultipleWhereBearingUpdateOperationsBeforeRepositoryExecution() thro
void allowsOneWhereBearingOperationWithDataOnlyOperations() throws Exception {
RdfRepository repository = Mockito.mock(RdfRepository.class);
when(repository.isEnabled()).thenReturn(true);
setRdfRepository(repository);
rdfResource = new RdfResource(authorizer, () -> repository);
String update =
"DELETE WHERE { <urn:first> ?predicate ?object }; "
+ "INSERT DATA { <urn:first> <urn:predicate> <urn:object> }";
Expand Down
Loading