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

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 @@ -26,7 +26,7 @@
public class ActionDoFnFactory {

public static DoFn<Integer, Row> of(ActionContext context) {
var action = context.getAction();
var action = context.action();
var actionType = action.getType();
return switch (actionType) {
case "bigquery" -> new BigQueryActionFn(context);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ public class BigQueryActionFn extends DoFn<Integer, Row> {
private final String sql;

public BigQueryActionFn(ActionContext context) {
var sql = ((BigQueryAction) context.getAction()).sql();
var sql = ((BigQueryAction) context.action()).sql();
if (StringUtils.isEmpty(sql)) {
throw new IllegalArgumentException("Options 'sql' not provided for preload query transform.");
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,15 +43,12 @@ public class CypherActionFn extends DoFn<Integer, Row> {
private Neo4jConnection connection;

public CypherActionFn(ActionContext context) {
this(
context,
() ->
new Neo4jConnection(context.getNeo4jConnectionParams(), context.getTemplateVersion()));
this(context, connectionSupplier(context));
}

@VisibleForTesting
CypherActionFn(ActionContext context, SerializableSupplier<Neo4jConnection> connectionProvider) {
CypherAction cypherAction = (CypherAction) context.getAction();
CypherAction cypherAction = (CypherAction) context.action();
String cypher = cypherAction.getQuery();
if (StringUtils.isEmpty(cypher)) {
throw new RuntimeException("Options 'cypher' not provided for cypher action transform.");
Expand Down Expand Up @@ -103,4 +100,10 @@ public void tearDown() {
connection.close();
}
}

private static SerializableSupplier<Neo4jConnection> connectionSupplier(ActionContext context) {
var provider = context.connectionParamsProvider();
var templateVersion = context.templateVersion();
return () -> new Neo4jConnection(provider.get(), templateVersion);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ public class HttpActionFn extends DoFn<Integer, Row> {
private final HttpAction action;

public HttpActionFn(ActionContext context) {
this.action = ((HttpAction) context.getAction());
this.action = ((HttpAction) context.action());
if (StringUtils.isEmpty(action.url())) {
throw new RuntimeException("URL not provided for HTTP action.");
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
/*
* Copyright (C) 2026 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.cloud.teleport.v2.neo4j.model.connection;

import com.google.cloud.teleport.v2.neo4j.model.InputValidator;
import com.google.cloud.teleport.v2.neo4j.model.Json;
import com.google.cloud.teleport.v2.neo4j.utils.FileSystemUtils;
import com.google.cloud.teleport.v2.neo4j.utils.SerializableSupplier;
import com.google.cloud.teleport.v2.utils.SecretManagerUtils;
import java.io.Serial;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.apache.commons.lang3.StringUtils;

/**
* Lazily resolves the Neo4j connection settings.
*
* <p>Only the connection reference (a GCS URI or a Secret Manager secret id) is captured by this
* provider, so the actual settings - including passwords and tokens - are neither read by the
* launcher nor embedded in the serialized Dataflow pipeline. Resolution happens on the first call
* to {@link #get()}, that is, on a worker.
*/
public class ConnectionParamsProvider implements SerializableSupplier<ConnectionParams> {

@Serial private static final long serialVersionUID = 1L;

// Workers are short-lived and may host many DoFn instances; sharing the resolved settings avoids
// a Secret Manager or GCS call per DoFn. Nothing is serialized: this cache lives in the worker
// JVM only.
private static final Map<String, ConnectionParams> CACHE = new ConcurrentHashMap<>();

private final String secretId;

private final String uri;

public ConnectionParamsProvider(String secretId, String uri) {
this.secretId = StringUtils.isNotEmpty(secretId) ? secretId : null;
this.uri = uri;
}

@Override
public ConnectionParams get() {
return CACHE.computeIfAbsent(cacheKey(), key -> resolve());
}

private String cacheKey() {
return secretId != null ? "secret:" + secretId : "uri:" + uri;
}

private ConnectionParams resolve() {
String connectionJson = readConnectionSettings();
Json.ParsingResult parsingResult = InputValidator.validateNeo4jConnection(connectionJson);
if (!parsingResult.isSuccessful()) {
throw new IllegalArgumentException(
String.join(
System.lineSeparator(),
parsingResult.formatErrors("Could not validate connection JSON")));
}
return Json.map(parsingResult, ConnectionParams.class);
}

private String readConnectionSettings() {
if (secretId != null) {
return SecretManagerUtils.getSecret(secretId);
}
try {
return FileSystemUtils.getPathContents(uri);
} catch (Exception e) {
throw new RuntimeException(
String.format("Unable to read Neo4j configuration at URI %s: ", uri), e);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,32 +16,13 @@
package com.google.cloud.teleport.v2.neo4j.model.job;

import com.google.cloud.teleport.v2.neo4j.model.connection.ConnectionParams;
import com.google.cloud.teleport.v2.neo4j.utils.SerializableSupplier;
import java.io.Serializable;
import org.neo4j.importer.v1.actions.Action;

/** Context for actions. */
public class ActionContext implements Serializable {

private final Action action;
private final ConnectionParams neo4jConnectionParams;
private final String templateVersion;

public ActionContext(
Action action, ConnectionParams neo4jConnectionParams, String templateVersion) {
this.action = action;
this.neo4jConnectionParams = neo4jConnectionParams;
this.templateVersion = templateVersion;
}

public Action getAction() {
return action;
}

public ConnectionParams getNeo4jConnectionParams() {
return neo4jConnectionParams;
}

public String getTemplateVersion() {
return templateVersion;
}
}
public record ActionContext(
Action action,
SerializableSupplier<ConnectionParams> connectionParamsProvider,
String templateVersion)
implements Serializable {}
Original file line number Diff line number Diff line change
Expand Up @@ -20,14 +20,10 @@
import com.google.cloud.teleport.metadata.TemplateCategory;
import com.google.cloud.teleport.v2.common.UncaughtExceptionLogger;
import com.google.cloud.teleport.v2.neo4j.model.InputValidator;
import com.google.cloud.teleport.v2.neo4j.model.Json;
import com.google.cloud.teleport.v2.neo4j.model.Json.ParsingResult;
import com.google.cloud.teleport.v2.neo4j.model.connection.ConnectionParams;
import com.google.cloud.teleport.v2.neo4j.model.connection.ConnectionParamsProvider;
import com.google.cloud.teleport.v2.neo4j.model.helpers.JobSpecMapper;
import com.google.cloud.teleport.v2.neo4j.model.helpers.OverlayTokenParser;
import com.google.cloud.teleport.v2.neo4j.options.Neo4jFlexTemplateOptions;
import com.google.cloud.teleport.v2.neo4j.utils.FileSystemUtils;
import com.google.cloud.teleport.v2.utils.SecretManagerUtils;
import org.apache.beam.runners.dataflow.options.DataflowPipelineOptions;
import org.apache.beam.sdk.io.FileSystems;
import org.apache.beam.sdk.options.PipelineOptionsFactory;
Expand Down Expand Up @@ -104,13 +100,16 @@ public static void main(String[] args) {
FileSystems.setDefaultPipelineOptions(options);
var overlayTokens = OverlayTokenParser.parse(options.getOptionsJson());
var templateVersion = readTemplateVersion(options);
var neo4jConnectionConfig = readConnectionConfiguration(options);
// Only the connection reference is read here; the settings are resolved on a worker.
var connectionParamsProvider =
new ConnectionParamsProvider(
options.getNeo4jConnectionSecretId(), options.getNeo4jConnectionUri());
var importSpecification = JobSpecMapper.parse(options.getJobSpecUri(), overlayTokens);
var importPipeline =
new Neo4jImportPipelineRunner(
options,
templateVersion,
neo4jConnectionConfig,
connectionParamsProvider,
overlayTokens,
ImportPipeline.of(importSpecification));
importPipeline.run();
Expand All @@ -124,30 +123,4 @@ private static String readTemplateVersion(Neo4jFlexTemplateOptions options) {
}
return labels.getOrDefault("goog-dataflow-provided-template-version", defaultVersion);
}

private static ConnectionParams readConnectionConfiguration(
Neo4jFlexTemplateOptions pipelineOptions) {
String neo4jConnectionJson = readConnectionSettings(pipelineOptions);
ParsingResult parsingResult = InputValidator.validateNeo4jConnection(neo4jConnectionJson);
if (!parsingResult.isSuccessful()) {
ValidationErrors.processValidations(
"Errors found validating Neo4j connection: ",
parsingResult.formatErrors("Could not validate connection JSON"));
}
return Json.map(parsingResult, ConnectionParams.class);
}

private static String readConnectionSettings(Neo4jFlexTemplateOptions options) {
String secretId = options.getNeo4jConnectionSecretId();
if (StringUtils.isNotEmpty(secretId)) {
return SecretManagerUtils.getSecret(secretId);
}
String uri = options.getNeo4jConnectionUri();
try {
return FileSystemUtils.getPathContents(uri);
} catch (Exception e) {
throw new RuntimeException(
String.format("Unable to read Neo4j configuration at URI %s: ", uri), e);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
import com.google.cloud.teleport.v2.neo4j.transforms.Neo4jRowWriterTransform;
import com.google.cloud.teleport.v2.neo4j.transforms.VerifyOrResetDatabaseFn;
import com.google.cloud.teleport.v2.neo4j.utils.ProcessingCoder;
import com.google.cloud.teleport.v2.neo4j.utils.SerializableSupplier;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
Expand Down Expand Up @@ -57,7 +58,7 @@ public class Neo4jImportPipelineRunner {

private final String templateVersion;

private final ConnectionParams neo4jConnectionConfig;
private final SerializableSupplier<ConnectionParams> connectionParamsProvider;

private final OverlayTokens overlayTokens;

Expand All @@ -72,13 +73,13 @@ public class Neo4jImportPipelineRunner {
public Neo4jImportPipelineRunner(
PipelineOptions options,
String templateVersion,
ConnectionParams neo4jConnectionConfig,
SerializableSupplier<ConnectionParams> connectionParamsProvider,
OverlayTokens overlayTokens,
ImportPipeline pipeline) {

this.options = options;
this.templateVersion = templateVersion;
this.neo4jConnectionConfig = neo4jConnectionConfig;
this.connectionParamsProvider = connectionParamsProvider;
this.overlayTokens = overlayTokens;
this.pipelineDescription = pipeline;
this.pipelineRegistry = new PipelineRegistry();
Expand Down Expand Up @@ -139,7 +140,7 @@ void handleTarget(Pipeline pipeline, TargetStep step) {
new Neo4jRowWriterTransform(
pipelineDescription.configuration(),
ReportedSourceType.reportedSourceTypeOf(sourceContext.step),
neo4jConnectionConfig,
connectionParamsProvider,
templateVersion,
stepSequence,
dependencies,
Expand Down Expand Up @@ -228,11 +229,12 @@ private PCollection<Long> checkConnectionOrResetDb(Pipeline pipeline) {
.apply("Start " + description, Create.of(1L))
.apply(
description,
ParDo.of(new VerifyOrResetDatabaseFn(neo4jConnectionConfig, templateVersion, resetDb)));
ParDo.of(
new VerifyOrResetDatabaseFn(connectionParamsProvider, templateVersion, resetDb)));
}

private ActionContext newActionContext(Action action) {
return new ActionContext(action, neo4jConnectionConfig, templateVersion);
return new ActionContext(action, connectionParamsProvider, templateVersion);
}

private static class PipelineRegistry {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ public class Neo4jRowWriterTransform extends PTransform<PCollection<Row>, PColle
public Neo4jRowWriterTransform(
Configuration configuration,
ReportedSourceType reportedSourceType,
ConnectionParams neoConnection,
SerializableSupplier<ConnectionParams> connectionParamsProvider,
String templateVersion,
StepSequence targetSequence,
List<PCollection<?>> dependencies,
Expand All @@ -84,7 +84,7 @@ public Neo4jRowWriterTransform(
targetSequence,
dependencies,
step,
() -> new Neo4jConnection(neoConnection, templateVersion));
() -> new Neo4jConnection(connectionParamsProvider.get(), templateVersion));
}

@VisibleForTesting
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,11 @@

import com.google.cloud.teleport.v2.neo4j.database.Neo4jConnection;
import com.google.cloud.teleport.v2.neo4j.model.connection.ConnectionParams;
import com.google.cloud.teleport.v2.neo4j.utils.SerializableSupplier;
import org.apache.beam.sdk.transforms.DoFn;

public class VerifyOrResetDatabaseFn extends DoFn<Long, Long> {
private final ConnectionParams neo4jConnectionConfig;
private final SerializableSupplier<ConnectionParams> connectionParamsProvider;

private final String templateVersion;

Expand All @@ -29,15 +30,17 @@ public class VerifyOrResetDatabaseFn extends DoFn<Long, Long> {
private transient Neo4jConnection connection;

public VerifyOrResetDatabaseFn(
ConnectionParams neo4jConnectionConfig, String templateVersion, boolean resetDb) {
this.neo4jConnectionConfig = neo4jConnectionConfig;
SerializableSupplier<ConnectionParams> connectionParamsProvider,
String templateVersion,
boolean resetDb) {
this.connectionParamsProvider = connectionParamsProvider;
this.templateVersion = templateVersion;
this.resetDb = resetDb;
}

@Setup
public void prepare() {
this.connection = new Neo4jConnection(neo4jConnectionConfig, templateVersion);
this.connection = new Neo4jConnection(connectionParamsProvider.get(), templateVersion);
}

@Teardown
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,16 +44,16 @@ public void sends_transaction_metadata_for_autocommit_Cypher_action() {
ActionStage.POST_NODES,
"RETURN 42",
CypherExecutionMode.AUTOCOMMIT),
mock(ConnectionParams.class),
() -> mock(ConnectionParams.class),
"a-version");
CypherActionFn actionFn = new CypherActionFn(context, () -> connection);
var actionFn = new CypherActionFn(context, () -> connection);
actionFn.setup();

actionFn.processElement(mock(ProcessContext.class));

Map<String, String> expectedTxMetadata =
var expectedTxMetadata =
Map.of("sink", "neo4j", "step", "cypher-action", "execution", "autocommit");
TransactionConfig expectedTransactionConfig =
var expectedTransactionConfig =
TransactionConfig.builder()
.withMetadata(Map.of("app", "dataflow", "metadata", expectedTxMetadata))
.build();
Expand All @@ -70,16 +70,16 @@ public void sends_transaction_metadata_for_transactional_Cypher_action() {
ActionStage.POST_NODES,
"RETURN 42",
CypherExecutionMode.TRANSACTION),
mock(ConnectionParams.class),
() -> mock(ConnectionParams.class),
"a-version");
CypherActionFn actionFn = new CypherActionFn(context, () -> connection);
var actionFn = new CypherActionFn(context, () -> connection);
actionFn.setup();

actionFn.processElement(mock(ProcessContext.class));

Map<String, String> expectedTxMetadata =
var expectedTxMetadata =
Map.of("sink", "neo4j", "step", "cypher-action", "execution", "transaction");
TransactionConfig expectedTransactionConfig =
var expectedTransactionConfig =
TransactionConfig.builder()
.withMetadata(Map.of("app", "dataflow", "metadata", expectedTxMetadata))
.build();
Expand Down
Loading
Loading