diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/insights/workflows/dataAssets/DataAssetsWorkflow.java b/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/insights/workflows/dataAssets/DataAssetsWorkflow.java index 744f229ff9d8..f1274058da4f 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/insights/workflows/dataAssets/DataAssetsWorkflow.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/insights/workflows/dataAssets/DataAssetsWorkflow.java @@ -14,6 +14,8 @@ import java.util.Map; import java.util.Optional; import java.util.Set; +import java.util.UUID; +import java.util.concurrent.CancellationException; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; @@ -63,6 +65,7 @@ public class DataAssetsWorkflow implements DataInsightsWorkflow { private final int retentionDays = 30; private final Long startTimestamp; private final Long endTimestamp; + private final long snapshotTimestamp; private final int batchSize; private final SearchRepository searchRepository; private final CollectionDAO collectionDAO; @@ -74,6 +77,7 @@ public class DataAssetsWorkflow implements DataInsightsWorkflow { private DataInsightsEntityEnricherProcessor entityEnricher; private Processor entityProcessor; private Sink searchIndexSink; + private DataInsightsExtensions extensions; @Getter private final WorkflowStats workflowStats = new WorkflowStats("DataAssetsWorkflow"); private volatile boolean stopped = false; @@ -116,6 +120,7 @@ public DataAssetsWorkflow( } this.batchSize = batchSize; + this.snapshotTimestamp = timestamp; this.searchRepository = searchRepository; this.collectionDAO = collectionDAO; this.entityTypes = entityTypes; @@ -224,6 +229,30 @@ public void process() throws SearchIndexException { } LOG.info("[Data Insights] Processing Data Assets Insights."); initialize(); + DataInsightsExtension.RunContext runContext = + new DataInsightsExtension.RunContext( + UUID.randomUUID().toString(), + System.currentTimeMillis(), + snapshotTimestamp, + collectionDAO, + searchRepository, + dataAssetsConfig, + () -> stopped); + try (DataInsightsExtensions runExtensions = DataInsightsExtensions.open(runContext)) { + this.extensions = runExtensions; + processSources(); + if (!stopped && !workflowStats.hasFailed()) { + runExtensions.complete(); + } + } catch (CancellationException ex) { + stopped = true; + LOG.info("[Data Insights] Data Assets workflow stopped: {}", ex.getMessage()); + } finally { + this.extensions = null; + } + } + + private void processSources() throws SearchIndexException { Map contextData = new HashMap<>(); contextData.put(START_TIMESTAMP_KEY, startTimestamp); @@ -284,6 +313,7 @@ private void processSource( continue; } + extensions.beforeBatch(batch.getData()); record EntityFuture(EntityInterface entity, Future future) {} List entityFutures = new ArrayList<>(); for (EntityInterface entity : batch.getData()) { @@ -296,6 +326,7 @@ record EntityFuture(EntityInterface entity, Future future) {} try { List> enriched = entityEnricher.enrichSingle(entity, contextData); + enriched.forEach(extensions::enrich); List bulkOps = (List) entityProcessor.process(enriched, contextData); EntityReference ref = entity.getEntityReference(); diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/insights/workflows/dataAssets/DataInsightsExtension.java b/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/insights/workflows/dataAssets/DataInsightsExtension.java new file mode 100644 index 000000000000..1abfa115d280 --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/insights/workflows/dataAssets/DataInsightsExtension.java @@ -0,0 +1,61 @@ +package org.openmetadata.service.apps.bundles.insights.workflows.dataAssets; + +import java.util.List; +import java.util.Map; +import java.util.concurrent.CancellationException; +import java.util.function.BooleanSupplier; +import org.openmetadata.schema.EntityInterface; +import org.openmetadata.schema.entity.applications.configuration.internal.DataAssetsConfig; +import org.openmetadata.service.jdbi3.CollectionDAO; +import org.openmetadata.service.search.SearchRepository; + +/** Run-scoped additions to DI snapshots and consumers of a successfully indexed DI run. */ +public interface DataInsightsExtension { + Session open(RunContext context); + + record RunContext( + String runId, + long capturedAt, + long snapshotTimestamp, + CollectionDAO collectionDAO, + SearchRepository searchRepository, + DataAssetsConfig configuration, + BooleanSupplier cancelled) { + public RunContext( + String runId, + long capturedAt, + long snapshotTimestamp, + CollectionDAO collectionDAO, + SearchRepository searchRepository, + DataAssetsConfig configuration) { + this( + runId, + capturedAt, + snapshotTimestamp, + collectionDAO, + searchRepository, + configuration, + () -> false); + } + + public void requireActive() { + if (cancelled.getAsBoolean() || Thread.currentThread().isInterrupted()) { + throw new CancellationException( + "Data Insights run was cancelled or lost its execution lease"); + } + } + } + + /** Enrichment can run concurrently; completion runs once, while the DI job still owns its lease. */ + interface Session extends AutoCloseable { + /** Allows bounded bulk lookups before the batch's concurrent enrichment starts. */ + default void beforeBatch(List entities) {} + + default void enrich(Map snapshot) {} + + default void complete() {} + + @Override + default void close() {} + } +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/insights/workflows/dataAssets/DataInsightsExtensions.java b/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/insights/workflows/dataAssets/DataInsightsExtensions.java new file mode 100644 index 000000000000..06031d654fa6 --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/insights/workflows/dataAssets/DataInsightsExtensions.java @@ -0,0 +1,81 @@ +package org.openmetadata.service.apps.bundles.insights.workflows.dataAssets; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.ServiceLoader; +import org.openmetadata.schema.EntityInterface; +import org.openmetadata.service.apps.bundles.insights.workflows.dataAssets.DataInsightsExtension.RunContext; +import org.openmetadata.service.apps.bundles.insights.workflows.dataAssets.DataInsightsExtension.Session; + +/** Keeps extension state local to one DI run, including cleanup after startup or indexing failure. */ +public final class DataInsightsExtensions implements AutoCloseable { + private final RunContext context; + private final List sessions = new ArrayList<>(); + + private DataInsightsExtensions(RunContext context) { + this.context = context; + } + + public static DataInsightsExtensions open(RunContext context) { + return open(context, ServiceLoader.load(DataInsightsExtension.class)); + } + + static DataInsightsExtensions open( + RunContext context, Iterable extensions) { + DataInsightsExtensions run = new DataInsightsExtensions(context); + try { + for (DataInsightsExtension extension : extensions) { + Session session = extension.open(context); + if (session == null) { + throw new IllegalStateException( + "Data Insights extension %s returned a null session" + .formatted(extension.getClass().getName())); + } + run.sessions.add(session); + } + } catch (RuntimeException | Error failure) { + try { + run.close(); + } catch (RuntimeException cleanupFailure) { + failure.addSuppressed(cleanupFailure); + } + throw failure; + } + return run; + } + + public void enrich(Map snapshot) { + context.requireActive(); + sessions.forEach(session -> session.enrich(snapshot)); + } + + public void complete() { + context.requireActive(); + sessions.forEach(Session::complete); + } + + public void beforeBatch(List entities) { + context.requireActive(); + sessions.forEach(session -> session.beforeBatch(entities)); + } + + @Override + public void close() { + RuntimeException failure = null; + for (Session session : sessions.reversed()) { + try { + session.close(); + } catch (RuntimeException exception) { + if (failure == null) { + failure = exception; + } else { + failure.addSuppressed(exception); + } + } + } + if (failure != null) { + throw failure; + } + } +} diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/apps/bundles/insights/workflows/dataAssets/DataInsightsExtensionsTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/apps/bundles/insights/workflows/dataAssets/DataInsightsExtensionsTest.java new file mode 100644 index 000000000000..d83259837030 --- /dev/null +++ b/openmetadata-service/src/test/java/org/openmetadata/service/apps/bundles/insights/workflows/dataAssets/DataInsightsExtensionsTest.java @@ -0,0 +1,166 @@ +package org.openmetadata.service.apps.bundles.insights.workflows.dataAssets; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.CancellationException; +import org.junit.jupiter.api.Test; +import org.openmetadata.service.apps.bundles.insights.workflows.dataAssets.DataInsightsExtension.RunContext; +import org.openmetadata.service.apps.bundles.insights.workflows.dataAssets.DataInsightsExtension.Session; + +class DataInsightsExtensionsTest { + private static final RunContext CONTEXT = new RunContext("run", 2000, 1000, null, null, null); + + @Test + void batchPreparationPrecedesEnrichmentAndCancellationStopsCompletion() { + var cancelled = new java.util.concurrent.atomic.AtomicBoolean(); + var context = new RunContext("run", 2000, 1000, null, null, null, cancelled::get); + List calls = new ArrayList<>(); + DataInsightsExtension extension = + ignored -> + new Session() { + @Override + public void beforeBatch( + List entities) { + calls.add("batch"); + } + + @Override + public void enrich(Map snapshot) { + calls.add("asset"); + } + + @Override + public void complete() { + calls.add("complete"); + } + }; + try (var run = DataInsightsExtensions.open(context, List.of(extension))) { + run.beforeBatch(List.of()); + run.enrich(new HashMap<>()); + cancelled.set(true); + assertThrows(CancellationException.class, run::complete); + assertThrows(CancellationException.class, () -> run.enrich(new HashMap<>())); + assertEquals(List.of("batch", "asset"), calls); + } + } + + @Test + void startupAndCleanupFailuresAreBothPreserved() { + DataInsightsExtension opened = + context -> + new Session() { + @Override + public void close() { + throw new IllegalStateException("close"); + } + }; + DataInsightsExtension failed = + context -> { + throw new IllegalArgumentException("open"); + }; + var error = + assertThrows( + IllegalArgumentException.class, + () -> DataInsightsExtensions.open(CONTEXT, List.of(opened, failed))); + assertEquals("open", error.getMessage()); + assertEquals("close", error.getSuppressed()[0].getMessage()); + } + + @Test + void nullSessionFailsFastWithProviderName() { + var error = + assertThrows( + IllegalStateException.class, + () -> DataInsightsExtensions.open(CONTEXT, List.of(new NullSessionExtension()))); + + assertTrue(error.getMessage().contains(NullSessionExtension.class.getName())); + } + + @Test + void onlySessionsWriteToTheSnapshotAndCompletionIsExplicit() { + List events = new ArrayList<>(); + DataInsightsExtension extension = + context -> + new Session() { + @Override + public void enrich(Map snapshot) { + events.add("enriched"); + snapshot.put("added", true); + } + + @Override + public void complete() { + events.add("completed"); + } + + @Override + public void close() { + events.add("closed"); + } + }; + var snapshot = new HashMap(); + try (var run = DataInsightsExtensions.open(CONTEXT, List.of(extension))) { + run.enrich(snapshot); + assertEquals(List.of("enriched"), events); + run.complete(); + } + + assertEquals(Map.of("added", true), snapshot); + assertEquals(List.of("enriched", "completed", "closed"), events); + } + + @Test + void failedStartupClosesAlreadyOpenedSessions() { + List events = new ArrayList<>(); + DataInsightsExtension opened = context -> closingSession(events, "first"); + DataInsightsExtension failed = + context -> { + throw new IllegalStateException("source failed"); + }; + + assertThrows( + IllegalStateException.class, + () -> DataInsightsExtensions.open(CONTEXT, List.of(opened, failed))); + assertEquals(List.of("first"), events); + } + + @Test + void failureToCloseOneSessionDoesNotLeakAnother() { + List events = new ArrayList<>(); + DataInsightsExtension opened = context -> closingSession(events, "first"); + DataInsightsExtension failed = + context -> + new Session() { + @Override + public void close() { + throw new IllegalStateException("cleanup failed"); + } + }; + var run = DataInsightsExtensions.open(CONTEXT, List.of(opened, failed)); + + assertThrows(IllegalStateException.class, run::close); + assertEquals(List.of("first"), events); + } + + private static Session closingSession(List events, String event) { + return new Session() { + @Override + public void close() { + events.add(event); + } + }; + } + + private static final class NullSessionExtension implements DataInsightsExtension { + @Override + public Session open(RunContext context) { + return null; + } + } +}